From a570fd0bebf2fa64f83f9c49d6c1a94fcd87cb1d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 17 Dec 2019 23:28:58 -0500 Subject: [PATCH 001/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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/872] 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 636a0066f3509316725b92a2852cb2abfeecbb0a Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Mon, 3 Mar 2025 21:25:24 +0300 Subject: [PATCH 790/872] examples folder --- example/0001.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 example/0001.js diff --git a/example/0001.js b/example/0001.js new file mode 100644 index 00000000..ed59304f --- /dev/null +++ b/example/0001.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 example1 = twoSum([2, 7, 11, 15], 9); // [0,1] +const example2 = twoSum([3, 2, 4], 6); // [1,2] +const example3 = twoSum([3, 3], 6); // [0,1] + +console.log(example1); +console.log(example2); +console.log(example3); From 35a795a6b75dc98dccffd404438c4f8c119c11d2 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Mon, 3 Mar 2025 22:39:13 +0300 Subject: [PATCH 791/872] Create 0167.js --- example/0167.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 example/0167.js diff --git a/example/0167.js b/example/0167.js new file mode 100644 index 00000000..028d9258 --- /dev/null +++ b/example/0167.js @@ -0,0 +1,32 @@ +/** + * 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 example1 = twoSum([2,7,11,15], 9); // [1,2] +const example2 = twoSum([2, 3, 4], 6); // [1,3] +const example3 = twoSum([-1,0], -1); // [1,2] + +console.log(example1); +console.log(example2); +console.log(example3); From bfbb8d339ca723490778ceb571327ab09fb42b5d Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Mon, 3 Mar 2025 23:13:06 +0300 Subject: [PATCH 792/872] Create 0344.js --- 0344-reverse-string.js | 8 ++++++++ example/0344.js | 24 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 example/0344.js diff --git a/0344-reverse-string.js b/0344-reverse-string.js index e459e954..9685e42a 100644 --- a/0344-reverse-string.js +++ b/0344-reverse-string.js @@ -18,3 +18,11 @@ var reverseString = function(s) { [s[s.length - 1 - i], s[i]] = [s[i], s[s.length - 1 - i]]; } }; + +// let left = 0, right = s.length - 1; +// while (left < right) { +// [s[left], s[right]] = [s[right], s[left]]; +// left++; +// right--; +// } +// return s diff --git a/example/0344.js b/example/0344.js new file mode 100644 index 00000000..33d5bb5e --- /dev/null +++ b/example/0344.js @@ -0,0 +1,24 @@ +/** + * 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) { + +}; + +const example1 = reverseString(["h","e","l","l","o"]); // ["o","l","l","e","h"] +const example2 = reverseString(["H","a","n","n","a","h"]); // ["h","a","n","n","a","H"] + +console.log(example1); +console.log(example2); From 79671ae8811611cf4cb5bd7dd133ace0b5197f5a Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Mon, 3 Mar 2025 23:52:26 +0300 Subject: [PATCH 793/872] Create 0125.js --- 0125-valid-palindrome.js | 12 ++++++++++++ example/0125.js | 27 +++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 example/0125.js diff --git a/0125-valid-palindrome.js b/0125-valid-palindrome.js index 74ad00f1..c3a24c19 100644 --- a/0125-valid-palindrome.js +++ b/0125-valid-palindrome.js @@ -18,3 +18,15 @@ var isPalindrome = function(s) { const string = s.replace(/[^A-Z\d]+/ig, '').toLowerCase(); return string.split('').reverse().join('') === string; }; + + +// s = s.replace(/[^A-Za-z0-9]/g, '').toLowerCase(); +// let left = 0, right = s.length - 1; + +// while (left < right) { +// if (s[left] !== s[right]) return false; +// left++; +// right--; +// } + +// return true; \ No newline at end of file diff --git a/example/0125.js b/example/0125.js new file mode 100644 index 00000000..4cbbe881 --- /dev/null +++ b/example/0125.js @@ -0,0 +1,27 @@ +/** + * 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 example1 = isPalindrome("A man, a plan, a canal: Panama" ); // true +const example2 = isPalindrome("race a car"); // false +const example3 = isPalindrome(" "); // true + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file From b5a24562c0c555e95358c58cea97eb451d2080b0 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 01:24:45 +0300 Subject: [PATCH 794/872] Create 0015.js --- 0015-3sum.js | 60 +++++++++++++++++++++++++++++++++++++++++++++++++ example/0015.js | 32 ++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 example/0015.js diff --git a/0015-3sum.js b/0015-3sum.js index 35d01c95..565ee7b5 100644 --- a/0015-3sum.js +++ b/0015-3sum.js @@ -41,3 +41,63 @@ var threeSum = function(nums) { return result; }; + +// var threeSum = function(nums) { +// nums.sort((a, b) => a - b); +// const result = []; + +// for (let i = 0; i < nums.length - 2; i++) { +// if (i > 0 && nums[i] === nums[i - 1]) continue; // Пропускаем дубли + +// let left = i + 1, right = nums.length - 1; + +// while (left < right) { +// const sum = nums[i] + nums[left] + nums[right]; + +// if (sum === 0) { +// result.push([nums[i], nums[left], nums[right]]); +// left++; +// right--; + +// while (left < right && nums[left] === nums[left - 1]) left++; // Пропуск дубликатов слева +// while (left < right && nums[right] === nums[right + 1]) right--; // Пропуск дубликатов справа +// } else if (sum < 0) { +// left++; +// } else { +// right--; +// } +// } +// } + +// return result; +// }; + +// O(n^2) +// с = - (a + b) +// var threeSum = function(nums) { +// nums.sort((a, b) => a - b); // O(n log n) +// const result = new Set(); +// const n = nums.length; + +// for (let i = 0; i < n; i++) { +// let target = -nums[i]; +// let left = i + 1; +// let right = n - 1; + +// while (left < right) { +// let currentSum = nums[left] + nums[right]; + +// if (currentSum === target) { +// result.add(JSON.stringify([nums[i], nums[left], nums[right]])); +// left++; +// right--; +// } else if (currentSum > target) { +// right--; +// } else { +// left++; +// } +// } +// } + +// return Array.from(result, JSON.parse); // Преобразуем Set обратно в массив +// }; \ No newline at end of file diff --git a/example/0015.js b/example/0015.js new file mode 100644 index 00000000..1ad1b7bf --- /dev/null +++ b/example/0015.js @@ -0,0 +1,32 @@ +/** + * 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 example1 = threeSum([-1,0,1,2,-1,-4]); // [[-1,-1,2],[-1,0,1]] +const example2 = threeSum([0,1,1]); // [] +const example3 = threeSum([0,0,0]); // [[0,0,0]] +const example4 = threeSum([-4, -1, -1,0,1,2]); // [[-1,-1,2],[-1,0,1]] +const example5 = threeSum([-3, -2, 1, 2]); // [[ -3, 1, 2 ]] +const example6 = threeSum([-2, -1, 3]); // [[ -2, -1, 3 ]] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); From a9af7ba66cb6169852944d49a8f4852ed03d52d1 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 01:44:40 +0300 Subject: [PATCH 795/872] Create 0977.js --- 0977-squares-of-a-sorted-array.js | 19 +++++++++++++++++++ example/0977.js | 23 +++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 example/0977.js diff --git a/0977-squares-of-a-sorted-array.js b/0977-squares-of-a-sorted-array.js index e1a37507..a7747688 100644 --- a/0977-squares-of-a-sorted-array.js +++ b/0977-squares-of-a-sorted-array.js @@ -15,3 +15,22 @@ var sortedSquares = function(A) { return A.map(n => Math.pow(n, 2)).sort((a, b) => a - b); }; + +// O(n) without sorting +// var sortedSquares = function(nums) { +// let n = nums.length; +// let result = new Array(n); +// let left = 0, right = n - 1; + +// for (let i = n - 1; i >= 0; i--) { +// if (Math.abs(nums[left]) > Math.abs(nums[right])) { +// result[i] = nums[left] * nums[left]; +// left++; +// } else { +// result[i] = nums[right] * nums[right]; +// right--; +// } +// } + +// return result; +// }; \ No newline at end of file diff --git a/example/0977.js b/example/0977.js new file mode 100644 index 00000000..fade9f82 --- /dev/null +++ b/example/0977.js @@ -0,0 +1,23 @@ +/** + * 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(nums) { + +}; + +const example1 = sortedSquares([-4,-1,0,3,10]); // [0,1,9,16,100] +const example2 = sortedSquares([-7,-3,2,3,11]); // [4,9,9,49,121] + +console.log(example1); +console.log(example2); From 0584e1815182814478a1f7ce89c418e3fccc2138 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 02:07:26 +0300 Subject: [PATCH 796/872] Create 0011.js --- example/0011.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 example/0011.js diff --git a/example/0011.js b/example/0011.js new file mode 100644 index 00000000..f0267b88 --- /dev/null +++ b/example/0011.js @@ -0,0 +1,27 @@ +/** + * 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) { + +}; + + +const example1 = maxArea([1,8,6,2,5,4,8,3,7]); // 49 +const example2 = maxArea([1,1]); // 1 + +console.log(example1); +console.log(example2); \ No newline at end of file From a07543ade56ca447666aab37083b145637544cef Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 02:51:14 +0300 Subject: [PATCH 797/872] Create 0026.js --- example/0011.js | 12 +++++++++++- example/0026.js | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 example/0026.js diff --git a/example/0011.js b/example/0011.js index f0267b88..23dcde07 100644 --- a/example/0011.js +++ b/example/0011.js @@ -22,6 +22,16 @@ var maxArea = function(height) { const example1 = maxArea([1,8,6,2,5,4,8,3,7]); // 49 const example2 = maxArea([1,1]); // 1 +const example3 = maxArea([9,0,8]); // 16 +const example4 = maxArea([9,0,8,4,0,0,0,0,0,0,4]); // 40 +const example5 = maxArea([9,8,4,0,0,0,0,0,0,4]); // 36 +const example6 = maxArea([4,0,0,0,0,0,0,4]); // 28 +const example7 = maxArea([1,0,4,0,0,0,0,0,0,4]); // 28 console.log(example1); -console.log(example2); \ No newline at end of file +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); +console.log(example7); \ No newline at end of file diff --git a/example/0026.js b/example/0026.js new file mode 100644 index 00000000..515c3cc0 --- /dev/null +++ b/example/0026.js @@ -0,0 +1,39 @@ +/** + * 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) { + +}; + + +const example1 = removeDuplicates([1,1,2]); // 2, nums = [1,2,_] +const example2 = removeDuplicates([0,0,1,1,1,2,2,3,3,4]); // 5, nums = [0,1,2,3,4,_,_,_,_,_] +const example3 = removeDuplicates([2,3,3,3,3]); // 2, nums = [2,3,_,_,_] +const example4 = removeDuplicates([1]); // 1, nums = [1] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); \ No newline at end of file From d374bf1b3f615c4ec9f158067307492c53f92911 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 03:18:55 +0300 Subject: [PATCH 798/872] Create 0283.js --- 0026-remove-duplicates-from-sorted-array.js | 11 ++++++++ 0283-move-zeroes.js | 13 +++++++++ example/0283.js | 29 +++++++++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 example/0283.js diff --git a/0026-remove-duplicates-from-sorted-array.js b/0026-remove-duplicates-from-sorted-array.js index 326d46ef..ad3696ca 100644 --- a/0026-remove-duplicates-from-sorted-array.js +++ b/0026-remove-duplicates-from-sorted-array.js @@ -32,3 +32,14 @@ var removeDuplicates = function(nums) { } return ++i; }; + +// var removeDuplicates = function(nums) { +// let k = 0; +// for (let i = 0; i < nums.length; i++) { +// if (nums[k] !== nums[i]) { +// k=k+1 +// nums[k] = nums[i]; +// } +// } +// return k+1; +// }; diff --git a/0283-move-zeroes.js b/0283-move-zeroes.js index d3008579..6a04291e 100644 --- a/0283-move-zeroes.js +++ b/0283-move-zeroes.js @@ -20,3 +20,16 @@ var moveZeroes = function(nums) { } } }; + +// write and reed +// var moveZeroes = function(nums) { +// let w = 0; +// for (let r = 0; r < nums.length; r++) { +// if (nums[r] !== 0) { +// [nums[w], nums[r]] = [nums[r], nums[w]]; +// w=w+1 +// } +// } + +// return nums +// }; \ No newline at end of file diff --git a/example/0283.js b/example/0283.js new file mode 100644 index 00000000..701caca5 --- /dev/null +++ b/example/0283.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) { + +}; + +const example1 = moveZeroes([0,1,0,3,12]); // [1,3,12,0,0] +const example2 = moveZeroes([0]); // [0] +const example3 = moveZeroes([0,1,3,12]); // [1,3,12,0] +const example4 = moveZeroes([0,1,0,3,12]); // [1,3,12] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); + \ No newline at end of file From 6b35a337e69edd7bee92ba422c29c219df42fefb Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 03:42:37 +0300 Subject: [PATCH 799/872] Create 0392.js --- 0392-is-subsequence.js | 13 +++++++++++++ example/0392.js | 31 +++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 example/0392.js diff --git a/0392-is-subsequence.js b/0392-is-subsequence.js index a041d570..ed3b1301 100644 --- a/0392-is-subsequence.js +++ b/0392-is-subsequence.js @@ -25,3 +25,16 @@ var isSubsequence = function(s, t) { } return count === s.length; }; + +// var isSubsequence = function(s, t) { +// let p1 = 0; +// let p2 = 0; +// while (p1 < s.length && p2 < t.length) { +// if (s[p1] === t[p2]) { +// p1 += 1 +// } +// p2 += 1 +// } + +// return p1 === s.length +// }; diff --git a/example/0392.js b/example/0392.js new file mode 100644 index 00000000..8b441b2b --- /dev/null +++ b/example/0392.js @@ -0,0 +1,31 @@ +/** + * 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(sub, t) { + +}; + +const example1 = isSubsequence('abc', 'ahbgdc'); // true +const example2 = isSubsequence('axc', 'ahbgdc'); // false +const example3 = isSubsequence('abc', 'ab1c'); // true +const example4 = isSubsequence('abc', 'abb1abc'); // true + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); + \ No newline at end of file From 37425e779029d201da3b786867f41580f3550738 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 05:40:57 +0300 Subject: [PATCH 800/872] Create 0844.js --- 0392-is-subsequence.js | 8 ++-- 0844-backspace-string-compare.js | 69 ++++++++++++++++++++++++++++++++ example/0392.js | 2 +- example/0844.js | 30 ++++++++++++++ 4 files changed, 104 insertions(+), 5 deletions(-) create mode 100644 example/0844.js diff --git a/0392-is-subsequence.js b/0392-is-subsequence.js index ed3b1301..310d34f8 100644 --- a/0392-is-subsequence.js +++ b/0392-is-subsequence.js @@ -26,15 +26,15 @@ var isSubsequence = function(s, t) { return count === s.length; }; -// var isSubsequence = function(s, t) { +// var isSubsequence = function(sub, t) { // let p1 = 0; // let p2 = 0; -// while (p1 < s.length && p2 < t.length) { -// if (s[p1] === t[p2]) { +// while (p1 < sub.length && p2 < t.length) { +// if (sub[p1] === t[p2]) { // p1 += 1 // } // p2 += 1 // } -// return p1 === s.length +// return p1 === sub.length // }; diff --git a/0844-backspace-string-compare.js b/0844-backspace-string-compare.js index c5dab2e4..a33f2a04 100644 --- a/0844-backspace-string-compare.js +++ b/0844-backspace-string-compare.js @@ -28,3 +28,72 @@ function handleBackspaces(input) { return result; }, []).join(''); } + +// (сзади идем) +// O(n+m) O(1) +// var backspaceCompare = function(s, t) { +// n = s.length - 1 +// m = t.length - 1 +// skip_s = 0; +// skip_t = 0; + +// while (n >= 0 && m>= 0) { +// // todo: implement skip (if # or skip_counter > 0) + +// if (s[n] != s[m]) { +// return false +// } + +// n = n - 1 +// m = m - 1 +// } + +// return n === m +// }; + +// XXX:GPT +// var backspaceCompare = function(s, t) { +// let n = s.length - 1; +// let m = t.length - 1; +// let skip_s = 0; +// let skip_t = 0; + +// while (n >= 0 || m >= 0) { +// while (n >= 0) { // Обрабатываем backspace в `s` +// if (s[n] === '#') { +// skip_s++; +// n--; +// } else if (skip_s > 0) { +// skip_s--; +// n--; +// } else { +// break; +// } +// } + +// while (m >= 0) { // Обрабатываем backspace в `t` +// if (t[m] === '#') { +// skip_t++; +// m--; +// } else if (skip_t > 0) { +// skip_t--; +// m--; +// } else { +// break; +// } +// } + +// if (n >= 0 && m >= 0 && s[n] !== t[m]) { +// return false; +// } + +// if ((n >= 0) !== (m >= 0)) { +// return false; +// } + +// n--; +// m--; +// } + +// return true; +// }; \ No newline at end of file diff --git a/example/0392.js b/example/0392.js index 8b441b2b..550f9a9b 100644 --- a/example/0392.js +++ b/example/0392.js @@ -15,7 +15,7 @@ * @param {string} t * @return {boolean} */ -var isSubsequence = function(sub, t) { +var isSubsequence = function(s, t) { }; diff --git a/example/0844.js b/example/0844.js new file mode 100644 index 00000000..40fa4ad7 --- /dev/null +++ b/example/0844.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) { + +}; + +const example1 = backspaceCompare('ab#c', 'ad#c'); // true 'ac' +const example2 = backspaceCompare('ab##', 'c#d#'); // true '' +const example3 = backspaceCompare('a#c', 'b'); // false +const example4 = backspaceCompare('a#b', 'a#bb'); // false + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); + \ No newline at end of file From 15ea0e27cb279da2542b39ed6250b92852a3ef2e Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 06:31:09 +0300 Subject: [PATCH 801/872] Create 0088.js --- 0088-merge-sorted-array.js | 60 ++++++++++++++++++++++++++++++++++++++ example/0088.js | 41 ++++++++++++++++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 example/0088.js diff --git a/0088-merge-sorted-array.js b/0088-merge-sorted-array.js index c94a4117..fd547a93 100644 --- a/0088-merge-sorted-array.js +++ b/0088-merge-sorted-array.js @@ -32,3 +32,63 @@ var merge = function(nums1, m, nums2, n) { nums1[i--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--]; } }; + +// FOWARD +// var merge = function(nums1, m, nums2, n) { +// let result = []; +// let p1 = 0; +// let p2 = 0; + +// while (p1 < m && p2 < n) { +// if (nums1[p1] < nums2[p2]) { +// result.push(nums1[p1]); +// p1++; +// } else { +// result.push(nums2[p2]); +// p2++; +// } +// } + +// while (p1 < m) { +// result.push(nums1[p1]); +// p1++; +// } + +// while (p2 < n) { +// result.push(nums2[p2]); +// p2++; +// } + +// for (let i = 0; i < result.length; i++) { +// nums1[i] = result[i]; +// } + +// return nums1 +// }; + + +// BACKWARD +// var merge = function(nums1, m, nums2, n) { +// let p1 = m - 1; +// let p2 = n - 1; +// let result = m + n - 1; + +// while (p1 >= 0 && p2 >= 0) { +// if (nums1[p1] > nums2[p2]) { +// nums1[result] = nums1[p1]; +// p1--; +// } else { +// nums1[result] = nums2[p2]; +// p2--; +// } +// result--; +// } + +// while (p2 >= 0) { +// nums1[result] = nums2[p2]; +// p2--; +// result--; +// } + +// return nums1 +// }; \ No newline at end of file diff --git a/example/0088.js b/example/0088.js new file mode 100644 index 00000000..81313cbb --- /dev/null +++ b/example/0088.js @@ -0,0 +1,41 @@ +/** + * 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) { + +}; + + +const example1 = merge([1,2,3,0,0,0], 3, [2,5,6], 3); // [1,2,2,3,5,6] +const example2 = merge([1], 1 , [], 0); // [1] +const example3 = merge([0], 0, [1], 1); // [1] +const example4 = merge([1,2,0,0], 2, [5,6], 2); // [1,2,5,6] +const example5 = merge([1,2,3,0,0,0], 4, [2,5,6], 2); // [1, 2, 2, 3, 0, 5] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); + \ No newline at end of file From 7b52fa1ef37c7e1d63d6aa99b1fa0b5bdd19186a Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 07:54:50 +0300 Subject: [PATCH 802/872] group examples by theme --- README.md | 813 ++-------------------------- README1.md | 769 ++++++++++++++++++++++++++ example/{ => 0.ArraysHash}/0001.js | 0 example/{ => 0.ArraysHash}/0167.js | 0 example/{ => 1.TwoPointers}/0011.js | 0 example/{ => 1.TwoPointers}/0015.js | 0 example/{ => 1.TwoPointers}/0026.js | 0 example/{ => 1.TwoPointers}/0088.js | 0 example/{ => 1.TwoPointers}/0125.js | 0 example/{ => 1.TwoPointers}/0283.js | 0 example/{ => 1.TwoPointers}/0344.js | 0 example/{ => 1.TwoPointers}/0392.js | 0 example/{ => 1.TwoPointers}/0844.js | 0 example/{ => 1.TwoPointers}/0977.js | 0 14 files changed, 819 insertions(+), 763 deletions(-) create mode 100644 README1.md rename example/{ => 0.ArraysHash}/0001.js (100%) rename example/{ => 0.ArraysHash}/0167.js (100%) rename example/{ => 1.TwoPointers}/0011.js (100%) rename example/{ => 1.TwoPointers}/0015.js (100%) rename example/{ => 1.TwoPointers}/0026.js (100%) rename example/{ => 1.TwoPointers}/0088.js (100%) rename example/{ => 1.TwoPointers}/0125.js (100%) rename example/{ => 1.TwoPointers}/0283.js (100%) rename example/{ => 1.TwoPointers}/0344.js (100%) rename example/{ => 1.TwoPointers}/0392.js (100%) rename example/{ => 1.TwoPointers}/0844.js (100%) rename example/{ => 1.TwoPointers}/0977.js (100%) diff --git a/README.md b/README.md index c6aa5c7c..ace51e23 100644 --- a/README.md +++ b/README.md @@ -1,769 +1,56 @@ -# LeetCode solutions in JavaScript +# LeetCode solutions in JavaScript -[https://leetcode.com/](https://leetcode.com/) +This is my way for learning algorithms on JS. -## Table of Contents: +Repository with prepared empty tasks for training in [Example folder](https://github.com/Barklim/leetcode-javascript/tree/master/example) with test cases. -|#|Title|Difficulty| -|:---|:---|:---| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| -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| +``` +/** + * 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. + */ -## License +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function (nums, target) { + +}; -[MIT License](https://opensource.org/licenses/MIT) +const example1 = twoSum([2, 7, 11, 15], 9); // [0,1] +const example2 = twoSum([3, 2, 4], 6); // [1,2] +const example3 = twoSum([3, 3], 6); // [0,1] -Copyright (c) 2019-2025 [Josh Crozier](https://joshcrozier.com) +console.log(example1); +console.log(example2); +console.log(example3); +``` + +## Test cases + +Test cases is groupped inderections for learning in propper order for learning how it recommended in [neetcode](https://neetcode.io/roadmap) + +``` +example + 0.ArraysHash + 1.TwoPointers + ... + 18.MathGeometry +``` + +## Links + +[List of solutions](https://github.com/Barklim/leetcode-javascript/blob/master/README.md) + +This repo is Copy of [leetcode-javascript](https://github.com/JoshCrozier/leetcode-javascript) diff --git a/README1.md b/README1.md new file mode 100644 index 00000000..9fb5d6c0 --- /dev/null +++ b/README1.md @@ -0,0 +1,769 @@ +# LeetCode solutions in JavaScript + +[https://leetcode.com/](https://leetcode.com/) + +## Table of Contents: + +|#|Title|Difficulty| +|:---|:---|:---| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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| +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 + +[MIT License](https://opensource.org/licenses/MIT) + +Copyright (c) 2019-2025 [Josh Crozier](https://joshcrozier.com) diff --git a/example/0001.js b/example/0.ArraysHash/0001.js similarity index 100% rename from example/0001.js rename to example/0.ArraysHash/0001.js diff --git a/example/0167.js b/example/0.ArraysHash/0167.js similarity index 100% rename from example/0167.js rename to example/0.ArraysHash/0167.js diff --git a/example/0011.js b/example/1.TwoPointers/0011.js similarity index 100% rename from example/0011.js rename to example/1.TwoPointers/0011.js diff --git a/example/0015.js b/example/1.TwoPointers/0015.js similarity index 100% rename from example/0015.js rename to example/1.TwoPointers/0015.js diff --git a/example/0026.js b/example/1.TwoPointers/0026.js similarity index 100% rename from example/0026.js rename to example/1.TwoPointers/0026.js diff --git a/example/0088.js b/example/1.TwoPointers/0088.js similarity index 100% rename from example/0088.js rename to example/1.TwoPointers/0088.js diff --git a/example/0125.js b/example/1.TwoPointers/0125.js similarity index 100% rename from example/0125.js rename to example/1.TwoPointers/0125.js diff --git a/example/0283.js b/example/1.TwoPointers/0283.js similarity index 100% rename from example/0283.js rename to example/1.TwoPointers/0283.js diff --git a/example/0344.js b/example/1.TwoPointers/0344.js similarity index 100% rename from example/0344.js rename to example/1.TwoPointers/0344.js diff --git a/example/0392.js b/example/1.TwoPointers/0392.js similarity index 100% rename from example/0392.js rename to example/1.TwoPointers/0392.js diff --git a/example/0844.js b/example/1.TwoPointers/0844.js similarity index 100% rename from example/0844.js rename to example/1.TwoPointers/0844.js diff --git a/example/0977.js b/example/1.TwoPointers/0977.js similarity index 100% rename from example/0977.js rename to example/1.TwoPointers/0977.js From d63cee7899ec8b6b774caed028d726809d859976 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 09:04:59 +0300 Subject: [PATCH 803/872] Create 0217.js --- 0217-contains-duplicate.js | 11 +++++++++++ README.md | 4 ++-- example/0.ArraysHash/0217.js | 23 +++++++++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 example/0.ArraysHash/0217.js diff --git a/0217-contains-duplicate.js b/0217-contains-duplicate.js index 951c214f..4b2bae35 100644 --- a/0217-contains-duplicate.js +++ b/0217-contains-duplicate.js @@ -14,3 +14,14 @@ var containsDuplicate = function(nums) { return new Set(nums).size !== nums.length; }; + +// var containsDuplicate = function(nums) { +// const set = new Set() +// for (let i = 0; i < nums.length; i++) { +// if (set.has(nums[i])) { +// return true +// } +// set.add(nums[i], i) +// } +// return false +// } diff --git a/README.md b/README.md index ace51e23..e67b78e8 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ console.log(example3); ## Test cases -Test cases is groupped inderections for learning in propper order for learning how it recommended in [neetcode](https://neetcode.io/roadmap) +Test cases is groupped inderections for learning in propper order how it recommended in [neetcode](https://neetcode.io/roadmap) ``` example @@ -51,6 +51,6 @@ example ## Links -[List of solutions](https://github.com/Barklim/leetcode-javascript/blob/master/README.md) +[List of solutions](https://github.com/Barklim/leetcode-javascript/blob/master/README1.md) This repo is Copy of [leetcode-javascript](https://github.com/JoshCrozier/leetcode-javascript) diff --git a/example/0.ArraysHash/0217.js b/example/0.ArraysHash/0217.js new file mode 100644 index 00000000..4c43c373 --- /dev/null +++ b/example/0.ArraysHash/0217.js @@ -0,0 +1,23 @@ +/** + * 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) { + +}; + +const example1 = containsDuplicate([1,2,3,3]); // true +const example2 = containsDuplicate([1,2,3,4]); // false + +console.log(example1); +console.log(example2); + \ No newline at end of file From 0a431191d5a2ea8102c7ab0117a2533269a6668f Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 09:31:15 +0300 Subject: [PATCH 804/872] Create 0412.js --- 0412-fizz-buzz.js | 16 ++++++++++++++++ example/20.0ther/0412.js | 27 +++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 example/20.0ther/0412.js diff --git a/0412-fizz-buzz.js b/0412-fizz-buzz.js index ed737dd8..7df71869 100644 --- a/0412-fizz-buzz.js +++ b/0412-fizz-buzz.js @@ -20,3 +20,19 @@ var fizzBuzz = function(n) { ? 'FizzBuzz' : i % 3 === 0 ? 'Fizz' : i % 5 === 0 ? 'Buzz' : String(i) ); }; + +// var fizzBuzz = function(n) { +// const result = [] +// for (let i = 1; i <= n; i++) { +// if (i % 3 === 0 && i % 5 === 0) { +// result.push('FizzBuzz') +// } else if(i % 3 === 0) { +// result.push('Fizz') +// } else if(i % 5 === 0) { +// result.push('Buzz') +// } else { +// result.push(i+'') +// } +// } +// return result; +// }; \ No newline at end of file diff --git a/example/20.0ther/0412.js b/example/20.0ther/0412.js new file mode 100644 index 00000000..27328c9c --- /dev/null +++ b/example/20.0ther/0412.js @@ -0,0 +1,27 @@ +/** + * 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) { + +}; + +const example1 = fizzBuzz(3); // ["1","2","Fizz"] +const example2 = fizzBuzz(5); // ["1","2","Fizz","4","Buzz"] +const example3 = fizzBuzz(15); // ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] + +console.log(example1); +console.log(example2); +console.log(example3); From b8fe79d4ffbf8946008a69d3c189aac7c8539328 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 10:10:35 +0300 Subject: [PATCH 805/872] Create 0242.js --- 0242-valid-anagram.js | 20 ++++++++++++++++++++ example/0.ArraysHash/0242.js | 26 ++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 example/0.ArraysHash/0242.js diff --git a/0242-valid-anagram.js b/0242-valid-anagram.js index e922f3d0..4a5403a8 100644 --- a/0242-valid-anagram.js +++ b/0242-valid-anagram.js @@ -15,3 +15,23 @@ var isAnagram = function(s, t) { const sort = str => str.split('').sort().join(''); return sort(s) === sort(t); }; + +// var isAnagram = function(s, t) { +// if (s.length !== t.length) { +// return false; +// } + +// const countS = {}; +// const countT = {}; +// for (let i = 0; i < s.length; i++) { +// countS[s[i]] = (countS[s[i]] || 0) + 1; +// countT[t[i]] = (countT[t[i]] || 0) + 1; +// } + +// for (const key in countS) { +// if (countS[key] !== countT[key]) { +// return false; +// } +// } +// return true; +// } diff --git a/example/0.ArraysHash/0242.js b/example/0.ArraysHash/0242.js new file mode 100644 index 00000000..4c8769b5 --- /dev/null +++ b/example/0.ArraysHash/0242.js @@ -0,0 +1,26 @@ +/** + * 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 example1 = isAnagram('anagram', "nagaram"); // true +const example2 = isAnagram("rat", 'car'); // false +const example3 = isAnagram('racecar', 'carrace'); // true +const example4 = isAnagram('jar', 'jam'); // false + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); From dadfe3fe557a12e8148474822b505ef05e82a773 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 13:12:19 +0300 Subject: [PATCH 806/872] Create 0049.js --- 0049-group-anagrams.js | 17 +++++++++++++++++ example/0.ArraysHash/0001.js | 2 ++ example/0.ArraysHash/0049.js | 30 ++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 example/0.ArraysHash/0049.js diff --git a/0049-group-anagrams.js b/0049-group-anagrams.js index 3f48828b..0b237f12 100644 --- a/0049-group-anagrams.js +++ b/0049-group-anagrams.js @@ -24,3 +24,20 @@ var groupAnagrams = function(strs) { return Object.values(map); }; + +// var groupAnagrams = function(strs) { +// const res = {}; +// for (let s of strs) { +// // Создаем массив частот букв +// const count = new Array(26).fill(0); +// for (let c of s) { +// count[c.charCodeAt(0) - 'a'.charCodeAt(0)] += 1; +// } +// const key = count.join(','); +// if (!res[key]) { +// res[key] = []; +// } +// res[key].push(s); +// } +// return Object.values(res); +// } diff --git a/example/0.ArraysHash/0001.js b/example/0.ArraysHash/0001.js index ed59304f..832be269 100644 --- a/example/0.ArraysHash/0001.js +++ b/example/0.ArraysHash/0001.js @@ -24,7 +24,9 @@ var twoSum = function (nums, target) { const example1 = twoSum([2, 7, 11, 15], 9); // [0,1] const example2 = twoSum([3, 2, 4], 6); // [1,2] const example3 = twoSum([3, 3], 6); // [0,1] +const example4 = twoSum([4 ,5, 6], 10); // [0,2] console.log(example1); console.log(example2); console.log(example3); +console.log(example4); diff --git a/example/0.ArraysHash/0049.js b/example/0.ArraysHash/0049.js new file mode 100644 index 00000000..a91467a9 --- /dev/null +++ b/example/0.ArraysHash/0049.js @@ -0,0 +1,30 @@ +/** + * 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 example1 = groupAnagrams(["eat","tea","tan","ate","nat","bat"]); // [["bat"],["nat","tan"],["ate","eat","tea"]] +const example2 = groupAnagrams([""]); // [[""]] +const example3 = groupAnagrams(["a"]); // [["a"]] +const example4 = groupAnagrams(["act","pots","tops","cat","stop","hat"]); // [["hat"],["act", "cat"],["stop", "pots", "tops"]] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); + \ No newline at end of file From f5a7c9fa5cfcfaab84bbcbce7d70ced1603203ce Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 16:18:31 +0300 Subject: [PATCH 807/872] Create 0347.js --- 0347-top-k-frequent-elements.js | 30 ++++++++++++++++++++++++++++++ example/0.ArraysHash/0347.js | 25 +++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 example/0.ArraysHash/0347.js diff --git a/0347-top-k-frequent-elements.js b/0347-top-k-frequent-elements.js index 87b6b3e5..c8b6400d 100644 --- a/0347-top-k-frequent-elements.js +++ b/0347-top-k-frequent-elements.js @@ -22,3 +22,33 @@ var topKFrequent = function(nums, k) { .slice(0, k) .map(([value]) => value) }; + +/** + * Почему Map + Sort быстрее на малых данных + * 1. Оптимизированные встроенные методы JS + * 2. Низкий константный оверхед + * 3. Быстродействие Map в JS + * 4. JS-движки оптимизируют Map + sort() + */ +// Bucket sort +// var topKFrequent = function (nums, k) { +// const count = {}; +// const freq = Array.from({ length: nums.length + 1 }, () => []); + +// for (const n of nums) { +// count[n] = (count[n] || 0) + 1; +// } +// for (const n in count) { +// freq[count[n]].push(parseInt(n)); +// } + +// const res = []; +// for (let i = freq.length - 1; i > 0; i--) { +// for (const n of freq[i]) { +// res.push(n); +// if (res.length === k) { +// return res; +// } +// } +// } +// }; diff --git a/example/0.ArraysHash/0347.js b/example/0.ArraysHash/0347.js new file mode 100644 index 00000000..2285fb6d --- /dev/null +++ b/example/0.ArraysHash/0347.js @@ -0,0 +1,25 @@ +/** + * 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 example1 = topKFrequent([1, 1, 1, 2, 2, 3], 2); // [1,2] +const example2 = topKFrequent([1], 1); // [1] +const example3 = topKFrequent([3, 3, 5, 5, 5, 6], 2); // [3, 5] + +console.log(example1); +console.log(example2); +console.log(example3); From d7eb918b6b205f42618791316f19336cf57473fe Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 17:39:13 +0300 Subject: [PATCH 808/872] Create 0271.js --- example/0.ArraysHash/0271.js | 50 ++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 example/0.ArraysHash/0271.js diff --git a/example/0.ArraysHash/0271.js b/example/0.ArraysHash/0271.js new file mode 100644 index 00000000..0ac480fc --- /dev/null +++ b/example/0.ArraysHash/0271.js @@ -0,0 +1,50 @@ +/** + * @param {string[]} strs + * @returns {string} + */ +var encode = function (strs) {}; + +/** + * @param {string} str + * @returns {string[]} + */ +var decode = function (str) {}; + +const example1 = encode(["neet", "code", "love", "you"]); // 4#neet4#code4#love3#you +const example2 = decode(example1); // ["neet","code","love","you"] +const example3 = encode(["we", "say", ":", "yes"]); // 2#we3#say1#:3#yes +const example4 = decode(example3); // ["we","say",":","yes"] +const example5 = encode(["ne#et", "co#de", "lo#ve", "you"]); // 5#ne#et5#co#de5#lo#ve3#you +const example6 = decode(example1); // ["ne#et", "co#de", "lo#ve", "you"] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); + +// var encode = function (strs) { +// let res = ""; +// for (let s of strs) { +// res += s.length + "#" + s; +// } +// return res; +// }; + +// var decode = function (str) { +// let res = []; +// let i = 0; +// while (i < str.length) { +// let j = i; +// while (str[j] !== "#") { +// j++; +// } +// let length = parseInt(str.substring(i, j)); +// i = j + 1; +// j = i + length; +// res.push(str.substring(i, j)); +// i = j; +// } +// return res; +// }; From 3d4cccb284f11a852539a33a2d9e6a9bef8f1f54 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 21:28:44 +0300 Subject: [PATCH 809/872] Create 0238.js --- 0238-product-of-array-except-self.js | 26 ++++++++++++++++++++++++ example/0.ArraysHash/0238.js | 30 ++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 example/0.ArraysHash/0238.js diff --git a/0238-product-of-array-except-self.js b/0238-product-of-array-except-self.js index f297cd25..79914964 100644 --- a/0238-product-of-array-except-self.js +++ b/0238-product-of-array-except-self.js @@ -28,3 +28,29 @@ var productExceptSelf = function(nums) { } return nums.map(n => product / n); }; + +// https://leetcode.com/discuss/study-guide/5119937/prefix-sum-problems + +// Brute Force +// var productExceptSelf = function (nums) { +// const n = nums.length; +// const res = new Array(n); + +// for (let i = 0; i < n; i++) { +// let prod = 1; +// for (let j = 0; j < n; j++) { +// if (i !== j) { +// prod *= nums[j]; +// } +// } +// res[i] = prod; +// } +// return res; +// }; + +// https://neetcode.io/problems/products-of-array-discluding-self +// https://www.youtube.com/watch?v=yuws7YK0Yng + +// 2. Division +// 3. Prefix & Suffix +// 4. Prefix & Suffix (Optimal) \ No newline at end of file diff --git a/example/0.ArraysHash/0238.js b/example/0.ArraysHash/0238.js new file mode 100644 index 00000000..160bbaf3 --- /dev/null +++ b/example/0.ArraysHash/0238.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 example1 = productExceptSelf([1,2,3,4]); // [24,12,8,6] +const example2 = productExceptSelf([-1,1,0,-3,3]); // [0,0,9,0,0] +const example3 = productExceptSelf([1,2,4,6]); // [48,24,12,8] +const example4 = productExceptSelf([-1,0,1,2,3]); // [0,-6,0,0,0] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); From e53e9881d5af0482b613fa51b497ea6026524a7e Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 4 Mar 2025 21:37:39 +0300 Subject: [PATCH 810/872] Create 0036.js --- example/0.ArraysHash/0036.js | 48 ++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 example/0.ArraysHash/0036.js diff --git a/example/0.ArraysHash/0036.js b/example/0.ArraysHash/0036.js new file mode 100644 index 00000000..fbde1c73 --- /dev/null +++ b/example/0.ArraysHash/0036.js @@ -0,0 +1,48 @@ +/** + * 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 example1 = isValidSudoku([ + ["5", "3", ".", ".", "7", ".", ".", ".", "."], + ["6", ".", ".", "1", "9", "5", ".", ".", "."], + [".", "9", "8", ".", ".", ".", ".", "6", "."], + ["8", ".", ".", ".", "6", ".", ".", ".", "3"], + ["4", ".", ".", "8", ".", "3", ".", ".", "1"], + ["7", ".", ".", ".", "2", ".", ".", ".", "6"], + [".", "6", ".", ".", ".", ".", "2", "8", "."], + [".", ".", ".", "4", "1", "9", ".", ".", "5"], + [".", ".", ".", ".", "8", ".", ".", "7", "9"], +]); // true +const example2 = isValidSudoku([ + ["8", "3", ".", ".", "7", ".", ".", ".", "."], + ["6", ".", ".", "1", "9", "5", ".", ".", "."], + [".", "9", "8", ".", ".", ".", ".", "6", "."], + ["8", ".", ".", ".", "6", ".", ".", ".", "3"], + ["4", ".", ".", "8", ".", "3", ".", ".", "1"], + ["7", ".", ".", ".", "2", ".", ".", ".", "6"], + [".", "6", ".", ".", ".", ".", "2", "8", "."], + [".", ".", ".", "4", "1", "9", ".", ".", "5"], + [".", ".", ".", ".", "8", ".", ".", "7", "9"], +]); // false + +console.log(example1); +console.log(example2); From a23a5f165972ec33f022054e4b29732ed9942fb9 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Wed, 5 Mar 2025 01:29:25 +0300 Subject: [PATCH 811/872] Create 0128.js --- example/0.ArraysHash/0128.js | 52 ++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 example/0.ArraysHash/0128.js diff --git a/example/0.ArraysHash/0128.js b/example/0.ArraysHash/0128.js new file mode 100644 index 00000000..64c8bf4b --- /dev/null +++ b/example/0.ArraysHash/0128.js @@ -0,0 +1,52 @@ +/** + * 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 (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, count); + } + } + + return result; +}; + + +const example1 = longestConsecutive([100,4,200,1,3,2]); // 4 +const example2 = longestConsecutive([0,3,7,2,5,8,4,6,0,1]); // 9 +const example3 = longestConsecutive([1,0,1,2]); // 3 +const example4 = longestConsecutive([2,20,4,10,3,4,5]); // 4 +const example5 = longestConsecutive([0,3,2,5,4,6,1,1]); // 7 +const example6 = longestConsecutive([1,3,5,7]); // 1 +const example7 = longestConsecutive([]); // 0 + + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); +console.log(example7); From 2c02944aa7aa17ebaad655f2f82884eb405d7035 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Wed, 5 Mar 2025 16:58:39 +0300 Subject: [PATCH 812/872] Create 0042.js --- 0042-trapping-rain-water.js | 23 +++++++++++++++++++++++ example/1.TwoPointers/0042.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 example/1.TwoPointers/0042.js diff --git a/0042-trapping-rain-water.js b/0042-trapping-rain-water.js index 15766764..1d60097b 100644 --- a/0042-trapping-rain-water.js +++ b/0042-trapping-rain-water.js @@ -22,3 +22,26 @@ var trap = function(height) { return result; }; + +// var trap = function(height) { +// let res = 0 +// let left = 0 +// let right = height.length - 1 +// let maxLeft = height[left] +// let maxRight = height[right] + +// while (left < right) { +// if (maxLeft < maxRight) { +// left++ +// maxLeft = Math.max(maxLeft, height[left]) +// res = res + (maxLeft - height[left]) +// // +// } else { +// right-- +// maxRight = Math.max(maxRight, height[right]) +// res = res + (maxRight - height[right]) +// } +// } + +// return res +// }; \ No newline at end of file diff --git a/example/1.TwoPointers/0042.js b/example/1.TwoPointers/0042.js new file mode 100644 index 00000000..28fac23c --- /dev/null +++ b/example/1.TwoPointers/0042.js @@ -0,0 +1,28 @@ +/** + * 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 example1 = trap([0,1,0,2,1,0,1,3,2,1,2,1]); // 6 +const example2 = trap([4,2,0,3,2,5]); // 9 +const example3 = trap([0,2,0,3,1,0,1,3,2,1]); // 9 +const example4 = trap([1,0,2]); // 1 +const example5 = trap([2,0,1,3]); // 3 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); \ No newline at end of file From b9a3e54b38f7f8ae2fb08d40f8f4ac71ed0409ea Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Thu, 6 Mar 2025 04:49:09 +0300 Subject: [PATCH 813/872] Create 0009.js --- 0009-palindrome-number.js | 17 +++++++++++++++++ example/20.0ther/0009.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 example/20.0ther/0009.js diff --git a/0009-palindrome-number.js b/0009-palindrome-number.js index a4691dc2..172bec71 100644 --- a/0009-palindrome-number.js +++ b/0009-palindrome-number.js @@ -17,3 +17,20 @@ var isPalindrome = function(x) { if (x < 0) return false; return +String(x).split('').reverse().join('') === x; }; + +// var isPalindrome = function (x) { +// if (x < 0) return false; + +// const strNum = x.toString(); +// let left = 0; +// let right = strNum.length - 1; + +// while (left < right) { +// if (strNum[left] !== strNum[right]) { +// return false; +// } +// left++; +// right--; +// } +// return true; +// }; diff --git a/example/20.0ther/0009.js b/example/20.0ther/0009.js new file mode 100644 index 00000000..032ee5bf --- /dev/null +++ b/example/20.0ther/0009.js @@ -0,0 +1,28 @@ +/** + * 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 (nums) { + +}; + +const example1 = isPalindrome(121); // true +const example2 = isPalindrome(-121); // false +const example3 = isPalindrome(10); // false +const example4 = isPalindrome(3003); // true + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); From acacc3493dadd1788e0e90b4f2c74141e90bbcd8 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Thu, 6 Mar 2025 07:22:18 +0300 Subject: [PATCH 814/872] Update 0088.js --- example/1.TwoPointers/0088.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/example/1.TwoPointers/0088.js b/example/1.TwoPointers/0088.js index 81313cbb..271e5d29 100644 --- a/example/1.TwoPointers/0088.js +++ b/example/1.TwoPointers/0088.js @@ -32,10 +32,16 @@ const example2 = merge([1], 1 , [], 0); // [1] const example3 = merge([0], 0, [1], 1); // [1] const example4 = merge([1,2,0,0], 2, [5,6], 2); // [1,2,5,6] const example5 = merge([1,2,3,0,0,0], 4, [2,5,6], 2); // [1, 2, 2, 3, 0, 5] +const example6 = merge([1,2,3,4], 4, [5,6], 2); // [1,2,3,4,5,6] +const example7 = merge([1,2,3,4], 2, [5,6], 2); // [1,2,5,6] +const example8 = merge([1,2], 2, [3,4,5,6], 3); // [1,2,3,4,5] console.log(example1); console.log(example2); console.log(example3); console.log(example4); console.log(example5); +console.log(example6); +console.log(example7); +console.log(example8); \ No newline at end of file From 0a4d37c34c7c7d75e95611944a48d95835ce04ca Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Thu, 6 Mar 2025 09:04:04 +0300 Subject: [PATCH 815/872] Update 0026.js and 0283.js --- example/1.TwoPointers/0026.js | 4 +++- example/1.TwoPointers/0283.js | 6 +++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/example/1.TwoPointers/0026.js b/example/1.TwoPointers/0026.js index 515c3cc0..c936242b 100644 --- a/example/1.TwoPointers/0026.js +++ b/example/1.TwoPointers/0026.js @@ -32,8 +32,10 @@ const example1 = removeDuplicates([1,1,2]); // 2, nums = [1,2,_] const example2 = removeDuplicates([0,0,1,1,1,2,2,3,3,4]); // 5, nums = [0,1,2,3,4,_,_,_,_,_] const example3 = removeDuplicates([2,3,3,3,3]); // 2, nums = [2,3,_,_,_] const example4 = removeDuplicates([1]); // 1, nums = [1] +const example5 = removeDuplicates([0,1,1,1,2,2,3,3,4]); // 5, nums = [0,1,2,3,4,_,_,_,_,_] console.log(example1); console.log(example2); console.log(example3); -console.log(example4); \ No newline at end of file +console.log(example4); +console.log(example5); \ No newline at end of file diff --git a/example/1.TwoPointers/0283.js b/example/1.TwoPointers/0283.js index 701caca5..2e40bc67 100644 --- a/example/1.TwoPointers/0283.js +++ b/example/1.TwoPointers/0283.js @@ -20,10 +20,14 @@ var moveZeroes = function(nums) { const example1 = moveZeroes([0,1,0,3,12]); // [1,3,12,0,0] const example2 = moveZeroes([0]); // [0] const example3 = moveZeroes([0,1,3,12]); // [1,3,12,0] -const example4 = moveZeroes([0,1,0,3,12]); // [1,3,12] +const example4 = moveZeroes([0,1,0,3,12]); // [1,3,12,0,0] +const example5 = moveZeroes([1,2,0,3,12]); // [1,2,3,12,0] +const example6 = moveZeroes([0,0,0,1]); // [1,0,0,0] console.log(example1); console.log(example2); console.log(example3); console.log(example4); +console.log(example5); +console.log(example6); \ No newline at end of file From 439125162680233761a4f5bc6fe36cab87cf63f1 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Thu, 6 Mar 2025 21:00:28 +0300 Subject: [PATCH 816/872] Create 0643.js --- 0643-maximum-average-subarray-i.js | 32 +++++++++++++++++++++++++++++ example/2.SlidingWindow/0643.js | 33 ++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 example/2.SlidingWindow/0643.js diff --git a/0643-maximum-average-subarray-i.js b/0643-maximum-average-subarray-i.js index 413edd4f..eb1913c8 100644 --- a/0643-maximum-average-subarray-i.js +++ b/0643-maximum-average-subarray-i.js @@ -29,3 +29,35 @@ var findMaxAverage = function(nums, k) { return max / k; }; + +// gpt +// var findMaxAverage = function (nums, k) { +// let maxSum = nums.slice(0, k).reduce((acc, num) => acc + num, 0); +// let windowSum = maxSum; + +// for (let end = k; end < nums.length; end++) { +// windowSum += nums[end] - nums[end - k]; +// maxSum = Math.max(maxSum, windowSum); +// } + +// return maxSum / k; +// }; + +// var findMaxAverage = function(nums, k) { +// let begin = 0; // Begin +// let window_state = 0; // WindowState +// let result = -Infinity; + +// for (let end = 0; end < nums.length; end++) { +// window_state += nums[end]; + +// // end - begin = window size +// if (end - begin + 1 === k) { // Window condition +// result = Math.max(result, window_state); +// window_state -= nums[begin]; +// begin++; // Shrink window +// } +// } + +// return result/k; +// }; diff --git a/example/2.SlidingWindow/0643.js b/example/2.SlidingWindow/0643.js new file mode 100644 index 00000000..46906cee --- /dev/null +++ b/example/2.SlidingWindow/0643.js @@ -0,0 +1,33 @@ +/** + * 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) { + +}; + + +const example1 = findMaxAverage([1,12,-5,-6,50,3], 4); // 12.75 +const example2 = findMaxAverage([5], 1); // 5 +const example3 = findMaxAverage([3, 3], 2); // 3 +const example4 = findMaxAverage([4 ,5, 6], 2); // 5.5 +const example5 = findMaxAverage([4 ,5, 6], 1); // 6 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); From 1d1c44214874c03e9706d30581f8003e813907d3 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Thu, 6 Mar 2025 21:51:06 +0300 Subject: [PATCH 817/872] Create 0209.js --- 0209-minimum-size-subarray-sum.js | 20 ++++++++++++++++++++ example/2.SlidingWindow/0209.js | 29 +++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 example/2.SlidingWindow/0209.js diff --git a/0209-minimum-size-subarray-sum.js b/0209-minimum-size-subarray-sum.js index ee8208ed..884019d9 100644 --- a/0209-minimum-size-subarray-sum.js +++ b/0209-minimum-size-subarray-sum.js @@ -27,3 +27,23 @@ var minSubArrayLen = function(target, nums) { return result === Infinity ? 0 : result; }; + +// var minSubArrayLen = function(target, nums) { +// let begin = 0 +// let window_state = 0 +// let result = Infinity; + +// for (let end = 0; end < nums.length; end++) { +// window_state += nums[end] + +// while (window_state >= target) { +// let window_size = end - begin + 1 +// result = Math.min(result, window_size) +// window_state -= nums[begin] +// begin++ +// } +// } + +// if (result === Infinity) return 0 +// return result +// }; \ No newline at end of file diff --git a/example/2.SlidingWindow/0209.js b/example/2.SlidingWindow/0209.js new file mode 100644 index 00000000..ba00d1ca --- /dev/null +++ b/example/2.SlidingWindow/0209.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) { + +}; + + +const example1 = minSubArrayLen(7, [2,3,1,2,4,3]); // 2 +const example2 = minSubArrayLen(4, [1,4,4]); // 1 +const example3 = minSubArrayLen(11, [1,1,1,1,1,1,1,1]); // 0 +const example4 = minSubArrayLen(3, [1,1,2,1,3,1,1,1]); // 1 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); From 55216a1a1998aca24f0e382558df56cfad107926 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Thu, 6 Mar 2025 23:02:16 +0300 Subject: [PATCH 818/872] Create 1004.js --- 1004-max-consecutive-ones-iii.js | 23 +++++++++++++++++++++++ example/2.SlidingWindow/1004.js | 27 +++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 example/2.SlidingWindow/1004.js diff --git a/1004-max-consecutive-ones-iii.js b/1004-max-consecutive-ones-iii.js index ec74165e..f73ea4d7 100644 --- a/1004-max-consecutive-ones-iii.js +++ b/1004-max-consecutive-ones-iii.js @@ -27,3 +27,26 @@ var longestOnes = function(nums, k) { return right - left; }; + +// var longestOnes = function(nums, k) { +// let begin = 0 +// let window_state = 0 // this is how many zeros you saw +// let result = 0 + +// for (let end = 0; end < nums.length; end++ ) { +// if (nums[end] === 0) { +// window_state += 1 +// } + +// // window condition - when count 0 > k +// while (window_state > k) { +// if (nums[begin] === 0) { +// window_state -= 1 +// } +// begin++ +// } +// result = Math.max(result, end - begin + 1) +// } + +// return result +// }; diff --git a/example/2.SlidingWindow/1004.js b/example/2.SlidingWindow/1004.js new file mode 100644 index 00000000..78ff5242 --- /dev/null +++ b/example/2.SlidingWindow/1004.js @@ -0,0 +1,27 @@ +/** + * 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) { + +}; + +const example1 = longestOnes([1,1,1,0,0,0,1,1,1,1,0], 2); // 6 [1,1,1,0,0,1!,1,1,1,1,1!] +const example2 = longestOnes([0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], 3); // 10 [0,0,1,1,1!,1!,1,1,1,1!,1,1,0,0,0,1,1,1,1] +const example3 = longestOnes([1,0,1,0,0,1], 1); // 3 +const example4 = longestOnes([1,0,0,1,0,0,0,1], 2); // 4 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); From 12db4cf8cf18a61be3e01fcda8f5256d48ce704a Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Thu, 6 Mar 2025 23:23:28 +0300 Subject: [PATCH 819/872] Create 1493.js --- ...barray-of-1s-after-deleting-one-element.js | 24 ++++++++++++++ example/2.SlidingWindow/1493.js | 31 +++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 example/2.SlidingWindow/1493.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 index c1a11255..b6729832 100644 --- a/1493-longest-subarray-of-1s-after-deleting-one-element.js +++ b/1493-longest-subarray-of-1s-after-deleting-one-element.js @@ -27,3 +27,27 @@ var longestSubarray = function(nums) { return max - (nums.includes(0) ? 0 : 1); }; + +// 1004. +// var longestSubarray = function(nums) { +// const k = 1 +// let begin = 0 +// let window_state = 0 +// let result = 0 + +// for (let end = 0; end < nums.length; end++ ) { +// if (nums[end] === 0) { +// window_state += 1 +// } + +// while (window_state > k) { +// if (nums[begin] === 0) { +// window_state -= 1 +// } +// begin++ +// } +// result = Math.max(result, end - begin + 1) +// } + +// return result - 1 +// }; \ No newline at end of file diff --git a/example/2.SlidingWindow/1493.js b/example/2.SlidingWindow/1493.js new file mode 100644 index 00000000..76777bc8 --- /dev/null +++ b/example/2.SlidingWindow/1493.js @@ -0,0 +1,31 @@ +/** + * 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) { + +}; + +// 1004. +const example1 = longestSubarray([1,1,0,1]); // 3 [1,1,1] +const example2 = longestSubarray([0,1,1,1,0,1,1,0,1]); // 5 [1,1,1,1,1] +const example3 = longestSubarray([1,1,1]); // 2 +const example4 = longestSubarray([0,1,0,1,0,1,1,0]); // 3 +const example5 = longestSubarray([0,0]); // 0 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); From a34d017204df5a8f9bfb63e67dd1a7e37cc3367a Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Fri, 7 Mar 2025 00:02:49 +0300 Subject: [PATCH 820/872] Create 0904.js --- example/2.SlidingWindow/0904.js | 41 +++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 example/2.SlidingWindow/0904.js diff --git a/example/2.SlidingWindow/0904.js b/example/2.SlidingWindow/0904.js new file mode 100644 index 00000000..3adab2d7 --- /dev/null +++ b/example/2.SlidingWindow/0904.js @@ -0,0 +1,41 @@ +/** + * @param {number[]} fruits + * @return {number} + */ +var totalFruit = function(fruits) { + +}; + +const example1 = totalFruit([1,2,1]); // 3 +const example2 = totalFruit([0,1,2,2]); // 3 +const example3 = totalFruit([1,2,3,2,2]); // 4 +const example4 = totalFruit([4,5,6]); // 2 +const example5 = totalFruit([4,5,5,5,1,6,6]); // no 5 -> 4 [4,5,5,5] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); + +// var totalFruit = function(fruits) { +// let begin = 0; +// let window_state = new Map(); +// let result = 0; + +// for (let end = 0; end < fruits.length; end++) { +// window_state.set(fruits[end], (window_state.get(fruits[end]) || 0) + 1); + +// while (window_state.size > 2) { +// window_state.set(fruits[begin], window_state.get(fruits[begin]) - 1); +// if (window_state.get(fruits[begin]) === 0) { +// window_state.delete(fruits[begin]); +// } +// begin++; +// } + +// result = Math.max(result, end - begin + 1); +// } + +// return result; +// }; \ No newline at end of file From 1939556c7604d2d78fdca73a24824ebed2adaf59 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Fri, 7 Mar 2025 03:40:12 +0300 Subject: [PATCH 821/872] Create 0121.js --- 0121-best-time-to-buy-and-sell-stock.js | 13 ++++++++++ example/2.SlidingWindow/0121.js | 33 +++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 example/2.SlidingWindow/0121.js diff --git a/0121-best-time-to-buy-and-sell-stock.js b/0121-best-time-to-buy-and-sell-stock.js index 20d2557f..d95424ed 100644 --- a/0121-best-time-to-buy-and-sell-stock.js +++ b/0121-best-time-to-buy-and-sell-stock.js @@ -27,3 +27,16 @@ var maxProfit = function(prices) { return max; }; + +// var maxProfit = function(prices) { +// let max_Profit = 0 +// let current_min = prices[0] + +// for (let i = 0; i < prices.length; i++) { +// let price = prices[i] +// max_Profit = Math.max(max_Profit, price - current_min) +// current_min = Math.min(current_min, price) +// } + +// return max_Profit +// }; \ No newline at end of file diff --git a/example/2.SlidingWindow/0121.js b/example/2.SlidingWindow/0121.js new file mode 100644 index 00000000..74fc7cc3 --- /dev/null +++ b/example/2.SlidingWindow/0121.js @@ -0,0 +1,33 @@ +/** + * 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) { + +}; + + +const example1 = maxProfit([7,1,5,3,6,4]); // 5 +const example2 = maxProfit([7,6,4,3,1]); // 0 +const example3 = maxProfit([10,1,5,6,7,1]); // 6 +const example4 = maxProfit([10,8,7,5,2]); // 0 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); From 853055b7d4bcab57849540c9aa1e16f7cdbda9d8 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Fri, 7 Mar 2025 16:01:49 +0300 Subject: [PATCH 822/872] Create 0003.js --- ...-substring-without-repeating-characters.js | 16 ++++++++++ example/2.SlidingWindow/0003.js | 32 +++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 example/2.SlidingWindow/0003.js diff --git a/0003-longest-substring-without-repeating-characters.js b/0003-longest-substring-without-repeating-characters.js index 2bdecb15..d8a3ff48 100644 --- a/0003-longest-substring-without-repeating-characters.js +++ b/0003-longest-substring-without-repeating-characters.js @@ -20,3 +20,19 @@ var lengthOfLongestSubstring = function(s) { return Math.max(max, i - offset + 1); }, 0); }; + +// var lengthOfLongestSubstring = function(s) { +// let begin = 0; +// const window_state = new Set(); // charSet +// let result = 0; + +// for (let end = 0; end < s.length; end++) { +// while (window_state.has(s[end])) { +// window_state.delete(s[begin]); +// begin++; +// } +// window_state.add(s[end]); +// result = Math.max(result, end - begin + 1); +// } +// return result; +// }; diff --git a/example/2.SlidingWindow/0003.js b/example/2.SlidingWindow/0003.js new file mode 100644 index 00000000..6d941715 --- /dev/null +++ b/example/2.SlidingWindow/0003.js @@ -0,0 +1,32 @@ +/** + * 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 example1 = lengthOfLongestSubstring("abcabcbb"); // 3 +const example2 = lengthOfLongestSubstring("bbbbb"); // 1 +const example3 = lengthOfLongestSubstring("pwwkew"); // 3 +const example4 = lengthOfLongestSubstring("zxyzxyz"); // 3 +const example5 = lengthOfLongestSubstring("xxxx"); // 1 +const example6 = lengthOfLongestSubstring("xxxox"); // 2 +const example7 = lengthOfLongestSubstring("xxxoox"); // 2 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); +console.log(example7); From 19931e7d6d1145abf5a9977fbc51fd27c2c57cbf Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Fri, 7 Mar 2025 16:05:10 +0300 Subject: [PATCH 823/872] Create 0424.js --- ...longest-repeating-character-replacement.js | 25 ++++++++++++ example/2.SlidingWindow/0424.js | 39 +++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 example/2.SlidingWindow/0424.js diff --git a/0424-longest-repeating-character-replacement.js b/0424-longest-repeating-character-replacement.js index 2db1471e..a635041e 100644 --- a/0424-longest-repeating-character-replacement.js +++ b/0424-longest-repeating-character-replacement.js @@ -30,3 +30,28 @@ var characterReplacement = function(s, k) { return Math.max(maxLength, right - left + 1); }, 0); }; + +// var characterReplacement = function(s, k) { +// const window_state = new Set(s); // charSet +// let result = 0; + +// for (let char of window_state) { +// let begin = 0; +// let count = 0 +// for (let end = 0; end < s.length; end++) { +// if (s[end] === char) { +// count++; +// } + +// while ((end - begin + 1) - count > k) { +// if (s[begin] === char) { +// count--; +// } +// begin++; +// } + +// result = Math.max(result, end - begin + 1); +// } +// } +// return result; +// }; diff --git a/example/2.SlidingWindow/0424.js b/example/2.SlidingWindow/0424.js new file mode 100644 index 00000000..aeb9b6a1 --- /dev/null +++ b/example/2.SlidingWindow/0424.js @@ -0,0 +1,39 @@ +/** + * 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 example1 = characterReplacement("ABAB", 2); // 4 +const example2 = characterReplacement("AABABBA", 1); // 4 +const example3 = characterReplacement("XYYX", 2); // 4 +const example4 = characterReplacement("AAABABB", 1); // 5 +const example5 = characterReplacement("", 1); // 0 +const example6 = characterReplacement("AAABBBXXXAABBXX", 1); // 4 +const example7 = characterReplacement("AAABBBXXXAABBXX", 2); // 5 +const example8 = characterReplacement("AAABBBXXXAABBXX", 3); // 6 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); +console.log(example7); +console.log(example8); From ff29dd0e1e9a6fbba4faa3c88e0944123da1b451 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Fri, 7 Mar 2025 17:06:01 +0300 Subject: [PATCH 824/872] Create 2523.js Create 2523.js --- example/Dayly/2523.js | 45 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 example/Dayly/2523.js diff --git a/example/Dayly/2523.js b/example/Dayly/2523.js new file mode 100644 index 00000000..ec807b5e --- /dev/null +++ b/example/Dayly/2523.js @@ -0,0 +1,45 @@ +/** + * @param {number} left + * @param {number} right + * @return {number[]} + */ +var closestPrimes = function(left, right) { + +}; + +const example1 = closestPrimes(10, 19); // [11,13] +const example2 = closestPrimes(4, 6); //[-1,-1] +const example3 = closestPrimes(0 ,0); // [-1,-1] +const example4 = closestPrimes(16, 20); // [17,19] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); + +// var closestPrimes = function(left, right) { +// function isPrime(n) { +// if (n < 2) return false; +// if (n === 2 || n === 3) return true; +// if (n % 2 === 0 || n % 3 === 0) return false; +// for (let i = 5; i * i <= n; i += 6) { +// if (n % i === 0 || n % (i + 2) === 0) return false; +// } +// return true; +// } + +// let prevPrime = -1, minDiff = Infinity; +// let result = [-1, -1]; + +// for (let i = left; i <= right; i++) { +// if (isPrime(i)) { +// if (prevPrime !== -1 && i - prevPrime < minDiff) { +// minDiff = i - prevPrime; +// result = [prevPrime, i]; +// } +// prevPrime = i; +// } +// } + +// return result; +// }; \ No newline at end of file From 22737fd07721ffdb261c180092f186f2aa3508a5 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Fri, 7 Mar 2025 18:16:54 +0300 Subject: [PATCH 825/872] Create 1768.js --- example/ProgrammingSkills/0.Basic/1768.js | 42 +++++ example/README.md | 204 ++++++++++++++++++++++ 2 files changed, 246 insertions(+) create mode 100644 example/ProgrammingSkills/0.Basic/1768.js create mode 100644 example/README.md diff --git a/example/ProgrammingSkills/0.Basic/1768.js b/example/ProgrammingSkills/0.Basic/1768.js new file mode 100644 index 00000000..f38b0260 --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/1768.js @@ -0,0 +1,42 @@ +/** + * 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) { + +}; + +const example1 = mergeAlternately("abc", "pqr"); // "apbqcr" +const example2 = mergeAlternately("ab","pqrs"); // "apbqrs" +const example3 = mergeAlternately("abcd", "pq"); // "apbqcd" +const example4 = mergeAlternately("12", "some"); // "1s2ome" +const example5 = mergeAlternately("1234", "so"); // "1s2o34" + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); + +// 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/example/README.md b/example/README.md new file mode 100644 index 00000000..74ea78f3 --- /dev/null +++ b/example/README.md @@ -0,0 +1,204 @@ +# Order + +Better order to solve problems + +## Lists + +### [0.ArraaysHash](https://github.com/Barklim/leetcode-javascript/tree/master/example/0.ArraysHash) + +1. Two sum +167. Two Integer Sum II +0. +217. Contains Duplicate +242. Valid Anagram +49. Group Anagrams +347. Top K Frequent Elements +271. Encode Decode +238. Product of Array Except Self +36. Valid Sudoku +128. Longest Consecutive Sequence + +### [1.TwoPointers](https://github.com/Barklim/leetcode-javascript/tree/master/example/1.TwoPointers) + +344. Reverse string leetcode +125. Valid Palendrom +15. 3sum +977. Squares of a sorted Array +11. Container With Most Water +26. Remove duplicates +283. Move Zeroes +392. Ls Subseq +844. Backspace String compare +88. Merge sorted Array +0. +42. Trapping Rain Water + +### [2.SlidingWindow](https://github.com/Barklim/leetcode-javascript/tree/master/example/2.SlidingWindow) + +643. Maximum Average Subarray +209. Minimum size Subarray Sum +1004. Max Consecutive One iii +1493. Longest Subarray of 1s After Deleting One Element +904. Fruit Into Baskets +0. +121. Best Time to Buy and Sell Stock +424. Longest Repeating Character Replacement + +### Linked list + +707. Design Linked List +876. Middle of the Linked List +2095. Delete the Middle Node of a Linked List +206. Reverse Linked List +234. Palindrome Linked List +83. Remove Duplicates from Sorted List +19. Remove Nth Node from End of List +43. Swap Nodes in Pairs +21. Merge Two sorted Lists +141. Linked List Cycle + +### HashMap + +706. Design Hash map + +### LRU Cache + +146. LRU Cache + +### Stack, Queue + +20. Valid Parentheses +1047. Remove All Adjacent duplicates in String +2390. Removing Stars From a string +71. Simplify Path +933. Number of Recent Calls + +### Binare Tree, DFS + +104. Maximum Depth of Binary Tree +226. Invert Binary Tree +101. Symmetric Tree +100. Same Tree +112. Path sum + +### Binary Search Tree + +700. Search in a Binary search tree +701. Insert into a Binary search tree +98. Validate Binary Search tree (нужно следить за диапозоном хранимых/возможным значений) +110. Balanced Binary tree + +### Binary Tree, BFS + +102. Binary Tree Level Order Traversal +515. Find Largest Value in Each Tree Row +199. Binary Tree Right Side View +117. Populating Next Right Pointers in Each Node ii +1325. Delete Leaves With a Given Value +1302. Deepest Leaves Sum +543. Diameter of Binary Tree (104 task) +103. Binary Tree Zigzag level Order Traversal +236. Lowest Common Ancestor of a Binary tree + +### Trie, Autocomplete + +208. Implement trie +1268. Search suggestion system + +### Heap Pt.1 + +215. Kth Largest Element in an Array (минхипа максхипа) +703. Kth Largest Element in a Stream +347. Top K Frequent Elements +451. Sort Characters By Frequency + +### Heap Pt.2 + +1046. Last stone Weight +502. IPO +295. Find Median from Data Stream +1962. Remove stones to minimize the total +23. Merge k sorted Lists +642. Design Search Autocomplete System + +### Intervals + +252. Meeting Rooms (сортировать по дате начала митинга) +56. Merge Intervals +57. Insert Intervals +253. Meeting Rooms ii + +### Graphs Workshop + +752. Open the lock +433. Minimum Genetic Mutation +2101. Detonation the Maximum Bombs +841. Keys and rooms +1971. Find if path Exists in Graph +133. clone graph +1557. Minimum number of Vertices to Reach All Nodes + +### Graphs Workshop 2 + +323. Number of Connected components in an Undirected Graph (547. none premium) +200. Number of Islands +1466. Reorder Routes to Make All Paths Lead to the City Zero +695. Max Area of island +2368. Reachable Nodes with restrictions +542. 01 Matrix +994. Rotting oranges +1129. Shortest Path with Alternating Colors +1926. Nearest Exit from Entrance in Maze +1091. Shortest path in Binary Matrix +433. Minimum Genetic mutation (752.) + +### Dijkstra + +743. Network delay time +1514. Path with maximum Probability +787. Cheapest Flights Within K Stops + +### Topological sort Pt.1 + +2115. Find all possible Recipes from given Supplies + +### Topological sort Pt.2 + +207. Course Schedule +210. Course Schedule ii +1136. Parallel Courses + +### Backtracking Pt.1 + +46. Permutations +77. Combinations +78. Subsets +22. Generate Paretheses + +### Backtracking Pt.2 + +216. Combination Sum iii +17. letter combinations of a phone number +51. N-Queens +489. Robot room cleaner + +### Dynamic Programming Pt.1 + +509. Fibonacci Number +70. Climbing Stairs +746. Min Cost Climbing Stairs +322. Coin Change +198. House Robber + +### Dynamic Programming Pt.2 + +91. Decode ways +62. Unique paths +64. Minimum path sum +72. Edit Distance + +## Programming skills + +### [0.Basic](https://github.com/Barklim/leetcode-javascript/tree/master/example/ProgrammingSkills/0.Basic) + +1768. Merge Strings Alternately \ No newline at end of file From 9cfd4edd08892f1ba3c5626d8862fade5e6ca206 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Sat, 8 Mar 2025 00:40:42 +0300 Subject: [PATCH 826/872] Update 0128.js --- example/0.ArraysHash/0128.js | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/example/0.ArraysHash/0128.js b/example/0.ArraysHash/0128.js index 64c8bf4b..a7630df0 100644 --- a/example/0.ArraysHash/0128.js +++ b/example/0.ArraysHash/0128.js @@ -14,23 +14,7 @@ * @return {number} */ var longestConsecutive = function(nums) { - const set = new Set(nums); - let result = 0; - - 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, count); - } - } - - return result; + }; From 139e7f4cee2be2610fc8bdd3587efac8d7eed90b Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Sat, 8 Mar 2025 05:51:28 +0300 Subject: [PATCH 827/872] Create 2379.js Create 2379.js --- example/Dayly/2379.js | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 example/Dayly/2379.js diff --git a/example/Dayly/2379.js b/example/Dayly/2379.js new file mode 100644 index 00000000..1f9faa5f --- /dev/null +++ b/example/Dayly/2379.js @@ -0,0 +1,40 @@ +/** + * @param {string} blocks + * @param {number} k + * @return {number} + */ +var minimumRecolors = function(blocks, k) { + +}; + +const example1 = minimumRecolors('WBBWWBBWBW', 7); // 3 +const example2 = minimumRecolors('WBWBBBW', 2); // 0 +const example3 = minimumRecolors('WWBWBB', 4); // 1 + +console.log(example1); +console.log(example2); +console.log(example3); + +// var minimumRecolors = function(blocks, k) { +// let begin = 0 +// let window_state = 0 +// let result = Infinity; + +// for (let end = 0; end < blocks.length; end++) { +// if (blocks[end] === 'W') { +// window_state += 1 +// } + +// while (end - begin + 1 === k) { +// result = Math.min(result, window_state) +// if (blocks[begin] === 'W') { +// window_state -= 1 +// } +// begin++ +// } +// } + +// if (result === Infinity) return 0 +// return result +// }; + From b06f32100e2d76ea491df5260f550c0d4a9dc766 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Sat, 8 Mar 2025 06:21:36 +0300 Subject: [PATCH 828/872] Create 0389.js --- 0389-find-the-difference.js | 7 +++++++ example/ProgrammingSkills/0.Basic/0389.js | 16 ++++++++++++++++ example/README.md | 3 ++- 3 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 example/ProgrammingSkills/0.Basic/0389.js diff --git a/0389-find-the-difference.js b/0389-find-the-difference.js index d789a16e..4566e927 100644 --- a/0389-find-the-difference.js +++ b/0389-find-the-difference.js @@ -22,3 +22,10 @@ var findTheDifference = function(s, t) { s.split('').forEach(c => map.set(c, map.get(c) - 1)); return Array.from(map).find(([letter, count]) => count)[0]; }; + +// var findTheDifference = function(s, t) { +// const map = new Map() +// t.split('').forEach(char => map.set(char, (map.get(char) || 0 ) + 1)) +// s.split('').forEach(char => map.set(char, map.get(char) - 1)) +// return Array.from(map).find(([char, count]) => count)[0] +// }; diff --git a/example/ProgrammingSkills/0.Basic/0389.js b/example/ProgrammingSkills/0.Basic/0389.js new file mode 100644 index 00000000..f5ccad70 --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/0389.js @@ -0,0 +1,16 @@ +/** + * @param {string} s + * @param {string} t + * @return {character} + */ +var findTheDifference = function(s, t) { + +}; + +const example1 = findTheDifference("abcd", "abcde"); // "e" +const example2 = findTheDifference("","y"); // "y" +const example3 = findTheDifference("bro", "rosb"); // "s" + +console.log(example1); +console.log(example2); +console.log(example3); diff --git a/example/README.md b/example/README.md index 74ea78f3..82aa1c71 100644 --- a/example/README.md +++ b/example/README.md @@ -201,4 +201,5 @@ Better order to solve problems ### [0.Basic](https://github.com/Barklim/leetcode-javascript/tree/master/example/ProgrammingSkills/0.Basic) -1768. Merge Strings Alternately \ No newline at end of file +1768. Merge Strings Alternately +389. Find the Difference \ No newline at end of file From ec67269cbe4f21376b0464553d8065eb11da49f8 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Sun, 9 Mar 2025 03:04:38 +0300 Subject: [PATCH 829/872] Create 0028.js --- 0028-implement-strstr.js | 4 ++++ example/ProgrammingSkills/0.Basic/0028.js | 18 ++++++++++++++++++ example/README.md | 7 ++++++- 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 example/ProgrammingSkills/0.Basic/0028.js diff --git a/0028-implement-strstr.js b/0028-implement-strstr.js index f7cc484e..47d6f8d8 100644 --- a/0028-implement-strstr.js +++ b/0028-implement-strstr.js @@ -24,3 +24,7 @@ var strStr = function(haystack, needle) { const split = haystack.split(needle); return split.length > 1 ? split[0].length : -1; }; + +// var strStr = function(haystack, needle) { +// return haystack.indexOf(needle) +// }; \ No newline at end of file diff --git a/example/ProgrammingSkills/0.Basic/0028.js b/example/ProgrammingSkills/0.Basic/0028.js new file mode 100644 index 00000000..10d81267 --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/0028.js @@ -0,0 +1,18 @@ +/** + * @param {string} haystack + * @param {string} needle + * @return {number} + */ +var strStr = function(haystack, needle) { + +}; + +const example1 = strStr("sadbutsad", "sad"); // 0 +const example2 = strStr("leetcode","leeto"); // -1 +const example3 = strStr("bro", "rosb"); // -1 +const example4 = strStr("asasadbutsad", "sad"); // 3 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/README.md b/example/README.md index 82aa1c71..5ee0711f 100644 --- a/example/README.md +++ b/example/README.md @@ -43,6 +43,10 @@ Better order to solve problems 0. 121. Best Time to Buy and Sell Stock 424. Longest Repeating Character Replacement +- 424. Longest Repeating Character Replacement +- 567. Permutation in String +- 76. Minimum Window Substring +- 239. Sliding Window Maximum ### Linked list @@ -202,4 +206,5 @@ Better order to solve problems ### [0.Basic](https://github.com/Barklim/leetcode-javascript/tree/master/example/ProgrammingSkills/0.Basic) 1768. Merge Strings Alternately -389. Find the Difference \ No newline at end of file +389. Find the Difference +28. Find the Index of the First Occurrence in a String \ No newline at end of file From 2703152acbccaacb373f5f4b87fc1ed6bb806f7a Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Mon, 10 Mar 2025 00:10:20 +0300 Subject: [PATCH 830/872] Create 3208.js --- example/Dayly/3208.js | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 example/Dayly/3208.js diff --git a/example/Dayly/3208.js b/example/Dayly/3208.js new file mode 100644 index 00000000..d7197573 --- /dev/null +++ b/example/Dayly/3208.js @@ -0,0 +1,36 @@ +/** + * @param {number[]} colors + * @param {number} k + * @return {number} + */ +var numberOfAlternatingGroups = function(colors, k) { + +}; + +const example1 = numberOfAlternatingGroups([0,1,0,1,0], 3); // 3 +const example2 = numberOfAlternatingGroups([0,1,0,0,1,0,1], 6); // 2 +const example3 = numberOfAlternatingGroups([1,1,0,1], 4); // 0 +const example4 = numberOfAlternatingGroups([1,1,1,1,1,1,0,1], 2); // 2 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); + +// var numberOfAlternatingGroups = function(colors, k) { +// colors.push(...colors.slice(0, k - 1)); +// let begin = 0; +// let result = 0; + +// for (let end = 0; end < colors.length; end++) { +// if (colors[end] === colors[end - 1]) { +// begin = end +// } + +// if (end - begin + 1 >= k) { +// result++ +// } +// } + +// return result +// }; \ No newline at end of file From 82aace9160e7bc45604610e5cd47c38b6eb72597 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Mon, 10 Mar 2025 02:53:27 +0300 Subject: [PATCH 831/872] Create 0066.js --- 0066-plus-one.js | 4 +++ example/ProgrammingSkills/0.Basic/0066.js | 18 ++++++++++++ example/ProgrammingSkills/0.Basic/0459.js | 35 +++++++++++++++++++++++ example/README.md | 4 ++- 4 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 example/ProgrammingSkills/0.Basic/0066.js create mode 100644 example/ProgrammingSkills/0.Basic/0459.js diff --git a/0066-plus-one.js b/0066-plus-one.js index 20987a33..712d5b5e 100644 --- a/0066-plus-one.js +++ b/0066-plus-one.js @@ -39,3 +39,7 @@ var plusOne = function(digits) { var plusOne = function(digits) { return String(BigInt(digits.join('')) + BigInt(1)).split(''); }; + +// var plusOne = function(digits) { +// return String(parseInt(digits.join('')) + 1).split(''); +// }; \ No newline at end of file diff --git a/example/ProgrammingSkills/0.Basic/0066.js b/example/ProgrammingSkills/0.Basic/0066.js new file mode 100644 index 00000000..26647893 --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/0066.js @@ -0,0 +1,18 @@ +/** + * @param {number[]} digits + * @return {number[]} + */ +var plusOne = function(digits) { + +}; + +const example1 = plusOne([1,2,3]); // [1,2,4] +const example2 = plusOne([4,3,2,1]); // [4,3,2,2] +const example3 = plusOne([9]); // [1,0] +const example4 = plusOne([1,9,9]); // [2,0,0] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); + diff --git a/example/ProgrammingSkills/0.Basic/0459.js b/example/ProgrammingSkills/0.Basic/0459.js new file mode 100644 index 00000000..347e67fc --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/0459.js @@ -0,0 +1,35 @@ +/** + * @param {string} s + * @return {boolean} + */ +var repeatedSubstringPattern = function(s) { + +}; + +const example1 = repeatedSubstringPattern("abab"); // true +const example2 = repeatedSubstringPattern("aba"); // false +const example3 = repeatedSubstringPattern("abcabcabcabc"); // true +const example4 = repeatedSubstringPattern("121"); // false +const example5 = repeatedSubstringPattern("123123"); // true + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); + +// var repeatedSubstringPattern = function(s) { +// return (s + s).slice(1, s.length * 2 - 1).indexOf(s) !== -1 +// }; + +// var repeatedSubstringPattern = function(s) { +// const n = s.length; + +// for (let i = 1; i <= Math.floor(n / 2); i++) { +// if (n % i === 0 && s.slice(0, i).repeat(n / i) === s) { +// return true; +// } +// } + +// return false; +// }; \ No newline at end of file diff --git a/example/README.md b/example/README.md index 5ee0711f..b2f35e75 100644 --- a/example/README.md +++ b/example/README.md @@ -207,4 +207,6 @@ Better order to solve problems 1768. Merge Strings Alternately 389. Find the Difference -28. Find the Index of the First Occurrence in a String \ No newline at end of file +28. Find the Index of the First Occurrence in a String +459. Repeated Substring Pattern +66. Plus One \ No newline at end of file From a7eb7f7ffa8c057cf34c4f36e0b87826286794f5 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Mon, 10 Mar 2025 04:36:57 +0300 Subject: [PATCH 832/872] Create 0707.js --- example/3.Linkedlist/0707.js | 186 +++++++++++++++++++++++++++++++++++ 1 file changed, 186 insertions(+) create mode 100644 example/3.Linkedlist/0707.js diff --git a/example/3.Linkedlist/0707.js b/example/3.Linkedlist/0707.js new file mode 100644 index 00000000..34cf1443 --- /dev/null +++ b/example/3.Linkedlist/0707.js @@ -0,0 +1,186 @@ + +var MyLinkedList = function() { + +}; + +/** + * @param {number} index + * @return {number} + */ +MyLinkedList.prototype.get = function(index) { + +}; + +/** + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtHead = function(val) { + +}; + +/** + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtTail = function(val) { + +}; + +/** + * @param {number} index + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtIndex = function(index, val) { + +}; + +/** + * @param {number} index + * @return {void} + */ +MyLinkedList.prototype.deleteAtIndex = function(index) { + +}; + +/** + * Your MyLinkedList object will be instantiated and called as such: + * var obj = new MyLinkedList() + * var param_1 = obj.get(index) + * obj.addAtHead(val) + * obj.addAtTail(val) + * obj.addAtIndex(index,val) + * obj.deleteAtIndex(index) + */ + + +// var obj = new MyLinkedList() +// var param_1 = obj.get(index) +// obj.addAtHead(val) +// obj.addAtTail(val) +// obj.addAtIndex(index,val) +// obj.deleteAtIndex(index) + +const myLinkedList = new MyLinkedList(); +myLinkedList.addAtHead(1); +myLinkedList.addAtTail(3); +myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3 +myLinkedList.get(1); // return 2 +myLinkedList.deleteAtIndex(1); // now the linked list is 1->3 +myLinkedList.get(1); // return 3 + +console.log(myLinkedList); +console.log(myLinkedList.get(1)); // 3 +console.log(myLinkedList.get(2)); // -1 +console.log(myLinkedList.get(3)); // -1 + + +// class Node { +// constructor(val = null, prev = null, next = null) { +// this.val = val +// this.prev = prev +// this.next = next +// } +// } + +// var MyLinkedList = function() { +// this.head = new Node() +// this.tail = new Node() +// this.length = 0 +// this.head.next = this.tail +// this.tail.prev = this.head +// }; + +// /** +// * @param {number} index +// * @return {number} +// */ +// MyLinkedList.prototype.get = function(idx) { +// if (idx < 0 || idx >= this.length) return -1 + +// let curNode = this.head.next + +// while (idx--) curNode = curNode.next + +// return curNode.val +// }; + +// /** +// * @param {number} val +// * @return {void} +// */ +// MyLinkedList.prototype.addAtHead = function(val) { +// let prev = this.head +// let next = this.head.next + +// let node = new Node(val, prev, next) + +// prev.next = node +// next.prev = node + +// this.length++ +// }; + +// /** +// * @param {number} val +// * @return {void} +// */ +// MyLinkedList.prototype.addAtTail = function(val) { +// let prev = this.tail.prev +// let next = this.tail + +// let node = new Node(val, prev, next) + +// prev.next = node +// next.prev = node + +// this.length++ +// }; + +// /** +// * @param {number} index +// * @param {number} val +// * @return {void} +// */ +// MyLinkedList.prototype.addAtIndex = function(idx, val) { +// if (idx < 0 || idx > this.length) return null + +// if (idx === this.length) { +// this.addAtTail(val) +// return +// } + +// let prev = this.head + +// while (idx--) prev = prev.next + +// let next = prev.next + +// let node = new Node(val, prev, next) + +// prev.next = node +// next.prev = node + +// this.length++ +// }; + +// /** +// * @param {number} index +// * @return {void} +// */ +// MyLinkedList.prototype.deleteAtIndex = function(idx) { +// if (idx < 0 || idx >= this.length) return null + +// let prev = this.head + +// while (idx--) prev = prev.next + +// let next = prev.next.next + +// prev.next = next +// next.prev = prev + +// this.length-- +// }; + From 0156d6a8173f8b8a8de37728a34d5bc3dc8c5b5a Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Mon, 10 Mar 2025 16:23:47 +0300 Subject: [PATCH 833/872] Create linked list --- ...delete-the-middle-node-of-a-linked-list.js | 32 ++++++----- example/3.Linkedlist/0707.js | 16 ++++++ example/3.Linkedlist/0876.js | 48 ++++++++++++++++ example/3.Linkedlist/2095.js | 56 +++++++++++++++++++ 4 files changed, 137 insertions(+), 15 deletions(-) create mode 100644 example/3.Linkedlist/0876.js create mode 100644 example/3.Linkedlist/2095.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 index 92ff7870..e4408b38 100644 --- a/2095-delete-the-middle-node-of-a-linked-list.js +++ b/2095-delete-the-middle-node-of-a-linked-list.js @@ -24,19 +24,21 @@ * @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; + // slow = head + // fast = head.next.next + let slow = new Node(0, null, 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/example/3.Linkedlist/0707.js b/example/3.Linkedlist/0707.js index 34cf1443..268ee42f 100644 --- a/example/3.Linkedlist/0707.js +++ b/example/3.Linkedlist/0707.js @@ -74,6 +74,9 @@ console.log(myLinkedList); console.log(myLinkedList.get(1)); // 3 console.log(myLinkedList.get(2)); // -1 console.log(myLinkedList.get(3)); // -1 +myLinkedList.addAtTail(4); +console.log(myLinkedList.get(2)); // 2 +console.log(myLinkedList); // class Node { @@ -184,3 +187,16 @@ console.log(myLinkedList.get(3)); // -1 // this.length-- // }; +// MyLinkedList.prototype.toArray = function() { +// const nodes = []; + +// let currentNode = this.head; +// while (currentNode) { +// nodes.push(currentNode.val); +// currentNode = currentNode.next; +// } + +// return nodes; +// }; + + diff --git a/example/3.Linkedlist/0876.js b/example/3.Linkedlist/0876.js new file mode 100644 index 00000000..c56e7b9d --- /dev/null +++ b/example/3.Linkedlist/0876.js @@ -0,0 +1,48 @@ +/** + * 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) { + +}; + +const myLinkedList = new MyLinkedList(); +let head = myLinkedList.head; +myLinkedList.addAtHead(1); +myLinkedList.addAtTail(2); +myLinkedList.addAtTail(3); + +console.log('middleNode'); +console.log(middleNode(head).val); // 1 2 3 // 2 +myLinkedList.addAtTail(4); +console.log(middleNode(head).val); // 1 2 3 4 // 2 +myLinkedList.addAtTail(5); +console.log(middleNode(head).val); // 12 3 45 // 3 +myLinkedList.addAtTail(6); +console.log(middleNode(head).val); // 12 3 4 56 // 3 +myLinkedList.addAtTail(7); +myLinkedList.addAtTail(8); +console.log(middleNode(head).val); // 123 4 5 678 // 4 +myLinkedList.addAtTail(9); +console.log(middleNode(head).val); // 1234 5 6789 // 5 + + + \ No newline at end of file diff --git a/example/3.Linkedlist/2095.js b/example/3.Linkedlist/2095.js new file mode 100644 index 00000000..545cde66 --- /dev/null +++ b/example/3.Linkedlist/2095.js @@ -0,0 +1,56 @@ +/** + * 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) { + +}; + +const myLinkedList = new MyLinkedList(); +let head = myLinkedList.head; +myLinkedList.addAtHead(1); +myLinkedList.addAtTail(2); +myLinkedList.addAtTail(3); +myLinkedList.addAtTail(4); +myLinkedList.addAtTail(5); +myLinkedList.addAtTail(6); +myLinkedList.addAtTail(7); + +console.log('deleteNode'); +console.log(myLinkedList.toArray().join(',')); + +console.log('deleteNode 4'); +deleteMiddle(head) // 123 4 567 // 123 567 +console.log(myLinkedList.toArray().join(',')); + +console.log('deleteNode 35'); // 12 3 5 67 // 12 5 67 +deleteMiddle(head) +console.log(myLinkedList.toArray().join(',')); + +console.log('deleteNode 3'); // 12 3 67 // 12 67 +deleteMiddle(head) +console.log(myLinkedList.toArray().join(',')); + + + From 02a3ca7355a0448e43969c8bf20d6d78d22e3f9a Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Mon, 10 Mar 2025 18:52:03 +0300 Subject: [PATCH 834/872] Create 3306.js --- example/Dayly/2062.js | 47 +++++++++++++++++++++++++++++++++ example/Dayly/3306.js | 61 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 example/Dayly/2062.js create mode 100644 example/Dayly/3306.js diff --git a/example/Dayly/2062.js b/example/Dayly/2062.js new file mode 100644 index 00000000..ad0246f2 --- /dev/null +++ b/example/Dayly/2062.js @@ -0,0 +1,47 @@ +/** + * @param {string} word + * @return {number} + */ +var countVowelSubstrings = function(word) { + +}; + +const example1 = countVowelSubstrings('aeiouu'); // 2 +const example2 = countVowelSubstrings('unicornarihan'); // 0 +const example3 = countVowelSubstrings('cuaieuouac'); // 7 + +console.log(example1); +console.log(example2); +console.log(example3); + +// var countVowelSubstrings = function(word) { +// return solve(word, 5) - solve(word, 4) +// }; + +// var solve = function(word, n) { +// const vowels = new Set(['a', 'e', 'i', 'o', 'u']) +// const freqMap = new Map() +// let l = 0, r = 0, result = 0 + +// while (r < word.length) { +// if (vowels.has(word[r])) { +// freqMap.set(word[r], (freqMap.get(word[r]) || 0) + 1) +// } else { +// freqMap.clear() +// l = r + 1 +// } + +// while (freqMap.size > n) { +// freqMap.set(word[l], freqMap.get(word[l]) - 1) +// if (freqMap.get(word[l]) === 0) { +// freqMap.delete(word[l]) +// } +// l++ +// } + +// result += r - l + 1 +// r++ +// } + +// return result +// } \ No newline at end of file diff --git a/example/Dayly/3306.js b/example/Dayly/3306.js new file mode 100644 index 00000000..7e3ec0d4 --- /dev/null +++ b/example/Dayly/3306.js @@ -0,0 +1,61 @@ +/** + * @param {string} word + * @param {number} k + * @return {number} + */ +var countVowelSubstrings = function(word, k) { + +}; + +const example1 = countVowelSubstrings('aeiouu', 0); // 2 +const example2 = countVowelSubstrings('unicornarihan', 0); // 0 +const example3 = countVowelSubstrings('cuaieuouac', 0); // 7 +const example4 = countVowelSubstrings('aeioqq', 1); // 0 +const example5 = countVowelSubstrings('aeiou', 0); // 1 +const example6 = countVowelSubstrings('ieaouqqieaouqq', 1); // 3 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); + +// var countVowelSubstrings = function(word, k) { +// return solve(word, k) - solve(word, k + 1); +// }; + +// var solve = function(word, k) { +// const vowels = new Set(['a', 'e', 'i', 'o', 'u']); +// let vowelMap = new Map(); +// let result = 0; +// let consonants = 0; +// let left = 0; + +// for (let right = 0; right < word.length; right++) { +// let char = word[right]; + +// if (vowels.has(char)) { +// vowelMap.set(char, (vowelMap.get(char) || 0) + 1); +// } else { +// consonants++; +// } + +// while (vowelMap.size === 5 && consonants >= k) { +// result += word.length - right; +// let leftChar = word[left]; + +// if (vowels.has(leftChar)) { +// vowelMap.set(leftChar, vowelMap.get(leftChar) - 1); +// if (vowelMap.get(leftChar) === 0) { +// vowelMap.delete(leftChar); +// } +// } else { +// consonants--; +// } +// left++; +// } +// } + +// return result; +// } \ No newline at end of file From bec0c9cc94ef132f5094f0ca32d4ea00ecfcbfc8 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 11 Mar 2025 00:59:46 +0300 Subject: [PATCH 835/872] Create 0206.js --- dStructure/linkedList.js | 363 +++++++++++++++++++++++++++++++++++ dStructure/linkedList2.js | 119 ++++++++++++ example/3.Linkedlist/0206.js | 29 +++ example/3.Linkedlist/0876.js | 55 ++++-- example/3.Linkedlist/2095.js | 49 +++-- 5 files changed, 587 insertions(+), 28 deletions(-) create mode 100644 dStructure/linkedList.js create mode 100644 dStructure/linkedList2.js create mode 100644 example/3.Linkedlist/0206.js diff --git a/dStructure/linkedList.js b/dStructure/linkedList.js new file mode 100644 index 00000000..39dec167 --- /dev/null +++ b/dStructure/linkedList.js @@ -0,0 +1,363 @@ +class Comparator { + /** + * Constructor. + * @param {function(a: *, b: *)} [compareFunction] - It may be custom compare function that, let's + * say may compare custom objects together. + */ + constructor(compareFunction) { + this.compare = compareFunction || Comparator.defaultCompareFunction; + } + + /** + * Default comparison function. It just assumes that "a" and "b" are strings or numbers. + * @param {(string|number)} a + * @param {(string|number)} b + * @returns {number} + */ + static defaultCompareFunction(a, b) { + if (a === b) { + return 0; + } + + return a < b ? -1 : 1; + } + + /** + * Checks if two variables are equal. + * @param {*} a + * @param {*} b + * @return {boolean} + */ + equal(a, b) { + return this.compare(a, b) === 0; + } + + /** + * Checks if variable "a" is less than "b". + * @param {*} a + * @param {*} b + * @return {boolean} + */ + lessThan(a, b) { + return this.compare(a, b) < 0; + } + + /** + * Checks if variable "a" is greater than "b". + * @param {*} a + * @param {*} b + * @return {boolean} + */ + greaterThan(a, b) { + return this.compare(a, b) > 0; + } + + /** + * Checks if variable "a" is less than or equal to "b". + * @param {*} a + * @param {*} b + * @return {boolean} + */ + lessThanOrEqual(a, b) { + return this.lessThan(a, b) || this.equal(a, b); + } + + /** + * Checks if variable "a" is greater than or equal to "b". + * @param {*} a + * @param {*} b + * @return {boolean} + */ + greaterThanOrEqual(a, b) { + return this.greaterThan(a, b) || this.equal(a, b); + } + + /** + * Reverses the comparison order. + */ + reverse() { + const compareOriginal = this.compare; + this.compare = (a, b) => compareOriginal(b, a); + } + } + +class LinkedListNode { + constructor(value, next = null) { + this.value = value; + this.next = next; + } + + toString(callback) { + return callback ? callback(this.value) : `${this.value}`; + } +} + +class LinkedList { + /** + * @param {Function} [comparatorFunction] + */ + constructor(comparatorFunction) { + /** @var LinkedListNode */ + this.head = null; + + /** @var LinkedListNode */ + this.tail = null; + + this.compare = new Comparator(comparatorFunction); + } + + /** + * @param {*} value + * @return {LinkedList} + */ + prepend(value) { + // Make new node to be a head. + const newNode = new LinkedListNode(value, this.head); + this.head = newNode; + + // If there is no tail yet let's make new node a tail. + if (!this.tail) { + this.tail = newNode; + } + + return this; + } + + /** + * @param {*} value + * @return {LinkedList} + */ + append(value) { + const newNode = new LinkedListNode(value); + + // If there is no head yet let's make new node a head. + if (!this.head) { + this.head = newNode; + this.tail = newNode; + + return this; + } + + // Attach new node to the end of linked list. + this.tail.next = newNode; + this.tail = newNode; + + return this; + } + + /** + * @param {*} value + * @param {number} index + * @return {LinkedList} + */ + insert(value, rawIndex) { + const index = rawIndex < 0 ? 0 : rawIndex; + if (index === 0) { + this.prepend(value); + } else { + let count = 1; + let currentNode = this.head; + const newNode = new LinkedListNode(value); + while (currentNode) { + if (count === index) break; + currentNode = currentNode.next; + count += 1; + } + if (currentNode) { + newNode.next = currentNode.next; + currentNode.next = newNode; + } else { + if (this.tail) { + this.tail.next = newNode; + this.tail = newNode; + } else { + this.head = newNode; + this.tail = newNode; + } + } + } + return this; + } + + /** + * @param {*} value + * @return {LinkedListNode} + */ + delete(value) { + if (!this.head) { + return null; + } + + let deletedNode = null; + + // If the head must be deleted then make next node that is different + // from the head to be a new head. + while (this.head && this.compare.equal(this.head.value, value)) { + deletedNode = this.head; + this.head = this.head.next; + } + + let currentNode = this.head; + + if (currentNode !== null) { + // If next node must be deleted then make next node to be a next next one. + while (currentNode.next) { + if (this.compare.equal(currentNode.next.value, value)) { + deletedNode = currentNode.next; + currentNode.next = currentNode.next.next; + } else { + currentNode = currentNode.next; + } + } + } + + // Check if tail must be deleted. + if (this.compare.equal(this.tail.value, value)) { + this.tail = currentNode; + } + + return deletedNode; + } + + /** + * @param {Object} findParams + * @param {*} findParams.value + * @param {function} [findParams.callback] + * @return {LinkedListNode} + */ + find({ value = undefined, callback = undefined }) { + if (!this.head) { + return null; + } + + let currentNode = this.head; + + while (currentNode) { + // If callback is specified then try to find node by callback. + if (callback && callback(currentNode.value)) { + return currentNode; + } + + // If value is specified then try to compare by value.. + if (value !== undefined && this.compare.equal(currentNode.value, value)) { + return currentNode; + } + + currentNode = currentNode.next; + } + + return null; + } + + /** + * @return {LinkedListNode} + */ + deleteTail() { + const deletedTail = this.tail; + + if (this.head === this.tail) { + // There is only one node in linked list. + this.head = null; + this.tail = null; + + return deletedTail; + } + + // If there are many nodes in linked list... + + // Rewind to the last node and delete "next" link for the node before the last one. + let currentNode = this.head; + while (currentNode.next) { + if (!currentNode.next.next) { + currentNode.next = null; + } else { + currentNode = currentNode.next; + } + } + + this.tail = currentNode; + + return deletedTail; + } + + /** + * @return {LinkedListNode} + */ + deleteHead() { + if (!this.head) { + return null; + } + + const deletedHead = this.head; + + if (this.head.next) { + this.head = this.head.next; + } else { + this.head = null; + this.tail = null; + } + + return deletedHead; + } + + /** + * @param {*[]} values - Array of values that need to be converted to linked list. + * @return {LinkedList} + */ + fromArray(values) { + values.forEach((value) => this.append(value)); + + return this; + } + + /** + * @return {LinkedListNode[]} + */ + toArray() { + const nodes = []; + + let currentNode = this.head; + while (currentNode) { + nodes.push(currentNode); + currentNode = currentNode.next; + } + + return nodes; + } + + /** + * @param {function} [callback] + * @return {string} + */ + toString(callback) { + return this.toArray().map((node) => node.toString(callback)).toString(); + } + + /** + * Reverse a linked list. + * @returns {LinkedList} + */ + reverse() { + let currNode = this.head; + let prevNode = null; + let nextNode = null; + + while (currNode) { + // Store next node. + nextNode = currNode.next; + + // Change next node of the current node so it would link to previous node. + currNode.next = prevNode; + + // Move prevNode and currNode nodes one step forward. + prevNode = currNode; + currNode = nextNode; + } + + // Reset head and tail. + this.tail = this.head; + this.head = prevNode; + + return this; + } +} \ No newline at end of file diff --git a/dStructure/linkedList2.js b/dStructure/linkedList2.js new file mode 100644 index 00000000..c075ddbb --- /dev/null +++ b/dStructure/linkedList2.js @@ -0,0 +1,119 @@ +class Node { + constructor(val = null, prev = null, next = null) { + this.val = val + this.prev = prev + this.next = next + } +} + +var MyLinkedList = function() { + this.head = new Node() + this.tail = new Node() + this.length = 0 + this.head.next = this.tail + this.tail.prev = this.head +}; + +/** + * @param {number} index + * @return {number} + */ +MyLinkedList.prototype.get = function(idx) { + if (idx < 0 || idx >= this.length) return -1 + + let curNode = this.head.next + + while (idx--) curNode = curNode.next + + return curNode.val +}; + +/** + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtHead = function(val) { + let prev = this.head + let next = this.head.next + + let node = new Node(val, prev, next) + + prev.next = node + next.prev = node + + this.length++ +}; + +/** + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtTail = function(val) { + let prev = this.tail.prev + let next = this.tail + + let node = new Node(val, prev, next) + + prev.next = node + next.prev = node + + this.length++ +}; + +/** + * @param {number} index + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtIndex = function(idx, val) { + if (idx < 0 || idx > this.length) return null + + if (idx === this.length) { + this.addAtTail(val) + return + } + + let prev = this.head + + while (idx--) prev = prev.next + + let next = prev.next + + let node = new Node(val, prev, next) + + prev.next = node + next.prev = node + + this.length++ +}; + +/** + * @param {number} index + * @return {void} + */ +MyLinkedList.prototype.deleteAtIndex = function(idx) { + if (idx < 0 || idx >= this.length) return null + + let prev = this.head + + while (idx--) prev = prev.next + + let next = prev.next.next + + prev.next = next + next.prev = prev + + this.length-- +}; + +MyLinkedList.prototype.toArray = function() { + const nodes = []; + + let currentNode = this.head; + while (currentNode) { + nodes.push(currentNode.val); + currentNode = currentNode.next; + } + + return nodes; +}; \ No newline at end of file diff --git a/example/3.Linkedlist/0206.js b/example/3.Linkedlist/0206.js new file mode 100644 index 00000000..78770076 --- /dev/null +++ b/example/3.Linkedlist/0206.js @@ -0,0 +1,29 @@ +/** + * 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) { + +}; + +const myLinkedList = new LinkedList(); +myLinkedList.append(1); +myLinkedList.append(2); +myLinkedList.append(3); +myLinkedList.append(4); + +console.log('reverseList'); +console.log(myLinkedList.toString()); +console.log('reverseList reversed'); +const list = reverseList(myLinkedList.head) +console.log(list.value); +console.log(list.next.value); +console.log(list.next.next.value); +console.log(list.next.next.next.value); \ No newline at end of file diff --git a/example/3.Linkedlist/0876.js b/example/3.Linkedlist/0876.js index c56e7b9d..1526a0d2 100644 --- a/example/3.Linkedlist/0876.js +++ b/example/3.Linkedlist/0876.js @@ -24,25 +24,48 @@ var middleNode = function(head) { }; -const myLinkedList = new MyLinkedList(); +const myLinkedList = new LinkedList(); let head = myLinkedList.head; -myLinkedList.addAtHead(1); -myLinkedList.addAtTail(2); -myLinkedList.addAtTail(3); +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(3); + +const runMiddleNode = () => middleNode(myLinkedList.head).value console.log('middleNode'); -console.log(middleNode(head).val); // 1 2 3 // 2 -myLinkedList.addAtTail(4); -console.log(middleNode(head).val); // 1 2 3 4 // 2 -myLinkedList.addAtTail(5); -console.log(middleNode(head).val); // 12 3 45 // 3 -myLinkedList.addAtTail(6); -console.log(middleNode(head).val); // 12 3 4 56 // 3 -myLinkedList.addAtTail(7); -myLinkedList.addAtTail(8); -console.log(middleNode(head).val); // 123 4 5 678 // 4 -myLinkedList.addAtTail(9); -console.log(middleNode(head).val); // 1234 5 6789 // 5 +console.log(myLinkedList.toString()); // 123 +console.log(runMiddleNode()); // 1 2 3 // 2 +myLinkedList.append(4); +console.log(runMiddleNode()); // 1 2 3 4 // 3 +myLinkedList.append(5); +console.log(runMiddleNode()); // 12 3 45 // 3 +myLinkedList.append(6); +console.log(runMiddleNode()); // 12 3 4 56 // 4 +myLinkedList.append(7); +myLinkedList.append(8); +console.log(runMiddleNode()); // 123 4 5 678 // 5 +myLinkedList.append(9); +console.log(runMiddleNode()); // 1234 5 6789 // 5 + +// const myLinkedList = new MyLinkedList(); +// let head = myLinkedList.head; +// myLinkedList.addAtHead(1); +// myLinkedList.addAtTail(2); +// myLinkedList.addAtTail(3); + +// console.log('middleNode'); +// console.log(middleNode(head).val); // 1 2 3 // 2 +// myLinkedList.addAtTail(4); +// console.log(middleNode(head).val); // 1 2 3 4 // 3 +// myLinkedList.addAtTail(5); +// console.log(middleNode(head).val); // 12 3 45 // 3 +// myLinkedList.addAtTail(6); +// console.log(middleNode(head).val); // 12 3 4 56 // 4 +// myLinkedList.addAtTail(7); +// myLinkedList.addAtTail(8); +// console.log(middleNode(head).val); // 123 4 5 678 // 5 +// myLinkedList.addAtTail(9); +// console.log(middleNode(head).val); // 1234 5 6789 // 5 \ No newline at end of file diff --git a/example/3.Linkedlist/2095.js b/example/3.Linkedlist/2095.js index 545cde66..d4a2f38a 100644 --- a/example/3.Linkedlist/2095.js +++ b/example/3.Linkedlist/2095.js @@ -27,30 +27,55 @@ var deleteMiddle = function(head) { }; -const myLinkedList = new MyLinkedList(); +const myLinkedList = new LinkedList(); let head = myLinkedList.head; -myLinkedList.addAtHead(1); -myLinkedList.addAtTail(2); -myLinkedList.addAtTail(3); -myLinkedList.addAtTail(4); -myLinkedList.addAtTail(5); -myLinkedList.addAtTail(6); -myLinkedList.addAtTail(7); +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(3); +myLinkedList.append(4); +myLinkedList.append(5); +myLinkedList.append(6); +myLinkedList.append(7); console.log('deleteNode'); console.log(myLinkedList.toArray().join(',')); console.log('deleteNode 4'); -deleteMiddle(head) // 123 4 567 // 123 567 +deleteMiddle(myLinkedList.head) // 123 4 567 // 123 567 console.log(myLinkedList.toArray().join(',')); -console.log('deleteNode 35'); // 12 3 5 67 // 12 5 67 -deleteMiddle(head) +console.log('deleteNode 35'); // 12 3 5 67 // 12 3 67 +deleteMiddle(myLinkedList.head) console.log(myLinkedList.toArray().join(',')); console.log('deleteNode 3'); // 12 3 67 // 12 67 -deleteMiddle(head) +deleteMiddle(myLinkedList.head) console.log(myLinkedList.toArray().join(',')); +// const myLinkedList = new MyLinkedList(); +// let head = myLinkedList.head; +// myLinkedList.addAtHead(1); +// myLinkedList.addAtTail(2); +// myLinkedList.addAtTail(3); +// myLinkedList.addAtTail(4); +// myLinkedList.addAtTail(5); +// myLinkedList.addAtTail(6); +// myLinkedList.addAtTail(7); + +// console.log('deleteNode'); +// console.log(myLinkedList.toArray().join(',')); + +// console.log('deleteNode 4'); +// deleteMiddle(head) // 123 4 567 // 123 567 +// console.log(myLinkedList.toArray().join(',')); + +// console.log('deleteNode 35'); // 12 3 5 67 // 12 3 67 +// deleteMiddle(head) +// console.log(myLinkedList.toArray().join(',')); + +// console.log('deleteNode 3'); // 12 3 67 // 12 67 +// deleteMiddle(head) +// console.log(myLinkedList.toArray().join(',')); + From f6faf9816681b61c501366e387c7352c39693eb9 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 11 Mar 2025 04:26:26 +0300 Subject: [PATCH 836/872] Create 0234.js --- 0234-palindrome-linked-list.js | 43 +++++++++++++++++++++++ example/3.Linkedlist/0234.js | 62 ++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100644 example/3.Linkedlist/0234.js diff --git a/0234-palindrome-linked-list.js b/0234-palindrome-linked-list.js index 37b4a5e6..bed51189 100644 --- a/0234-palindrome-linked-list.js +++ b/0234-palindrome-linked-list.js @@ -28,3 +28,46 @@ var isPalindrome = function(head) { return a === b; }; + +// var isPalindrome = function(head) { +// var middle = function(head) { +// let slow = head; +// let fast = head; + +// while (fast && fast.next) { +// slow = slow.next; +// fast = fast.next.next; +// } + +// return slow; +// } + +// var reverse = function(head) { +// let prev = null; +// let tail = head; + +// while (tail) { +// const next = tail.next; +// tail.next = prev; +// prev = tail; +// tail = next; +// } + +// return prev; +// } + +// mid = middle(head) +// second = reverse(mid) +// first = head + +// while (first && second) { +// // !!! value, val +// if (first.value !== second.value) { +// return false +// } +// first = first.next +// second = second.next +// } + +// return true +// }; \ No newline at end of file diff --git a/example/3.Linkedlist/0234.js b/example/3.Linkedlist/0234.js new file mode 100644 index 00000000..943eb40f --- /dev/null +++ b/example/3.Linkedlist/0234.js @@ -0,0 +1,62 @@ +/** + * 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) { + +}; + +const myLinkedList = new LinkedList(); +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(2); +myLinkedList.append(1); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(1); +myLinkedList2.append(2); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(1); +myLinkedList3.append(2); +myLinkedList3.append(4); +myLinkedList3.append(2); +myLinkedList3.append(1); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(1); +myLinkedList4.append(2); +myLinkedList4.append(4); +myLinkedList4.append(4); +myLinkedList4.append(2); +myLinkedList4.append(1); + +const myLinkedList5 = new LinkedList(); +myLinkedList5.prepend(1); +myLinkedList5.append(2); +myLinkedList5.append(4); +myLinkedList5.append(5); +myLinkedList5.append(2); +myLinkedList5.append(1); + +const executeList = list => isPalindrome(list.head) + +const execute = list => { + console.log(list.toString()); + console.log(executeList(list)); +} + +console.log('middleNode'); + +execute(myLinkedList) // 1 2 2 1 // true +execute(myLinkedList2) // 1 2 // false +execute(myLinkedList3) // 1 2 4 2 1 // true +execute(myLinkedList4) // 1 2 4 4 2 1 // true +execute(myLinkedList5) // 1 2 4 5 2 1 // false \ No newline at end of file From 60bf56c72cb47bbd013fcdd5b860559126a5646d Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 11 Mar 2025 05:02:18 +0300 Subject: [PATCH 837/872] Create 0083.js --- 0083-remove-duplicates-from-sorted-list.js | 14 + dStructure/linkedList.js | 670 +++++++++++---------- example/3.Linkedlist/0083.js | 62 ++ 3 files changed, 417 insertions(+), 329 deletions(-) create mode 100644 example/3.Linkedlist/0083.js diff --git a/0083-remove-duplicates-from-sorted-list.js b/0083-remove-duplicates-from-sorted-list.js index b1e7de59..4ab63de3 100644 --- a/0083-remove-duplicates-from-sorted-list.js +++ b/0083-remove-duplicates-from-sorted-list.js @@ -33,3 +33,17 @@ var deleteDuplicates = function(head) { return result.next; }; + +// var deleteDuplicates = function(head) { +// let current = head + +// while (current && current.next) { +// if (current.val === current.next.val) { +// current.next = current.next.next +// } else { +// current = current.next +// } +// } + +// return head +// }; diff --git a/dStructure/linkedList.js b/dStructure/linkedList.js index 39dec167..3d2ffecd 100644 --- a/dStructure/linkedList.js +++ b/dStructure/linkedList.js @@ -1,363 +1,375 @@ -class Comparator { - /** - * Constructor. - * @param {function(a: *, b: *)} [compareFunction] - It may be custom compare function that, let's - * say may compare custom objects together. - */ - constructor(compareFunction) { - this.compare = compareFunction || Comparator.defaultCompareFunction; - } - - /** - * Default comparison function. It just assumes that "a" and "b" are strings or numbers. - * @param {(string|number)} a - * @param {(string|number)} b - * @returns {number} - */ - static defaultCompareFunction(a, b) { - if (a === b) { - return 0; - } - - return a < b ? -1 : 1; - } - - /** - * Checks if two variables are equal. - * @param {*} a - * @param {*} b - * @return {boolean} - */ - equal(a, b) { - return this.compare(a, b) === 0; - } - - /** - * Checks if variable "a" is less than "b". - * @param {*} a - * @param {*} b - * @return {boolean} - */ - lessThan(a, b) { - return this.compare(a, b) < 0; - } - - /** - * Checks if variable "a" is greater than "b". - * @param {*} a - * @param {*} b - * @return {boolean} - */ - greaterThan(a, b) { - return this.compare(a, b) > 0; - } - - /** - * Checks if variable "a" is less than or equal to "b". - * @param {*} a - * @param {*} b - * @return {boolean} - */ - lessThanOrEqual(a, b) { - return this.lessThan(a, b) || this.equal(a, b); - } - - /** - * Checks if variable "a" is greater than or equal to "b". - * @param {*} a - * @param {*} b - * @return {boolean} - */ - greaterThanOrEqual(a, b) { - return this.greaterThan(a, b) || this.equal(a, b); - } - - /** - * Reverses the comparison order. - */ - reverse() { - const compareOriginal = this.compare; - this.compare = (a, b) => compareOriginal(b, a); - } +class LinkedListNode { + constructor(val, next = null) { + this.val = val; + this.next = next; } -class LinkedListNode { - constructor(value, next = null) { - this.value = value; - this.next = next; - } - - toString(callback) { - return callback ? callback(this.value) : `${this.value}`; - } + toString(callback) { + return callback ? callback(this.val) : `${this.val}`; + } } class LinkedList { - /** - * @param {Function} [comparatorFunction] - */ - constructor(comparatorFunction) { - /** @var LinkedListNode */ - this.head = null; - - /** @var LinkedListNode */ - this.tail = null; - - this.compare = new Comparator(comparatorFunction); + /** + * @param {Function} [comparatorFunction] + */ + constructor(comparatorFunction) { + /** @var LinkedListNode */ + this.head = null; + + /** @var LinkedListNode */ + this.tail = null; + + this.compare = new Comparator(comparatorFunction); + } + + /** + * @param {*} val + * @return {LinkedList} + */ + prepend(val) { + // Make new node to be a head. + const newNode = new LinkedListNode(val, this.head); + this.head = newNode; + + // If there is no tail yet let's make new node a tail. + if (!this.tail) { + this.tail = newNode; } - - /** - * @param {*} value - * @return {LinkedList} - */ - prepend(value) { - // Make new node to be a head. - const newNode = new LinkedListNode(value, this.head); + + return this; + } + + /** + * @param {*} val + * @return {LinkedList} + */ + append(val) { + const newNode = new LinkedListNode(val); + + // If there is no head yet let's make new node a head. + if (!this.head) { this.head = newNode; - - // If there is no tail yet let's make new node a tail. - if (!this.tail) { - this.tail = newNode; - } - - return this; - } - - /** - * @param {*} value - * @return {LinkedList} - */ - append(value) { - const newNode = new LinkedListNode(value); - - // If there is no head yet let's make new node a head. - if (!this.head) { - this.head = newNode; - this.tail = newNode; - - return this; - } - - // Attach new node to the end of linked list. - this.tail.next = newNode; this.tail = newNode; - + return this; } - - /** - * @param {*} value - * @param {number} index - * @return {LinkedList} - */ - insert(value, rawIndex) { - const index = rawIndex < 0 ? 0 : rawIndex; - if (index === 0) { - this.prepend(value); + + // Attach new node to the end of linked list. + this.tail.next = newNode; + this.tail = newNode; + + return this; + } + + /** + * @param {*} val + * @param {number} index + * @return {LinkedList} + */ + insert(val, rawIndex) { + const index = rawIndex < 0 ? 0 : rawIndex; + if (index === 0) { + this.prepend(val); + } else { + let count = 1; + let currentNode = this.head; + const newNode = new LinkedListNode(val); + while (currentNode) { + if (count === index) break; + currentNode = currentNode.next; + count += 1; + } + if (currentNode) { + newNode.next = currentNode.next; + currentNode.next = newNode; } else { - let count = 1; - let currentNode = this.head; - const newNode = new LinkedListNode(value); - while (currentNode) { - if (count === index) break; - currentNode = currentNode.next; - count += 1; - } - if (currentNode) { - newNode.next = currentNode.next; - currentNode.next = newNode; + if (this.tail) { + this.tail.next = newNode; + this.tail = newNode; } else { - if (this.tail) { - this.tail.next = newNode; - this.tail = newNode; - } else { - this.head = newNode; - this.tail = newNode; - } + this.head = newNode; + this.tail = newNode; } } - return this; } - - /** - * @param {*} value - * @return {LinkedListNode} - */ - delete(value) { - if (!this.head) { - return null; - } - - let deletedNode = null; - - // If the head must be deleted then make next node that is different - // from the head to be a new head. - while (this.head && this.compare.equal(this.head.value, value)) { - deletedNode = this.head; - this.head = this.head.next; - } - - let currentNode = this.head; - - if (currentNode !== null) { - // If next node must be deleted then make next node to be a next next one. - while (currentNode.next) { - if (this.compare.equal(currentNode.next.value, value)) { - deletedNode = currentNode.next; - currentNode.next = currentNode.next.next; - } else { - currentNode = currentNode.next; - } - } - } - - // Check if tail must be deleted. - if (this.compare.equal(this.tail.value, value)) { - this.tail = currentNode; - } - - return deletedNode; - } - - /** - * @param {Object} findParams - * @param {*} findParams.value - * @param {function} [findParams.callback] - * @return {LinkedListNode} - */ - find({ value = undefined, callback = undefined }) { - if (!this.head) { - return null; - } - - let currentNode = this.head; - - while (currentNode) { - // If callback is specified then try to find node by callback. - if (callback && callback(currentNode.value)) { - return currentNode; - } - - // If value is specified then try to compare by value.. - if (value !== undefined && this.compare.equal(currentNode.value, value)) { - return currentNode; - } - - currentNode = currentNode.next; - } - + return this; + } + + /** + * @param {*} val + * @return {LinkedListNode} + */ + delete(val) { + if (!this.head) { return null; } - - /** - * @return {LinkedListNode} - */ - deleteTail() { - const deletedTail = this.tail; - - if (this.head === this.tail) { - // There is only one node in linked list. - this.head = null; - this.tail = null; - - return deletedTail; - } - - // If there are many nodes in linked list... - - // Rewind to the last node and delete "next" link for the node before the last one. - let currentNode = this.head; + + let deletedNode = null; + + // If the head must be deleted then make next node that is different + // from the head to be a new head. + while (this.head && this.compare.equal(this.head.val, val)) { + deletedNode = this.head; + this.head = this.head.next; + } + + let currentNode = this.head; + + if (currentNode !== null) { + // If next node must be deleted then make next node to be a next next one. while (currentNode.next) { - if (!currentNode.next.next) { - currentNode.next = null; + if (this.compare.equal(currentNode.next.val, val)) { + deletedNode = currentNode.next; + currentNode.next = currentNode.next.next; } else { currentNode = currentNode.next; } } - + } + + // Check if tail must be deleted. + if (this.compare.equal(this.tail.val, val)) { this.tail = currentNode; - - return deletedTail; } - - /** - * @return {LinkedListNode} - */ - deleteHead() { - if (!this.head) { - return null; + + return deletedNode; + } + + /** + * @param {Object} findParams + * @param {*} findParams.val + * @param {function} [findParams.callback] + * @return {LinkedListNode} + */ + find({ val = undefined, callback = undefined }) { + if (!this.head) { + return null; + } + + let currentNode = this.head; + + while (currentNode) { + // If callback is specified then try to find node by callback. + if (callback && callback(currentNode.val)) { + return currentNode; } - - const deletedHead = this.head; - - if (this.head.next) { - this.head = this.head.next; - } else { - this.head = null; - this.tail = null; + + // If val is specified then try to compare by val.. + if (val !== undefined && this.compare.equal(currentNode.val, val)) { + return currentNode; } - - return deletedHead; + + currentNode = currentNode.next; } - - /** - * @param {*[]} values - Array of values that need to be converted to linked list. - * @return {LinkedList} - */ - fromArray(values) { - values.forEach((value) => this.append(value)); - - return this; + + return null; + } + + /** + * @return {LinkedListNode} + */ + deleteTail() { + const deletedTail = this.tail; + + if (this.head === this.tail) { + // There is only one node in linked list. + this.head = null; + this.tail = null; + + return deletedTail; } - - /** - * @return {LinkedListNode[]} - */ - toArray() { - const nodes = []; - - let currentNode = this.head; - while (currentNode) { - nodes.push(currentNode); + + // If there are many nodes in linked list... + + // Rewind to the last node and delete "next" link for the node before the last one. + let currentNode = this.head; + while (currentNode.next) { + if (!currentNode.next.next) { + currentNode.next = null; + } else { currentNode = currentNode.next; } - - return nodes; } - - /** - * @param {function} [callback] - * @return {string} - */ - toString(callback) { - return this.toArray().map((node) => node.toString(callback)).toString(); + + this.tail = currentNode; + + return deletedTail; + } + + /** + * @return {LinkedListNode} + */ + deleteHead() { + if (!this.head) { + return null; } - - /** - * Reverse a linked list. - * @returns {LinkedList} - */ - reverse() { - let currNode = this.head; - let prevNode = null; - let nextNode = null; - - while (currNode) { - // Store next node. - nextNode = currNode.next; - - // Change next node of the current node so it would link to previous node. - currNode.next = prevNode; - - // Move prevNode and currNode nodes one step forward. - prevNode = currNode; - currNode = nextNode; - } - - // Reset head and tail. - this.tail = this.head; - this.head = prevNode; - - return this; + + const deletedHead = this.head; + + if (this.head.next) { + this.head = this.head.next; + } else { + this.head = null; + this.tail = null; + } + + return deletedHead; + } + + /** + * @param {*[]} values - Array of values that need to be converted to linked list. + * @return {LinkedList} + */ + fromArray(values) { + values.forEach((val) => this.append(val)); + + return this; + } + + /** + * @return {LinkedListNode[]} + */ + toArray() { + const nodes = []; + + let currentNode = this.head; + while (currentNode) { + nodes.push(currentNode); + currentNode = currentNode.next; } + + return nodes; + } + + /** + * @param {function} [callback] + * @return {string} + */ + toString(callback) { + return this.toArray().map((node) => node.toString(callback)).toString(); + } + + /** + * Reverse a linked list. + * @returns {LinkedList} + */ + reverse() { + let currNode = this.head; + let prevNode = null; + let nextNode = null; + + while (currNode) { + // Store next node. + nextNode = currNode.next; + + // Change next node of the current node so it would link to previous node. + currNode.next = prevNode; + + // Move prevNode and currNode nodes one step forward. + prevNode = currNode; + currNode = nextNode; + } + + // Reset head and tail. + this.tail = this.head; + this.head = prevNode; + + return this; + } +} + +class Comparator { + /** + * Constructor. + * @param {function(a: *, b: *)} [compareFunction] - It may be custom compare function that, let's + * say may compare custom objects together. + */ + constructor(compareFunction) { + this.compare = compareFunction || Comparator.defaultCompareFunction; + } + + /** + * Default comparison function. It just assumes that "a" and "b" are strings or numbers. + * @param {(string|number)} a + * @param {(string|number)} b + * @returns {number} + */ + static defaultCompareFunction(a, b) { + if (a === b) { + return 0; + } + + return a < b ? -1 : 1; + } + + /** + * Checks if two variables are equal. + * @param {*} a + * @param {*} b + * @return {boolean} + */ + equal(a, b) { + return this.compare(a, b) === 0; + } + + /** + * Checks if variable "a" is less than "b". + * @param {*} a + * @param {*} b + * @return {boolean} + */ + lessThan(a, b) { + return this.compare(a, b) < 0; + } + + /** + * Checks if variable "a" is greater than "b". + * @param {*} a + * @param {*} b + * @return {boolean} + */ + greaterThan(a, b) { + return this.compare(a, b) > 0; + } + + /** + * Checks if variable "a" is less than or equal to "b". + * @param {*} a + * @param {*} b + * @return {boolean} + */ + lessThanOrEqual(a, b) { + return this.lessThan(a, b) || this.equal(a, b); + } + + /** + * Checks if variable "a" is greater than or equal to "b". + * @param {*} a + * @param {*} b + * @return {boolean} + */ + greaterThanOrEqual(a, b) { + return this.greaterThan(a, b) || this.equal(a, b); + } + + /** + * Reverses the comparison order. + */ + reverse() { + const compareOriginal = this.compare; + this.compare = (a, b) => compareOriginal(b, a); + } +} + +const traversList = (linkedList) => { + let currentNode = linkedList; + let res = [] + + while (currentNode) { + res.push(currentNode.val) + currentNode = currentNode.next; + } + + return res.join(',') } \ No newline at end of file diff --git a/example/3.Linkedlist/0083.js b/example/3.Linkedlist/0083.js new file mode 100644 index 00000000..81eccb80 --- /dev/null +++ b/example/3.Linkedlist/0083.js @@ -0,0 +1,62 @@ +/** + * 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 myLinkedList = new LinkedList(); +myLinkedList.prepend(1); +myLinkedList.append(1); +myLinkedList.append(2); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(1); +myLinkedList2.append(1); +myLinkedList2.append(2); +myLinkedList2.append(3); +myLinkedList2.append(3); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(1); +myLinkedList3.append(2); +myLinkedList3.append(4); +myLinkedList3.append(4); +myLinkedList3.append(4); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(1); +myLinkedList4.append(2); +myLinkedList4.append(4); +myLinkedList4.append(4); +myLinkedList4.append(5); +myLinkedList4.append(6); + +const myLinkedList5 = new LinkedList(); +myLinkedList5.prepend(1); +myLinkedList5.append(2); + +const executeList = list => deleteDuplicates(list.head) + +const execute = list => { + console.log('travers') + console.log(list.toString()); + const list1 = executeList(list) + console.log(traversList(list1)) +} + +execute(myLinkedList) // 1 1 2 // 1 2 +execute(myLinkedList2) // 1 1 2 3 3 // 1 2 3 +execute(myLinkedList3) // 1 2 4 4 4 // 1 2 4 +execute(myLinkedList4) // 1 2 4 4 5 6 // 1 2 4 5 6 +execute(myLinkedList5) // 1 2 // 1 2 + + \ No newline at end of file From caa021e7121fa238c77fce6fc5dcd4309696dc2b Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 11 Mar 2025 05:18:20 +0300 Subject: [PATCH 838/872] Create 0019.js --- 0019-remove-nth-node-from-end-of-list.js | 42 ++++++++++++++++++ example/3.Linkedlist/0019.js | 55 ++++++++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 example/3.Linkedlist/0019.js diff --git a/0019-remove-nth-node-from-end-of-list.js b/0019-remove-nth-node-from-end-of-list.js index 1e133150..707ba41e 100644 --- a/0019-remove-nth-node-from-end-of-list.js +++ b/0019-remove-nth-node-from-end-of-list.js @@ -38,3 +38,45 @@ var removeNthFromEnd = function(head, n) { return result.next; }; + +// var removeNthFromEnd = function(head, n) { +// const result = new LinkedListNode(); +// 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; +// }; + + +// var removeNthFromEnd = function(head, n) { +// const dummy = new LinkedListNode(); +// dummy.next = head + +// first = dummy +// second = dummy + +// for (let i = 0; i <= n; i++) { +// first = first.next; +// } + +// while (first) { +// first = first.next; +// second = second.next; +// } + +// second.next = second.next.next; + +// return dummy.next; +// }; diff --git a/example/3.Linkedlist/0019.js b/example/3.Linkedlist/0019.js new file mode 100644 index 00000000..42f67694 --- /dev/null +++ b/example/3.Linkedlist/0019.js @@ -0,0 +1,55 @@ +/** + * 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 myLinkedList = new LinkedList(); +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(3); +myLinkedList.append(4); +myLinkedList.append(5); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(1); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(1); +myLinkedList3.append(2); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(1); +myLinkedList4.append(2); +myLinkedList4.append(3); +myLinkedList4.append(4); +myLinkedList4.append(5); +myLinkedList4.append(6); +myLinkedList4.append(7); + +const executeList = (list, n) => removeNthFromEnd(list.head, n) + +const execute = (list, n) => { + console.log('travers') + console.log(list.toString()); + const list1 = executeList(list, n) + console.log(traversList(list1)) +} + +execute(myLinkedList, 2) // 1,2,3,4,5 // 1,2,3,5 +execute(myLinkedList2, 1) // 1 // [] +execute(myLinkedList3, 1) // 1,2 // 1 +execute(myLinkedList4, 4) // 1,2,3,4,5,6,7 // 1,2,3,5,6,7 +execute(myLinkedList4, 2) // 1,2,3,5,6,7 // 1,2,3,5,7 + + \ No newline at end of file From 4bdcd73a8a6aaa4feb2756b39b805c817fba1b07 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 11 Mar 2025 05:46:00 +0300 Subject: [PATCH 839/872] Create 0024.js --- 0024-swap-nodes-in-pairs.js | 20 +++++++++++++ example/3.Linkedlist/0024.js | 55 ++++++++++++++++++++++++++++++++++++ example/README.md | 2 +- 3 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 example/3.Linkedlist/0024.js diff --git a/0024-swap-nodes-in-pairs.js b/0024-swap-nodes-in-pairs.js index 39a27600..13ec0679 100644 --- a/0024-swap-nodes-in-pairs.js +++ b/0024-swap-nodes-in-pairs.js @@ -29,3 +29,23 @@ var swapPairs = function(head) { return result; }; + +// var swapPairs = function(head) { +// let dummy = new LinkedListNode() +// dummy.next = head + +// current = dummy + +// while (current.next && current.next.next) { +// first = current.next +// second = current.next.next + +// first.next = second.next +// second.next = first +// current.next = second + +// current = first +// } + +// return dummy.next +// }; \ No newline at end of file diff --git a/example/3.Linkedlist/0024.js b/example/3.Linkedlist/0024.js new file mode 100644 index 00000000..2e46b4bf --- /dev/null +++ b/example/3.Linkedlist/0024.js @@ -0,0 +1,55 @@ +/** + * 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) { + +}; + +const myLinkedList = new LinkedList(); +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(3); +myLinkedList.append(4); + +const myLinkedList2 = new LinkedList(); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(1); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(1); +myLinkedList4.append(2); +myLinkedList4.append(3); + +const myLinkedList5 = new LinkedList(); +myLinkedList5.prepend(1); +myLinkedList5.append(2); +myLinkedList5.append(3); +myLinkedList5.append(4); +myLinkedList5.append(5); +myLinkedList5.append(6); + +const executeList = (list, n) => swapPairs(list.head) + +const execute = list => { + console.log('travers') + console.log(list.toString()); + const list1 = executeList(list) + console.log(traversList(list1)) +} + +execute(myLinkedList) // 1,2,3,4, // 1,2,3,5 +execute(myLinkedList2) // [] // [] +execute(myLinkedList3) // [1] // [1] +execute(myLinkedList4) // 1,2,3 // 2,1,3 +execute(myLinkedList5) // 1,2,3,4,5,6 // 2,1,4,3,6,5 + + \ No newline at end of file diff --git a/example/README.md b/example/README.md index b2f35e75..12578b5b 100644 --- a/example/README.md +++ b/example/README.md @@ -57,7 +57,7 @@ Better order to solve problems 234. Palindrome Linked List 83. Remove Duplicates from Sorted List 19. Remove Nth Node from End of List -43. Swap Nodes in Pairs +24. Swap Nodes in Pairs 21. Merge Two sorted Lists 141. Linked List Cycle From d7fe3403d8fc50d59dbd63ee50834ae6c289db11 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 11 Mar 2025 06:05:53 +0300 Subject: [PATCH 840/872] Create 0021.js --- 0021-merge-two-sorted-lists.js | 28 +++++++++++++++++++ example/3.Linkedlist/0021.js | 50 ++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 example/3.Linkedlist/0021.js diff --git a/0021-merge-two-sorted-lists.js b/0021-merge-two-sorted-lists.js index f5c16393..b1e9b07d 100644 --- a/0021-merge-two-sorted-lists.js +++ b/0021-merge-two-sorted-lists.js @@ -33,3 +33,31 @@ var mergeTwoLists = function(l1, l2) { return l1; }; + +// var mergeTwoLists = function(list1, list2) { +// const dummy = new LinkedListNode(); +// current = dummy + +// p1 = list1 +// p2 = list2 + +// while (p1 && p2) { +// if (p1.val < p2.val) { +// current.next = p1 +// p1 = p1.next +// } else { +// current.next = p2 +// p2 = p2.next +// } + +// current = current.next +// } + +// if (p1) { +// current.next = p1 +// } else { +// current.next = p2 +// } + +// return dummy.next +// }; \ No newline at end of file diff --git a/example/3.Linkedlist/0021.js b/example/3.Linkedlist/0021.js new file mode 100644 index 00000000..daa79431 --- /dev/null +++ b/example/3.Linkedlist/0021.js @@ -0,0 +1,50 @@ +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} list1 + * @param {ListNode} list2 + * @return {ListNode} + */ +var mergeTwoLists = function(list1, list2) { + +}; + +const myLinkedList = new LinkedList(); +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(4); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(1); +myLinkedList2.append(3); +myLinkedList2.append(4); + +const myLinkedList3 = new LinkedList(); + +const myLinkedList4 = new LinkedList(); + +const myLinkedList5 = new LinkedList(); + +const myLinkedList6 = new LinkedList(); +myLinkedList6.prepend(0); + +const executeList = (list, list2) => mergeTwoLists(list.head, list2.head) + +const execute = (list, list2) => { + console.log('travers') + console.log(list.toString()); + console.log(list2.toString()); + const list1 = executeList(list, list2) + console.log(traversList(list1)) +} + +execute(myLinkedList, myLinkedList2) // 1,2,4 1,3,4 // 1,1,2,3,4,4 +execute(myLinkedList3, myLinkedList4) // [] [] // [] +execute(myLinkedList5, myLinkedList6) // [] [0] // [0] + + \ No newline at end of file From 0e670d54dd84e1e1046b729f043106a877328a9e Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 11 Mar 2025 08:53:12 +0300 Subject: [PATCH 841/872] Create 1358.js --- example/Dayly/1358.js | 47 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 example/Dayly/1358.js diff --git a/example/Dayly/1358.js b/example/Dayly/1358.js new file mode 100644 index 00000000..46552125 --- /dev/null +++ b/example/Dayly/1358.js @@ -0,0 +1,47 @@ +/** + * @param {string} s + * @return {number} + */ +var numberOfSubstrings = function(s) { + +}; + +const example1 = numberOfSubstrings('abcabc'); // 10 +const example2 = numberOfSubstrings('aaacb'); // 3 +const example3 = numberOfSubstrings('abc'); // 1 + +console.log(example1); +console.log(example2); +console.log(example3); + +// var numberOfSubstrings = function(s) { +// return solve(s, 3) - solve(s, 2) +// }; + +// var solve = function(word, n) { +// const vowels = new Set(['a', 'b', 'c']) +// const freqMap = new Map() +// let l = 0, r = 0, result = 0 + +// while (r < word.length) { +// if (vowels.has(word[r])) { +// freqMap.set(word[r], (freqMap.get(word[r]) || 0) + 1) +// } else { +// freqMap.clear() +// l = r + 1 +// } + +// while (freqMap.size > n) { +// freqMap.set(word[l], freqMap.get(word[l]) - 1) +// if (freqMap.get(word[l]) === 0) { +// freqMap.delete(word[l]) +// } +// l++ +// } + +// result += r - l + 1 +// r++ +// } + +// return result +// } \ No newline at end of file From d3a8027bd87c554ab78a7af88629709e1d03c908 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 11 Mar 2025 09:50:44 +0300 Subject: [PATCH 842/872] Create 1822.js --- example/ProgrammingSkills/0.Basic/1822.js | 29 +++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 example/ProgrammingSkills/0.Basic/1822.js diff --git a/example/ProgrammingSkills/0.Basic/1822.js b/example/ProgrammingSkills/0.Basic/1822.js new file mode 100644 index 00000000..a081caa1 --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/1822.js @@ -0,0 +1,29 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var arraySign = function(nums) { + +}; + +const example1 = arraySign([-1,-2,-3,-4,3,2,1]); // 1 +const example2 = arraySign([1,5,0,2,-3]); // 0 +const example3 = arraySign([-1,1,-1,1,-1]); // -1 + +console.log(example1); +console.log(example2); +console.log(example3); + +// var arraySign = function(nums) { +// let minusCount = 0; +// for (const number of nums) { +// if (number === 0) { +// return 0 +// } + +// if (number < 0) { +// minusCount += 1 +// } +// } +// return minusCount % 2 === 0 ? 1 : -1 +// }; \ No newline at end of file From 35af9f97d83cd637739c9537657c8b7106edc547 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 11 Mar 2025 09:58:57 +0300 Subject: [PATCH 843/872] Create 1502.js --- example/ProgrammingSkills/0.Basic/1502.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 example/ProgrammingSkills/0.Basic/1502.js diff --git a/example/ProgrammingSkills/0.Basic/1502.js b/example/ProgrammingSkills/0.Basic/1502.js new file mode 100644 index 00000000..a52f9bce --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/1502.js @@ -0,0 +1,19 @@ +/** + * 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) { + +} \ No newline at end of file From 910b5ee724bfe0a063000908ccc826a16533457f Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 11 Mar 2025 11:40:40 +0300 Subject: [PATCH 844/872] Create 0567.js --- 0567-permutation-in-string.js | 36 +++++++++++++++++++++++++++++++++ example/2.SlidingWindow/0567.js | 19 +++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 example/2.SlidingWindow/0567.js diff --git a/0567-permutation-in-string.js b/0567-permutation-in-string.js index 20c61c88..44910e18 100644 --- a/0567-permutation-in-string.js +++ b/0567-permutation-in-string.js @@ -36,3 +36,39 @@ var checkInclusion = function(s1, s2) { return isMatch(map1, map2); }; + +// 6 solutions + +// var checkInclusion = function(s1, s2) { +// if (s1.length > s2.length) return false; + +// // Массивы для подсчета количества букв +// const s1arr = new Array(26).fill(0); +// const s2arr = new Array(26).fill(0); + +// // Заполняем массивы для первых символов +// for (let i = 0; i < s1.length; i++) { +// s1arr[s1.charCodeAt(i) - 'a'.charCodeAt(0)]++; +// s2arr[s2.charCodeAt(i) - 'a'.charCodeAt(0)]++; +// } + +// // Проверка на соответствие +// const matches = (s1arr, s2arr) => { +// for (let i = 0; i < 26; i++) { +// if (s1arr[i] !== s2arr[i]) return false; +// } +// return true; +// }; + +// // Сдвигаем окно по строке s2 +// for (let i = 0; i < s2.length - s1.length; i++) { +// if (matches(s1arr, s2arr)) return true; + +// // Обновляем массивы для следующего окна +// s2arr[s2.charCodeAt(i + s1.length) - 'a'.charCodeAt(0)]++; +// s2arr[s2.charCodeAt(i) - 'a'.charCodeAt(0)]--; +// } + +// // Последняя проверка на совпадение +// return matches(s1arr, s2arr); +// }; diff --git a/example/2.SlidingWindow/0567.js b/example/2.SlidingWindow/0567.js new file mode 100644 index 00000000..eaf0b130 --- /dev/null +++ b/example/2.SlidingWindow/0567.js @@ -0,0 +1,19 @@ +/** + * @param {string} s1 + * @param {string} s2 + * @return {boolean} + */ +var checkInclusion = function(s1, s2) { + +}; + + +const example1 = checkInclusion("ab", "eidbaooo"); // true +const example2 = checkInclusion("ab", "eidboaoo"); // false +const example3 = checkInclusion("abc", "lecabee"); // true +const example4 = checkInclusion("abc", "lecaabee"); // false + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); From 975e1e81162c9aace68ee602cfb43eda2fcf827f Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 11 Mar 2025 11:51:21 +0300 Subject: [PATCH 845/872] Create 0076.js --- 0076-minimum-window-substring.js | 44 ++++++++++++++++++++++++++++++++ example/2.SlidingWindow/0076.js | 23 +++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 example/2.SlidingWindow/0076.js diff --git a/0076-minimum-window-substring.js b/0076-minimum-window-substring.js index 7879c4ac..7a5edc9c 100644 --- a/0076-minimum-window-substring.js +++ b/0076-minimum-window-substring.js @@ -42,3 +42,47 @@ var minWindow = function(s, t) { return end !== Infinity ? s.slice(start, end + 1) : ''; }; + +// var minWindow = function(s, t) { +// if (s.length < t.length) { +// return ""; +// } + +// const charCount = new Map(); +// for (const ch of t) { +// charCount.set(ch, (charCount.get(ch) || 0) + 1); +// } + +// let targetCharsRemaining = t.length; +// let minWindow = [0, Number.POSITIVE_INFINITY]; +// let startIndex = 0; + +// for (let endIndex = 0; endIndex < s.length; endIndex++) { +// const ch = s[endIndex]; +// if (charCount.has(ch) && charCount.get(ch) > 0) { +// targetCharsRemaining--; +// } +// charCount.set(ch, (charCount.get(ch) || 0) - 1); + +// if (targetCharsRemaining === 0) { +// while (true) { +// const charAtStart = s[startIndex]; +// if (charCount.has(charAtStart) && charCount.get(charAtStart) === 0) { +// break; +// } +// charCount.set(charAtStart, (charCount.get(charAtStart) || 0) + 1); +// startIndex++; +// } + +// if (endIndex - startIndex < minWindow[1] - minWindow[0]) { +// minWindow = [startIndex, endIndex]; +// } + +// charCount.set(s[startIndex], (charCount.get(s[startIndex]) || 0) + 1); +// targetCharsRemaining++; +// startIndex++; +// } +// } + +// return minWindow[1] >= s.length ? "" : s.slice(minWindow[0], minWindow[1] + 1); +// }; diff --git a/example/2.SlidingWindow/0076.js b/example/2.SlidingWindow/0076.js new file mode 100644 index 00000000..9a6448a9 --- /dev/null +++ b/example/2.SlidingWindow/0076.js @@ -0,0 +1,23 @@ +/** + * @param {string} s + * @param {string} t + * @return {string} + */ +var minWindow = function(s, t) { + +}; + + +const example1 = minWindow("ADOBECODEBANC", "ABC"); // "BANC" +const example2 = minWindow("a", "a"); // "a" +const example3 = minWindow("a", "aa"); // "" +const example4 = minWindow("OUZODYXAZV", "XYZ"); // "YXAZ" +const example5 = minWindow("xyz", "xyz"); // "xyz" +const example6 = minWindow("x", "xy"); // "" + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); From 19fec7c06daa6c29a5324a6a5e8e69d13772a43f Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 11 Mar 2025 11:59:12 +0300 Subject: [PATCH 846/872] Create 0239.js --- 0239-sliding-window-maximum.js | 24 ++++++++++++++++++++++++ example/2.SlidingWindow/0239.js | 17 +++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 example/2.SlidingWindow/0239.js diff --git a/0239-sliding-window-maximum.js b/0239-sliding-window-maximum.js index b4845467..45ab46fb 100644 --- a/0239-sliding-window-maximum.js +++ b/0239-sliding-window-maximum.js @@ -34,3 +34,27 @@ var maxSlidingWindow = function(nums, k) { return result; }; + +// var maxSlidingWindow = function(nums, k) { +// let res = []; +// let deque = []; + +// for (let idx = 0; idx < nums.length; idx++) { +// let num = nums[idx]; + +// while (deque.length && deque[deque.length - 1] < num) { +// deque.pop(); +// } +// deque.push(num); + +// if (idx >= k && nums[idx - k] === deque[0]) { +// deque.shift(); +// } + +// if (idx >= k - 1) { +// res.push(deque[0]); +// } +// } + +// return res; +// }; diff --git a/example/2.SlidingWindow/0239.js b/example/2.SlidingWindow/0239.js new file mode 100644 index 00000000..700d131c --- /dev/null +++ b/example/2.SlidingWindow/0239.js @@ -0,0 +1,17 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var maxSlidingWindow = function(nums, k) { + +}; + + +const example1 = maxSlidingWindow([1,3,-1,-3,5,3,6,7], 3); // [3,3,5,5,6,7] +const example2 = maxSlidingWindow([1], 1); // [1] +const example3 = maxSlidingWindow([1,2,1,0,4,2,6], 3); // [2,2,4,4,6] + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file From fc896ed22416269466c674a4e608439df926a4e1 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Wed, 12 Mar 2025 14:24:00 +0300 Subject: [PATCH 847/872] Create 2529.js --- example/Dayly/2529.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 example/Dayly/2529.js diff --git a/example/Dayly/2529.js b/example/Dayly/2529.js new file mode 100644 index 00000000..a044f0d4 --- /dev/null +++ b/example/Dayly/2529.js @@ -0,0 +1,15 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var maximumCount = function(nums) { + +}; + +const example1 = maximumCount([-2,-1,-1,1,2,3]); // 3 +const example2 = maximumCount([-3,-2,-1,0,0,1,2]); // 3 +const example3 = maximumCount([5,20,66,1314]); // 4 + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file From 94720984c148e09ca8c084ccaef510eb6080d62b Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Wed, 12 Mar 2025 15:45:41 +0300 Subject: [PATCH 848/872] Create 0896.js --- example/ProgrammingSkills/0.Basic/0896.js | 38 +++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 example/ProgrammingSkills/0.Basic/0896.js diff --git a/example/ProgrammingSkills/0.Basic/0896.js b/example/ProgrammingSkills/0.Basic/0896.js new file mode 100644 index 00000000..c63d96c0 --- /dev/null +++ b/example/ProgrammingSkills/0.Basic/0896.js @@ -0,0 +1,38 @@ +/** + * @param {number[]} nums + * @return {boolean} + */ +var isMonotonic = function(nums) { + +}; + +const example1 = isMonotonic([1,2,2,3]); // true +const example2 = isMonotonic([6,5,4,4]); // true +const example3 = isMonotonic([1,3,2]); // false + +console.log(example1); +console.log(example2); +console.log(example3); + +var isMonotonic = function(nums) { + let n = nums.length + if (n === 1) return true + + let isInc = true + let isDec = true + + for (let i = 1; i < n; i++) { + if (!isInc && !isDec) { + return false + } + + if (nums[i - 1] > nums[i]) { + isInc = false + } + + if (nums[i - 1] < nums[i]) { + isDec = false + } + } + return isInc || isDec +}; From 6b2b68c086ac2e8d06c1950aa78c1d64c21c4095 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Thu, 13 Mar 2025 04:26:03 +0300 Subject: [PATCH 849/872] Create 3356.js --- example/Dayly/3356.js | 55 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 example/Dayly/3356.js diff --git a/example/Dayly/3356.js b/example/Dayly/3356.js new file mode 100644 index 00000000..a54f5205 --- /dev/null +++ b/example/Dayly/3356.js @@ -0,0 +1,55 @@ +/** + * @param {number[]} nums + * @param {number[][]} queries + * @return {number} + */ +var minZeroArray = function(nums, queries) { + +}; + + +const example1 = minZeroArray([2,0,2], [[0,2,1],[0,2,1],[1,1,3]]); // 2 +const example2 = minZeroArray([4,3,2,1], [[1,3,2],[0,2,1]]); // -1 + +console.log(example1); +console.log(example2); + +// var minZeroArray = function(nums, queries) { +// const n = nums.length; +// let left = 0; +// let right = queries.length; +// let result = -1; + +// const canZeroArray = function(nums, queries, k) { +// const n = nums.length; +// const diff = new Array(n + 1).fill(0); + +// for (let i = 0; i < k; i++) { +// let [l, r, val] = queries[i]; +// diff[l] -= val; +// if (r + 1 < n) { +// diff[r + 1] += val; +// } +// } + +// let currentDecrement = 0; +// for (let i = 0; i < n; i++) { +// currentDecrement += diff[i]; +// if (nums[i] + currentDecrement > 0) { +// return false; +// } +// } +// return true; +// } + +// while (left <= right) { +// const mid = Math.trunc((left + right) / 2); + +// if (canZeroArray(nums.slice(), queries, mid)) { +// result = mid; +// right = mid - 1; +// } +// else { left = mid + 1; } +// } +// return result; +// }; \ No newline at end of file From 058d082405f03ec6be336cdae5281e67164519f6 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Thu, 13 Mar 2025 10:33:05 +0300 Subject: [PATCH 850/872] add linked lists --- 0002-add-two-numbers.js | 22 ++++++++++ 0143-reorder-list.js | 24 +++++++++++ example/3.Linkedlist/0002.js | 79 ++++++++++++++++++++++++++++++++++++ example/3.Linkedlist/0138.js | 66 ++++++++++++++++++++++++++++++ example/3.Linkedlist/0141.js | 15 +++++++ example/3.Linkedlist/0143.js | 55 +++++++++++++++++++++++++ example/3.Linkedlist/0287.js | 57 ++++++++++++++++++++++++++ example/README.md | 10 ++++- 8 files changed, 326 insertions(+), 2 deletions(-) create mode 100644 example/3.Linkedlist/0002.js create mode 100644 example/3.Linkedlist/0138.js create mode 100644 example/3.Linkedlist/0141.js create mode 100644 example/3.Linkedlist/0143.js create mode 100644 example/3.Linkedlist/0287.js diff --git a/0002-add-two-numbers.js b/0002-add-two-numbers.js index 81b72151..63ca74dc 100644 --- a/0002-add-two-numbers.js +++ b/0002-add-two-numbers.js @@ -36,3 +36,25 @@ var addTwoNumbers = function(l1, l2) { return result.next; }; + +// var addTwoNumbers = function(l1, l2) { +// const dummy = new LinkedListNode(); +// let cur = dummy; + +// let carry = 0; +// while (l1 || l2 || carry) { +// const v1 = l1 ? l1.val : 0; +// const v2 = l2 ? l2.val : 0; + +// let val = v1 + v2 + carry; +// carry = Math.floor(val / 10); +// val = val % 10; +// cur.next = new LinkedListNode(val); + +// cur = cur.next; +// l1 = l1 ? l1.next : null; +// l2 = l2 ? l2.next : null; +// } + +// return dummy.next; +// }; diff --git a/0143-reorder-list.js b/0143-reorder-list.js index e1739ce2..1838188e 100644 --- a/0143-reorder-list.js +++ b/0143-reorder-list.js @@ -55,3 +55,27 @@ var reorderList = function(head) { list2 = center1.next; } }; + +// var reorderList = function(head) { +// if (!head) return; + +// const nodes = []; +// let cur = head; +// while (cur) { +// nodes.push(cur); +// cur = cur.next; +// } + +// let i = 0, j = nodes.length - 1; +// while (i < j) { +// nodes[i].next = nodes[j]; +// i++; +// if (i >= j) break; +// nodes[j].next = nodes[i]; +// j--; +// } + +// nodes[i].next = null; + +// return head +// }; diff --git a/example/3.Linkedlist/0002.js b/example/3.Linkedlist/0002.js new file mode 100644 index 00000000..b648c09f --- /dev/null +++ b/example/3.Linkedlist/0002.js @@ -0,0 +1,79 @@ +/** + * 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 myLinkedList = new LinkedList(); +myLinkedList.prepend(2); +myLinkedList.append(4); +myLinkedList.append(3); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(5); +myLinkedList2.append(6); +myLinkedList2.append(4); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(0); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(0); + +const myLinkedList5 = new LinkedList(); +myLinkedList5.prepend(9); +myLinkedList5.append(9); +myLinkedList5.append(9); +myLinkedList5.append(9); +myLinkedList5.append(9); +myLinkedList5.append(9); +myLinkedList5.append(9); + +const myLinkedList6 = new LinkedList(); +myLinkedList6.prepend(9); +myLinkedList6.append(9); +myLinkedList6.append(9); +myLinkedList6.append(9); + +const myLinkedList7 = new LinkedList(); +myLinkedList7.prepend(1); +myLinkedList7.append(2); +myLinkedList7.append(3); + +const myLinkedList8 = new LinkedList(); +myLinkedList8.prepend(4); +myLinkedList8.append(5); +myLinkedList8.append(6); + +const myLinkedList9 = new LinkedList(); +myLinkedList3.prepend(9); + +const myLinkedList10 = new LinkedList(); +myLinkedList4.prepend(9); + + +const executeList = (l1, l2) => addTwoNumbers(l1.head, l2.head) + +const execute = (l1, l2) => { + console.log('travers') + console.log(l1.toString()); + console.log(l2.toString()); + const list1 = executeList(l1, l2) + console.log(traversList(list1)) +} + +execute(myLinkedList, myLinkedList2) // [2,4,3] [5,6,4] // [7,0,8] +execute(myLinkedList3, myLinkedList4) // [0] [0] // [0] ??? +execute(myLinkedList5, myLinkedList6) // [9,9,9,9,9,9,9] [9,9,9,9] // [8,9,9,9,0,0,0,1] +execute(myLinkedList7, myLinkedList8) // [1,2,3] [4,5,6] // [5,7,9] +execute(myLinkedList9, myLinkedList10) // [9] [9] // [8,1] diff --git a/example/3.Linkedlist/0138.js b/example/3.Linkedlist/0138.js new file mode 100644 index 00000000..331aa89d --- /dev/null +++ b/example/3.Linkedlist/0138.js @@ -0,0 +1,66 @@ +/** + * // 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) { + map = new Map(); + + if (head === null) return null; + if (map.has(head)) return map.get(head); + + const copy = new LinkedListNode(head.val); + map.set(head, copy); + copy.next = copyRandomList(head.next); + copy.random = map.get(head.random) || null; + return copy; +}; + +const myLinkedList = new LinkedList(); +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(3); +myLinkedList.append(4); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(1); +myLinkedList2.append(2); +myLinkedList2.append(3); +myLinkedList2.append(4); +myLinkedList2.append(5); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(2); +myLinkedList3.append(4); +myLinkedList3.append(6); +myLinkedList3.append(8); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(2); +myLinkedList4.append(4); +myLinkedList4.append(6); +myLinkedList4.append(8); +myLinkedList4.append(10); + + +const executeList = list => copyRandomList(list.head) + +const execute = list => { + console.log('travers') + console.log(list.toString()); + const list1 = executeList(list) + console.log(traversList(list1)) +} + +execute(myLinkedList) // [1,2,3,4] // [1,4,2,3] +execute(myLinkedList2) // [1,2,3,4,5] // [1,5,2,4,3] +execute(myLinkedList3) // [2,4,6,8] // [2,8,4,6] +execute(myLinkedList4) // [2,4,6,8,10] // [2,10,4,8,6] diff --git a/example/3.Linkedlist/0141.js b/example/3.Linkedlist/0141.js new file mode 100644 index 00000000..fc032cc7 --- /dev/null +++ b/example/3.Linkedlist/0141.js @@ -0,0 +1,15 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} head + * @return {boolean} + */ +var hasCycle = function(head) { + +}; \ No newline at end of file diff --git a/example/3.Linkedlist/0143.js b/example/3.Linkedlist/0143.js new file mode 100644 index 00000000..3cfdadf9 --- /dev/null +++ b/example/3.Linkedlist/0143.js @@ -0,0 +1,55 @@ +/** + * 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) { + +}; + +const myLinkedList = new LinkedList(); +myLinkedList.prepend(1); +myLinkedList.append(2); +myLinkedList.append(3); +myLinkedList.append(4); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(1); +myLinkedList2.append(2); +myLinkedList2.append(3); +myLinkedList2.append(4); +myLinkedList2.append(5); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(2); +myLinkedList3.append(4); +myLinkedList3.append(6); +myLinkedList3.append(8); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(2); +myLinkedList4.append(4); +myLinkedList4.append(6); +myLinkedList4.append(8); +myLinkedList4.append(10); + + +const executeList = list => reorderList(list.head) + +const execute = list => { + console.log('travers') + console.log(list.toString()); + const list1 = executeList(list) + console.log(traversList(list1)) +} + +execute(myLinkedList) // [1,2,3,4] // [1,4,2,3] +execute(myLinkedList2) // [1,2,3,4,5] // [1,5,2,4,3] +execute(myLinkedList3) // [2,4,6,8] // [2,8,4,6] +execute(myLinkedList4) // [2,4,6,8,10] // [2,10,4,8,6] diff --git a/example/3.Linkedlist/0287.js b/example/3.Linkedlist/0287.js new file mode 100644 index 00000000..ef4f444b --- /dev/null +++ b/example/3.Linkedlist/0287.js @@ -0,0 +1,57 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function(nums) { + +}; + +// const myLinkedList = new LinkedList(); +// myLinkedList.prepend(1); +// myLinkedList.append(3); +// myLinkedList.append(4); +// myLinkedList.append(2); +// myLinkedList.append(2); + +// const myLinkedList2 = new LinkedList(); +// myLinkedList2.prepend(3); +// myLinkedList2.append(1); +// myLinkedList2.append(3); +// myLinkedList2.append(4); +// myLinkedList2.append(2); + +// const myLinkedList3 = new LinkedList(); +// myLinkedList3.prepend(3); +// myLinkedList3.append(3); +// myLinkedList3.append(3); +// myLinkedList3.append(3); +// myLinkedList3.append(3); + +// const myLinkedList4 = new LinkedList(); +// myLinkedList4.prepend(1); +// myLinkedList4.append(2); +// myLinkedList4.append(3); +// myLinkedList4.append(2); +// myLinkedList4.append(2); + +// const myLinkedList5 = new LinkedList(); +// myLinkedList5.prepend(1); +// myLinkedList5.append(2); +// myLinkedList5.append(3); +// myLinkedList5.append(4); +// myLinkedList5.append(4); + +// const executeList = list => reorderList(list.head) + +// const execute = list => { +// console.log('travers') +// console.log(list.toString()); +// const list1 = executeList(list) +// console.log(traversList(list1)) +// } + +// execute(myLinkedList) // [1,3,4,2,2] // 2 +// execute(myLinkedList2) // [3,1,3,4,2] // 3 +// execute(myLinkedList3) // [3,3,3,3,3] // 3 +// execute(myLinkedList4) // [1,2,3,2,2] // 2 +// execute(myLinkedList5) // [1,2,3,4,4] // 4 diff --git a/example/README.md b/example/README.md index 12578b5b..e2f54d19 100644 --- a/example/README.md +++ b/example/README.md @@ -42,13 +42,12 @@ Better order to solve problems 904. Fruit Into Baskets 0. 121. Best Time to Buy and Sell Stock -424. Longest Repeating Character Replacement - 424. Longest Repeating Character Replacement - 567. Permutation in String - 76. Minimum Window Substring - 239. Sliding Window Maximum -### Linked list +### [Linked list](https://github.com/Barklim/leetcode-javascript/tree/master/example/3.Linkedlist) 707. Design Linked List 876. Middle of the Linked List @@ -60,6 +59,13 @@ Better order to solve problems 24. Swap Nodes in Pairs 21. Merge Two sorted Lists 141. Linked List Cycle +0. +143. Reorder List +- 138. Copy List with Random Pointer +- 2. Add Two Numbers +- 287. Find the Duplicate Number +- 23. Merge k Sorted Lists +- 25. Reverse Nodes in k-Group ### HashMap From c71e97f81ccac12c62afb35954f366e11a057641 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Thu, 13 Mar 2025 18:34:30 +0300 Subject: [PATCH 851/872] simulation topics --- 0013-roman-to-integer.js | 23 ++++++++++++++++++ 0058-length-of-last-word.js | 15 ++++++++++++ .../ProgrammingSkills/1.Simulation/0058.js | 15 ++++++++++++ .../ProgrammingSkills/1.Simulation/0709.js | 24 +++++++++++++++++++ example/README.md | 7 +++++- 5 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 example/ProgrammingSkills/1.Simulation/0058.js create mode 100644 example/ProgrammingSkills/1.Simulation/0709.js diff --git a/0013-roman-to-integer.js b/0013-roman-to-integer.js index acbb22f8..98fc3a39 100644 --- a/0013-roman-to-integer.js +++ b/0013-roman-to-integer.js @@ -46,3 +46,26 @@ var romanToInt = function(s) { return result; }, 0); }; + +// var romanToInt = function(s) { +// let res = 0; +// const roman = { +// 'I': 1, +// 'V': 5, +// 'X': 10, +// 'L': 50, +// 'C': 100, +// 'D': 500, +// 'M': 1000 +// }; + +// for (let i = 0; i < s.length - 1; i++) { +// if (roman[s[i]] < roman[s[i + 1]]) { +// res -= roman[s[i]]; +// } else { +// res += roman[s[i]]; +// } +// } + +// return res + roman[s[s.length - 1]]; +// }; diff --git a/0058-length-of-last-word.js b/0058-length-of-last-word.js index db2632c8..d57d3a84 100644 --- a/0058-length-of-last-word.js +++ b/0058-length-of-last-word.js @@ -21,3 +21,18 @@ var lengthOfLastWord = function(s) { return s.trim().split(/\s+/).pop().length; }; + +// var lengthOfLastWord = function(s) { +// let end = s.length - 1; + +// while (end >= 0 && s[end] === ' ') { +// end--; +// } + +// let start = end; +// while (start >= 0 && s[start] !== ' ') { +// start--; +// } + +// return end - start; +// }; diff --git a/example/ProgrammingSkills/1.Simulation/0058.js b/example/ProgrammingSkills/1.Simulation/0058.js new file mode 100644 index 00000000..c340ada6 --- /dev/null +++ b/example/ProgrammingSkills/1.Simulation/0058.js @@ -0,0 +1,15 @@ +/** + * @param {string} s + * @return {number} + */ +var lengthOfLastWord = function(s) { + +}; + +const example1 = lengthOfLastWord("Hello World"); // 5 +const example2 = lengthOfLastWord(" fly me to the moon "); // 4 +const example3 = lengthOfLastWord("luffy is still joyboy"); // 6 + +console.log(example1); +console.log(example2); +console.log(example3); diff --git a/example/ProgrammingSkills/1.Simulation/0709.js b/example/ProgrammingSkills/1.Simulation/0709.js new file mode 100644 index 00000000..421e25f2 --- /dev/null +++ b/example/ProgrammingSkills/1.Simulation/0709.js @@ -0,0 +1,24 @@ +/** + * @param {string} s + * @return {string} + */ +var toLowerCase = function(s) { + let result = ''; + for (let i = 0; i < s.length; i++) { + const ascii = s.charCodeAt(i); + if (ascii >= 65 && ascii <= 90) { + result += String.fromCharCode(ascii + 32); + } else { + result += s.charAt(i); + } + } + return result; +}; + +const example1 = lengthOfLastWord("Hello World"); // 5 +const example2 = lengthOfLastWord(" fly me to the moon "); // 4 +const example3 = lengthOfLastWord("luffy is still joyboy"); // 6 + +console.log(example1); +console.log(example2); +console.log(example3); diff --git a/example/README.md b/example/README.md index e2f54d19..2b19936b 100644 --- a/example/README.md +++ b/example/README.md @@ -215,4 +215,9 @@ Better order to solve problems 389. Find the Difference 28. Find the Index of the First Occurrence in a String 459. Repeated Substring Pattern -66. Plus One \ No newline at end of file +66. Plus One + +### [0.Basic](https://github.com/Barklim/leetcode-javascript/tree/master/example/ProgrammingSkills/1.Simulation) + +58. Length of Last Word +1041. Robot Bounded In Circle \ No newline at end of file From 590e0e25a7343ee869c9e85316c3ff5e89398f11 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Fri, 14 Mar 2025 17:17:58 +0300 Subject: [PATCH 852/872] binary search --- 0074-search-a-2d-matrix.js | 36 ++++++++++++++++++++++++++++++++++ 0704-binary-search.js | 14 +++++++++++++ 0875-koko-eating-bananas.js | 23 ++++++++++++++++++++++ example/4.BinarySearch/0074.js | 18 +++++++++++++++++ example/4.BinarySearch/0704.js | 18 +++++++++++++++++ example/4.BinarySearch/0875.js | 20 +++++++++++++++++++ example/Dayly/2226.js | 30 ++++++++++++++++++++++++++++ example/README.md | 6 ++++++ 8 files changed, 165 insertions(+) create mode 100644 example/4.BinarySearch/0074.js create mode 100644 example/4.BinarySearch/0704.js create mode 100644 example/4.BinarySearch/0875.js create mode 100644 example/Dayly/2226.js diff --git a/0074-search-a-2d-matrix.js b/0074-search-a-2d-matrix.js index 8cb17adb..e99f8663 100644 --- a/0074-search-a-2d-matrix.js +++ b/0074-search-a-2d-matrix.js @@ -20,3 +20,39 @@ var searchMatrix = function(matrix, target) { .filter(row => row[0] <= target && row[row.length - 1] >= target) .find(row => row.includes(target)) !== undefined; }; + +// var searchMatrix = function(matrix, target) { +// const ROWS = matrix.length; +// const COLS = matrix[0].length; + +// let top = 0; +// let bot = ROWS - 1; +// while (top <= bot) { +// const row = Math.floor((top + bot) / 2); +// if (target > matrix[row][COLS - 1]) { +// top = row + 1; +// } else if (target < matrix[row][0]) { +// bot = row - 1; +// } else { +// break; +// } +// } + +// if (!(top <= bot)) { +// return false; +// } +// const row = Math.floor((top + bot) / 2); +// let l = 0; +// let r = COLS - 1; +// while (l <= r) { +// const m = Math.floor((l + r) / 2); +// if (target > matrix[row][m]) { +// l = m + 1; +// } else if (target < matrix[row][m]) { +// r = m - 1; +// } else { +// return true; +// } +// } +// return false; +// }; diff --git a/0704-binary-search.js b/0704-binary-search.js index a8cf2011..7ba581fd 100644 --- a/0704-binary-search.js +++ b/0704-binary-search.js @@ -28,3 +28,17 @@ var search = function(nums, target) { return -1; }; + +// var search = function(nums, target) { +// l = 0 +// r = nums.length + +// while (l <= r) { +// pivot = Math.floor((l + r) / 2) +// if (nums[pivot] === target) return pivot +// if (target < nums[pivot]) r = pivot - 1 +// else l = pivot + 1 +// } + +// return - 1 +// }; diff --git a/0875-koko-eating-bananas.js b/0875-koko-eating-bananas.js index 68ee313c..05875855 100644 --- a/0875-koko-eating-bananas.js +++ b/0875-koko-eating-bananas.js @@ -40,3 +40,26 @@ var minEatingSpeed = function(piles, h) { return result; }; + +// var minEatingSpeed = function(piles, h) { +// l = 0 +// r = Math.max(...piles) +// res = r + +// while (l <= r) { +// m = Math.floor((l + r)/2) + +// totalTime = 0 +// for (const p of piles) { +// totalTime += Math.ceil( p / m) +// } + +// if (totalTime <= h) { +// res = m +// r = m - 1 +// } else { +// l = m + 1 +// } +// } +// return res +// }; diff --git a/example/4.BinarySearch/0074.js b/example/4.BinarySearch/0074.js new file mode 100644 index 00000000..056c21a1 --- /dev/null +++ b/example/4.BinarySearch/0074.js @@ -0,0 +1,18 @@ +/** + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var searchMatrix = function(matrix, target) { + +}; + +const example1 = searchMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,60]], 3); // true +const example2 = searchMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,60]], 13); // false +const example3 = searchMatrix([[1,2,4,8],[10,11,12,13],[14,20,30,40]], 10); // true +const example4 = searchMatrix([[1,2,4,8],[10,11,12,13],[14,20,30,40]], 15); // false + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/4.BinarySearch/0704.js b/example/4.BinarySearch/0704.js new file mode 100644 index 00000000..b7b1ae47 --- /dev/null +++ b/example/4.BinarySearch/0704.js @@ -0,0 +1,18 @@ +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function(nums, target) { + +}; + +const example1 = search([-1,0,3,5,9,12], 9); // 4 +const example2 = search([-1,0,3,5,9,12], 2); // -1 +const example3 = search([-1,0,2,4,6,8], 4); // 3 +const example4 = search([-1,0,2,4,6,8], 3); // -1 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/4.BinarySearch/0875.js b/example/4.BinarySearch/0875.js new file mode 100644 index 00000000..1208f7e4 --- /dev/null +++ b/example/4.BinarySearch/0875.js @@ -0,0 +1,20 @@ +/** + * @param {number[]} piles + * @param {number} h + * @return {number} + */ +var minEatingSpeed = function(piles, h) { + +}; + +const example1 = minEatingSpeed([3,6,7,11], 8); // 4 +const example2 = minEatingSpeed([30,11,23,4,20], 5); // 30 +const example3 = minEatingSpeed([30,11,23,4,20], 6); // 23 +const example4 = minEatingSpeed([1,4,3,2], 9); // 2 +const example5 = minEatingSpeed([25,10,23,4], 4); // 25 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); diff --git a/example/Dayly/2226.js b/example/Dayly/2226.js new file mode 100644 index 00000000..8cfcbc54 --- /dev/null +++ b/example/Dayly/2226.js @@ -0,0 +1,30 @@ +/** + * @param {number[]} candies + * @param {number} k + * @return {number} + */ +var maximumCandies = function(candies, k) { + l = 1 + r = Math.max(...candies) + result = 0 + + while (l <= r) { + mid = Math.floor((l+r)/2) + childredCount = candies.reduce((sum, pile) => sum + Math.floor(pile/mid), 0) + + if (childredCount >= k) { + result = mid + l = mid + 1 + } else { + r = mid - 1 + } + } + + return result +}; + +const example1 = maximumCandies([5,8,6], 3); // 5 +const example2 = maximumCandies([2,5], 11); // 0 + +console.log(example1); +console.log(example2); diff --git a/example/README.md b/example/README.md index 2b19936b..e1631c56 100644 --- a/example/README.md +++ b/example/README.md @@ -67,6 +67,12 @@ Better order to solve problems - 23. Merge k Sorted Lists - 25. Reverse Nodes in k-Group +### [Binary Search](https://github.com/Barklim/leetcode-javascript/tree/master/example/4.BinarySearch) + +704. Binary Search +74. Search a 2D Matrix +875. Koko Eating Bananas + ### HashMap 706. Design Hash map From b131fee516447c1c147409957ab7546a4720fc41 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Fri, 14 Mar 2025 20:50:21 +0300 Subject: [PATCH 853/872] binary search --- 0033-search-in-rotated-sorted-array.js | 37 +++++++++ 0153-find-minimum-in-rotated-sorted-array.js | 23 ++++++ example/4.BinarySearch/0004.js | 18 +++++ example/4.BinarySearch/0033.js | 26 ++++++ example/4.BinarySearch/0153.js | 19 +++++ example/4.BinarySearch/0981.js | 85 ++++++++++++++++++++ example/README.md | 8 +- 7 files changed, 214 insertions(+), 2 deletions(-) create mode 100644 example/4.BinarySearch/0004.js create mode 100644 example/4.BinarySearch/0033.js create mode 100644 example/4.BinarySearch/0153.js create mode 100644 example/4.BinarySearch/0981.js diff --git a/0033-search-in-rotated-sorted-array.js b/0033-search-in-rotated-sorted-array.js index 632b7e3c..0f360821 100644 --- a/0033-search-in-rotated-sorted-array.js +++ b/0033-search-in-rotated-sorted-array.js @@ -42,3 +42,40 @@ var search = function(nums, target) { return -1; }; + +// var search = function(nums, target) { +// let l = 0; +// let r = nums.length - 1; + +// while (l < r) { +// const m = Math.floor((l + r) / 2); +// if (nums[m] > nums[r]) { +// l = m + 1; +// } else { +// r = m; +// } +// } + +// const pivot = l; + +// const result = binarySearch(nums, target, 0, pivot - 1); +// if (result !== -1) { +// return result; +// } + +// return binarySearch(nums, target, pivot, nums.length - 1); +// }; + +// var binarySearch = function(nums, target, left, right) { +// while (left <= right) { +// const mid = Math.floor((left + right) / 2); +// if (nums[mid] === target) { +// return mid; +// } else if (nums[mid] < target) { +// left = mid + 1; +// } else { +// right = mid - 1; +// } +// } +// return -1; +// } diff --git a/0153-find-minimum-in-rotated-sorted-array.js b/0153-find-minimum-in-rotated-sorted-array.js index 4146f626..30fad009 100644 --- a/0153-find-minimum-in-rotated-sorted-array.js +++ b/0153-find-minimum-in-rotated-sorted-array.js @@ -37,3 +37,26 @@ var findMin = function(nums) { return nums[left]; }; + +// var findMin = function(nums) { +// let l = 0; +// let r = nums.length - 1; +// let res = nums[0]; + +// while (l <= r) { +// if (nums[l] <= nums[r]) { +// res = Math.min(res, nums[l]); +// break; +// } + +// // let m = l + Math.floor((r - l) / 2); +// let m = Math.floor((l + r) / 2); +// res = Math.min(res, nums[m]); +// if (nums[m] >= nums[l]) { +// l = m + 1; +// } else { +// r = m - 1; +// } +// } +// return res; +// }; diff --git a/example/4.BinarySearch/0004.js b/example/4.BinarySearch/0004.js new file mode 100644 index 00000000..457b00d2 --- /dev/null +++ b/example/4.BinarySearch/0004.js @@ -0,0 +1,18 @@ +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var findMedianSortedArrays = function(nums1, nums2) { + +}; + +const example1 = search([1,3], [2]); // 2 +const example2 = search([1,2], [3,4]); // 2.5 +const example3 = search([1,2], [3]); // 2 +const example4 = search([1,3], [2,4]); // 2.5 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); \ No newline at end of file diff --git a/example/4.BinarySearch/0033.js b/example/4.BinarySearch/0033.js new file mode 100644 index 00000000..83d9a250 --- /dev/null +++ b/example/4.BinarySearch/0033.js @@ -0,0 +1,26 @@ +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function(nums, target) { + +}; + +const example1 = search([4,5,6,7,0,1,2], 0); // 4 +const example2 = search([4,5,6,7,0,1,2], 3); // -1 +const example3 = search([1], 0); // -1 +const example4 = search([3,4,5,1,2], 1); // 3 +const example5 = search([4,5,6,7,0,1,2], 2); // 6 +const example6 = search([11,13,15,17], 13); // 1 +const example7 = search([4,5,0,1,2,3], 0); // 2 +const example8 = search([4,5,6,7], 5); // 1 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); +console.log(example7); +console.log(example8); diff --git a/example/4.BinarySearch/0153.js b/example/4.BinarySearch/0153.js new file mode 100644 index 00000000..4ab6b9c8 --- /dev/null +++ b/example/4.BinarySearch/0153.js @@ -0,0 +1,19 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var findMin = function(nums) { + +}; + +const example1 = findMin([3,4,5,1,2]); // 1 +const example2 = findMin([4,5,6,7,0,1,2]); // 0 +const example3 = findMin([11,13,15,17]); // 11 +const example4 = findMin([4,5,0,1,2,3]); // 0 +const example5 = findMin([4,5,6,7]); // 4 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); diff --git a/example/4.BinarySearch/0981.js b/example/4.BinarySearch/0981.js new file mode 100644 index 00000000..9b36ac85 --- /dev/null +++ b/example/4.BinarySearch/0981.js @@ -0,0 +1,85 @@ +var TimeMap = function() { + +}; + +/** + * @param {string} key + * @param {string} value + * @param {number} timestamp + * @return {void} + */ +TimeMap.prototype.set = function(key, value, timestamp) { + +}; + +/** + * @param {string} key + * @param {number} timestamp + * @return {string} + */ +TimeMap.prototype.get = function(key, timestamp) { + +}; + +/** + * Your TimeMap object will be instantiated and called as such: + * var obj = new TimeMap() + * obj.set(key,value,timestamp) + * var param_2 = obj.get(key,timestamp) + */ + +// Input +// ["TimeMap", "set", "get", "get", "set", "get", "get"] +// [[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]] +// Output +// [null, null, "bar", "bar", null, "bar2", "bar2"] + + +const timeMap = new TimeMap(); +timeMap.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1. +timeMap.get("foo", 1); // return "bar" +timeMap.get("foo", 3); // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar". +timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4. +timeMap.get("foo", 4); // return "bar2" +timeMap.get("foo", 5); // return "bar2" + +// var TimeMap = function() { +// this.keyStore = new Map(); +// }; + +// /** +// * @param {string} key +// * @param {string} value +// * @param {number} timestamp +// * @return {void} +// */ +// TimeMap.prototype.set = function(key, value, timestamp) { +// if (!this.keyStore.has(key)) { +// this.keyStore.set(key, []); +// } +// this.keyStore.get(key).push([timestamp, value]); +// }; + +// /** +// * @param {string} key +// * @param {number} timestamp +// * @return {string} +// */ +// TimeMap.prototype.get = function(key, timestamp) { +// const values = this.keyStore.get(key) || []; +// let left = 0; +// let right = values.length - 1; +// let result = ''; + +// while (left <= right) { +// const mid = Math.floor((left + right) / 2); +// if (values[mid][0] <= timestamp) { +// result = values[mid][1]; +// left = mid + 1; +// } else { +// right = mid - 1; +// } +// } + +// return result; +// }; diff --git a/example/README.md b/example/README.md index e1631c56..0efdc4ac 100644 --- a/example/README.md +++ b/example/README.md @@ -70,8 +70,12 @@ Better order to solve problems ### [Binary Search](https://github.com/Barklim/leetcode-javascript/tree/master/example/4.BinarySearch) 704. Binary Search -74. Search a 2D Matrix -875. Koko Eating Bananas +- 74. Search a 2D Matrix +- 875. Koko Eating Bananas +- 153. Find Minimum in Rotated Sorted Array +- 33. Search in Rotated Sorted Array +- 981. Time Based Key-Value Store +- 4. Median of Two Sorted Arrays ### HashMap From 0f3804b5255c0bfad62842333ce7be991e128021 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Sat, 15 Mar 2025 05:41:18 +0300 Subject: [PATCH 854/872] Create 2560.js --- example/Dayly/2560.js | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 example/Dayly/2560.js diff --git a/example/Dayly/2560.js b/example/Dayly/2560.js new file mode 100644 index 00000000..94485b76 --- /dev/null +++ b/example/Dayly/2560.js @@ -0,0 +1,40 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +const minCapability = (nums, k) => { + const canStealKHouses = (capability) => { + let count = 0; + let i = 0; + while (i < nums.length) { + if (nums[i] <= capability) { + count++; + i += 2; + } else { + i++; + } + } + return count >= k; + }; + + let left = Math.min(...nums); + let right = Math.max(...nums); + + while (left < right) { + let mid = Math.floor((left + right) / 2); + if (canStealKHouses(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; +}; + +const example1 = minCapability([2,3,5,9], 2); // 5 +const example2 = minCapability([2,7,9,3,1], 2); // 2 + +console.log(example1); +console.log(example2); \ No newline at end of file From 47d644786577a9b02b294b1b19e4b73f6fd689da Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Sat, 15 Mar 2025 12:16:35 +0300 Subject: [PATCH 855/872] stack --- 2390-removing-stars-from-a-string.js | 10 +++++++++ example/5.Stack/0020.js | 24 ++++++++++++++++++++ example/5.Stack/0022.js | 10 +++++++++ example/5.Stack/0071.js | 19 ++++++++++++++++ example/5.Stack/0084.js | 17 ++++++++++++++ example/5.Stack/0150.js | 15 +++++++++++++ example/5.Stack/0739.js | 19 ++++++++++++++++ example/5.Stack/0853.js | 21 ++++++++++++++++++ example/5.Stack/0933.js | 33 ++++++++++++++++++++++++++++ example/5.Stack/1047.js | 13 +++++++++++ example/5.Stack/2390.js | 19 ++++++++++++++++ example/README.md | 17 +++++++++----- 12 files changed, 212 insertions(+), 5 deletions(-) create mode 100644 example/5.Stack/0020.js create mode 100644 example/5.Stack/0022.js create mode 100644 example/5.Stack/0071.js create mode 100644 example/5.Stack/0084.js create mode 100644 example/5.Stack/0150.js create mode 100644 example/5.Stack/0739.js create mode 100644 example/5.Stack/0853.js create mode 100644 example/5.Stack/0933.js create mode 100644 example/5.Stack/1047.js create mode 100644 example/5.Stack/2390.js diff --git a/2390-removing-stars-from-a-string.js b/2390-removing-stars-from-a-string.js index 1130802e..942a0a0c 100644 --- a/2390-removing-stars-from-a-string.js +++ b/2390-removing-stars-from-a-string.js @@ -31,3 +31,13 @@ var removeStars = function(s) { } return result.join(''); }; + +// var removeStars = function(s) { +// const stack = []; + +// for (const char of s) { +// char === '*' ? stack.pop(): stack.push(char) +// } + +// return stack.join(''); +// }; diff --git a/example/5.Stack/0020.js b/example/5.Stack/0020.js new file mode 100644 index 00000000..8484efe6 --- /dev/null +++ b/example/5.Stack/0020.js @@ -0,0 +1,24 @@ +/** + * @param {string} s + * @return {boolean} + */ +var isValid = function(s) { + +}; + +const example1 = isValid('()'); // true +const example2 = isValid('()[]{}'); // true +const example3 = isValid('(]'); // false +const example4 = isValid('([])'); // true + +const example5 = isValid('[]'); // true +const example6 = isValid('([{}])'); // true +const example7 = isValid('[(])'); // false + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); +console.log(example7); diff --git a/example/5.Stack/0022.js b/example/5.Stack/0022.js new file mode 100644 index 00000000..c3bae815 --- /dev/null +++ b/example/5.Stack/0022.js @@ -0,0 +1,10 @@ +/** + * @param {number} n + * @return {string[]} + */ +var generateParenthesis = function(n) { + +}; + +const example1 = generateParenthesis(3); // ["((()))","(()())","(())()","()(())","()()()"] +const example2 = generateParenthesis(1); // ["()"] \ No newline at end of file diff --git a/example/5.Stack/0071.js b/example/5.Stack/0071.js new file mode 100644 index 00000000..58c8b469 --- /dev/null +++ b/example/5.Stack/0071.js @@ -0,0 +1,19 @@ +/** + * @param {string} path + * @return {string} + */ +var simplifyPath = function(path) { + +}; + +const example1 = isValid("/home/"); // "/home" +const example2 = isValid("/home//foo/"); // "/home/foo" +const example3 = isValid("/home/user/Documents/../Pictures"); // "/home/user/Pictures" +const example4 = isValid("/../"); // "/" +const example5 = isValid("/.../a/../b/c/../d/./"); // "/.../b/d" + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); diff --git a/example/5.Stack/0084.js b/example/5.Stack/0084.js new file mode 100644 index 00000000..1efaa070 --- /dev/null +++ b/example/5.Stack/0084.js @@ -0,0 +1,17 @@ +/** + * @param {number[]} heights + * @return {number} + */ +var largestRectangleArea = function(heights) { + +}; + +const example1 = isValid([2,1,5,6,2,3]); // 10 +const example2 = isValid([2,4]); // 4 +const example3 = isValid([7,1,7,2,2,4]); // 8 +const example4 = isValid([1,3,7]); // 7 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/5.Stack/0150.js b/example/5.Stack/0150.js new file mode 100644 index 00000000..970d0d18 --- /dev/null +++ b/example/5.Stack/0150.js @@ -0,0 +1,15 @@ +/** + * @param {string[]} tokens + * @return {number} + */ +var evalRPN = function(tokens) { + +}; + +const example1 = evalRPN(["2","1","+","3","*"]); // 9 +const example2 = evalRPN(["4","13","5","/","+"]); // 6 +const example3 = evalRPN(["10","6","9","3","+","-11","*","/","*","17","+","5","+"]); // 22 + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file diff --git a/example/5.Stack/0739.js b/example/5.Stack/0739.js new file mode 100644 index 00000000..4557cdfb --- /dev/null +++ b/example/5.Stack/0739.js @@ -0,0 +1,19 @@ +/** + * @param {number[]} temperatures + * @return {number[]} + */ +var dailyTemperatures = function(temperatures) { + +}; + +const example1 = dailyTemperatures([73,74,75,71,69,72,76,73]); // [1,1,4,2,1,1,0,0] +const example2 = dailyTemperatures([30,40,50,60]); // [1,1,1,0] +const example3 = dailyTemperatures([30,60,90]); // [1,1,0] +const example4 = dailyTemperatures([30,38,30,36,35,40,28]); // [1,4,1,2,1,0,0] +const example5 = dailyTemperatures([22,21,20]); // [0,0,0] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); diff --git a/example/5.Stack/0853.js b/example/5.Stack/0853.js new file mode 100644 index 00000000..767f2653 --- /dev/null +++ b/example/5.Stack/0853.js @@ -0,0 +1,21 @@ +/** + * @param {number} target + * @param {number[]} position + * @param {number[]} speed + * @return {number} + */ +var carFleet = function(target, position, speed) { + +}; + +const example1 = carFleet(12, [10,8,0,5,3], [2,4,1,1,3]); // 3 +const example2 = carFleet(10, [3], [3]); // 1 +const example3 = carFleet(100, [0,2,4], [4,2,1]); // 1 +const example4 = carFleet(10, [1,4], [3,2]); // 1 +const example5 = carFleet(10, [4,1,0,7], [2,2,1,1]); // 3 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); \ No newline at end of file diff --git a/example/5.Stack/0933.js b/example/5.Stack/0933.js new file mode 100644 index 00000000..4e32a4b8 --- /dev/null +++ b/example/5.Stack/0933.js @@ -0,0 +1,33 @@ +var RecentCounter = function() { + +}; + +/** + * @param {number} t + * @return {number} + */ +RecentCounter.prototype.ping = function(t) { + +}; + +var obj = new RecentCounter() +var param_1 = obj.ping(1) + +console.log(param_1); // 1 +console.log(obj.ping(3001)); // 2 +console.log(obj.ping()); // 3 + +function callPingMultipleTimes(obj, times, start = 1, step = 1) { + let results = []; + let t = start; + + for (let i = 0; i < times; i++) { + results.push(obj.ping(t)); + t += step; + } + + return results; +} + +var obj = new RecentCounter(); +console.log(callPingMultipleTimes(obj, 500, 1, 1000)); diff --git a/example/5.Stack/1047.js b/example/5.Stack/1047.js new file mode 100644 index 00000000..ac769944 --- /dev/null +++ b/example/5.Stack/1047.js @@ -0,0 +1,13 @@ +/** + * @param {string} s + * @return {string} + */ +var removeDuplicates = function(s) { + +}; + +const example1 = removeDuplicates('abbaca'); // "ca" +const example2 = removeDuplicates('azxxzy'); // "ay" + +console.log(example1); +console.log(example2); diff --git a/example/5.Stack/2390.js b/example/5.Stack/2390.js new file mode 100644 index 00000000..96852239 --- /dev/null +++ b/example/5.Stack/2390.js @@ -0,0 +1,19 @@ +/** + * @param {string} s + * @return {string} + */ +var removeStars = function(s) { + const stack = []; + + for (const char of s) { + char === '*' ? stack.pop(): stack.push(char) + } + + return stack.join(''); +}; + +const example1 = removeStars('leet**cod*e'); // 'lecoe' +const example2 = removeStars('erase*****'); // '' + +console.log(example1); +console.log(example2); diff --git a/example/README.md b/example/README.md index 0efdc4ac..68988f79 100644 --- a/example/README.md +++ b/example/README.md @@ -42,8 +42,8 @@ Better order to solve problems 904. Fruit Into Baskets 0. 121. Best Time to Buy and Sell Stock -- 424. Longest Repeating Character Replacement -- 567. Permutation in String +424. Longest Repeating Character Replacement +567. Permutation in String - 76. Minimum Window Substring - 239. Sliding Window Maximum @@ -62,8 +62,8 @@ Better order to solve problems 0. 143. Reorder List - 138. Copy List with Random Pointer -- 2. Add Two Numbers -- 287. Find the Duplicate Number +2. Add Two Numbers +287. Find the Duplicate Number - 23. Merge k Sorted Lists - 25. Reverse Nodes in k-Group @@ -85,13 +85,20 @@ Better order to solve problems 146. LRU Cache -### Stack, Queue +### [Stack, Queue](https://github.com/Barklim/leetcode-javascript/tree/master/example/5.Stack) 20. Valid Parentheses 1047. Remove All Adjacent duplicates in String 2390. Removing Stars From a string 71. Simplify Path 933. Number of Recent Calls +0. +155. Min Stack +150. Evaluate Reverse Polish Notation +22. Generate Parentheses +739. Daily Temperatures +853. Car Fleet +84. Largest Rectangle in Histogram ### Binare Tree, DFS From 521ec6289c54f5c0cd8d21e0f983563739a9a56d Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Sat, 15 Mar 2025 14:23:20 +0300 Subject: [PATCH 856/872] add tree examples --- example/5.Stack/2390.js | 6 ------ example/6.Tree/0098.js | 23 +++++++++++++++++++++++ example/6.Tree/0100.js | 24 ++++++++++++++++++++++++ example/6.Tree/0101.js | 25 +++++++++++++++++++++++++ example/6.Tree/0102.js | 25 +++++++++++++++++++++++++ example/6.Tree/0103.js | 23 +++++++++++++++++++++++ example/6.Tree/0104.js | 25 +++++++++++++++++++++++++ example/6.Tree/0110.js | 27 +++++++++++++++++++++++++++ example/6.Tree/0112.js | 24 ++++++++++++++++++++++++ example/6.Tree/0117.js | 23 +++++++++++++++++++++++ example/6.Tree/0199.js | 29 +++++++++++++++++++++++++++++ example/6.Tree/0226.js | 27 +++++++++++++++++++++++++++ example/6.Tree/0236.js | 28 ++++++++++++++++++++++++++++ example/6.Tree/0515.js | 21 +++++++++++++++++++++ example/6.Tree/0543.js | 21 +++++++++++++++++++++ example/6.Tree/0700.js | 22 ++++++++++++++++++++++ example/6.Tree/0701.js | 24 ++++++++++++++++++++++++ example/6.Tree/1302.js | 21 +++++++++++++++++++++ example/6.Tree/1325.js | 24 ++++++++++++++++++++++++ example/README.md | 24 +++++++++++++++++------- 20 files changed, 453 insertions(+), 13 deletions(-) create mode 100644 example/6.Tree/0098.js create mode 100644 example/6.Tree/0100.js create mode 100644 example/6.Tree/0101.js create mode 100644 example/6.Tree/0102.js create mode 100644 example/6.Tree/0103.js create mode 100644 example/6.Tree/0104.js create mode 100644 example/6.Tree/0110.js create mode 100644 example/6.Tree/0112.js create mode 100644 example/6.Tree/0117.js create mode 100644 example/6.Tree/0199.js create mode 100644 example/6.Tree/0226.js create mode 100644 example/6.Tree/0236.js create mode 100644 example/6.Tree/0515.js create mode 100644 example/6.Tree/0543.js create mode 100644 example/6.Tree/0700.js create mode 100644 example/6.Tree/0701.js create mode 100644 example/6.Tree/1302.js create mode 100644 example/6.Tree/1325.js diff --git a/example/5.Stack/2390.js b/example/5.Stack/2390.js index 96852239..865937cf 100644 --- a/example/5.Stack/2390.js +++ b/example/5.Stack/2390.js @@ -3,13 +3,7 @@ * @return {string} */ var removeStars = function(s) { - const stack = []; - for (const char of s) { - char === '*' ? stack.pop(): stack.push(char) - } - - return stack.join(''); }; const example1 = removeStars('leet**cod*e'); // 'lecoe' diff --git a/example/6.Tree/0098.js b/example/6.Tree/0098.js new file mode 100644 index 00000000..437c2492 --- /dev/null +++ b/example/6.Tree/0098.js @@ -0,0 +1,23 @@ +/** + * 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) { + +}; + +const example1 = isValidBST(); // root = [2,1,3] // true +const example2 = isValidBST(); // root = [5,1,4,null,null,3,6] // false +const example3 = isValidBST(); // root = [1,2,3] // false + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file diff --git a/example/6.Tree/0100.js b/example/6.Tree/0100.js new file mode 100644 index 00000000..87956500 --- /dev/null +++ b/example/6.Tree/0100.js @@ -0,0 +1,24 @@ +/** + * 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 example1 = isSameTree(); // p = [1,2,3], q = [1,2,3] // true +const example2 = isSameTree(); // p = [1,2], q = [1,null,2] // false +const example3 = isSameTree(); // p = [1,2,1], q = [1,1,2] // false + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file diff --git a/example/6.Tree/0101.js b/example/6.Tree/0101.js new file mode 100644 index 00000000..5e427dc7 --- /dev/null +++ b/example/6.Tree/0101.js @@ -0,0 +1,25 @@ +/** + * 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) { + +}; + +const example1 = isSymmetric(); // [1,2,2,3,4,4,3] // true +const example2 = isSymmetric(); // [1,2,2,null,3,null,3] // false +const example3 = isSymmetric(); // [1,2,3,null,null,4] // 3 +const example4 = isSymmetric(); // [] // 0 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); \ No newline at end of file diff --git a/example/6.Tree/0102.js b/example/6.Tree/0102.js new file mode 100644 index 00000000..61889573 --- /dev/null +++ b/example/6.Tree/0102.js @@ -0,0 +1,25 @@ +/** + * 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 example1 = levelOrder(); // root = [3,9,20,null,null,15,7] // [[3],[9,20],[15,7]] +const example2 = levelOrder(); // root = [1] // [[1]] +const example3 = levelOrder(); // root = [] // [] +const example4 = levelOrder(); // root = [1,2,3,4,5,6,7] // [[1],[2,3],[4,5,6,7]] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); \ No newline at end of file diff --git a/example/6.Tree/0103.js b/example/6.Tree/0103.js new file mode 100644 index 00000000..fb419726 --- /dev/null +++ b/example/6.Tree/0103.js @@ -0,0 +1,23 @@ +/** + * 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 example1 = zigzagLevelOrder(); // root = [3,9,20,null,null,15,7] // [[3],[20,9],[15,7]] +const example2 = zigzagLevelOrder(); // root = [[1] // [[1]] +const example3 = zigzagLevelOrder(); // root = [] // [] + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file diff --git a/example/6.Tree/0104.js b/example/6.Tree/0104.js new file mode 100644 index 00000000..1357a968 --- /dev/null +++ b/example/6.Tree/0104.js @@ -0,0 +1,25 @@ +/** + * 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) { + +}; + +const example1 = maxDepth(); // [3,9,20,null,null,15,7] // 3 +const example2 = maxDepth(); // [1,null,2] // 2 +const example3 = maxDepth(); // [1,2,3,null,null,4] // 3 +const example4 = maxDepth(); // [] // 0 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); \ No newline at end of file diff --git a/example/6.Tree/0110.js b/example/6.Tree/0110.js new file mode 100644 index 00000000..315053cc --- /dev/null +++ b/example/6.Tree/0110.js @@ -0,0 +1,27 @@ +/** + * 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) { + +}; + +const example1 = isBalanced(); // root = [3,9,20,null,null,15,7] // true +const example2 = isBalanced(); // root = [1,2,2,3,3,null,null,4,4] // false +const example3 = isBalanced(); // root = [] // true +const example4 = isBalanced(); // root = [1,2,3,null,null,4] // true +const example5 = isBalanced(); // root = [1,2,3,null,null,4,null,5] // false + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); \ No newline at end of file diff --git a/example/6.Tree/0112.js b/example/6.Tree/0112.js new file mode 100644 index 00000000..990ff17a --- /dev/null +++ b/example/6.Tree/0112.js @@ -0,0 +1,24 @@ +/** + * 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) { + +}; + +const example1 = hasPathSum(); // root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 // true +const example2 = hasPathSum(); // root = [1,2,3], targetSum = 5 // false +const example3 = hasPathSum(); // root = [], targetSum = 0 // false + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file diff --git a/example/6.Tree/0117.js b/example/6.Tree/0117.js new file mode 100644 index 00000000..cdc5c394 --- /dev/null +++ b/example/6.Tree/0117.js @@ -0,0 +1,23 @@ +/** + * // 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 example1 = connect(); // root = [1,2,3,4,5,null,7] // [1,#,2,3,#,4,5,7,#] +const example2 = connect(); // root = [] // [] + +console.log(example1); +console.log(example2); \ No newline at end of file diff --git a/example/6.Tree/0199.js b/example/6.Tree/0199.js new file mode 100644 index 00000000..d76de689 --- /dev/null +++ b/example/6.Tree/0199.js @@ -0,0 +1,29 @@ +/** + * 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) { + +}; + +const example1 = rightSideView(); // [1,2,3,null,5,null,4] // [1,3,4] +const example2 = rightSideView(); // root = [1,2,3,4,null,null,null,5] // [1,3,4,5] +const example3 = rightSideView(); // root = [1,null,3] // [1,3] +const example4 = rightSideView(); // root = [] // [] +const example5 = rightSideView(); // root = [1,2,3] // [1,3] +const example6 = rightSideView(); // root = [1,2,3,4,5,6,7] // [1,3,7] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); \ No newline at end of file diff --git a/example/6.Tree/0226.js b/example/6.Tree/0226.js new file mode 100644 index 00000000..83113aed --- /dev/null +++ b/example/6.Tree/0226.js @@ -0,0 +1,27 @@ +/** + * 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 invertTree = function(root) { + +}; + +const example1 = invertTree(); // [4,2,7,1,3,6,9] //[ 4,7,2,9,6,3,1] +const example2 = invertTree(); // [2,1,3] // [2,3,1] +const example3 = invertTree(); // [] // [] +const example4 = invertTree(); // [1,2,3,4,5,6,7] // [1,3,2,7,6,5,4] +const example5 = invertTree(); // [3,2,1] // [3,1,2] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); \ No newline at end of file diff --git a/example/6.Tree/0236.js b/example/6.Tree/0236.js new file mode 100644 index 00000000..168f7bc1 --- /dev/null +++ b/example/6.Tree/0236.js @@ -0,0 +1,28 @@ +/** + * 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) { + +}; + +const example1 = lowestCommonAncestor(); // root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 // 3 +const example2 = lowestCommonAncestor(); // root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 // 5 +const example3 = lowestCommonAncestor(); // root = [1,2], p = 1, q = 2 // 1 +const example4 = lowestCommonAncestor(); // root = [5,3,8,1,4,7,9,null,2], p = 3, q = 8 // 5 +const example5 = lowestCommonAncestor(); // root = [5,3,8,1,4,7,9,null,2], p = 3, q = 4 // 3 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); \ No newline at end of file diff --git a/example/6.Tree/0515.js b/example/6.Tree/0515.js new file mode 100644 index 00000000..f5ced128 --- /dev/null +++ b/example/6.Tree/0515.js @@ -0,0 +1,21 @@ +/** + * 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) { + +}; + +const example1 = largestValues(); // root = [1,3,2,5,3,null,9] // [1,3,9] +const example2 = largestValues(); // root = [1,2,3] // [1,3] + +console.log(example1); +console.log(example2); \ No newline at end of file diff --git a/example/6.Tree/0543.js b/example/6.Tree/0543.js new file mode 100644 index 00000000..4c1ebd85 --- /dev/null +++ b/example/6.Tree/0543.js @@ -0,0 +1,21 @@ +/** + * 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) { + +}; + +const example1 = diameterOfBinaryTree(); // root = [1,2,3,4,5] // 3 +const example2 = diameterOfBinaryTree(); // root = [1,2] // 1 + +console.log(example1); +console.log(example2); \ No newline at end of file diff --git a/example/6.Tree/0700.js b/example/6.Tree/0700.js new file mode 100644 index 00000000..17fefb57 --- /dev/null +++ b/example/6.Tree/0700.js @@ -0,0 +1,22 @@ +/** + * 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) { + +}; + +const example1 = searchBST(); // root = [4,2,7,1,3], val = 2 // [2,1,3] +const example2 = searchBST(); // root = [4,2,7,1,3], val = 5 // [] + +console.log(example1); +console.log(example2); \ No newline at end of file diff --git a/example/6.Tree/0701.js b/example/6.Tree/0701.js new file mode 100644 index 00000000..cea39be5 --- /dev/null +++ b/example/6.Tree/0701.js @@ -0,0 +1,24 @@ +/** + * 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) { + +}; + +const example1 = insertIntoBST(); // root = [4,2,7,1,3], val = 5 // [4,2,7,1,3,5] +const example2 = insertIntoBST(); // root = [40,20,60,10,30,50,70], val = 25 // [40,20,60,10,30,50,70,null,null,25] +const example3 = insertIntoBST(); //root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 // [4,2,7,1,3,5] + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file diff --git a/example/6.Tree/1302.js b/example/6.Tree/1302.js new file mode 100644 index 00000000..d41df5f8 --- /dev/null +++ b/example/6.Tree/1302.js @@ -0,0 +1,21 @@ +/** + * 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 deepestLeavesSum = function(root) { + +}; + +const example1 = isValidBST(); // root = [1,2,3,4,5,null,6,7,null,null,null,null,8] // 15 +const example2 = isValidBST(); // root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] // 19 + +console.log(example1); +console.log(example2); \ No newline at end of file diff --git a/example/6.Tree/1325.js b/example/6.Tree/1325.js new file mode 100644 index 00000000..ecdf7354 --- /dev/null +++ b/example/6.Tree/1325.js @@ -0,0 +1,24 @@ +/** + * 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} target + * @return {TreeNode} + */ +var removeLeafNodes = function(root, target) { + +}; + +const example1 = removeLeafNodes(); // root = [1,2,3,2,null,2,4], target = 2 // [1,null,3,null,4] +const example2 = removeLeafNodes(); // root = [1,3,3,3,2], target = 3 // [1,3,null,null,2] +const example3 = removeLeafNodes(); // root = [1,2,null,2,null,2], target = 2 // [1] + +console.log(example1); +console.log(example2); +console.log(example3); \ No newline at end of file diff --git a/example/README.md b/example/README.md index 68988f79..a191fc45 100644 --- a/example/README.md +++ b/example/README.md @@ -91,16 +91,16 @@ Better order to solve problems 1047. Remove All Adjacent duplicates in String 2390. Removing Stars From a string 71. Simplify Path -933. Number of Recent Calls +- 933. Number of Recent Calls 0. -155. Min Stack -150. Evaluate Reverse Polish Notation +- 155. Min Stack +- 150. Evaluate Reverse Polish Notation 22. Generate Parentheses -739. Daily Temperatures -853. Car Fleet -84. Largest Rectangle in Histogram +- 739. Daily Temperatures +- 853. Car Fleet +- 84. Largest Rectangle in Histogram -### Binare Tree, DFS +### [Binare Tree, DFS](https://github.com/Barklim/leetcode-javascript/tree/master/example/6.Tree) 104. Maximum Depth of Binary Tree 226. Invert Binary Tree @@ -126,11 +126,21 @@ Better order to solve problems 543. Diameter of Binary Tree (104 task) 103. Binary Tree Zigzag level Order Traversal 236. Lowest Common Ancestor of a Binary tree +0. +572. Subtree of Another Tree +1448. Count Good Nodes in Binary Tree +230. Kth Smallest Element in a BST +105. Construct Binary Tree from Preorder and Inorder Traversal +124. Binary Tree Maximum Path Sum +297. Serialize and Deserialize Binary Tree ### Trie, Autocomplete 208. Implement trie 1268. Search suggestion system +0. +211. Design Add and Search Words Data Structure +212. Word Search II ### Heap Pt.1 From 0276071783b95c39cda41129f5604cc752bd6d51 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Sat, 15 Mar 2025 14:32:47 +0300 Subject: [PATCH 857/872] add tries examples --- example/7.Tries/0208.js | 36 ++++++++++++++++++++++++++++++++++++ example/7.Tries/0211.js | 27 +++++++++++++++++++++++++++ example/7.Tries/0212.js | 15 +++++++++++++++ example/7.Tries/1268.js | 15 +++++++++++++++ example/README.md | 2 +- 5 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 example/7.Tries/0208.js create mode 100644 example/7.Tries/0211.js create mode 100644 example/7.Tries/0212.js create mode 100644 example/7.Tries/1268.js diff --git a/example/7.Tries/0208.js b/example/7.Tries/0208.js new file mode 100644 index 00000000..f2b7b98c --- /dev/null +++ b/example/7.Tries/0208.js @@ -0,0 +1,36 @@ + +var Trie = function() { + +}; + +/** + * @param {string} word + * @return {void} + */ +Trie.prototype.insert = function(word) { + +}; + +/** + * @param {string} word + * @return {boolean} + */ +Trie.prototype.search = function(word) { + +}; + +/** + * @param {string} prefix + * @return {boolean} + */ +Trie.prototype.startsWith = function(prefix) { + +}; + +/** + * Your Trie object will be instantiated and called as such: + * var obj = new Trie() + * obj.insert(word) + * var param_2 = obj.search(word) + * var param_3 = obj.startsWith(prefix) + */ \ No newline at end of file diff --git a/example/7.Tries/0211.js b/example/7.Tries/0211.js new file mode 100644 index 00000000..b0f4036b --- /dev/null +++ b/example/7.Tries/0211.js @@ -0,0 +1,27 @@ + +var WordDictionary = function() { + +}; + +/** + * @param {string} word + * @return {void} + */ +WordDictionary.prototype.addWord = function(word) { + +}; + +/** + * @param {string} word + * @return {boolean} + */ +WordDictionary.prototype.search = function(word) { + +}; + +/** + * Your WordDictionary object will be instantiated and called as such: + * var obj = new WordDictionary() + * obj.addWord(word) + * var param_2 = obj.search(word) + */ \ No newline at end of file diff --git a/example/7.Tries/0212.js b/example/7.Tries/0212.js new file mode 100644 index 00000000..e4ec0175 --- /dev/null +++ b/example/7.Tries/0212.js @@ -0,0 +1,15 @@ +/** + * @param {character[][]} board + * @param {string[]} words + * @return {string[]} + */ +var findWords = function(board, words) { + +}; + +const example1 = suggestedProducts([["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], ["oath","pea","eat","rain"]); // ["eat","oath"] +const example2 = suggestedProducts([["a","b"],["c","d"]], ["abcb"]); // [] + +console.log(example1); +console.log(example2); + diff --git a/example/7.Tries/1268.js b/example/7.Tries/1268.js new file mode 100644 index 00000000..cb3066a0 --- /dev/null +++ b/example/7.Tries/1268.js @@ -0,0 +1,15 @@ +/** + * @param {string[]} products + * @param {string} searchWord + * @return {string[][]} + */ +var suggestedProducts = function(products, searchWord) { + +}; + +const example1 = suggestedProducts(["mobile","mouse","moneypot","monitor","mousepad"], "mouse"); // [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]] +const example2 = suggestedProducts(["havana"], "havana"); // [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]] + +console.log(example1); +console.log(example2); + diff --git a/example/README.md b/example/README.md index a191fc45..177966d7 100644 --- a/example/README.md +++ b/example/README.md @@ -134,7 +134,7 @@ Better order to solve problems 124. Binary Tree Maximum Path Sum 297. Serialize and Deserialize Binary Tree -### Trie, Autocomplete +### [Trie, Autocomplete](https://github.com/Barklim/leetcode-javascript/tree/master/example/7.Tries) 208. Implement trie 1268. Search suggestion system From c5cbab8c43e291280de73dd646e492fc3b28949e Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Sun, 16 Mar 2025 11:15:47 +0300 Subject: [PATCH 858/872] Create 2594.js --- example/Dayly/2594.js | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 example/Dayly/2594.js diff --git a/example/Dayly/2594.js b/example/Dayly/2594.js new file mode 100644 index 00000000..4a052a91 --- /dev/null +++ b/example/Dayly/2594.js @@ -0,0 +1,40 @@ +/** + * @param {number[]} ranks + * @param {number} cars + * @return {number} + */ +var repairCars = function(ranks, cars) { + +}; + +const example1 = repairCars([4,2,3,1], 10); // 16 +const example2 = repairCars([5,1,8], 6); // 16 + +console.log(example1); +console.log(example2); + +// var repairCars = function(ranks, cars) { +// let left = 1 +// let right = Math.max(...ranks)*cars*cars + +// var canRepairAll = function(time) { +// let totalCarsRepaired = 0 +// for (let rank of ranks) { +// totalCarsRepaired += Math.floor(Math.sqrt(time/rank)) +// if (totalCarsRepaired >= cars) return true +// } +// return false +// } + +// while (left < right) { +// let mid = Math.floor((left + right)/2) + +// if (canRepairAll(mid)) { +// right = mid +// } else { +// left = mid + 1 +// } +// } + +// return left +// }; \ No newline at end of file From f96350b732bd1472f5ac4f453f794fae4cc95a5c Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Sun, 16 Mar 2025 11:58:15 +0300 Subject: [PATCH 859/872] add heap examples --- example/8.Heap/0023.js | 23 +++++++++++++++ example/8.Heap/0215.js | 18 ++++++++++++ example/8.Heap/0295.js | 34 +++++++++++++++++++++ example/8.Heap/0347.js | 17 +++++++++++ example/8.Heap/0355.js | 67 ++++++++++++++++++++++++++++++++++++++++++ example/8.Heap/0451.js | 15 ++++++++++ example/8.Heap/0502.js | 16 ++++++++++ example/8.Heap/0621.js | 20 +++++++++++++ example/8.Heap/0642.js | 1 + example/8.Heap/0703.js | 31 +++++++++++++++++++ example/8.Heap/0973.js | 18 ++++++++++++ example/8.Heap/1046.js | 17 +++++++++++ example/8.Heap/1962.js | 14 +++++++++ example/README.md | 2 +- 14 files changed, 292 insertions(+), 1 deletion(-) create mode 100644 example/8.Heap/0023.js create mode 100644 example/8.Heap/0215.js create mode 100644 example/8.Heap/0295.js create mode 100644 example/8.Heap/0347.js create mode 100644 example/8.Heap/0355.js create mode 100644 example/8.Heap/0451.js create mode 100644 example/8.Heap/0502.js create mode 100644 example/8.Heap/0621.js create mode 100644 example/8.Heap/0642.js create mode 100644 example/8.Heap/0703.js create mode 100644 example/8.Heap/0973.js create mode 100644 example/8.Heap/1046.js create mode 100644 example/8.Heap/1962.js diff --git a/example/8.Heap/0023.js b/example/8.Heap/0023.js new file mode 100644 index 00000000..c057f5f6 --- /dev/null +++ b/example/8.Heap/0023.js @@ -0,0 +1,23 @@ +/** + * 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 example1 = mergeKLists([[1,4,5],[1,3,4],[2,6]]); // 1,1,2,3,4,4,5,6] +const example2 = mergeKLists([]); // [] +const example3 = mergeKLists([[]]); // [] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/8.Heap/0215.js b/example/8.Heap/0215.js new file mode 100644 index 00000000..971883b6 --- /dev/null +++ b/example/8.Heap/0215.js @@ -0,0 +1,18 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var findKthLargest = function(nums, k) { + +}; + +const example1 = findKthLargest([3,2,1,5,6,4], 2); // 5 +const example2 = findKthLargest([3,2,3,1,2,4,5,5,6], 4); // 4 +const example3 = findKthLargest([2,3,1,5,4], 2); // 4 +const example4 = findKthLargest([2,3,1,1,5,5,4], 3); // 4 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/8.Heap/0295.js b/example/8.Heap/0295.js new file mode 100644 index 00000000..a9a5394f --- /dev/null +++ b/example/8.Heap/0295.js @@ -0,0 +1,34 @@ + +var MedianFinder = function() { + +}; + +/** + * @param {number} num + * @return {void} + */ +MedianFinder.prototype.addNum = function(num) { + +}; + +/** + * @return {number} + */ +MedianFinder.prototype.findMedian = function() { + +}; + +const medianFinder = new MedianFinder(); +medianFinder.addNum(1); // arr = [1] +medianFinder.addNum(2); // arr = [1, 2] +medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) +medianFinder.addNum(3); // arr[1, 2, 3] +medianFinder.findMedian(); // return 2.0 + +const medianFinder2 = new MedianFinder(); +medianFinder2.addNum(1); // arr = [1] +medianFinder2.findMedian(); // return 1.0 +medianFinder2.addNum(3); // arr = [1, 3] +medianFinder2.findMedian(); // return 2.0 +medianFinder2.addNum(2); // arr[1, 2, 3] +medianFinder2.findMedian(); // return 2.0 diff --git a/example/8.Heap/0347.js b/example/8.Heap/0347.js new file mode 100644 index 00000000..20d78459 --- /dev/null +++ b/example/8.Heap/0347.js @@ -0,0 +1,17 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = function(nums, k) { + +}; + + +const example1 = topKFrequent([1, 1, 1, 2, 2, 3], 2); // [1,2] +const example2 = topKFrequent([1], 1); // [1] +const example3 = topKFrequent([3, 3, 5, 5, 5, 6], 2); // [3, 5] + +console.log(example1); +console.log(example2); +console.log(example3); diff --git a/example/8.Heap/0355.js b/example/8.Heap/0355.js new file mode 100644 index 00000000..61215a67 --- /dev/null +++ b/example/8.Heap/0355.js @@ -0,0 +1,67 @@ +var Twitter = function() { + +}; + +/** + * @param {number} userId + * @param {number} tweetId + * @return {void} + */ +Twitter.prototype.postTweet = function(userId, tweetId) { + +}; + +/** + * @param {number} userId + * @return {number[]} + */ +Twitter.prototype.getNewsFeed = function(userId) { + +}; + +/** + * @param {number} followerId + * @param {number} followeeId + * @return {void} + */ +Twitter.prototype.follow = function(followerId, followeeId) { + +}; + +/** + * @param {number} followerId + * @param {number} followeeId + * @return {void} + */ +Twitter.prototype.unfollow = function(followerId, followeeId) { + +}; + +/** + * Your Twitter object will be instantiated and called as such: + * var obj = new Twitter() + * obj.postTweet(userId,tweetId) + * var param_2 = obj.getNewsFeed(userId) + * obj.follow(followerId,followeeId) + * obj.unfollow(followerId,followeeId) + */ + +const twitter = new Twitter(); +twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). +twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5] +twitter.follow(1, 2); // User 1 follows user 2. +twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). +twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. +twitter.unfollow(1, 2); // User 1 unfollows user 2. +twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2. + +const twitter2 = new Twitter(); +twitter2.postTweet(1, 10); // User 1 posts a new tweet with id = 10. +twitter2.postTweet(2, 20); // User 2 posts a new tweet with id = 20. +twitter2.getNewsFeed(1); // User 1's news feed should only contain their own tweets -> [10]. +twitter2.getNewsFeed(2); // User 2's news feed should only contain their own tweets -> [20]. +twitter2.follow(1, 2); // User 1 follows user 2. +twitter2.getNewsFeed(1); // User 1's news feed should contain both tweets from user 1 and user 2 -> [20, 10]. +twitter2.getNewsFeed(2); // User 2's news feed should still only contain their own tweets -> [20]. +twitter2.unfollow(1, 2); // User 1 follows user 2. +twitter2.getNewsFeed(1); // User 1's news feed should only contain their own tweets -> [10]. \ No newline at end of file diff --git a/example/8.Heap/0451.js b/example/8.Heap/0451.js new file mode 100644 index 00000000..9f620986 --- /dev/null +++ b/example/8.Heap/0451.js @@ -0,0 +1,15 @@ +/** + * @param {string} s + * @return {string} + */ +var frequencySort = function(s) { + +}; + +const example1 = frequencySort("tree"); // "eert" +const example2 = frequencySort("cccaaa"); // "aaaccc" +const example3 = frequencySort("Aabb"); // "bbAa" + +console.log(example1); +console.log(example2); +console.log(example3); diff --git a/example/8.Heap/0502.js b/example/8.Heap/0502.js new file mode 100644 index 00000000..06d45854 --- /dev/null +++ b/example/8.Heap/0502.js @@ -0,0 +1,16 @@ +/** + * @param {number} k + * @param {number} w + * @param {number[]} profits + * @param {number[]} capital + * @return {number} + */ +var findMaximizedCapital = function(k, w, profits, capital) { + +}; + +const example1 = findMaximizedCapital(2, 0, [1,2,3], [0,1,1]); // 4 +const example2 = findMaximizedCapital(3, 0, [1,2,3], [0,1,2]); // 6 + +console.log(example1); +console.log(example2); \ No newline at end of file diff --git a/example/8.Heap/0621.js b/example/8.Heap/0621.js new file mode 100644 index 00000000..e47ca682 --- /dev/null +++ b/example/8.Heap/0621.js @@ -0,0 +1,20 @@ +/** + * @param {character[]} tasks + * @param {number} n + * @return {number} + */ +var leastInterval = function(tasks, n) { + +}; + +const example1 = leastInterval(["A","A","A","B","B","B"], 2); // 8 +const example2 = leastInterval(["A","C","A","B","D","B"], 1); // 6 +const example3 = leastInterval(["A","A","A", "B","B","B"], 3); // 10 +const example4 = leastInterval(["X","X","Y","Y"], 2); // 5 +const example5 = leastInterval(["A","A","A","B","C"], 3); // 9 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); diff --git a/example/8.Heap/0642.js b/example/8.Heap/0642.js new file mode 100644 index 00000000..4da6a8e2 --- /dev/null +++ b/example/8.Heap/0642.js @@ -0,0 +1 @@ +console.log(example1); \ No newline at end of file diff --git a/example/8.Heap/0703.js b/example/8.Heap/0703.js new file mode 100644 index 00000000..c5025b2a --- /dev/null +++ b/example/8.Heap/0703.js @@ -0,0 +1,31 @@ +/** + * @param {number} k + * @param {number[]} nums + */ +var KthLargest = function(k, nums) { + +}; + +/** + * @param {number} val + * @return {number} + */ +KthLargest.prototype.add = function(val) { + +}; + +var obj = new KthLargest(k, nums) +var param_1 = obj.add(val) + +const kthLargest = new KthLargest(3, [4, 5, 8, 2]); +kthLargest.add(3); // return 4 +kthLargest.add(5); // return 5 +kthLargest.add(10); // return 5 +kthLargest.add(9); // return 8 +kthLargest.add(4); // return 8 + +const kthLargest2 = new KthLargest(4, [7, 7, 7, 7, 8, 3]); +kthLargest2.add(2); // return 7 +kthLargest2.add(10); // return 7 +kthLargest2.add(9); // return 7 +kthLargest2.add(9); // return 8 diff --git a/example/8.Heap/0973.js b/example/8.Heap/0973.js new file mode 100644 index 00000000..20818eb3 --- /dev/null +++ b/example/8.Heap/0973.js @@ -0,0 +1,18 @@ +/** + * @param {number[][]} points + * @param {number} k + * @return {number[][]} + */ +var kClosest = function(points, k) { + +}; + +const example1 = kClosest([[1,3],[-2,2]], 1); // [[-2,2]] +const example2 = kClosest([[3,3],[5,-1],[-2,4]], 2); // [[3,3],[-2,4]] +const example3 = kClosest([[0,2],[2,2]], 1); // [[0,2]] +const example4 = kClosest([[0,2],[2,0],[2,2]], 2); // [[[0,2],[2,0]] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/8.Heap/1046.js b/example/8.Heap/1046.js new file mode 100644 index 00000000..7477352a --- /dev/null +++ b/example/8.Heap/1046.js @@ -0,0 +1,17 @@ +/** + * @param {number[]} stones + * @return {number} + */ +var lastStoneWeight = function(stones) { + +}; + +const example1 = lastStoneWeight([2,7,4,1,8,1]); // 1 +const example2 = lastStoneWeight([1]); // 1 +const example3 = lastStoneWeight([2,3,6,2,4]); // 1 +const example4 = lastStoneWeight([1,2]); // 1 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/8.Heap/1962.js b/example/8.Heap/1962.js new file mode 100644 index 00000000..a11e39ae --- /dev/null +++ b/example/8.Heap/1962.js @@ -0,0 +1,14 @@ +/** + * @param {number[]} piles + * @param {number} k + * @return {number} + */ +var minStoneSum = function(piles, k) { + +}; + +const example1 = minStoneSum([5,4,9], 2); // 12 +const example2 = minStoneSum([4,3,6,7], 3); // 12 + +console.log(example1); +console.log(example2); diff --git a/example/README.md b/example/README.md index 177966d7..13a29339 100644 --- a/example/README.md +++ b/example/README.md @@ -142,7 +142,7 @@ Better order to solve problems 211. Design Add and Search Words Data Structure 212. Word Search II -### Heap Pt.1 +### [Heap Pt.1]((https://github.com/Barklim/leetcode-javascript/tree/master/example/8.Heap)) 215. Kth Largest Element in an Array (минхипа максхипа) 703. Kth Largest Element in a Stream From db22a7191fc0d740c91359dbb31c6e96aff54673 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Sun, 16 Mar 2025 12:21:33 +0300 Subject: [PATCH 860/872] add intervals --- example/9.Intervals/0056.js | 17 +++++++++++++++++ example/9.Intervals/0057.js | 18 ++++++++++++++++++ example/9.Intervals/0252.js | 17 +++++++++++++++++ example/9.Intervals/0253.js | 17 +++++++++++++++++ example/9.Intervals/0435.js | 19 +++++++++++++++++++ example/9.Intervals/1851.js | 18 ++++++++++++++++++ example/README.md | 7 +++++-- 7 files changed, 111 insertions(+), 2 deletions(-) create mode 100644 example/9.Intervals/0056.js create mode 100644 example/9.Intervals/0057.js create mode 100644 example/9.Intervals/0252.js create mode 100644 example/9.Intervals/0253.js create mode 100644 example/9.Intervals/0435.js create mode 100644 example/9.Intervals/1851.js diff --git a/example/9.Intervals/0056.js b/example/9.Intervals/0056.js new file mode 100644 index 00000000..a9845157 --- /dev/null +++ b/example/9.Intervals/0056.js @@ -0,0 +1,17 @@ +/** + * @param {number[][]} intervals + * @return {number[][]} + */ +var merge = function(intervals) { + +}; + +const example1 = merge([[1,3],[2,6],[8,10],[15,18]]); // [[1,6],[8,10],[15,18]] +const example2 = merge([[1,4],[4,5]]); // [[1,5]] +const example3 = merge([[1,3],[1,5],[6,7]]); // [[1,5],[6,7]] +const example4 = merge([[1,2],[2,3]]); // [[1,3]] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/9.Intervals/0057.js b/example/9.Intervals/0057.js new file mode 100644 index 00000000..1918c08b --- /dev/null +++ b/example/9.Intervals/0057.js @@ -0,0 +1,18 @@ +/** + * @param {number[][]} intervals + * @param {number[]} newInterval + * @return {number[][]} + */ +var insert = function(intervals, newInterval) { + +}; + +const example1 = insert([[1,3],[6,9]], [2,5]); // [[1,5],[6,9]] +const example2 = insert([[1,2],[3,5],[6,7],[8,10],[12,16]], [4,8]); // [[1,2],[3,10],[12,16]] +const example3 = insert([[1,3],[4,6]], [2,5]); // [[1,6]] +const example4 = insert([[1,2],[3,5],[9,10]], [6,7]); // [[1,2],[3,5],[6,7],[9,10]] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/9.Intervals/0252.js b/example/9.Intervals/0252.js new file mode 100644 index 00000000..e8cc38f2 --- /dev/null +++ b/example/9.Intervals/0252.js @@ -0,0 +1,17 @@ +/** + * @param {Interval[]} intervals + * @returns {boolean} + */ +var canAttendMeetings = function (intervals) { + +}; + +const example1 = canAttendMeetings(); // +const example2 = canAttendMeetings(); // +const example3 = canAttendMeetings([(0,30),(5,10),(15,20)]); // false +const example4 = canAttendMeetings([(5,8),(9,15)]); // true + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/9.Intervals/0253.js b/example/9.Intervals/0253.js new file mode 100644 index 00000000..78493361 --- /dev/null +++ b/example/9.Intervals/0253.js @@ -0,0 +1,17 @@ +/** + * @param {Interval[]} intervals + * @returns {number} + */ +var minMeetingRooms = function(intervals) { + +}; + +const example1 = merge(); // [[1,6],[8,10],[15,18]] +const example2 = merge(); // [[1,5]] +const example3 = merge([(0,40),(5,10),(15,20)]); // 2 +const example4 = merge([(4,9)]); // 1 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/9.Intervals/0435.js b/example/9.Intervals/0435.js new file mode 100644 index 00000000..688fb4c1 --- /dev/null +++ b/example/9.Intervals/0435.js @@ -0,0 +1,19 @@ +/** + * @param {number[][]} intervals + * @return {number[][]} + */ +var eraseOverlapIntervals = function(intervals) { + +}; + +const example1 = eraseOverlapIntervals([[1,2],[2,3],[3,4],[1,3]]); // 1 +const example2 = eraseOverlapIntervals([[1,2],[1,2],[1,2]]); // 2 +const example3 = eraseOverlapIntervals([[1,2],[2,3]]); // 0 +const example4 = eraseOverlapIntervals([[1,2],[2,4],[1,4]]); // 1 +const example5 = eraseOverlapIntervals([[1,2],[2,4]]); // 0 + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); +console.log(example5); diff --git a/example/9.Intervals/1851.js b/example/9.Intervals/1851.js new file mode 100644 index 00000000..5ca4c146 --- /dev/null +++ b/example/9.Intervals/1851.js @@ -0,0 +1,18 @@ +/** + * @param {number[][]} intervals + * @param {number[]} queries + * @return {number[]} + */ +var minInterval = function(intervals, queries) { + +}; + +const example1 = minInterval([[1,4],[2,4],[3,6],[4,4]], [2,3,4,5]); // [3,3,1,4] +const example2 = minInterval([[2,3],[2,5],[1,8],[20,25]], [2,19,5,22]); // [2,-1,4,6] +const example3 = minInterval([[1,3],[2,3],[3,7],[6,6]], [2,3,1,7,6,8]); // [2,2,3,5,1,-1] +const example4 = minInterval([[1,2],[2,3]]); // [[1,3]] + +console.log(example1); +console.log(example2); +console.log(example3); +console.log(example4); diff --git a/example/README.md b/example/README.md index 13a29339..a70b23cd 100644 --- a/example/README.md +++ b/example/README.md @@ -142,7 +142,7 @@ Better order to solve problems 211. Design Add and Search Words Data Structure 212. Word Search II -### [Heap Pt.1]((https://github.com/Barklim/leetcode-javascript/tree/master/example/8.Heap)) +### [Heap Pt.1](https://github.com/Barklim/leetcode-javascript/tree/master/example/8.Heap) 215. Kth Largest Element in an Array (минхипа максхипа) 703. Kth Largest Element in a Stream @@ -158,12 +158,15 @@ Better order to solve problems 23. Merge k sorted Lists 642. Design Search Autocomplete System -### Intervals +### [Intervals](https://github.com/Barklim/leetcode-javascript/tree/master/example/9.Intervals) 252. Meeting Rooms (сортировать по дате начала митинга) 56. Merge Intervals 57. Insert Intervals 253. Meeting Rooms ii +0. +435. Non-overlapping Intervals +1851. Minimum Interval to Include Each Query ### Graphs Workshop From 3237c5ea65ee9de41675f8cfa7502dfc0d1fbd45 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Mon, 17 Mar 2025 01:11:32 +0300 Subject: [PATCH 861/872] Create 0045.js --- example/3.Linkedlist/0445.js | 56 ++++++++++++++++++++++++++++++++++++ example/5.Stack/0071.js | 10 +++---- example/README.md | 11 +++++-- 3 files changed, 70 insertions(+), 7 deletions(-) create mode 100644 example/3.Linkedlist/0445.js diff --git a/example/3.Linkedlist/0445.js b/example/3.Linkedlist/0445.js new file mode 100644 index 00000000..097daa83 --- /dev/null +++ b/example/3.Linkedlist/0445.js @@ -0,0 +1,56 @@ +/** + * 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 myLinkedList = new LinkedList(); +myLinkedList.prepend(7); +myLinkedList.append(2); +myLinkedList.append(4); +myLinkedList.append(3); + +const myLinkedList2 = new LinkedList(); +myLinkedList2.prepend(5); +myLinkedList2.append(6); +myLinkedList2.append(4); + +const myLinkedList3 = new LinkedList(); +myLinkedList3.prepend(0); + +const myLinkedList4 = new LinkedList(); +myLinkedList4.prepend(0); + +const myLinkedList5 = new LinkedList(); +myLinkedList5.prepend(1); +myLinkedList5.append(2); +myLinkedList5.append(3); + +const myLinkedList6 = new LinkedList(); +myLinkedList6.prepend(4); +myLinkedList6.append(5); +myLinkedList6.append(6); + +const executeList = (l1, l2) => addTwoNumbers(l1.head, l2.head) + +const execute = (l1, l2) => { + console.log('travers') + console.log(l1.toString()); + console.log(l2.toString()); + const list1 = executeList(l1, l2) + console.log(traversList(list1)) +} + +execute(myLinkedList, myLinkedList2) // [7,2,4,3] [5,6,4] // [7,8,0,7] +execute(myLinkedList3, myLinkedList4) // [0] [0] // [0] ??? +execute(myLinkedList5, myLinkedList6) // [1,2,3] [4,5,6] // [5,7,9] \ No newline at end of file diff --git a/example/5.Stack/0071.js b/example/5.Stack/0071.js index 58c8b469..1b683439 100644 --- a/example/5.Stack/0071.js +++ b/example/5.Stack/0071.js @@ -6,11 +6,11 @@ var simplifyPath = function(path) { }; -const example1 = isValid("/home/"); // "/home" -const example2 = isValid("/home//foo/"); // "/home/foo" -const example3 = isValid("/home/user/Documents/../Pictures"); // "/home/user/Pictures" -const example4 = isValid("/../"); // "/" -const example5 = isValid("/.../a/../b/c/../d/./"); // "/.../b/d" +const example1 = simplifyPath("/home/"); // "/home" +const example2 = simplifyPath("/home//foo/"); // "/home/foo" +const example3 = simplifyPath("/home/user/Documents/../Pictures"); // "/home/user/Pictures" +const example4 = simplifyPath("/../"); // "/" +const example5 = simplifyPath("/.../a/../b/c/../d/./"); // "/.../b/d" console.log(example1); console.log(example2); diff --git a/example/README.md b/example/README.md index a70b23cd..ffe10924 100644 --- a/example/README.md +++ b/example/README.md @@ -47,7 +47,7 @@ Better order to solve problems - 76. Minimum Window Substring - 239. Sliding Window Maximum -### [Linked list](https://github.com/Barklim/leetcode-javascript/tree/master/example/3.Linkedlist) +### [3.Linked list](https://github.com/Barklim/leetcode-javascript/tree/master/example/3.Linkedlist) 707. Design Linked List 876. Middle of the Linked List @@ -66,8 +66,10 @@ Better order to solve problems 287. Find the Duplicate Number - 23. Merge k Sorted Lists - 25. Reverse Nodes in k-Group +1. +445. Add Two Numbers II -### [Binary Search](https://github.com/Barklim/leetcode-javascript/tree/master/example/4.BinarySearch) +### [4.Binary Search](https://github.com/Barklim/leetcode-javascript/tree/master/example/4.BinarySearch) 704. Binary Search - 74. Search a 2D Matrix @@ -237,6 +239,11 @@ Better order to solve problems 64. Minimum path sum 72. Edit Distance +### Greedy +### Advanced Graphs +### Bit Manipulation +### Math & Geometry + ## Programming skills ### [0.Basic](https://github.com/Barklim/leetcode-javascript/tree/master/example/ProgrammingSkills/0.Basic) From 5f4d920becf4ec27a0d15202163ebf637c3892b1 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Mon, 17 Mar 2025 02:09:13 +0300 Subject: [PATCH 862/872] Create 1572.js --- .../ProgrammingSkills/1.Simulation/1572.js | 27 +++++++++++++++++++ example/README.md | 3 ++- 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 example/ProgrammingSkills/1.Simulation/1572.js diff --git a/example/ProgrammingSkills/1.Simulation/1572.js b/example/ProgrammingSkills/1.Simulation/1572.js new file mode 100644 index 00000000..dd72e23d --- /dev/null +++ b/example/ProgrammingSkills/1.Simulation/1572.js @@ -0,0 +1,27 @@ +/** + * @param {string} s + * @return {number} + */ +var diagonalSum = function(mat) { + +}; + +const example1 = diagonalSum([[1,2,3],[4,5,6],[7,8,9]]); // 25 +const example2 = diagonalSum([[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]); // 8 + +console.log(example1); +console.log(example2); + +// var diagonalSum = function(mat) { +// let n = mat.length; +// let row = 0; + +// const lambda = (sum, vec) => { +// sum += vec[row]; +// if (row !== n - row - 1) sum += vec[n - row - 1]; +// row++; +// return sum; +// }; + +// return mat.reduce(lambda, 0); +// }; \ No newline at end of file diff --git a/example/README.md b/example/README.md index ffe10924..45650e8f 100644 --- a/example/README.md +++ b/example/README.md @@ -257,4 +257,5 @@ Better order to solve problems ### [0.Basic](https://github.com/Barklim/leetcode-javascript/tree/master/example/ProgrammingSkills/1.Simulation) 58. Length of Last Word -1041. Robot Bounded In Circle \ No newline at end of file +1041. Robot Bounded In Circle +1572. Matrix Diagonal Sum \ No newline at end of file From 822bc797c1f6aa4cddc5d09cc671ea25103e360d Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Mon, 17 Mar 2025 04:17:47 +0300 Subject: [PATCH 863/872] add bintree implementation --- 0104-maximum-depth-of-binary-tree.js | 7 + dStructure/binTree.js | 103 +++++++++++++ dStructure/binTree2.js | 218 +++++++++++++++++++++++++++ example/6.Tree/0104.js | 19 +-- 4 files changed, 338 insertions(+), 9 deletions(-) create mode 100644 dStructure/binTree.js create mode 100644 dStructure/binTree2.js diff --git a/0104-maximum-depth-of-binary-tree.js b/0104-maximum-depth-of-binary-tree.js index 8b7858e0..388e3912 100644 --- a/0104-maximum-depth-of-binary-tree.js +++ b/0104-maximum-depth-of-binary-tree.js @@ -28,3 +28,10 @@ var maxDepth = function(root) { const [left, right] = [root.left, root.right].map(maxDepth); return 1 + Math.max(left, right); }; + +// var maxDepth = function(root) { +// if (!root) return 0; +// left = maxDepth(root.left) +// right = maxDepth(root.right) +// return 1 + Math.max(left, right); +// }; diff --git a/dStructure/binTree.js b/dStructure/binTree.js new file mode 100644 index 00000000..ccea5be2 --- /dev/null +++ b/dStructure/binTree.js @@ -0,0 +1,103 @@ +class TreeNode { + constructor(value) { + this.value = value; + this.left = null; + this.right = null + } +} + +class BinaryTree { + constructor() { + this.root = null; + } + + add(value) { + const newNode = new TreeNode(value) + if (!this.root) { + this.root = newNode; + return; + } + + let currentNode = this.root; + + while(currentNode) { + if (newNode.value < currentNode.value) { + if (!currentNode.left) { + currentNode.left = newNode; + return; + } + + currentNode = currentNode.left + } else { + if (!currentNode.right) { + currentNode.right = newNode; + return; + } + + currentNode = currentNode.right + } + + } + } + + search(value) { + let currentNode = this.root; + while (currentNode) { + if (value === currentNode.value) { + return currentNode; + } + if (value < currentNode.value) { + currentNode = currentNode.left; + } else { + currentNode = currentNode.right; + } + } + return null; + } + + print(root = this.root) { + if (!root) return true + console.log(root.value) + this.print(root.left) + this.print(root.right) + } +} + +function createTreeFromArray(arr) { + if (!arr.length || arr[0] === null) return null; + + let root = new TreeNode(arr[0]); + let queue = [root]; + let i = 1; + + while (i < arr.length) { + let current = queue.shift(); + + if (arr[i] !== null) { + current.left = new TreeNode(arr[i]); + queue.push(current.left); + } + i++; + + if (i < arr.length && arr[i] !== null) { + current.right = new TreeNode(arr[i]); + queue.push(current.right); + } + i++; + } + + return root; +} + +const myTree = new BinaryTree(); +const treeFromArray = createTreeFromArray([3,9,20,null,null,15,7]); +var myTreeStringify = JSON.stringify(treeFromArray, null, 2); + +const foundNode = myTree.search(10); + +console.log('!!! myTree'); +// console.log(myTree); +// console.log(myTree.print()); +console.log(myTreeStringify); +// console.log(foundNode); +console.log('!!!'); diff --git a/dStructure/binTree2.js b/dStructure/binTree2.js new file mode 100644 index 00000000..562d8c3c --- /dev/null +++ b/dStructure/binTree2.js @@ -0,0 +1,218 @@ +class TreeNode { + constructor(value) { + this.value = value; + this.left = null; + this.right = null + } +} + +class BinaryTree { + constructor() { + this.root = null; + } + + add(value) { + const newNode = new TreeNode(value) + if (!this.root) { + this.root = newNode; + return; + } + + let currentNode = this.root; + + while(currentNode) { + if (newNode.value < currentNode.value) { + if (!currentNode.left) { + currentNode.left = newNode; + return; + } + + currentNode = currentNode.left + } else { + if (!currentNode.right) { + currentNode.right = newNode; + return; + } + + currentNode = currentNode.right + } + + } + } + + preOrder(node, callback) { + if (!node) { + return; + } + + if (callback) { + callback(node) + } + + this.preOrder(node.left, callback); + this.preOrder(node.right, callback); + } + + inOrder(node, callback) { + if (!node) { + return; + } + + this.inOrder(node.left, callback); + if (callback) { + callback(node) + } + this.inOrder(node.right, callback); + } + + postOrder(node, callback) { + if (!node) { + return; + } + + this.postOrder(node.left, callback); + this.postOrder(node.right, callback); + if (callback) { + callback(node) + } + } + + traverseDFS(callback, method) { + if (method === 'preOrder') { + return this.preOrder(this.root, callback); + } + + if (method === 'inOrder') { + return this.inOrder(this.root, callback); + } + + if (method === 'postOrder') { + return this.postOrder(this.root, callback); + } + + } + + traverseBFS(callback) { + const queue = [this.root]; + + while(queue.length) { + const node = queue.shift(); + callback(node); + + if (node.left) { + queue.push(node.left); + } + + if (node.right) { + queue.push(node.right); + } + } + } + + search(value) { + let currentNode = this.root; + while (currentNode) { + if (value === currentNode.value) { + return currentNode; + } + if (value < currentNode.value) { + currentNode = currentNode.left; + } else { + currentNode = currentNode.right; + } + } + return null; + } + + print(root = this.root) { + if (!root) return true + console.log(root.value) + this.print(root.left) + this.print(root.right) + } +} + +function createTreeFromArray(arr) { + if (!arr.length || arr[0] === null) return null; + + let root = new TreeNode(arr[0]); + let queue = [root]; + let i = 1; + + while (i < arr.length) { + let current = queue.shift(); // Берем текущий узел + + if (arr[i] !== null) { + current.left = new TreeNode(arr[i]); + queue.push(current.left); + } + i++; + + if (i < arr.length && arr[i] !== null) { + current.right = new TreeNode(arr[i]); + queue.push(current.right); + } + i++; + } + + return root; +} + +const myTree = new BinaryTree() +myTree.add(8); +myTree.add(7); +myTree.add(9); +myTree.add(5); +myTree.add(10); +myTree.add(20); +myTree.add(6); +myTree.add(2); +myTree.add(11); + +/* + 8 + 7 9 + 5 10 +2 6 20 + 11 +*/ +var myTreeStringify = JSON.stringify(myTree, null, 2); + +// myTree.traverseDFS((node) => { +// console.log(node.value) +// }, 'preOrder') +// 8 7 5 2 6 9 10 20 11 + +// myTree.traverseDFS((node) => { +// console.log(node.value) +// }, 'inOrder') +// 2 5 6 7 8 9 10 11 20 + +// myTree.traverseDFS((node) => { +// console.log(node.value) +// }, 'postOrder') +// 2 6 5 7 11 20 10 9 8 + +// myTree.traverseBFS((node) => { +// console.log(node.value) +// }) +// 8 7 9 5 10 2 6 20 11 + +const foundNode = myTree.search(10); + +const myTree2 = new BinaryTree(); +const treeFromArray = createTreeFromArray([3,9,20,null,null,15,7]); +var myTreeStringify2 = JSON.stringify(treeFromArray, null, 2); + +// const myTree3 = new BinaryTree(); +// [3,9,20,null,null,15,7].forEach(value => myTree3.add(value)) +// var myTreeStringify3 = JSON.stringify(myTree3, null, 2); + +console.log('!!! myTree'); +// console.log(myTree); +// console.log(myTree.print()); +// console.log(myTreeStringify); +// console.log(foundNode); +console.log(myTreeStringify2); +// console.log(myTreeStringify3); +console.log('!!!'); diff --git a/example/6.Tree/0104.js b/example/6.Tree/0104.js index 1357a968..604c41a5 100644 --- a/example/6.Tree/0104.js +++ b/example/6.Tree/0104.js @@ -11,15 +11,16 @@ * @return {number} */ var maxDepth = function(root) { - + }; -const example1 = maxDepth(); // [3,9,20,null,null,15,7] // 3 -const example2 = maxDepth(); // [1,null,2] // 2 -const example3 = maxDepth(); // [1,2,3,null,null,4] // 3 -const example4 = maxDepth(); // [] // 0 +const testCases = [ + { input: [3,9,20,null,null,15,7], expected: 3 }, + { input: [1,null,2], expected: 2 }, + { input: [1,2,3,null,null,4], expected: 3 }, + { input: [], expected: 0 } +]; + +const results = testCases.map(({ input }) => maxDepth(createTreeFromArray(input))); -console.log(example1); -console.log(example2); -console.log(example3); -console.log(example4); \ No newline at end of file +console.log(results); From b144fc35c3b18598dbc7d3e9be29b563e3fa2352 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Mon, 17 Mar 2025 05:20:13 +0300 Subject: [PATCH 864/872] add inverted tree example --- 0226-invert-binary-tree.js | 23 +++++++++++++++++++++++ example/6.Tree/0226.js | 22 +++++++++++----------- 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/0226-invert-binary-tree.js b/0226-invert-binary-tree.js index 8ca433ef..940c6d95 100644 --- a/0226-invert-binary-tree.js +++ b/0226-invert-binary-tree.js @@ -21,3 +21,26 @@ var invertTree = function(node) { if (node) [node.left, node.right] = [invertTree(node.right), invertTree(node.left)]; return node; }; + +// var invertTree = function(root) { +// if (root === null) return null; + +// const node = new TreeNode(root.value); + +// node.right = invertTree(root.left); +// node.left = invertTree(root.right); + +// return node; +// }; + +// var invertTree = function(root) { +// if (root == null) return null; +// const queue = new Queue([root]); +// while (!queue.isEmpty()) { +// let node = queue.pop(); +// [node.left, node.right] = [node.right, node.left]; +// if (node.left != null) queue.push(node.left); +// if (node.right != null) queue.push(node.right); +// } +// return root; +// } diff --git a/example/6.Tree/0226.js b/example/6.Tree/0226.js index 83113aed..2fbcba37 100644 --- a/example/6.Tree/0226.js +++ b/example/6.Tree/0226.js @@ -11,17 +11,17 @@ * @return {TreeNode} */ var invertTree = function(root) { - + }; -const example1 = invertTree(); // [4,2,7,1,3,6,9] //[ 4,7,2,9,6,3,1] -const example2 = invertTree(); // [2,1,3] // [2,3,1] -const example3 = invertTree(); // [] // [] -const example4 = invertTree(); // [1,2,3,4,5,6,7] // [1,3,2,7,6,5,4] -const example5 = invertTree(); // [3,2,1] // [3,1,2] +const testCases = [ + { input: [4,2,7,1,3,6,9], expected: [ 4,7,2,9,6,3,1] }, + { input: [2,1,3], expected: [2,3,1] }, + { input: [], expected: [] }, + { input: [1,2,3,4,5,6,7], expected: [1,3,2,7,6,5,4] }, + { input: [3,2,1], expected: [3,1,2] } +]; -console.log(example1); -console.log(example2); -console.log(example3); -console.log(example4); -console.log(example5); \ No newline at end of file +const results = testCases.map(({ input }) => invertTree(createTreeFromArray(input))); +var myTreeStringify = JSON.stringify(results, null, 2); +console.log(myTreeStringify); From 16674371ca69174e61180b35ffa798d133402e96 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 18 Mar 2025 04:09:04 +0300 Subject: [PATCH 865/872] fix test cases for binary trees --- 0098-validate-binary-search-tree.js | 20 +++++++ 0101-symmetric-tree.js | 23 ++++++++ 0102-binary-tree-level-order-traversal.js | 25 +++++++++ 0110-balanced-binary-tree.js | 17 ++++++ 0112-path-sum.js | 22 ++++++++ 0700-search-in-a-binary-search-tree.js | 3 ++ dStructure/binTree.js | 65 ++++++++++++++++------- example/6.Tree/0098.js | 14 ++--- example/6.Tree/0101.js | 16 +++--- example/6.Tree/0102.js | 18 +++---- example/6.Tree/0110.js | 19 ++++--- example/6.Tree/0112.js | 15 +++--- example/6.Tree/0515.js | 35 ++++++++++-- example/6.Tree/1325.js | 31 ++++++++--- example/README.md | 8 ++- 15 files changed, 260 insertions(+), 71 deletions(-) diff --git a/0098-validate-binary-search-tree.js b/0098-validate-binary-search-tree.js index 73c8d164..864276fc 100644 --- a/0098-validate-binary-search-tree.js +++ b/0098-validate-binary-search-tree.js @@ -38,3 +38,23 @@ function traverse(root, min, max) { return traverse(root.left, min, root.val) && traverse(root.right, root.val, max); } + +// function isValidBST(root) { +// if (!root) return true; + +// let stack = [[root, -Infinity, Infinity]]; + +// while (stack.length) { +// let [node, minR, maxR] = stack.pop(); +// if (!node) continue; + +// if (node.val <= minR || node.val >= maxR) { +// return false; +// } + +// stack.push([node.left, minR, node.val]); +// stack.push([node.right, node.val, maxR]); +// } + +// return true; +// } diff --git a/0101-symmetric-tree.js b/0101-symmetric-tree.js index 548cfb75..bda84d1b 100644 --- a/0101-symmetric-tree.js +++ b/0101-symmetric-tree.js @@ -32,3 +32,26 @@ function isBalanced(a, b) { } return a.val === b.val && isBalanced(a.left, b.right) && isBalanced(a.right, b.left); } + +// Top solver not working +// function isSymmetric(root) { +// if (!root) return true; + +// let stack = [root.left, root.right]; + +// while (stack.length) { +// let right = stack.pop(); +// let left = stack.pop(); + +// if (!left && !right) continue; +// if (!left || !right) return false; +// if (left.val !== right.val) return false; + +// stack.push(left.left); +// stack.push(right.right); +// stack.push(left.right); +// stack.push(right.left); +// } + +// return true; +// } \ No newline at end of file diff --git a/0102-binary-tree-level-order-traversal.js b/0102-binary-tree-level-order-traversal.js index eb34e09b..113f00a4 100644 --- a/0102-binary-tree-level-order-traversal.js +++ b/0102-binary-tree-level-order-traversal.js @@ -38,3 +38,28 @@ function traverse(result, node, level = 0) { traverse(result, node.left, level + 1); traverse(result, node.right, level + 1); } + +// function levelOrder(root) { +// if (!root) return []; + +// let result = []; +// let queue = [root]; + +// while (queue.length) { +// let levelSize = queue.length; +// let currentLevel = []; + +// for (let i = 0; i < levelSize; i++) { +// let node = queue.shift(); +// currentLevel.push(node.val); + +// if (node.left) queue.push(node.left); +// if (node.right) queue.push(node.right); +// } + +// result.push(currentLevel); +// } + +// return result; +// } + diff --git a/0110-balanced-binary-tree.js b/0110-balanced-binary-tree.js index 2f4e7213..371361f3 100644 --- a/0110-balanced-binary-tree.js +++ b/0110-balanced-binary-tree.js @@ -28,3 +28,20 @@ function traverse(node, depth = 0) { if (!node) return depth; return Math.max(traverse(node.right, depth + 1), traverse(node.left, depth + 1)); } + +// function isBalanced(root) { +// function height(node) { +// if (!node) return 0; +// return 1 + Math.max(height(node.left), height(node.right)); +// } + +// if (!root) return true; + +// let leftH = height(root.left); +// let rightH = height(root.right); + +// if (Math.abs(leftH - rightH) > 1) return false; + +// return isBalanced(root.left) && isBalanced(root.right); +// } + diff --git a/0112-path-sum.js b/0112-path-sum.js index c4f37a2f..d02cb4c8 100644 --- a/0112-path-sum.js +++ b/0112-path-sum.js @@ -42,3 +42,25 @@ function traverse(result, node, sum = 0) { if (node.left) traverse(result, node.left, sum + node.val); if (node.right) traverse(result, node.right, sum + node.val); } + +// function hasPathSum(root, targetSum) { +// if (!root) return false; + +// let stack = [[root, 0]]; + +// while (stack.length) { +// let [node, currentSum] = stack.pop(); +// if (!node) continue; + +// currentSum += node.val; + +// if (!node.left && !node.right && currentSum === targetSum) { +// return true; +// } + +// stack.push([node.left, currentSum]); +// stack.push([node.right, currentSum]); +// } + +// return false; +// } diff --git a/0700-search-in-a-binary-search-tree.js b/0700-search-in-a-binary-search-tree.js index 3de1c309..95de17bc 100644 --- a/0700-search-in-a-binary-search-tree.js +++ b/0700-search-in-a-binary-search-tree.js @@ -32,3 +32,6 @@ var searchBST = function(root, val) { return null; }; + +// Or recursive +// searchBST(root.left, val) diff --git a/dStructure/binTree.js b/dStructure/binTree.js index ccea5be2..94398268 100644 --- a/dStructure/binTree.js +++ b/dStructure/binTree.js @@ -1,6 +1,6 @@ class TreeNode { - constructor(value) { - this.value = value; + constructor(val) { + this.val = val; this.left = null; this.right = null } @@ -11,8 +11,8 @@ class BinaryTree { this.root = null; } - add(value) { - const newNode = new TreeNode(value) + add(val) { + const newNode = new TreeNode(val) if (!this.root) { this.root = newNode; return; @@ -21,7 +21,7 @@ class BinaryTree { let currentNode = this.root; while(currentNode) { - if (newNode.value < currentNode.value) { + if (newNode.val < currentNode.val) { if (!currentNode.left) { currentNode.left = newNode; return; @@ -40,13 +40,13 @@ class BinaryTree { } } - search(value) { + search(val) { let currentNode = this.root; while (currentNode) { - if (value === currentNode.value) { + if (val === currentNode.val) { return currentNode; } - if (value < currentNode.value) { + if (val < currentNode.val) { currentNode = currentNode.left; } else { currentNode = currentNode.right; @@ -57,7 +57,7 @@ class BinaryTree { print(root = this.root) { if (!root) return true - console.log(root.value) + console.log(root.val) this.print(root.left) this.print(root.right) } @@ -89,15 +89,40 @@ function createTreeFromArray(arr) { return root; } -const myTree = new BinaryTree(); -const treeFromArray = createTreeFromArray([3,9,20,null,null,15,7]); -var myTreeStringify = JSON.stringify(treeFromArray, null, 2); +var levelOrder = function(root) { + if (!root) return []; -const foundNode = myTree.search(10); - -console.log('!!! myTree'); -// console.log(myTree); -// console.log(myTree.print()); -console.log(myTreeStringify); -// console.log(foundNode); -console.log('!!!'); + let result = []; + let queue = [root]; + + while (queue.length) { + let levelSize = queue.length; + let currentLevel = []; + + for (let i = 0; i < levelSize; i++) { + let node = queue.shift(); + currentLevel.push(node.val); + + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } + + result.push(currentLevel); + } + + return result; +}; + +// const myTree = new BinaryTree(); +// const treeFromArray = createTreeFromArray([3,9,20,null,null,15,7]); +// var myTreeStringify = JSON.stringify(treeFromArray, null, 2); + +// const foundNode = myTree.search(10); + +// console.log('!!! myTree'); +// // console.log(myTree); +// // console.log(myTree.print()); +// console.log(myTreeStringify); +// // console.log(foundNode); +// // levelOrder(createTreeFromArray([3,9,20,null,null,15,7])) +// console.log('!!!'); diff --git a/example/6.Tree/0098.js b/example/6.Tree/0098.js index 437c2492..ffb0b17c 100644 --- a/example/6.Tree/0098.js +++ b/example/6.Tree/0098.js @@ -14,10 +14,12 @@ var isValidBST = function(root) { }; -const example1 = isValidBST(); // root = [2,1,3] // true -const example2 = isValidBST(); // root = [5,1,4,null,null,3,6] // false -const example3 = isValidBST(); // root = [1,2,3] // false +const testCases = [ + { input: [2,1,3], expected: true }, + { input: [5,1,4,null,null,3,6], expected: false }, + { input: [1,2,3], expected: false }, + { input: [] , expected: true }, +]; -console.log(example1); -console.log(example2); -console.log(example3); \ No newline at end of file +const results = testCases.map(({ input }) => isValidBST(createTreeFromArray(input))); +console.log(results); \ No newline at end of file diff --git a/example/6.Tree/0101.js b/example/6.Tree/0101.js index 5e427dc7..a9e46c46 100644 --- a/example/6.Tree/0101.js +++ b/example/6.Tree/0101.js @@ -14,12 +14,12 @@ var isSymmetric = function(root) { }; -const example1 = isSymmetric(); // [1,2,2,3,4,4,3] // true -const example2 = isSymmetric(); // [1,2,2,null,3,null,3] // false -const example3 = isSymmetric(); // [1,2,3,null,null,4] // 3 -const example4 = isSymmetric(); // [] // 0 +const testCases = [ + { input: [1,2,2,3,4,4,3], expected: true }, + { input: [1,2,2,null,3,null,3], expected: false }, + { input: [1,2,3,null,null,4], expected: false }, + { input: [] , expected: true }, +]; -console.log(example1); -console.log(example2); -console.log(example3); -console.log(example4); \ No newline at end of file +const results = testCases.map(({ input }) => isSymmetric(createTreeFromArray(input))); +console.log(results); \ No newline at end of file diff --git a/example/6.Tree/0102.js b/example/6.Tree/0102.js index 61889573..ab001e76 100644 --- a/example/6.Tree/0102.js +++ b/example/6.Tree/0102.js @@ -11,15 +11,15 @@ * @return {number[][]} */ var levelOrder = function(root) { - + }; -const example1 = levelOrder(); // root = [3,9,20,null,null,15,7] // [[3],[9,20],[15,7]] -const example2 = levelOrder(); // root = [1] // [[1]] -const example3 = levelOrder(); // root = [] // [] -const example4 = levelOrder(); // root = [1,2,3,4,5,6,7] // [[1],[2,3],[4,5,6,7]] +const testCases = [ + { input: [3,9,20,null,null,15,7], expected: [[3],[9,20],[15,7]] }, + { input: [1], expected: [[1]] }, + { input: [] , expected: [] }, + { input: [1,2,3,4,5,6,7], expected: [[1],[2,3],[4,5,6,7]] } +]; -console.log(example1); -console.log(example2); -console.log(example3); -console.log(example4); \ No newline at end of file +const results = testCases.map(({ input }) => levelOrder(createTreeFromArray(input))); +console.log(results); diff --git a/example/6.Tree/0110.js b/example/6.Tree/0110.js index 315053cc..6d8ca09f 100644 --- a/example/6.Tree/0110.js +++ b/example/6.Tree/0110.js @@ -14,14 +14,13 @@ var isBalanced = function(root) { }; -const example1 = isBalanced(); // root = [3,9,20,null,null,15,7] // true -const example2 = isBalanced(); // root = [1,2,2,3,3,null,null,4,4] // false -const example3 = isBalanced(); // root = [] // true -const example4 = isBalanced(); // root = [1,2,3,null,null,4] // true -const example5 = isBalanced(); // root = [1,2,3,null,null,4,null,5] // false +const testCases = [ + { input: [3,9,20,null,null,15,7], expected: true }, + { input: [1,2,2,3,3,null,null,4,4], expected: false }, + { input: [] , expected: true }, + { input: [1,2,3,null,null,4], expected: true }, + { input: [1,2,3,null,null,4,null,5], expected: false } +]; -console.log(example1); -console.log(example2); -console.log(example3); -console.log(example4); -console.log(example5); \ No newline at end of file +const results = testCases.map(({ input }) => isBalanced(createTreeFromArray(input))); +console.log(results); \ No newline at end of file diff --git a/example/6.Tree/0112.js b/example/6.Tree/0112.js index 990ff17a..5b2ea437 100644 --- a/example/6.Tree/0112.js +++ b/example/6.Tree/0112.js @@ -13,12 +13,13 @@ */ var hasPathSum = function(root, targetSum) { -}; +}; -const example1 = hasPathSum(); // root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 // true -const example2 = hasPathSum(); // root = [1,2,3], targetSum = 5 // false -const example3 = hasPathSum(); // root = [], targetSum = 0 // false +const testCases = [ + { input: [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum: 22, expected: true }, + { input: [1,2,3], targetSum: 5, expected: false }, + { input: [] , targetSum: 0, expected: false }, +]; -console.log(example1); -console.log(example2); -console.log(example3); \ No newline at end of file +const results = testCases.map(({ input, targetSum }) => hasPathSum(createTreeFromArray(input), targetSum)); +console.log(results); \ No newline at end of file diff --git a/example/6.Tree/0515.js b/example/6.Tree/0515.js index f5ced128..5dc6eec4 100644 --- a/example/6.Tree/0515.js +++ b/example/6.Tree/0515.js @@ -14,8 +14,35 @@ var largestValues = function(root) { }; -const example1 = largestValues(); // root = [1,3,2,5,3,null,9] // [1,3,9] -const example2 = largestValues(); // root = [1,2,3] // [1,3] +const testCases = [ + { input: [1,3,2,5,3,null,9], expected: [1,3,9] }, + { input: [1,2,3], expected: [1,3] }, + { input: [] , expected: [] }, +]; -console.log(example1); -console.log(example2); \ No newline at end of file +const results = testCases.map(({ input }) => largestValues(createTreeFromArray(input))); +console.log(results); + +// function largestValues(root) { +// if (!root) return []; + +// let result = []; +// let queue = [root]; + +// while (queue.length) { +// let levelSize = queue.length; +// let levelMax = -Infinity; + +// for (let i = 0; i < levelSize; i++) { +// let node = queue.shift(); +// levelMax = Math.max(levelMax, node.val); + +// if (node.left) queue.push(node.left); +// if (node.right) queue.push(node.right); +// } + +// result.push(levelMax); +// } + +// return result; +// } \ No newline at end of file diff --git a/example/6.Tree/1325.js b/example/6.Tree/1325.js index ecdf7354..828853f1 100644 --- a/example/6.Tree/1325.js +++ b/example/6.Tree/1325.js @@ -15,10 +15,29 @@ var removeLeafNodes = function(root, target) { }; -const example1 = removeLeafNodes(); // root = [1,2,3,2,null,2,4], target = 2 // [1,null,3,null,4] -const example2 = removeLeafNodes(); // root = [1,3,3,3,2], target = 3 // [1,3,null,null,2] -const example3 = removeLeafNodes(); // root = [1,2,null,2,null,2], target = 2 // [1] +const testCases = [ + { input: [1,2,3,2,null,2,4], target: 2, expected: [1,null,3,null,4] }, + { input: [1,3,3,3,2], target: 3, expected: [1,3,null,null,2] }, + { input: [1,2,null,2,null,2], target: 2, expected: [1] }, + { input: [] , expected: [] }, +]; -console.log(example1); -console.log(example2); -console.log(example3); \ No newline at end of file +const results = testCases.map(({ input }) => removeLeafNodes(createTreeFromArray(input))); +const print = results.map(res => levelOrder(res)) + +console.log(results); +console.log(print); + +// Not working +// function removeLeafNodes(root, target) { +// if (!root) return null; + +// root.left = removeLeafNodes(root.left, target); +// root.right = removeLeafNodes(root.right, target); + +// if (!root.left && !root.right && root.val === target) { +// return null; +// } + +// return root; +// } \ No newline at end of file diff --git a/example/README.md b/example/README.md index 45650e8f..5f04b194 100644 --- a/example/README.md +++ b/example/README.md @@ -244,6 +244,12 @@ Better order to solve problems ### Bit Manipulation ### Math & Geometry +## [Blind 75 by BFE](https://www.greatfrontend.com/interviews/blind75) + +442. Find All Duplicates in an Array +9999. End of Array Reachable +9999. Maximum Sum in Contiguous Array + ## Programming skills ### [0.Basic](https://github.com/Barklim/leetcode-javascript/tree/master/example/ProgrammingSkills/0.Basic) @@ -258,4 +264,4 @@ Better order to solve problems 58. Length of Last Word 1041. Robot Bounded In Circle -1572. Matrix Diagonal Sum \ No newline at end of file +1572. Matrix Diagonal Sum From dfb704c444250f79377e2784330e44ef35f8355c Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 18 Mar 2025 23:55:55 +0300 Subject: [PATCH 866/872] add minheap examples --- 0215-kth-largest-element-in-an-array.js | 30 +++++++ 0347-top-k-frequent-elements.js | 22 +++++ 0703-kth-largest-element-in-a-stream.js | 25 ++++++ dStructure/MaxHeapAdhoc.js | 114 +++++++++++++++++++++++ dStructure/MinHeapAdhoc.js | 115 ++++++++++++++++++++++++ example/7.Tries/0208.js | 10 ++- example/8.Heap/0703.js | 12 +-- example/README.md | 83 +++++++++++++++++ 8 files changed, 405 insertions(+), 6 deletions(-) create mode 100644 dStructure/MaxHeapAdhoc.js create mode 100644 dStructure/MinHeapAdhoc.js diff --git a/0215-kth-largest-element-in-an-array.js b/0215-kth-largest-element-in-an-array.js index a41a489b..3f2558ce 100644 --- a/0215-kth-largest-element-in-an-array.js +++ b/0215-kth-largest-element-in-an-array.js @@ -16,3 +16,33 @@ var findKthLargest = function(nums, k) { return nums.sort((a, b) => a - b)[nums.length - k]; }; + +// var findKthLargest = function(nums, k) { + +// const min_heap = new MinHeapAdhoc(); + +// for (const num of nums) { +// min_heap.add(num) +// if (min_heap.heap.length > k) { +// min_heap.poll(); +// } +// } + +// return min_heap.heap[0] +// }; + + +// var findKthLargest = function(nums, k) { + +// const max_heap = new MaxHeapAdhoc(); + +// for (const num of nums) { +// max_heap.add(num) +// } + +// for (let i = 0; i < k - 1; i++) { +// max_heap.poll(); +// } + +// return max_heap.heap[0] +// }; diff --git a/0347-top-k-frequent-elements.js b/0347-top-k-frequent-elements.js index c8b6400d..f98077e5 100644 --- a/0347-top-k-frequent-elements.js +++ b/0347-top-k-frequent-elements.js @@ -52,3 +52,25 @@ var topKFrequent = function(nums, k) { // } // } // }; + +// var topKFrequent = function(nums, k) { +// const freqMap = new Map(); + +// // Подсчёт частоты элементов +// for (const num of nums) { +// freqMap.set(num, (freqMap.get(num) || 0) + 1); +// } + +// const minHeap = new MinHeapAdhoc(); + +// // Заполняем хипу +// for (const [num, freq] of freqMap.entries()) { +// minHeap.add([freq, num]); +// if (minHeap.heap.length > k) { +// minHeap.poll(); +// } +// } + +// // Извлекаем k самых частых элементов +// return minHeap.heap.map(item => item[1]); +// }; diff --git a/0703-kth-largest-element-in-a-stream.js b/0703-kth-largest-element-in-a-stream.js index d0b45129..2c245a7f 100644 --- a/0703-kth-largest-element-in-a-stream.js +++ b/0703-kth-largest-element-in-a-stream.js @@ -46,3 +46,28 @@ KthLargest.prototype.add = function(val) { return this.main.front().element; }; + +// var KthLargest = function(k, nums) { +// this.k = k; +// this.min_heap = new MinHeapAdhoc(); + +// // Добавляем элементы в хипу и оставляем только k наибольших +// for (const num of nums) { +// this.min_heap.add(num); +// if (this.min_heap.heap.length > k) { +// this.min_heap.poll(); +// } +// } +// }; + +// /** +// * @param {number} val +// * @return {number} +// */ +// KthLargest.prototype.add = function(val) { +// this.min_heap.add(val); +// if (this.min_heap.heap.length > this.k) { +// this.min_heap.poll(); +// } +// return this.min_heap.heap[0]; // k-й по величине элемент +// }; diff --git a/dStructure/MaxHeapAdhoc.js b/dStructure/MaxHeapAdhoc.js new file mode 100644 index 00000000..7028c31d --- /dev/null +++ b/dStructure/MaxHeapAdhoc.js @@ -0,0 +1,114 @@ +/** + * The minimalistic (ad hoc) version of a MaxHeap data structure that doesn't have + * external dependencies and that is easy to copy-paste and use during the + * coding interview if allowed by the interviewer (since many data + * structures in JS are missing). + */ +class MaxHeapAdhoc { + constructor(heap = []) { + this.heap = []; + heap.forEach(this.add); + } + + add(num) { + this.heap.push(num); + this.heapifyUp(); + } + + peek() { + return this.heap[0]; + } + + poll() { + if (this.heap.length === 0) return undefined; + const top = this.heap[0]; + this.heap[0] = this.heap[this.heap.length - 1]; + this.heap.pop(); + this.heapifyDown(); + return top; + } + + isEmpty() { + return this.heap.length === 0; + } + + toString() { + return this.heap.join(','); + } + + heapifyUp() { + let nodeIndex = this.heap.length - 1; + while (nodeIndex > 0) { + const parentIndex = this.getParentIndex(nodeIndex); + if (this.heap[parentIndex] >= this.heap[nodeIndex]) break; + this.swap(parentIndex, nodeIndex); + nodeIndex = parentIndex; + } + } + + heapifyDown() { + let nodeIndex = 0; + + while ( + ( + this.hasLeftChild(nodeIndex) && this.heap[nodeIndex] < this.leftChild(nodeIndex) + ) + || ( + this.hasRightChild(nodeIndex) && this.heap[nodeIndex] < this.rightChild(nodeIndex) + ) + ) { + const leftIndex = this.getLeftChildIndex(nodeIndex); + const rightIndex = this.getRightChildIndex(nodeIndex); + const left = this.leftChild(nodeIndex); + const right = this.rightChild(nodeIndex); + + if (this.hasLeftChild(nodeIndex) && this.hasRightChild(nodeIndex)) { + if (left >= right) { + this.swap(leftIndex, nodeIndex); + nodeIndex = leftIndex; + } else { + this.swap(rightIndex, nodeIndex); + nodeIndex = rightIndex; + } + } else if (this.hasLeftChild(nodeIndex)) { + this.swap(leftIndex, nodeIndex); + nodeIndex = leftIndex; + } + } + } + + getLeftChildIndex(parentIndex) { + return (2 * parentIndex) + 1; + } + + getRightChildIndex(parentIndex) { + return (2 * parentIndex) + 2; + } + + getParentIndex(childIndex) { + return Math.floor((childIndex - 1) / 2); + } + + hasLeftChild(parentIndex) { + return this.getLeftChildIndex(parentIndex) < this.heap.length; + } + + hasRightChild(parentIndex) { + return this.getRightChildIndex(parentIndex) < this.heap.length; + } + + leftChild(parentIndex) { + return this.heap[this.getLeftChildIndex(parentIndex)]; + } + + rightChild(parentIndex) { + return this.heap[this.getRightChildIndex(parentIndex)]; + } + + swap(indexOne, indexTwo) { + const tmp = this.heap[indexTwo]; + this.heap[indexTwo] = this.heap[indexOne]; + this.heap[indexOne] = tmp; + } + } + \ No newline at end of file diff --git a/dStructure/MinHeapAdhoc.js b/dStructure/MinHeapAdhoc.js new file mode 100644 index 00000000..35a64545 --- /dev/null +++ b/dStructure/MinHeapAdhoc.js @@ -0,0 +1,115 @@ +/** + * The minimalistic (ad hoc) version of a MinHeap data structure that doesn't have + * external dependencies and that is easy to copy-paste and use during the + * coding interview if allowed by the interviewer (since many data + * structures in JS are missing). + */ +class MinHeapAdhoc { + constructor(heap = []) { + this.heap = []; + heap.forEach(this.add); + } + + add(num) { + this.heap.push(num); + this.heapifyUp(); + } + + peek() { + return this.heap[0]; + } + + poll() { + if (this.heap.length === 0) return undefined; + const top = this.heap[0]; + this.heap[0] = this.heap[this.heap.length - 1]; + this.heap.pop(); + this.heapifyDown(); + return top; + } + + isEmpty() { + return this.heap.length === 0; + } + + toString() { + return this.heap.join(','); + } + + heapifyUp() { + let nodeIndex = this.heap.length - 1; + while (nodeIndex > 0) { + const parentIndex = this.getParentIndex(nodeIndex); + if (this.heap[parentIndex] <= this.heap[nodeIndex]) break; + this.swap(parentIndex, nodeIndex); + nodeIndex = parentIndex; + } + } + + heapifyDown() { + let nodeIndex = 0; + + while ( + ( + this.hasLeftChild(nodeIndex) + && this.heap[nodeIndex] > this.leftChild(nodeIndex) + ) + || ( + this.hasRightChild(nodeIndex) + && this.heap[nodeIndex] > this.rightChild(nodeIndex) + ) + ) { + const leftIndex = this.getLeftChildIndex(nodeIndex); + const rightIndex = this.getRightChildIndex(nodeIndex); + const left = this.leftChild(nodeIndex); + const right = this.rightChild(nodeIndex); + + if (this.hasLeftChild(nodeIndex) && this.hasRightChild(nodeIndex)) { + if (left <= right) { + this.swap(leftIndex, nodeIndex); + nodeIndex = leftIndex; + } else { + this.swap(rightIndex, nodeIndex); + nodeIndex = rightIndex; + } + } else if (this.hasLeftChild(nodeIndex)) { + this.swap(leftIndex, nodeIndex); + nodeIndex = leftIndex; + } + } + } + + getLeftChildIndex(parentIndex) { + return 2 * parentIndex + 1; + } + + getRightChildIndex(parentIndex) { + return 2 * parentIndex + 2; + } + + getParentIndex(childIndex) { + return Math.floor((childIndex - 1) / 2); + } + + hasLeftChild(parentIndex) { + return this.getLeftChildIndex(parentIndex) < this.heap.length; + } + + hasRightChild(parentIndex) { + return this.getRightChildIndex(parentIndex) < this.heap.length; + } + + leftChild(parentIndex) { + return this.heap[this.getLeftChildIndex(parentIndex)]; + } + + rightChild(parentIndex) { + return this.heap[this.getRightChildIndex(parentIndex)]; + } + + swap(indexOne, indexTwo) { + const tmp = this.heap[indexTwo]; + this.heap[indexTwo] = this.heap[indexOne]; + this.heap[indexOne] = tmp; + } +} \ No newline at end of file diff --git a/example/7.Tries/0208.js b/example/7.Tries/0208.js index f2b7b98c..51364c3f 100644 --- a/example/7.Tries/0208.js +++ b/example/7.Tries/0208.js @@ -33,4 +33,12 @@ Trie.prototype.startsWith = function(prefix) { * obj.insert(word) * var param_2 = obj.search(word) * var param_3 = obj.startsWith(prefix) - */ \ No newline at end of file + */ + +const trie = new Trie(); +trie.insert("apple"); +trie.search("apple"); // return True +trie.search("app"); // return False +trie.startsWith("app"); // return True +trie.insert("app"); +trie.search("app"); \ No newline at end of file diff --git a/example/8.Heap/0703.js b/example/8.Heap/0703.js index c5025b2a..dd70f97d 100644 --- a/example/8.Heap/0703.js +++ b/example/8.Heap/0703.js @@ -3,7 +3,7 @@ * @param {number[]} nums */ var KthLargest = function(k, nums) { - + }; /** @@ -11,11 +11,8 @@ var KthLargest = function(k, nums) { * @return {number} */ KthLargest.prototype.add = function(val) { - -}; -var obj = new KthLargest(k, nums) -var param_1 = obj.add(val) +}; const kthLargest = new KthLargest(3, [4, 5, 8, 2]); kthLargest.add(3); // return 4 @@ -24,8 +21,13 @@ kthLargest.add(10); // return 5 kthLargest.add(9); // return 8 kthLargest.add(4); // return 8 +console.log(kthLargest); + const kthLargest2 = new KthLargest(4, [7, 7, 7, 7, 8, 3]); kthLargest2.add(2); // return 7 kthLargest2.add(10); // return 7 kthLargest2.add(9); // return 7 kthLargest2.add(9); // return 8 + +console.log(kthLargest2); + diff --git a/example/README.md b/example/README.md index 5f04b194..5852e635 100644 --- a/example/README.md +++ b/example/README.md @@ -159,6 +159,10 @@ Better order to solve problems 1962. Remove stones to minimize the total 23. Merge k sorted Lists 642. Design Search Autocomplete System +0. +999. K Closest Points to Origin +999. Task Scheduler +999. Design Twitter ### [Intervals](https://github.com/Barklim/leetcode-javascript/tree/master/example/9.Intervals) @@ -265,3 +269,82 @@ Better order to solve problems 58. Length of Last Word 1041. Robot Bounded In Circle 1572. Matrix Diagonal Sum + +### [Strong List](structy.net) + +1. Depth-First Search (DFS) +1. 79 - Word Search +2. 200 - Number of Islands +3. 695 - Max Area of Island +4. 463 - Island Perimeter +5. 733 - Flood Fill +6. 130 - Surrounded Regions +7. 417 - Pacific Atlantic Water Flow +8. 261 - Graph Valid Tree +9. 329 - Longest Increasing Path in a Matrix +10. 688 - Knight Probability in Chessboard +11. 332 - Reconstruct Itinerary +12. 1306 - Jump Game III +2. Breadth-First Search (BFS) +1. 286 - Walls and Gates +2. 542 - 01 Matrix +3. 994 - Rotting Oranges +4. 752 - Open the Lock +5. 127 - Word Ladder +6. 934 - Shortest Bridge +7. 1466 - Reorder Routes to Make All Paths Lead to the City Zero +8. 1162 - As Far from Land as Possible +9. 815 - Bus Routes +10. 1197 - Minimum Knight Moves +11. 1091 - Shortest Path in Binary Matrix +12. 1293 - Shortest Path in a Grid with Obstacles Elimination +3. Topological Sort +1. 207 (Course Schedule) +2. 210 (Course Schedule II) +3. 1136 (Parallel Courses) +4. 310 (Minimum Height Trees) +5. 444 (Sequence Reconstruction) +6. 269 (Alien Dictionary) +7. 802 Find Eventual Safe States +8. 1203 Sort Items by Groups Respecting Dependencies +9. 1192 Critical Connections in a Network (Tarjan's Algorithm) + +4. Dijkstra's Algorithm +1. 743 - Network Delay Time +2. 1334 - Find the City With the Smallest Number of Neighbors at a Threshold Distance +3. 1514 - Path with Maximum Probability +4. 1631 - Path With Minimum Effort +5. 778 - Swim in Rising Water +6. 1786 - Number of Restricted Paths From First to Last Node +7. 787 - Cheapest Flights Within K Stops +8 882 - Reachable Nodes In Subdivided Graph +9. 1368 - Minimum Cost to Make at Least One Valid Path in a Grid +10. 1791 - Minimum Number of Refueling Stops + +5. Union-Find (Disjoint Set Union) +1. 547 - Number of Provinces +2. 684 - Redundant Connection +3. 721 - Accounts Merge +4. 1584 - Min Cost to Connect All Points +5. 990 - Satisfiability of Equality Equations +6. 1319 - Number of Operations to Make Network Connected +7. 1202 - Smallest String With Swaps +8. 1632 - Rank Transform of a Matrix + +6. Floyd-Warshall / All-Pairs Shortest Path +1. 1462 - Course Schedule IV +2. 785 (Is Graph Bipartite?) +3. 886 (Possible Bipartition) +4. 1617 (Count Subtrees With Max Distance Between Cities) +5. 1125 (Smallest Sufficient Team) + +### Prefix sum + +303. +724. 560. 304. 1314. 268. +287. 189. 896. 674. + +### Tips && Trics + +102. = 199. +100. = 101 \ No newline at end of file From 3165ba3a28ee23fb24c38f7c74c7458c2fef4ea4 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Wed, 19 Mar 2025 21:54:58 +0300 Subject: [PATCH 867/872] Create 0451.js --- 0451-sort-characters-by-frequency.js | 26 ++++++++++++++++++++++++++ example/8.Heap/0451.js | 7 +++++++ 2 files changed, 33 insertions(+) diff --git a/0451-sort-characters-by-frequency.js b/0451-sort-characters-by-frequency.js index 4c29eed3..ec9edf6b 100644 --- a/0451-sort-characters-by-frequency.js +++ b/0451-sort-characters-by-frequency.js @@ -22,3 +22,29 @@ var frequencySort = function(s) { .map(entry => entry[0].repeat(entry[1])) .join(''); }; + +// Doesno work with big string Why? +// var frequencySort = function(s) { +// const freqMap = new Map(); + +// // Подсчёт частоты символов +// for (const ch of s) { +// freqMap.set(ch, (freqMap.get(ch) || 0) + 1); +// } + +// const maxHeap = new MaxHeapAdhoc(); + +// // Заполняем макс-хипу (отрицательное значение для симуляции макс-хипы) +// for (const [ch, freq] of freqMap.entries()) { +// maxHeap.add([-freq, ch.repeat(freq)]); +// } + +// let result = ""; + +// // Извлекаем символы в порядке убывания частоты +// while (maxHeap.heap.length) { +// result += maxHeap.poll()[1]; +// } + +// return result; +// }; \ No newline at end of file diff --git a/example/8.Heap/0451.js b/example/8.Heap/0451.js index 9f620986..781b9cf7 100644 --- a/example/8.Heap/0451.js +++ b/example/8.Heap/0451.js @@ -9,7 +9,14 @@ var frequencySort = function(s) { const example1 = frequencySort("tree"); // "eert" const example2 = frequencySort("cccaaa"); // "aaaccc" const example3 = frequencySort("Aabb"); // "bbAa" +const example4 = frequencySort("BbAaCc"); // "ccbaCBA" +const example5 = frequencySort("BbAAAaaCc"); // "AAAaacbCB" +const example6 = frequencySort("BabBbBbBbbABBABBbAabbbABBaBbBabaabBbbBAAaaAbbAABaAbBBaAaaaaBABbaBbAAbBBbbABBaaBBbabAbBBAAbAbaaaBrBBaAaabAbbBbABabABaBabBBBBBaAbAaABaaaAAaAgAaAaBAbaBaBaBbbbBbABBBBaaaBbbbAbbbBaBBaAbBBbbaaaaaBbbaaAAbAABBABBaAAABBbbBbBbbBbaABBAAbBAbabbbabwBbbBArABaBBbabBaBabABABaabBBABBAabBAAaabbbbBAababAaBaaAaBbBbBAAbaBabBbabaBaaBbaabABAbbBbaBAbabABbbaAaBbAAAbBbaabBBAbbbABbaabAAAaaaBaBaaaBBABbBAbAAbaABaabbbbBBAabbbBABBbaABBAAAabaAbaBAbbaBaBbAbaAAbBaBAbAabBBbBsBabbbAaBbabAAaABAaBAAAbbaBaAbABABBBAbABABbbbBaaBaBAbABAbaaAbBbAABBbAbbAaBbabaBbABAAbAABbbAabAaAaBbBBbAAbBbaaaBAbABBbBBaCabBBabBAaBbBaAbbBAbbBaBAabBAababAaAbaAaabBBBABabaabBAAAabBAAAbBAbAaaaAbAaBaAbbAaABABBbBBAABAabaAAbBaBbAAaabbABBBABaBAabAbAAbBbAabAbaBbAbBAABAABAAAbBaaaaBabbaBABBaABbAabBaBAbAbbABAbaAAbaAAaBaabaBbBBbBABAABBABBaabBBbBBABAAaAAbbBbABBBbAabAbABbAAAbbAbABbbAbBAbabbbBBBBbAAabaabBABABaaAbaBBBBbbABbBbBABBaAbAaBBABBBabAABBBBBbBBabBaaBbaaBaBbaBbbAABbbAaaBBBbabaabBABABBBGabbBAbaBabAaAAabbbBaabBBbABBabBabbBbAbbAaBbAaAabBabBBbaBLaAbbAaaBaabAAab"); // "AAAaacbCB" console.log(example1); console.log(example2); console.log(example3); +console.log(example4); +console.log(example5); +console.log(example6); + From c4f6af247fb4a18d018c002edf2f0944947cda34 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Sun, 23 Mar 2025 04:15:23 +0300 Subject: [PATCH 868/872] Update 0074.js --- 0074-search-a-2d-matrix.js | 65 ++++++++++++++++++++++++++++++++++++++ example/README.md | 4 ++- 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/0074-search-a-2d-matrix.js b/0074-search-a-2d-matrix.js index e99f8663..1c2e4f75 100644 --- a/0074-search-a-2d-matrix.js +++ b/0074-search-a-2d-matrix.js @@ -56,3 +56,68 @@ var searchMatrix = function(matrix, target) { // } // return false; // }; + + + + +// const searchMatrix = function (matrix, target) { +// const rowIndex = findRow(); +// if (rowIndex === true) { +// return true; +// } +// if (rowIndex < 0) { +// return false; +// } + +// return findNumInRow(matrix[rowIndex]); + +// function findRow() { +// let start = 0; +// let end = matrix.length - 1; + +// while (start <= end) { +// const middle = Math.floor((start + end) / 2); +// const potentialRow = matrix[middle]; +// const firstNumInRow = potentialRow[0]; +// const lastNumInRow = potentialRow[potentialRow.length - 1]; + +// if (firstNumInRow === target || lastNumInRow === target) { +// return true; +// } + +// if (firstNumInRow < target && lastNumInRow > target) { +// return middle; +// } + +// if (target > lastNumInRow) { +// start = middle + 1; +// } else { +// end = middle - 1; +// } +// } + +// return -1; +// } + +// function findNumInRow(row) { +// let start = 0; +// let end = row.length - 1; + +// while (start <= end) { +// const middle = Math.floor((start + end) / 2); +// const potentialResult = row[middle]; + +// if (potentialResult === target) { +// return true; +// } + +// if (target > potentialResult) { +// start = middle + 1; +// } else { +// end = middle - 1; +// } +// } + +// return false; +// } +// }; diff --git a/example/README.md b/example/README.md index 5852e635..335f4fbc 100644 --- a/example/README.md +++ b/example/README.md @@ -347,4 +347,6 @@ Better order to solve problems ### Tips && Trics 102. = 199. -100. = 101 \ No newline at end of file +100. = 101 + +### Ru companies \ No newline at end of file From a26f889c7accbb2e71a1dfe07cadee3f6d02d61f Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Tue, 25 Mar 2025 13:59:51 +0300 Subject: [PATCH 869/872] add new guide --- example/README.md | 126 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 118 insertions(+), 8 deletions(-) diff --git a/example/README.md b/example/README.md index 335f4fbc..793e221c 100644 --- a/example/README.md +++ b/example/README.md @@ -338,15 +338,125 @@ Better order to solve problems 4. 1617 (Count Subtrees With Max Distance Between Cities) 5. 1125 (Smallest Sufficient Team) -### Prefix sum -303. -724. 560. 304. 1314. 268. -287. 189. 896. 674. +### Ru companies -### Tips && Trics +##### Anagramms, Math, Simple nums -102. = 199. -100. = 101 +242. Valid Anagram +49. Group Angagrams +204. Count Primes +7. Reverse Integer +136. Single Number +137. Single Number ii + +##### ArraaysHash (Prefix sum) + +### Uni +303. 724. 304. 1314. 268. 287. 189. 674. +### Jandex +560. +### Oz +896. + +##### ArraaysHash + +1. Sum +36. Valid Sudoku +205. Isomorphic Strings +356. Line reflection +146. Lru Cache +2657. Find the Prefix Common + +##### TwoPointers + +977. Squares of a sorted Array +283. Move Zeroes +125. Valid Palendrom +167. Two Integer Sum II +161. One Edit Distance + +##### SlidingWindow + +228. Summary Ranges +485. Max Consecutive Ones +3. Longest... +849. Maximize Distance to closest person +443. String Compression + +##### Linked list + +### Сбебс +19. Remove Nth Node from End of List +143. Reorder List +23. Merge k Sorted Lists +### Jandex +206. Reverse Linked List +234. Palindrome Linked List +### Uni +876. Middle of the Linked List +143. Reorder List + +##### Binary Search + +704. Binary Search +852. Peak Index in a Mountain Array +33. Search in Rotated Sorted Array +34. Find First and Last Position of Element in Sorted Array +74. Search a 2D Matrix +69. Sqrt(x) +658. Find K Closesest Elements -### Ru companies \ No newline at end of file +##### Stack, Queue + +20. Valid Parentheses +1249. Minimum Remove to Make Valid Parentheses +739. Daily Temperatures +912. Sort an Array + +##### Binare Tree + +### Uni +144. +199. Binary Tree Right Side View +### Jandex +102. Binary Tree Level Order Traversal +* 101. Symmetric Tree +100. Same Tree +112. Path sum + +##### Heap + +215. Kth Largest Element in an Array +347. Top K Frequent Elements (не отсортирован) +912. Sort an Array + +##### Intervals + +### Uni +56. Merge Intervals +252. Meeting Rooms +1094. Car pooling +452. Minimum Number of Arrows to Burst Balloons +347. Top K Frequent Elements (не отсортирован) +### Avi +2. Add Two Numbers + +##### Graphs + +62. Unique paths +63. Unique paths ii +64. Minimum Path Sum +200. Number of Islands +207. Course Schedule +210. Course Schedule ii +130. Surronded Regions +695. Max Area of Island +1091. Shortest path in Binary Matrix + +##### Backtracking + +17. letter combinations of a phone number +46. Permatations +51. N-Queens +22. Generate Parentheses \ No newline at end of file From 5396da900a75887fb9c420d7260d225591bbe43a Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Sun, 30 Mar 2025 16:18:46 +0300 Subject: [PATCH 870/872] add js challenge --- example/README.md | 11 +++++++++++ example/js/2620.js | 27 +++++++++++++++++++++++++++ example/js/2626.js | 42 ++++++++++++++++++++++++++++++++++++++++++ example/js/2629.js | 40 ++++++++++++++++++++++++++++++++++++++++ example/js/2634.js | 41 +++++++++++++++++++++++++++++++++++++++++ example/js/2635.js | 37 +++++++++++++++++++++++++++++++++++++ example/js/2655.js | 32 ++++++++++++++++++++++++++++++++ example/js/2667.js | 23 +++++++++++++++++++++++ example/js/2704.js | 27 +++++++++++++++++++++++++++ 9 files changed, 280 insertions(+) create mode 100644 example/js/2620.js create mode 100644 example/js/2626.js create mode 100644 example/js/2629.js create mode 100644 example/js/2634.js create mode 100644 example/js/2635.js create mode 100644 example/js/2655.js create mode 100644 example/js/2667.js create mode 100644 example/js/2704.js diff --git a/example/README.md b/example/README.md index 793e221c..691c803a 100644 --- a/example/README.md +++ b/example/README.md @@ -270,6 +270,17 @@ Better order to solve problems 1041. Robot Bounded In Circle 1572. Matrix Diagonal Sum +## 30 Days of JavaScript + +2667. Create Hello World Function +2620. Counter +2704. To Be Or Not To Be +2665. Counter II +2635. Apply Transform Over Each Element in Array +2634. Filter Elements from Array +2626. Array Reduce Transformation +2629. Function Composition + ### [Strong List](structy.net) 1. Depth-First Search (DFS) diff --git a/example/js/2620.js b/example/js/2620.js new file mode 100644 index 00000000..807259a4 --- /dev/null +++ b/example/js/2620.js @@ -0,0 +1,27 @@ +/** + * 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) { + + return function() { + + }; +}; + +const counter = createCounter(10) +counter() +counter() +counter() +console.log(counter()) // 13 +console.log(counter()) // 14 \ No newline at end of file diff --git a/example/js/2626.js b/example/js/2626.js new file mode 100644 index 00000000..a111181b --- /dev/null +++ b/example/js/2626.js @@ -0,0 +1,42 @@ +/** + * 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) { + +}; + + +function sum1(accum, curr) { return accum + curr; } +ex1 = reduce([1,2,3,4], sum1, 0) + +function sum2(accum, curr) { return accum + curr * curr; } +ex2 = reduce([1,2,3,4], sum2, 100) + +function sum3(accum, curr) { return 0; } +ex3 = reduce([], sum3, 25) + +console.log(ex1) // 10 +console.log(ex2) // 130 +console.log(ex3) // 25 + \ No newline at end of file diff --git a/example/js/2629.js b/example/js/2629.js new file mode 100644 index 00000000..01bd9a5c --- /dev/null +++ b/example/js/2629.js @@ -0,0 +1,40 @@ +/** + * 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 function(x) { + + } +}; + + +functions1 = [x => x + 1, x => x * x, x => 2 * x] +ex1 = compose(functions1)(4) + +functions2 = [x => 10 * x, x => 10 * x, x => 10 * x] +ex2 = compose(functions2)(1) + +functions3 = [] +ex3 = compose(functions3)(42) + +console.log(ex1) // 65 +console.log(ex2) // 1000 +console.log(ex3) // 42 \ No newline at end of file diff --git a/example/js/2634.js b/example/js/2634.js new file mode 100644 index 00000000..e77df729 --- /dev/null +++ b/example/js/2634.js @@ -0,0 +1,41 @@ +/** + * 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) { + +}; + + +fn1 = function greaterThan10(n) { return n > 10; } +ex1 = filter([0,10,20,30], fn1) + +fn2 = function firstIndex(n, i) { return i === 0; } +ex2 = filter([1,2,3], fn2) + +fn3 = function plusOne(n) { return n + 1 } +ex3 = filter([-2,-1,0,1,2], fn3) + +console.log(ex1) // [20, 30] +console.log(ex2) // [1] +console.log(ex3) // [-2,0,1,2] + \ No newline at end of file diff --git a/example/js/2635.js b/example/js/2635.js new file mode 100644 index 00000000..74ff0a4f --- /dev/null +++ b/example/js/2635.js @@ -0,0 +1,37 @@ +/** + * 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 arr = [1,2,3] + +fn1 = function plusone(n) { return n + 1; } +ex1 = map(arr, fn1) + +fn2 = function plusI(n, i) { return n + i; } +ex2 = map(arr, fn2) + +fn3 = function constant() { return 42; } +ex3 = map(arr, fn3) + +console.log(ex1) +console.log(ex2) +console.log(ex3) + \ No newline at end of file diff --git a/example/js/2655.js b/example/js/2655.js new file mode 100644 index 00000000..a6452395 --- /dev/null +++ b/example/js/2655.js @@ -0,0 +1,32 @@ +/** + * 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) { + +}; + +const counter = createCounter(5) +// counter.increment(); // 6 +// counter.reset(); // 5 +// counter.decrement(); // 4 + +console.log(counter.increment()) // 6 +console.log(counter.increment()) // 7 +console.log(counter.reset()) // 5 +console.log(counter.decrement()) // 4 + \ No newline at end of file diff --git a/example/js/2667.js b/example/js/2667.js new file mode 100644 index 00000000..5c11e53c --- /dev/null +++ b/example/js/2667.js @@ -0,0 +1,23 @@ +/** + * 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 function(...args) { + + } +}; + +const f = createHelloWorld(); +f(); + +console.log(f()) // "Hello World" \ No newline at end of file diff --git a/example/js/2704.js b/example/js/2704.js new file mode 100644 index 00000000..84350183 --- /dev/null +++ b/example/js/2704.js @@ -0,0 +1,27 @@ +/** + * 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) { + +}; + +// expect(5).toBe(5); // true +// expect(5).notToBe(5); // throws "Equal" + +console.log(expect(5).toBe(5)) +console.log(expect(5).notToBe(5)) \ No newline at end of file From 8bf3bcd8eed4e429873115a51f26b71c71dbc549 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Thu, 3 Apr 2025 11:22:51 +0300 Subject: [PATCH 871/872] add classic examples --- 0122-best-time-to-buy-and-sell-stock-ii.js | 12 ++++ 0189-rotate-array.js | 14 ++++ example/README.md | 80 +++++++++++++++++++++- 3 files changed, 105 insertions(+), 1 deletion(-) diff --git a/0122-best-time-to-buy-and-sell-stock-ii.js b/0122-best-time-to-buy-and-sell-stock-ii.js index 5f963d71..137657c0 100644 --- a/0122-best-time-to-buy-and-sell-stock-ii.js +++ b/0122-best-time-to-buy-and-sell-stock-ii.js @@ -22,3 +22,15 @@ var maxProfit = function(prices) { return prices[i - 1] < price ? result + (price - prices[i - 1]) : result; }, 0); }; + +// var maxProfit = function(prices) { +// let profit = 0 + +// for (let i = 1; i < prices.length; i++) { +// if (prices[i] > prices[i - 1]) { +// profit += prices[i] - prices[i - 1] +// } +// } + +// return profit +// }; diff --git a/0189-rotate-array.js b/0189-rotate-array.js index b6bcc49a..9fed54f0 100644 --- a/0189-rotate-array.js +++ b/0189-rotate-array.js @@ -14,3 +14,17 @@ var rotate = function(nums, k) { nums.unshift(...nums.splice((k % nums.length) * -1)); }; + +// var rotate = function(nums, k) { +// const n = nums.length; +// k = k % n; +// const rotated = new Array(n).fill(0); + +// for (let i = 0; i < n; i++) { +// rotated[(i + k) % n] = nums[i]; +// } + +// for (let i = 0; i < n; i++) { +// nums[i] = rotated[i]; +// } +// }; \ No newline at end of file diff --git a/example/README.md b/example/README.md index 691c803a..46c890d8 100644 --- a/example/README.md +++ b/example/README.md @@ -470,4 +470,82 @@ Better order to solve problems 17. letter combinations of a phone number 46. Permatations 51. N-Queens -22. Generate Parentheses \ No newline at end of file +22. Generate Parentheses + + +### [classic](https://leetcode.com/explore/interview/card/top-interview-questions-easy) + +##### Array + +26. Remove Duplicates from Sorted Array +122. Best Time to Buy and Sell Stock II +189. Rotate Array +217. Contains Duplicate +136. Single Number +350. Intersection of Two Arrays II +66. Plus One +283. Move Zeroes +1. Two Sum +36. Valid Sudoku +48. Rotate Image + +##### String + +344. Reverse String +7. Reverse Integer +387. First Unique Character in a String +242. Valid Anagram +125. Valid Palindrome +8. String to Integer (atoi) +28. Implement strStr() +14. Longest Common Prefix + +##### Linked list + +237. Delete Node in a Linked List +19. Remove Nth Node From End of List +206. Reverse Linked List +21. Merge Two Sorted Lists +234. Palindrome Linked List +141. Linked List Cycle + +##### Trees + +104. Maximum Depth of Binary Tree +98. Validate Binary Search Tree +101. Symmetric Tree +102. Binary Tree Level Order Traversal +108. Convert Sorted Array to Binary Search Tree + +##### Sorting and Searching + +88. Merge Sorted Array +278. First Bad Version + +##### Dynamic Programming + +70. Climbing Stairs +121. Best Time to Buy and Sell Stock +53. Maximum Subarray +198. House Robber + +##### Design + +384. Shuffle an Array +155. Min Stack + +##### Math + +412. Fizz Buzz +204. Count Primes +326. Power of Three +13. Roman to Integer + +##### Other + +191. Number of 1 Bits +461. Hamming Distance +190. Reverse Bits +118. Pascal's Triangle +20. Valid Parentheses +268. Missing Number \ No newline at end of file From 7526801bfc5b46bae960560781c827160bf0ff87 Mon Sep 17 00:00:00 2001 From: Barklim <46284548+Barklim@users.noreply.github.c> Date: Sun, 6 Apr 2025 04:08:32 +0300 Subject: [PATCH 872/872] add js examples --- 2666-allow-one-function-call.js | 17 +++++++ 2722-join-two-arrays-by-id.js | 16 +++++++ example/README.md | 9 ++++ example/js/2623.js | 43 ++++++++++++++++++ example/js/2625.js | 27 ++++++++++++ example/js/2631.js | 56 +++++++++++++++++++++++ example/js/2666.js | 27 ++++++++++++ example/js/2677.js | 37 ++++++++++++++++ example/js/2705.js | 31 +++++++++++++ example/js/2722.js | 78 +++++++++++++++++++++++++++++++++ example/js/2724.js | 31 +++++++++++++ 11 files changed, 372 insertions(+) create mode 100644 example/js/2623.js create mode 100644 example/js/2625.js create mode 100644 example/js/2631.js create mode 100644 example/js/2666.js create mode 100644 example/js/2677.js create mode 100644 example/js/2705.js create mode 100644 example/js/2722.js create mode 100644 example/js/2724.js diff --git a/2666-allow-one-function-call.js b/2666-allow-one-function-call.js index 93bb604d..bc1da524 100644 --- a/2666-allow-one-function-call.js +++ b/2666-allow-one-function-call.js @@ -17,3 +17,20 @@ var once = function(fn) { return (...args) => fn && [fn(...args), fn = undefined][0]; }; + +// var once = function(fn) { + +// let hasBeenCalled = false; +// let result; + +// return function(...args) { +// if (!hasBeenCalled) { +// result = fn(...args); +// hasBeenCalled = true; +// return result; +// } else { +// return undefined; +// } +// } + +// }; diff --git a/2722-join-two-arrays-by-id.js b/2722-join-two-arrays-by-id.js index 5e81dde1..fb3893fd 100644 --- a/2722-join-two-arrays-by-id.js +++ b/2722-join-two-arrays-by-id.js @@ -30,3 +30,19 @@ var join = function(arr1, arr2) { [...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); }; + +// var join = function(arr1, arr2) { +// const result = {}; +// for (let i = 0; i < arr1.length; i++) { +// result[arr1[i].id] = arr1[i]; +// } +// for (let i = 0; i < arr2.length; i++) { +// if (result[arr2[i].id]) { +// for (const key in arr2[i]) result[arr2[i].id][key] = arr2[i][key]; +// } else { +// result[arr2[i].id] = arr2[i]; +// } +// } + +// return Object.values(result); +// }; diff --git a/example/README.md b/example/README.md index 46c890d8..b2389a66 100644 --- a/example/README.md +++ b/example/README.md @@ -280,6 +280,15 @@ Better order to solve problems 2634. Filter Elements from Array 2626. Array Reduce Transformation 2629. Function Composition +2666. Allow One Function Call +2623. Memoize + +2677. Chunk Array +2631. Group By +2724. Sort By +2722. Join Two Arrays by ID +2625. Flatten Deeply Nested Array +2705. Compact Object ### [Strong List](structy.net) diff --git a/example/js/2623.js b/example/js/2623.js new file mode 100644 index 00000000..7d8965ee --- /dev/null +++ b/example/js/2623.js @@ -0,0 +1,43 @@ +/** + * 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) { + + return function(...args) { + + } +} + +let callCount = 0; +const memoizedFn = memoize(function (a, b) { + callCount += 1; + return a + b; +}); +memoizedFn(2, 3); // 5 +memoizedFn(2, 3); // 5 +console.log(callCount); // 1 diff --git a/example/js/2625.js b/example/js/2625.js new file mode 100644 index 00000000..79f0d023 --- /dev/null +++ b/example/js/2625.js @@ -0,0 +1,27 @@ +/** + * 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) { + +}; + \ No newline at end of file diff --git a/example/js/2631.js b/example/js/2631.js new file mode 100644 index 00000000..36ed11fb --- /dev/null +++ b/example/js/2631.js @@ -0,0 +1,56 @@ +/** + * 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) { + +}; + +const array1 = [ + {id: 1}, + {id: 1}, + {id: 2} +] + +const fn = (item) => item.id + +console.log(array1.groupBy(fn)) +// { +// 1: [{id: 1}, {id: 1}], +// 2: [{id: 2}] +// } + +// Ex2 +const array2 = [1, 2, 3] +console.log(array2.groupBy(String)) +// { +// "1": [1], +// "2": [2], +// "3": [3], +// } + +// Ex3 +const array3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +const fn3 = function (n) { + return String(n > 5); +} +console.log(array3.groupBy(fn3)) \ No newline at end of file diff --git a/example/js/2666.js b/example/js/2666.js new file mode 100644 index 00000000..14019d9a --- /dev/null +++ b/example/js/2666.js @@ -0,0 +1,27 @@ +/** + * 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. + */ +var once = function(fn) { + + return function(...args){ + + } +}; + +let fn = (a,b,c) => (a + b + c) +let onceFn = once(fn) + +ex1 = onceFn(1,2,3); // 6 +ex2 = onceFn(2,3,6); // returns undefined without calling fn + +console.log(ex1) +console.log(ex2) + diff --git a/example/js/2677.js b/example/js/2677.js new file mode 100644 index 00000000..4336c420 --- /dev/null +++ b/example/js/2677.js @@ -0,0 +1,37 @@ +/** + * 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) { + +}; + +ex1 = chunk([1,2,3,4,5], 1) +console.log(ex1) // [[1],[2],[3],[4],[5]] + +ex2 = chunk([1,9,6,3,2], 3) +console.log(ex2) // [[1,9,6],[3,2]] + +ex3 = chunk([8,5,3,2,6], 6) +console.log(ex3) // [[8,5,3,2,6]] + +ex4 = chunk([], 1) +console.log(ex4) // [] + \ No newline at end of file diff --git a/example/js/2705.js b/example/js/2705.js new file mode 100644 index 00000000..9ce6a147 --- /dev/null +++ b/example/js/2705.js @@ -0,0 +1,31 @@ +/** + * 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) { + +}; + +ex1 = compactObject([null, 0, false, 1]) +console.log(ex1) // [1] + +ex2 = compactObject({"a": null, "b": [false, 1]}) +console.log(ex2) // {"b": [1]} + +ex3 = compactObject([null, 0, 5, [0], [false, 16]]) +console.log(ex3) // [5, [], [16]] \ No newline at end of file diff --git a/example/js/2722.js b/example/js/2722.js new file mode 100644 index 00000000..8956df7d --- /dev/null +++ b/example/js/2722.js @@ -0,0 +1,78 @@ +/** + * 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) { + +}; + + +arr1 = [ + {"id": 1, "x": 1}, + {"id": 2, "x": 9} +], +arr2 = [ + {"id": 3, "x": 5} +] + +ex1 = join(arr1, arr2) +console.log(ex1) +// [ +// {"id": 1, "x": 1}, +// {"id": 2, "x": 9}, +// {"id": 3, "x": 5} +// ] + + +arr1 = [ + {"id": 1, "x": 2, "y": 3}, + {"id": 2, "x": 3, "y": 6} +], +arr2 = [ + {"id": 2, "x": 10, "y": 20}, + {"id": 3, "x": 0, "y": 0} +] + +ex2 = join(arr1, arr2) +console.log(ex2) +// [ +// {"id": 1, "x": 2, "y": 3}, +// {"id": 2, "x": 10, "y": 20}, +// {"id": 3, "x": 0, "y": 0} +// ] + +arr1 = [ + {"id": 1, "b": {"b": 94}, "v": [4, 3], "y": 48} +], +arr2 = [ + {"id": 1, "b": {"c": 84}, "v": [1, 3]} +] + +ex3 = join(arr1, arr2) +console.log(ex3) +// [ +// {"id": 1, "b": {"c": 84}, "v": [1, 3], "y": 48} +// ] \ No newline at end of file diff --git a/example/js/2724.js b/example/js/2724.js new file mode 100644 index 00000000..6436853d --- /dev/null +++ b/example/js/2724.js @@ -0,0 +1,31 @@ +/** + * 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) { + +}; + +ex1 = sortBy([5, 4, 1, 2, 3], fn = (x) => x) +console.log(ex1) // [1, 2, 3, 4, 5] + +ex2 = sortBy([{"x": 1}, {"x": 0}, {"x": -1}], fn = (d) => d.x) +console.log(ex2) // [{"x": -1}, {"x": 0}, {"x": 1}] + +ex3 = sortBy([[3, 4], [5, 2], [10, 1]], fn = (x) => x[1]) +console.log(ex3) // [[10, 1], [5, 2], [3, 4]] + \ No newline at end of file