From a3e950c5b3c135b9523b6222d130c024f44d4d64 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 27 Apr 2025 22:34:19 -0500 Subject: [PATCH 001/495] Add solution #2302 --- README.md | 3 +- ...-count-subarrays-with-score-less-than-k.js | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 solutions/2302-count-subarrays-with-score-less-than-k.js diff --git a/README.md b/README.md index 6e93b5b0..f4832a9a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,505 LeetCode solutions in JavaScript +# 1,506 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1395,6 +1395,7 @@ 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium| 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium| +2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard| 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium| 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard| 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium| diff --git a/solutions/2302-count-subarrays-with-score-less-than-k.js b/solutions/2302-count-subarrays-with-score-less-than-k.js new file mode 100644 index 00000000..29aa7eda --- /dev/null +++ b/solutions/2302-count-subarrays-with-score-less-than-k.js @@ -0,0 +1,35 @@ +/** + * 2302. Count Subarrays With Score Less Than K + * https://leetcode.com/problems/count-subarrays-with-score-less-than-k/ + * Difficulty: Hard + * + * The score of an array is defined as the product of its sum and its length. + * - For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75. + * + * Given a positive integer array nums and an integer k, return the number of non-empty subarrays + * of nums whose score is strictly less than k. + * + * A subarray is a contiguous sequence of elements within an array. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var countSubarrays = function(nums, k) { + let result = 0; + let currentSum = 0; + let left = 0; + + for (let right = 0; right < nums.length; right++) { + currentSum += nums[right]; + while (currentSum * (right - left + 1) >= k) { + currentSum -= nums[left]; + left++; + } + result += right - left + 1; + } + + return result; +}; From c7e787da4762e52f126c184b57cb4b7a7fcc52ea Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 27 Apr 2025 22:36:41 -0500 Subject: [PATCH 002/495] Add solution #1733 --- README.md | 3 +- .../1733-minimum-number-of-people-to-teach.js | 63 +++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 solutions/1733-minimum-number-of-people-to-teach.js diff --git a/README.md b/README.md index f4832a9a..d902fbd0 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,506 LeetCode solutions in JavaScript +# 1,507 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1334,6 +1334,7 @@ 1727|[Largest Submatrix With Rearrangements](./solutions/1727-largest-submatrix-with-rearrangements.js)|Medium| 1728|[Cat and Mouse II](./solutions/1728-cat-and-mouse-ii.js)|Hard| 1732|[Find the Highest Altitude](./solutions/1732-find-the-highest-altitude.js)|Easy| +1733|[Minimum Number of People to Teach](./solutions/1733-minimum-number-of-people-to-teach.js)|Medium| 1748|[Sum of Unique Elements](./solutions/1748-sum-of-unique-elements.js)|Easy| 1749|[Maximum Absolute Sum of Any Subarray](./solutions/1749-maximum-absolute-sum-of-any-subarray.js)|Medium| 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| diff --git a/solutions/1733-minimum-number-of-people-to-teach.js b/solutions/1733-minimum-number-of-people-to-teach.js new file mode 100644 index 00000000..9307f936 --- /dev/null +++ b/solutions/1733-minimum-number-of-people-to-teach.js @@ -0,0 +1,63 @@ +/** + * 1733. Minimum Number of People to Teach + * https://leetcode.com/problems/minimum-number-of-people-to-teach/ + * Difficulty: Medium + * + * On a social network consisting of m users and some friendships between users, two users can + * communicate with each other if they know a common language. + * + * You are given an integer n, an array languages, and an array friendships where: + * - There are n languages numbered 1 through n, + * - languages[i] is the set of languages the ith user knows, and + * - friendships[i] = [ui, vi] denotes a friendship between the users ui and vi. + * + * You can choose one language and teach it to some users so that all friends can communicate + * with each other. Return the minimum number of users you need to teach. + * + * Note that friendships are not transitive, meaning if x is a friend of y and y is a friend of + * z, this doesn't guarantee that x is a friend of z. + */ + +/** + * @param {number} n + * @param {number[][]} languages + * @param {number[][]} friendships + * @return {number} + */ +var minimumTeachings = function(n, languages, friendships) { + const languageUsers = Array.from({ length: n + 1 }, () => new Set()); + const nonCommunicating = new Set(); + + for (let i = 0; i < languages.length; i++) { + for (const lang of languages[i]) { + languageUsers[lang].add(i + 1); + } + } + + for (const [u, v] of friendships) { + let canCommunicate = false; + for (const lang of languages[u - 1]) { + if (languages[v - 1].includes(lang)) { + canCommunicate = true; + break; + } + } + if (!canCommunicate) { + nonCommunicating.add(u); + nonCommunicating.add(v); + } + } + + let result = Infinity; + for (let lang = 1; lang <= n; lang++) { + let usersToTeach = 0; + for (const user of nonCommunicating) { + if (!languages[user - 1].includes(lang)) { + usersToTeach++; + } + } + result = Math.min(result, usersToTeach); + } + + return result; +}; From 3973adca6d5cb8ce80a570c9b4fe7017ccbe5b3b Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 27 Apr 2025 22:37:36 -0500 Subject: [PATCH 003/495] Add solution #1734 --- README.md | 3 +- solutions/1734-decode-xored-permutation.js | 40 ++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 solutions/1734-decode-xored-permutation.js diff --git a/README.md b/README.md index d902fbd0..9662191e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,507 LeetCode solutions in JavaScript +# 1,508 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1335,6 +1335,7 @@ 1728|[Cat and Mouse II](./solutions/1728-cat-and-mouse-ii.js)|Hard| 1732|[Find the Highest Altitude](./solutions/1732-find-the-highest-altitude.js)|Easy| 1733|[Minimum Number of People to Teach](./solutions/1733-minimum-number-of-people-to-teach.js)|Medium| +1734|[Decode XORed Permutation](./solutions/1734-decode-xored-permutation.js)|Medium| 1748|[Sum of Unique Elements](./solutions/1748-sum-of-unique-elements.js)|Easy| 1749|[Maximum Absolute Sum of Any Subarray](./solutions/1749-maximum-absolute-sum-of-any-subarray.js)|Medium| 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| diff --git a/solutions/1734-decode-xored-permutation.js b/solutions/1734-decode-xored-permutation.js new file mode 100644 index 00000000..72388a1a --- /dev/null +++ b/solutions/1734-decode-xored-permutation.js @@ -0,0 +1,40 @@ +/** + * 1734. Decode XORed Permutation + * https://leetcode.com/problems/decode-xored-permutation/ + * Difficulty: Medium + * + * There is an integer array perm that is a permutation of the first n positive integers, + * where n is always odd. + * + * It was encoded into another integer array encoded of length n - 1, such that + * encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1]. + * + * Given the encoded array, return the original array perm. It is guaranteed that the answer + * exists and is unique. + */ + +/** + * @param {number[]} encoded + * @return {number[]} + */ +var decode = function(encoded) { + const n = encoded.length + 1; + let totalXor = 0; + for (let i = 1; i <= n; i++) { + totalXor ^= i; + } + + let oddXor = 0; + for (let i = 1; i < encoded.length; i += 2) { + oddXor ^= encoded[i]; + } + + const result = new Array(n); + result[0] = totalXor ^ oddXor; + + for (let i = 0; i < n - 1; i++) { + result[i + 1] = result[i] ^ encoded[i]; + } + + return result; +}; From 104ae4ebe409b0af5f0f58777523d3cb9364d1f7 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 27 Apr 2025 22:50:41 -0500 Subject: [PATCH 004/495] Add solution #1735 --- README.md | 3 +- ...5-count-ways-to-make-array-with-product.js | 87 +++++++++++++++++++ 2 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 solutions/1735-count-ways-to-make-array-with-product.js diff --git a/README.md b/README.md index 9662191e..90af993a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,508 LeetCode solutions in JavaScript +# 1,509 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1336,6 +1336,7 @@ 1732|[Find the Highest Altitude](./solutions/1732-find-the-highest-altitude.js)|Easy| 1733|[Minimum Number of People to Teach](./solutions/1733-minimum-number-of-people-to-teach.js)|Medium| 1734|[Decode XORed Permutation](./solutions/1734-decode-xored-permutation.js)|Medium| +1735|[Count Ways to Make Array With Product](./solutions/1735-count-ways-to-make-array-with-product.js)|Hard| 1748|[Sum of Unique Elements](./solutions/1748-sum-of-unique-elements.js)|Easy| 1749|[Maximum Absolute Sum of Any Subarray](./solutions/1749-maximum-absolute-sum-of-any-subarray.js)|Medium| 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| diff --git a/solutions/1735-count-ways-to-make-array-with-product.js b/solutions/1735-count-ways-to-make-array-with-product.js new file mode 100644 index 00000000..4fa45784 --- /dev/null +++ b/solutions/1735-count-ways-to-make-array-with-product.js @@ -0,0 +1,87 @@ +/** + * 1735. Count Ways to Make Array With Product + * https://leetcode.com/problems/count-ways-to-make-array-with-product/ + * Difficulty: Hard + * + * You are given a 2D integer array, queries. For each queries[i], where queries[i] = [ni, ki], + * find the number of different ways you can place positive integers into an array of size ni + * such that the product of the integers is ki. As the number of ways may be too large, the + * answer to the ith query is the number of ways modulo 109 + 7. + * + * Return an integer array answer where answer.length == queries.length, and answer[i] is the + * answer to the ith query. + */ + +/** + * @param {number[][]} queries + * @return {number[]} + */ +var waysToFillArray = function(queries) { + const MOD = 1000000007n; + const MAX_N = 20000; + const factorial = new Array(MAX_N + 1).fill(1n); + const inverse = new Array(MAX_N + 1).fill(1n); + + for (let i = 1; i <= MAX_N; i++) { + factorial[i] = (factorial[i - 1] * BigInt(i)) % MOD; + } + inverse[MAX_N] = BigInt(modInverse(Number(factorial[MAX_N] % MOD), Number(MOD))); + for (let i = MAX_N - 1; i >= 0; i--) { + inverse[i] = (inverse[i + 1] * BigInt(i + 1)) % MOD; + } + + const result = []; + for (const [size, product] of queries) { + if (product === 1) { + result.push(1); + continue; + } + const factors = getPrimeFactors(product); + let ways = 1n; + for (const count of factors.values()) { + const n = size + count - 1; + ways = (ways * BigInt(combinations(n, count))) % MOD; + } + result.push(Number(ways)); + } + + return result; + + function modInverse(a, m) { + const m0 = m; + let t; + let q; + let x0 = 0; + let x1 = 1; + while (a > 1) { + q = Math.floor(a / m); + t = m; + m = a % m; + a = t; + t = x0; + x0 = x1 - q * x0; + x1 = t; + } + return x1 < 0 ? x1 + m0 : x1; + } + + function combinations(n, k) { + if (k < 0 || k > n || n < 0 || n > MAX_N || n - k < 0) return 0; + const result = (factorial[n] * inverse[k] * inverse[n - k]) % MOD; + return Number(result); + } + + function getPrimeFactors(num) { + const factors = new Map(); + for (let i = 2; i * i <= num; i++) { + while (num % i === 0) { + factors.set(i, (factors.get(i) || 0) + 1); + num /= i; + } + } + if (num > 1) { + factors.set(num, (factors.get(num) || 0) + 1); + } + return factors; + } +}; From db73f3ebd17af89f8116ab5fc99e5c02ca71a1d9 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 27 Apr 2025 22:51:52 -0500 Subject: [PATCH 005/495] Add solution #1736 --- README.md | 3 +- ...-latest-time-by-replacing-hidden-digits.js | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 solutions/1736-latest-time-by-replacing-hidden-digits.js diff --git a/README.md b/README.md index 90af993a..0e594712 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,509 LeetCode solutions in JavaScript +# 1,510 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1337,6 +1337,7 @@ 1733|[Minimum Number of People to Teach](./solutions/1733-minimum-number-of-people-to-teach.js)|Medium| 1734|[Decode XORed Permutation](./solutions/1734-decode-xored-permutation.js)|Medium| 1735|[Count Ways to Make Array With Product](./solutions/1735-count-ways-to-make-array-with-product.js)|Hard| +1736|[Latest Time by Replacing Hidden Digits](./solutions/1736-latest-time-by-replacing-hidden-digits.js)|Easy| 1748|[Sum of Unique Elements](./solutions/1748-sum-of-unique-elements.js)|Easy| 1749|[Maximum Absolute Sum of Any Subarray](./solutions/1749-maximum-absolute-sum-of-any-subarray.js)|Medium| 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| diff --git a/solutions/1736-latest-time-by-replacing-hidden-digits.js b/solutions/1736-latest-time-by-replacing-hidden-digits.js new file mode 100644 index 00000000..23e72a76 --- /dev/null +++ b/solutions/1736-latest-time-by-replacing-hidden-digits.js @@ -0,0 +1,38 @@ +/** + * 1736. Latest Time by Replacing Hidden Digits + * https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/ + * Difficulty: Easy + * + * You are given a string time in the form of hh:mm, where some of the digits in the string + * are hidden (represented by ?). + * + * The valid times are those inclusively between 00:00 and 23:59. + * + * Return the latest valid time you can get from time by replacing the hidden digits. + */ + +/** + * @param {string} time + * @return {string} + */ +var maximumTime = function(time) { + const result = time.split(''); + + if (result[0] === '?') { + result[0] = result[1] === '?' || result[1] <= '3' ? '2' : '1'; + } + + if (result[1] === '?') { + result[1] = result[0] === '2' ? '3' : '9'; + } + + if (result[3] === '?') { + result[3] = '5'; + } + + if (result[4] === '?') { + result[4] = '9'; + } + + return result.join(''); +}; From 2effdba00b024824f994a52e3eb40153a6c2ad7c Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 28 Apr 2025 18:35:41 -0500 Subject: [PATCH 006/495] Add solution #1737 --- README.md | 3 +- ...ters-to-satisfy-one-of-three-conditions.js | 59 +++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 solutions/1737-change-minimum-characters-to-satisfy-one-of-three-conditions.js diff --git a/README.md b/README.md index 0e594712..4d81ab69 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,510 LeetCode solutions in JavaScript +# 1,511 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1338,6 +1338,7 @@ 1734|[Decode XORed Permutation](./solutions/1734-decode-xored-permutation.js)|Medium| 1735|[Count Ways to Make Array With Product](./solutions/1735-count-ways-to-make-array-with-product.js)|Hard| 1736|[Latest Time by Replacing Hidden Digits](./solutions/1736-latest-time-by-replacing-hidden-digits.js)|Easy| +1737|[Change Minimum Characters to Satisfy One of Three Conditions](./solutions/1737-change-minimum-characters-to-satisfy-one-of-three-conditions.js)|Medium| 1748|[Sum of Unique Elements](./solutions/1748-sum-of-unique-elements.js)|Easy| 1749|[Maximum Absolute Sum of Any Subarray](./solutions/1749-maximum-absolute-sum-of-any-subarray.js)|Medium| 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| diff --git a/solutions/1737-change-minimum-characters-to-satisfy-one-of-three-conditions.js b/solutions/1737-change-minimum-characters-to-satisfy-one-of-three-conditions.js new file mode 100644 index 00000000..3a084982 --- /dev/null +++ b/solutions/1737-change-minimum-characters-to-satisfy-one-of-three-conditions.js @@ -0,0 +1,59 @@ +/** + * 1737. Change Minimum Characters to Satisfy One of Three Conditions + * https://leetcode.com/problems/change-minimum-characters-to-satisfy-one-of-three-conditions/ + * Difficulty: Medium + * + * You are given two strings a and b that consist of lowercase letters. In one operation, you can + * change any character in a or b to any lowercase letter. + * + * Your goal is to satisfy one of the following three conditions: + * - Every letter in a is strictly less than every letter in b in the alphabet. + * - Every letter in b is strictly less than every letter in a in the alphabet. + * - Both a and b consist of only one distinct letter. + * + * Return the minimum number of operations needed to achieve your goal. + */ + +/** + * @param {string} a + * @param {string} b + * @return {number} + */ +var minCharacters = function(a, b) { + const aFreq = getFrequency(a); + const bFreq = getFrequency(b); + + const condition1 = operationsForCondition1(aFreq, bFreq); + const condition2 = operationsForCondition1(bFreq, aFreq); + const condition3 = operationsForCondition3(aFreq, bFreq); + + return Math.min(condition1, condition2, condition3); + + function getFrequency(str) { + const freq = Array(26).fill(0); + for (const char of str) { + freq[char.charCodeAt(0) - 97]++; + } + return freq; + } + + function operationsForCondition1(aFreq, bFreq) { + let minOps = Infinity; + for (let i = 0; i < 25; i++) { + let ops = 0; + for (let j = 0; j <= i; j++) ops += aFreq[j]; + for (let j = i + 1; j < 26; j++) ops += bFreq[j]; + minOps = Math.min(minOps, ops); + } + return minOps; + } + + function operationsForCondition3(aFreq, bFreq) { + let minOps = Infinity; + for (let i = 0; i < 26; i++) { + const ops = a.length + b.length - aFreq[i] - bFreq[i]; + minOps = Math.min(minOps, ops); + } + return minOps; + } +}; From e2cc4ccc7774c4c992c7d053dc125c65039c471f Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 28 Apr 2025 18:36:55 -0500 Subject: [PATCH 007/495] Add solution #1738 --- README.md | 3 +- ...8-find-kth-largest-xor-coordinate-value.js | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 solutions/1738-find-kth-largest-xor-coordinate-value.js diff --git a/README.md b/README.md index 4d81ab69..279c0936 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,511 LeetCode solutions in JavaScript +# 1,512 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1339,6 +1339,7 @@ 1735|[Count Ways to Make Array With Product](./solutions/1735-count-ways-to-make-array-with-product.js)|Hard| 1736|[Latest Time by Replacing Hidden Digits](./solutions/1736-latest-time-by-replacing-hidden-digits.js)|Easy| 1737|[Change Minimum Characters to Satisfy One of Three Conditions](./solutions/1737-change-minimum-characters-to-satisfy-one-of-three-conditions.js)|Medium| +1738|[Find Kth Largest XOR Coordinate Value](./solutions/1738-find-kth-largest-xor-coordinate-value.js)|Medium| 1748|[Sum of Unique Elements](./solutions/1748-sum-of-unique-elements.js)|Easy| 1749|[Maximum Absolute Sum of Any Subarray](./solutions/1749-maximum-absolute-sum-of-any-subarray.js)|Medium| 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| diff --git a/solutions/1738-find-kth-largest-xor-coordinate-value.js b/solutions/1738-find-kth-largest-xor-coordinate-value.js new file mode 100644 index 00000000..383d4166 --- /dev/null +++ b/solutions/1738-find-kth-largest-xor-coordinate-value.js @@ -0,0 +1,37 @@ +/** + * 1738. Find Kth Largest XOR Coordinate Value + * https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/ + * Difficulty: Medium + * + * You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also + * given an integer k. + * + * The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where + * 0 <= i <= a < m and 0 <= j <= b < n (0-indexed). + * + * Find the kth largest value (1-indexed) of all the coordinates of matrix. + */ + +/** + * @param {number[][]} matrix + * @param {number} k + * @return {number} + */ +var kthLargestValue = function(matrix, k) { + const rows = matrix.length; + const cols = matrix[0].length; + const xorValues = new Array(rows * cols); + const prefixXor = Array.from({ length: rows + 1 }, () => Array(cols + 1).fill(0)); + + let index = 0; + for (let i = 1; i <= rows; i++) { + for (let j = 1; j <= cols; j++) { + prefixXor[i][j] = prefixXor[i-1][j] ^ prefixXor[i][j-1] + ^ prefixXor[i-1][j-1] ^ matrix[i-1][j-1]; + xorValues[index++] = prefixXor[i][j]; + } + } + + xorValues.sort((a, b) => b - a); + return xorValues[k-1]; +}; From 2c216ecf3ede59fb34105c69d4cd07f7c0c3302c Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 28 Apr 2025 18:43:54 -0500 Subject: [PATCH 008/495] Add solution #1739 --- README.md | 3 ++- solutions/1739-building-boxes.js | 38 ++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 solutions/1739-building-boxes.js diff --git a/README.md b/README.md index 279c0936..f32702e1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,512 LeetCode solutions in JavaScript +# 1,513 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1340,6 +1340,7 @@ 1736|[Latest Time by Replacing Hidden Digits](./solutions/1736-latest-time-by-replacing-hidden-digits.js)|Easy| 1737|[Change Minimum Characters to Satisfy One of Three Conditions](./solutions/1737-change-minimum-characters-to-satisfy-one-of-three-conditions.js)|Medium| 1738|[Find Kth Largest XOR Coordinate Value](./solutions/1738-find-kth-largest-xor-coordinate-value.js)|Medium| +1739|[Building Boxes](./solutions/1739-building-boxes.js)|Hard| 1748|[Sum of Unique Elements](./solutions/1748-sum-of-unique-elements.js)|Easy| 1749|[Maximum Absolute Sum of Any Subarray](./solutions/1749-maximum-absolute-sum-of-any-subarray.js)|Medium| 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| diff --git a/solutions/1739-building-boxes.js b/solutions/1739-building-boxes.js new file mode 100644 index 00000000..0a80282a --- /dev/null +++ b/solutions/1739-building-boxes.js @@ -0,0 +1,38 @@ +/** + * 1739. Building Boxes + * https://leetcode.com/problems/building-boxes/ + * Difficulty: Hard + * + * You have a cubic storeroom where the width, length, and height of the room are all equal to n + * units. You are asked to place n boxes in this room where each box is a cube of unit side + * length. There are however some rules to placing the boxes: + * - You can place the boxes anywhere on the floor. + * - If box x is placed on top of the box y, then each side of the four vertical sides of the box + * y must either be adjacent to another box or to a wall. + * + * Given an integer n, return the minimum possible number of boxes touching the floor. + */ + +/** + * @param {number} n + * @return {number} + */ +var minimumBoxes = function(n) { + if (n < 4) return n; + + let baseSize = 0; + let totalBoxes = 0; + const triangular = k => k * (k + 1) / 2; + + while (totalBoxes + triangular(baseSize + 1) <= n) { + baseSize++; + totalBoxes += triangular(baseSize); + } + + const remaining = n - totalBoxes; + let extraFloor = 0; + + while (triangular(extraFloor) < remaining) extraFloor++; + + return triangular(baseSize) + extraFloor; +}; From 1676eeea5d55f5dcd74bd9b0923b6ad9f2c9b2e0 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 28 Apr 2025 18:45:09 -0500 Subject: [PATCH 009/495] Add solution #1742 --- README.md | 3 +- .../1742-maximum-number-of-balls-in-a-box.js | 44 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 solutions/1742-maximum-number-of-balls-in-a-box.js diff --git a/README.md b/README.md index f32702e1..cbc8bed3 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,513 LeetCode solutions in JavaScript +# 1,514 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1341,6 +1341,7 @@ 1737|[Change Minimum Characters to Satisfy One of Three Conditions](./solutions/1737-change-minimum-characters-to-satisfy-one-of-three-conditions.js)|Medium| 1738|[Find Kth Largest XOR Coordinate Value](./solutions/1738-find-kth-largest-xor-coordinate-value.js)|Medium| 1739|[Building Boxes](./solutions/1739-building-boxes.js)|Hard| +1742|[Maximum Number of Balls in a Box](./solutions/1742-maximum-number-of-balls-in-a-box.js)|Easy| 1748|[Sum of Unique Elements](./solutions/1748-sum-of-unique-elements.js)|Easy| 1749|[Maximum Absolute Sum of Any Subarray](./solutions/1749-maximum-absolute-sum-of-any-subarray.js)|Medium| 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| diff --git a/solutions/1742-maximum-number-of-balls-in-a-box.js b/solutions/1742-maximum-number-of-balls-in-a-box.js new file mode 100644 index 00000000..e16d7ae5 --- /dev/null +++ b/solutions/1742-maximum-number-of-balls-in-a-box.js @@ -0,0 +1,44 @@ +/** + * 1742. Maximum Number of Balls in a Box + * https://leetcode.com/problems/maximum-number-of-balls-in-a-box/ + * Difficulty: Easy + * + * You are working in a ball factory where you have n balls numbered from lowLimit up to + * highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of + * boxes numbered from 1 to infinity. + * + * Your job at this factory is to put each ball in the box with a number equal to the sum + * of digits of the ball's number. For example, the ball number 321 will be put in the + * box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1. + * + * Given two integers lowLimit and highLimit, return the number of balls in the box with + * the most balls. + */ + +/** + * @param {number} lowLimit + * @param {number} highLimit + * @return {number} + */ +var countBalls = function(lowLimit, highLimit) { + const boxCounts = new Map(); + let result = 0; + + for (let ball = lowLimit; ball <= highLimit; ball++) { + const box = sumDigits(ball); + const count = (boxCounts.get(box) || 0) + 1; + boxCounts.set(box, count); + result = Math.max(result, count); + } + + return result; + + function sumDigits(num) { + let sum = 0; + while (num > 0) { + sum += num % 10; + num = Math.floor(num / 10); + } + return sum; + } +}; From ae644af81a5ae45080a73a4a679ba3619061a682 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 28 Apr 2025 18:46:21 -0500 Subject: [PATCH 010/495] Add solution #1743 --- README.md | 3 +- ...3-restore-the-array-from-adjacent-pairs.js | 51 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 solutions/1743-restore-the-array-from-adjacent-pairs.js diff --git a/README.md b/README.md index cbc8bed3..ad91ae03 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,514 LeetCode solutions in JavaScript +# 1,515 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1342,6 +1342,7 @@ 1738|[Find Kth Largest XOR Coordinate Value](./solutions/1738-find-kth-largest-xor-coordinate-value.js)|Medium| 1739|[Building Boxes](./solutions/1739-building-boxes.js)|Hard| 1742|[Maximum Number of Balls in a Box](./solutions/1742-maximum-number-of-balls-in-a-box.js)|Easy| +1743|[Restore the Array From Adjacent Pairs](./solutions/1743-restore-the-array-from-adjacent-pairs.js)|Medium| 1748|[Sum of Unique Elements](./solutions/1748-sum-of-unique-elements.js)|Easy| 1749|[Maximum Absolute Sum of Any Subarray](./solutions/1749-maximum-absolute-sum-of-any-subarray.js)|Medium| 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| diff --git a/solutions/1743-restore-the-array-from-adjacent-pairs.js b/solutions/1743-restore-the-array-from-adjacent-pairs.js new file mode 100644 index 00000000..f7cdbb9f --- /dev/null +++ b/solutions/1743-restore-the-array-from-adjacent-pairs.js @@ -0,0 +1,51 @@ +/** + * 1743. Restore the Array From Adjacent Pairs + * https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/ + * Difficulty: Medium + * + * There is an integer array nums that consists of n unique elements, but you have + * forgotten it. However, you do remember every pair of adjacent elements in nums. + * + * You are given a 2D integer array adjacentPairs of size n - 1 where each + * adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums. + * + * It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in + * adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear + * in any order. + * + * Return the original array nums. If there are multiple solutions, return any of them. + */ + +/** + * @param {number[][]} adjacentPairs + * @return {number[]} + */ +var restoreArray = function(adjacentPairs) { + const graph = new Map(); + for (const [u, v] of adjacentPairs) { + graph.set(u, (graph.get(u) || []).concat(v)); + graph.set(v, (graph.get(v) || []).concat(u)); + } + + let start; + for (const [node, neighbors] of graph) { + if (neighbors.length === 1) { + start = node; + break; + } + } + + const result = [start]; + let prev = start; + let curr = graph.get(start)[0]; + + while (graph.get(curr).length > 1) { + result.push(curr); + const next = graph.get(curr).find(n => n !== prev); + prev = curr; + curr = next; + } + result.push(curr); + + return result; +}; From aa29d7e169459cceb5c23ec860336a296ad2482b Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 28 Apr 2025 19:07:45 -0500 Subject: [PATCH 011/495] Add solution #2962 --- README.md | 3 +- ...re-max-element-appears-at-least-k-times.js | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 solutions/2962-count-subarrays-where-max-element-appears-at-least-k-times.js diff --git a/README.md b/README.md index ad91ae03..e8b6682d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,515 LeetCode solutions in JavaScript +# 1,516 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1493,6 +1493,7 @@ 2873|[Maximum Value of an Ordered Triplet I](./solutions/2873-maximum-value-of-an-ordered-triplet-i.js)|Easy| 2874|[Maximum Value of an Ordered Triplet II](./solutions/2874-maximum-value-of-an-ordered-triplet-ii.js)|Medium| 2948|[Make Lexicographically Smallest Array by Swapping Elements](./solutions/2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium| +2962|[Count Subarrays Where Max Element Appears at Least K Times](./solutions/2962-count-subarrays-where-max-element-appears-at-least-k-times.js)|Medium| 2965|[Find Missing and Repeated Values](./solutions/2965-find-missing-and-repeated-values.js)|Easy| 2999|[Count the Number of Powerful Integers](./solutions/2999-count-the-number-of-powerful-integers.js)|Hard| 3042|[Count Prefix and Suffix Pairs I](./solutions/3042-count-prefix-and-suffix-pairs-i.js)|Easy| diff --git a/solutions/2962-count-subarrays-where-max-element-appears-at-least-k-times.js b/solutions/2962-count-subarrays-where-max-element-appears-at-least-k-times.js new file mode 100644 index 00000000..1a67fad9 --- /dev/null +++ b/solutions/2962-count-subarrays-where-max-element-appears-at-least-k-times.js @@ -0,0 +1,35 @@ +/** + * 2962. Count Subarrays Where Max Element Appears at Least K Times + * https://leetcode.com/problems/count-subarrays-where-max-element-appears-at-least-k-times/ + * Difficulty: Medium + * + * You are given an integer array nums and a positive integer k. + * + * Return the number of subarrays where the maximum element of nums appears at least k times in + * that subarray. + * + * A subarray is a contiguous sequence of elements within an array. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var countSubarrays = function(nums, k) { + const maxNum = Math.max(...nums); + let maxCount = 0; + let left = 0; + let result = 0; + + for (let right = 0; right < nums.length; right++) { + if (nums[right] === maxNum) maxCount++; + while (maxCount >= k) { + result += nums.length - right; + if (nums[left] === maxNum) maxCount--; + left++; + } + } + + return result; +}; From 2755ed4935e3d69501132b823141db05503de18e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 28 Apr 2025 19:11:21 -0500 Subject: [PATCH 012/495] Add solution #1744 --- README.md | 3 +- ...our-favorite-candy-on-your-favorite-day.js | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 solutions/1744-can-you-eat-your-favorite-candy-on-your-favorite-day.js diff --git a/README.md b/README.md index e8b6682d..e2c18944 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,516 LeetCode solutions in JavaScript +# 1,517 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1343,6 +1343,7 @@ 1739|[Building Boxes](./solutions/1739-building-boxes.js)|Hard| 1742|[Maximum Number of Balls in a Box](./solutions/1742-maximum-number-of-balls-in-a-box.js)|Easy| 1743|[Restore the Array From Adjacent Pairs](./solutions/1743-restore-the-array-from-adjacent-pairs.js)|Medium| +1744|[Can You Eat Your Favorite Candy on Your Favorite Day?](./solutions/1744-can-you-eat-your-favorite-candy-on-your-favorite-day.js)|Medium| 1748|[Sum of Unique Elements](./solutions/1748-sum-of-unique-elements.js)|Easy| 1749|[Maximum Absolute Sum of Any Subarray](./solutions/1749-maximum-absolute-sum-of-any-subarray.js)|Medium| 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| diff --git a/solutions/1744-can-you-eat-your-favorite-candy-on-your-favorite-day.js b/solutions/1744-can-you-eat-your-favorite-candy-on-your-favorite-day.js new file mode 100644 index 00000000..ac72e529 --- /dev/null +++ b/solutions/1744-can-you-eat-your-favorite-candy-on-your-favorite-day.js @@ -0,0 +1,45 @@ +/** + * 1744. Can You Eat Your Favorite Candy on Your Favorite Day? + * https://leetcode.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day/ + * Difficulty: Medium + * + * You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] + * represents the number of candies of the ith type you have. You are also given a 2D array + * queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]. + * + * You play a game with the following rules: + * - You start eating candies on day 0. + * - You cannot eat any candy of type i unless you have eaten all candies of type i - 1. + * - You must eat at least one candy per day until you have eaten all the candies. + * + * Construct a boolean array answer such that answer.length == queries.length and answer[i] is + * true if you can eat a candy of type favoriteTypei on day favoriteDayi without eating more + * than dailyCapi candies on any day, and false otherwise. Note that you can eat different + * types of candy on the same day, provided that you follow rule 2. + * + * Return the constructed array answer. + */ + +/** + * @param {number[]} candiesCount + * @param {number[][]} queries + * @return {boolean[]} + */ +var canEat = function(candiesCount, queries) { + const prefixSums = [0]; + for (const count of candiesCount) { + prefixSums.push(prefixSums.at(-1) + count); + } + + const result = new Array(queries.length); + for (let i = 0; i < queries.length; i++) { + const [type, day, cap] = queries[i]; + const minCandies = day; + const maxCandies = (day + 1) * cap; + const typeStart = prefixSums[type]; + const typeEnd = prefixSums[type + 1] - 1; + result[i] = maxCandies > typeStart && minCandies <= typeEnd; + } + + return result; +}; From 69de7e1df68858dd5d8fbfe412bad50a1cef0f19 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 28 Apr 2025 19:12:15 -0500 Subject: [PATCH 013/495] Add solution #1745 --- README.md | 3 +- solutions/1745-palindrome-partitioning-iv.js | 37 ++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 solutions/1745-palindrome-partitioning-iv.js diff --git a/README.md b/README.md index e2c18944..c5ed546f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,517 LeetCode solutions in JavaScript +# 1,518 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1344,6 +1344,7 @@ 1742|[Maximum Number of Balls in a Box](./solutions/1742-maximum-number-of-balls-in-a-box.js)|Easy| 1743|[Restore the Array From Adjacent Pairs](./solutions/1743-restore-the-array-from-adjacent-pairs.js)|Medium| 1744|[Can You Eat Your Favorite Candy on Your Favorite Day?](./solutions/1744-can-you-eat-your-favorite-candy-on-your-favorite-day.js)|Medium| +1745|[Palindrome Partitioning IV](./solutions/1745-palindrome-partitioning-iv.js)|Hard| 1748|[Sum of Unique Elements](./solutions/1748-sum-of-unique-elements.js)|Easy| 1749|[Maximum Absolute Sum of Any Subarray](./solutions/1749-maximum-absolute-sum-of-any-subarray.js)|Medium| 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| diff --git a/solutions/1745-palindrome-partitioning-iv.js b/solutions/1745-palindrome-partitioning-iv.js new file mode 100644 index 00000000..7fefea0f --- /dev/null +++ b/solutions/1745-palindrome-partitioning-iv.js @@ -0,0 +1,37 @@ +/** + * 1745. Palindrome Partitioning IV + * https://leetcode.com/problems/palindrome-partitioning-iv/ + * Difficulty: Hard + * + * Given a string s, return true if it is possible to split the string s into three non-empty + * palindromic substrings. Otherwise, return false. + * + * A string is said to be palindrome if it the same string when reversed. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var checkPartitioning = function(s) { + const n = s.length; + const isPalindrome = Array.from({ length: n }, () => Array(n).fill(false)); + + for (let i = n - 1; i >= 0; i--) { + for (let j = i; j < n; j++) { + if (s[i] === s[j] && (j - i <= 2 || isPalindrome[i + 1][j - 1])) { + isPalindrome[i][j] = true; + } + } + } + + for (let i = 1; i < n - 1; i++) { + for (let j = i; j < n - 1; j++) { + if (isPalindrome[0][i - 1] && isPalindrome[i][j] && isPalindrome[j + 1][n - 1]) { + return true; + } + } + } + + return false; +}; From 6a6753594769a06a544697c072ce253b78e8fcdf Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 28 Apr 2025 19:13:56 -0500 Subject: [PATCH 014/495] Add solution #1750 --- README.md | 3 +- ...h-of-string-after-deleting-similar-ends.js | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 solutions/1750-minimum-length-of-string-after-deleting-similar-ends.js diff --git a/README.md b/README.md index c5ed546f..a7b90bd7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,518 LeetCode solutions in JavaScript +# 1,519 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1347,6 +1347,7 @@ 1745|[Palindrome Partitioning IV](./solutions/1745-palindrome-partitioning-iv.js)|Hard| 1748|[Sum of Unique Elements](./solutions/1748-sum-of-unique-elements.js)|Easy| 1749|[Maximum Absolute Sum of Any Subarray](./solutions/1749-maximum-absolute-sum-of-any-subarray.js)|Medium| +1750|[Minimum Length of String After Deleting Similar Ends](./solutions/1750-minimum-length-of-string-after-deleting-similar-ends.js)|Medium| 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| 1764|[Form Array by Concatenating Subarrays of Another Array](./solutions/1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| 1765|[Map of Highest Peak](./solutions/1765-map-of-highest-peak.js)|Medium| diff --git a/solutions/1750-minimum-length-of-string-after-deleting-similar-ends.js b/solutions/1750-minimum-length-of-string-after-deleting-similar-ends.js new file mode 100644 index 00000000..c8cdb813 --- /dev/null +++ b/solutions/1750-minimum-length-of-string-after-deleting-similar-ends.js @@ -0,0 +1,33 @@ +/** + * 1750. Minimum Length of String After Deleting Similar Ends + * https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/ + * Difficulty: Medium + * + * Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the + * following algorithm on the string any number of times: + * 1. Pick a non-empty prefix from the string s where all the characters in the prefix are equal. + * 2. Pick a non-empty suffix from the string s where all the characters in this suffix are equal. + * 3. The prefix and the suffix should not intersect at any index. + * 4. The characters from the prefix and suffix must be the same. + * 5. Delete both the prefix and the suffix. + * + * Return the minimum length of s after performing the above operation any number of times + * (possibly zero times). + */ + +/** + * @param {string} s + * @return {number} + */ +var minimumLength = function(s) { + let left = 0; + let right = s.length - 1; + + while (left < right && s[left] === s[right]) { + const char = s[left]; + while (left <= right && s[left] === char) left++; + while (left <= right && s[right] === char) right--; + } + + return Math.max(0, right - left + 1); +}; From e721284a4737f13debff65fca3c34c49563ff50e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 28 Apr 2025 19:15:23 -0500 Subject: [PATCH 015/495] Add solution #1751 --- README.md | 3 +- ...umber-of-events-that-can-be-attended-ii.js | 54 +++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 solutions/1751-maximum-number-of-events-that-can-be-attended-ii.js diff --git a/README.md b/README.md index a7b90bd7..4a63f8b7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,519 LeetCode solutions in JavaScript +# 1,520 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1348,6 +1348,7 @@ 1748|[Sum of Unique Elements](./solutions/1748-sum-of-unique-elements.js)|Easy| 1749|[Maximum Absolute Sum of Any Subarray](./solutions/1749-maximum-absolute-sum-of-any-subarray.js)|Medium| 1750|[Minimum Length of String After Deleting Similar Ends](./solutions/1750-minimum-length-of-string-after-deleting-similar-ends.js)|Medium| +1751|[Maximum Number of Events That Can Be Attended II](./solutions/1751-maximum-number-of-events-that-can-be-attended-ii.js)|Hard| 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| 1764|[Form Array by Concatenating Subarrays of Another Array](./solutions/1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| 1765|[Map of Highest Peak](./solutions/1765-map-of-highest-peak.js)|Medium| diff --git a/solutions/1751-maximum-number-of-events-that-can-be-attended-ii.js b/solutions/1751-maximum-number-of-events-that-can-be-attended-ii.js new file mode 100644 index 00000000..74cd6ee3 --- /dev/null +++ b/solutions/1751-maximum-number-of-events-that-can-be-attended-ii.js @@ -0,0 +1,54 @@ +/** + * 1751. Maximum Number of Events That Can Be Attended II + * https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/ + * Difficulty: Hard + * + * You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event + * starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value + * of valuei. You are also given an integer k which represents the maximum number of events you can + * attend. + * + * You can only attend one event at a time. If you choose to attend an event, you must attend the + * entire event. Note that the end day is inclusive: that is, you cannot attend two events where + * one of them starts and the other ends on the same day. + * + * Return the maximum sum of values that you can receive by attending events. + */ + +/** + * @param {number[][]} events + * @param {number} k + * @return {number} + */ +var maxValue = function(events, k) { + events.sort((a, b) => a[0] - b[0]); + const n = events.length; + const dp = Array.from({ length: k + 1 }, () => new Array(n + 1).fill(-1)); + + return maximize(0, k); + + function findNext(index, end) { + let left = index; + let right = n; + while (left < right) { + const mid = Math.floor((left + right) / 2); + if (events[mid][0] > end) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } + + function maximize(index, remaining) { + if (index >= n || remaining === 0) return 0; + if (dp[remaining][index] !== -1) return dp[remaining][index]; + + const nextIndex = findNext(index + 1, events[index][1]); + const take = events[index][2] + maximize(nextIndex, remaining - 1); + const skip = maximize(index + 1, remaining); + + return dp[remaining][index] = Math.max(take, skip); + } +}; From a4df445c1bf2bf1bc8dbaeca77891e6716566b1d Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 28 Apr 2025 21:30:18 -0500 Subject: [PATCH 016/495] Add solution #1753 --- README.md | 3 +- ...1753-maximum-score-from-removing-stones.js | 32 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 solutions/1753-maximum-score-from-removing-stones.js diff --git a/README.md b/README.md index 4a63f8b7..492b449e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,520 LeetCode solutions in JavaScript +# 1,521 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1350,6 +1350,7 @@ 1750|[Minimum Length of String After Deleting Similar Ends](./solutions/1750-minimum-length-of-string-after-deleting-similar-ends.js)|Medium| 1751|[Maximum Number of Events That Can Be Attended II](./solutions/1751-maximum-number-of-events-that-can-be-attended-ii.js)|Hard| 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| +1753|[Maximum Score From Removing Stones](./solutions/1753-maximum-score-from-removing-stones.js)|Medium| 1764|[Form Array by Concatenating Subarrays of Another Array](./solutions/1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| 1765|[Map of Highest Peak](./solutions/1765-map-of-highest-peak.js)|Medium| 1768|[Merge Strings Alternately](./solutions/1768-merge-strings-alternately.js)|Easy| diff --git a/solutions/1753-maximum-score-from-removing-stones.js b/solutions/1753-maximum-score-from-removing-stones.js new file mode 100644 index 00000000..24dfa2f0 --- /dev/null +++ b/solutions/1753-maximum-score-from-removing-stones.js @@ -0,0 +1,32 @@ +/** + * 1753. Maximum Score From Removing Stones + * https://leetcode.com/problems/maximum-score-from-removing-stones/ + * Difficulty: Medium + * + * You are playing a solitaire game with three piles of stones of sizes a, b, and c respectively. + * Each turn you choose two different non-empty piles, take one stone from each, and add 1 point + * to your score. The game stops when there are fewer than two non-empty piles (meaning there are + * no more available moves). + * + * Given three integers a, b, and c return the maximum score you can get. + */ + +/** + * @param {number} a + * @param {number} b + * @param {number} c + * @return {number} + */ +var maximumScore = function(a, b, c) { + const piles = [a, b, c].sort((x, y) => y - x); + let score = 0; + + while (piles[0] > 0 && piles[1] > 0) { + piles[0]--; + piles[1]--; + score++; + piles.sort((x, y) => y - x); + } + + return score; +}; From 80585265ad8aff8c9c88cbec45d81ee213d478fe Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 28 Apr 2025 21:32:03 -0500 Subject: [PATCH 017/495] Add solution #1754 --- README.md | 3 +- .../1754-largest-merge-of-two-strings.js | 44 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 solutions/1754-largest-merge-of-two-strings.js diff --git a/README.md b/README.md index 492b449e..5e2c3f4b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,521 LeetCode solutions in JavaScript +# 1,522 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1351,6 +1351,7 @@ 1751|[Maximum Number of Events That Can Be Attended II](./solutions/1751-maximum-number-of-events-that-can-be-attended-ii.js)|Hard| 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| 1753|[Maximum Score From Removing Stones](./solutions/1753-maximum-score-from-removing-stones.js)|Medium| +1754|[Largest Merge Of Two Strings](./solutions/1754-largest-merge-of-two-strings.js)|Medium| 1764|[Form Array by Concatenating Subarrays of Another Array](./solutions/1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| 1765|[Map of Highest Peak](./solutions/1765-map-of-highest-peak.js)|Medium| 1768|[Merge Strings Alternately](./solutions/1768-merge-strings-alternately.js)|Easy| diff --git a/solutions/1754-largest-merge-of-two-strings.js b/solutions/1754-largest-merge-of-two-strings.js new file mode 100644 index 00000000..0ba08bd4 --- /dev/null +++ b/solutions/1754-largest-merge-of-two-strings.js @@ -0,0 +1,44 @@ +/** + * 1754. Largest Merge Of Two Strings + * https://leetcode.com/problems/largest-merge-of-two-strings/ + * Difficulty: Medium + * + * You are given two strings word1 and word2. You want to construct a string merge in the + * following way: while either word1 or word2 are non-empty, choose one of the following + * options: + * - If word1 is non-empty, append the first character in word1 to merge and delete it from word1. + * - For example, if word1 = "abc" and merge = "dv", then after choosing this operation, + * word1 = "bc" and merge = "dva". + * - If word2 is non-empty, append the first character in word2 to merge and delete it from word2. + * - For example, if word2 = "abc" and merge = "", then after choosing this operation, + * word2 = "bc" and merge = "a". + * + * Return the lexicographically largest merge you can construct. + * + * A string a is lexicographically larger than a string b (of the same length) if in the first + * position where a and b differ, a has a character strictly larger than the corresponding + * character in b. For example, "abcd" is lexicographically larger than "abcc" because the + * first position they differ is at the fourth character, and d is greater than c. + */ + +/** + * @param {string} word1 + * @param {string} word2 + * @return {string} + */ +var largestMerge = function(word1, word2) { + let merge = ''; + let i = 0; + let j = 0; + + while (i < word1.length && j < word2.length) { + if (word1.slice(i) >= word2.slice(j)) { + merge += word1[i++]; + } else { + merge += word2[j++]; + } + } + + merge += word1.slice(i) + word2.slice(j); + return merge; +}; From dd9019a73eb0f4c5e2adb38a0e56e26070377325 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 28 Apr 2025 21:34:17 -0500 Subject: [PATCH 018/495] Add solution #1755 --- README.md | 3 +- solutions/1755-closest-subsequence-sum.js | 63 +++++++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 solutions/1755-closest-subsequence-sum.js diff --git a/README.md b/README.md index 5e2c3f4b..10c8e70c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,522 LeetCode solutions in JavaScript +# 1,523 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1352,6 +1352,7 @@ 1752|[Check if Array Is Sorted and Rotated](./solutions/1752-check-if-array-is-sorted-and-rotated.js)|Easy| 1753|[Maximum Score From Removing Stones](./solutions/1753-maximum-score-from-removing-stones.js)|Medium| 1754|[Largest Merge Of Two Strings](./solutions/1754-largest-merge-of-two-strings.js)|Medium| +1755|[Closest Subsequence Sum](./solutions/1755-closest-subsequence-sum.js)|Hard| 1764|[Form Array by Concatenating Subarrays of Another Array](./solutions/1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| 1765|[Map of Highest Peak](./solutions/1765-map-of-highest-peak.js)|Medium| 1768|[Merge Strings Alternately](./solutions/1768-merge-strings-alternately.js)|Easy| diff --git a/solutions/1755-closest-subsequence-sum.js b/solutions/1755-closest-subsequence-sum.js new file mode 100644 index 00000000..bad15f92 --- /dev/null +++ b/solutions/1755-closest-subsequence-sum.js @@ -0,0 +1,63 @@ +/** + * 1755. Closest Subsequence Sum + * https://leetcode.com/problems/closest-subsequence-sum/ + * Difficulty: Hard + * + * You are given an integer array nums and an integer goal. + * + * You want to choose a subsequence of nums such that the sum of its elements is the closest + * possible to goal. That is, if the sum of the subsequence's elements is sum, then you want + * to minimize the absolute difference abs(sum - goal). + * + * Return the minimum possible value of abs(sum - goal). + * + * Note that a subsequence of an array is an array formed by removing some elements (possibly + * all or none) of the original array. + */ + +/** + * @param {number[]} nums + * @param {number} goal + * @return {number} + */ +var minAbsDifference = function(nums, goal) { + const n = nums.length; + const half = Math.floor(n / 2); + const leftSums = new Set(); + const rightSums = new Set(); + + generateSums(0, half, leftSums); + generateSums(half, n, rightSums); + + const rightArray = [...rightSums].sort((a, b) => a - b); + let minDiff = Infinity; + + for (const leftSum of leftSums) { + const target = goal - leftSum; + let left = 0; + let right = rightArray.length - 1; + + while (left <= right) { + const mid = Math.floor((left + right) / 2); + const sum = leftSum + rightArray[mid]; + minDiff = Math.min(minDiff, Math.abs(sum - goal)); + + if (sum < goal) { + left = mid + 1; + } else { + right = mid - 1; + } + } + } + + return minDiff; + + function generateSums(start, end, sums, current = 0) { + if (start === end) { + sums.add(current); + return; + } + generateSums(start + 1, end, sums, current); + generateSums(start + 1, end, sums, current + nums[start]); + } +}; From efd66fff11d4252395d8da2b97813f1a5a3001a5 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 28 Apr 2025 21:35:39 -0500 Subject: [PATCH 019/495] Add solution #1758 --- README.md | 3 +- ...anges-to-make-alternating-binary-string.js | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 solutions/1758-minimum-changes-to-make-alternating-binary-string.js diff --git a/README.md b/README.md index 10c8e70c..52a6bfc8 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,523 LeetCode solutions in JavaScript +# 1,524 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1353,6 +1353,7 @@ 1753|[Maximum Score From Removing Stones](./solutions/1753-maximum-score-from-removing-stones.js)|Medium| 1754|[Largest Merge Of Two Strings](./solutions/1754-largest-merge-of-two-strings.js)|Medium| 1755|[Closest Subsequence Sum](./solutions/1755-closest-subsequence-sum.js)|Hard| +1758|[Minimum Changes To Make Alternating Binary String](./solutions/1758-minimum-changes-to-make-alternating-binary-string.js)|Easy| 1764|[Form Array by Concatenating Subarrays of Another Array](./solutions/1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| 1765|[Map of Highest Peak](./solutions/1765-map-of-highest-peak.js)|Medium| 1768|[Merge Strings Alternately](./solutions/1768-merge-strings-alternately.js)|Easy| diff --git a/solutions/1758-minimum-changes-to-make-alternating-binary-string.js b/solutions/1758-minimum-changes-to-make-alternating-binary-string.js new file mode 100644 index 00000000..dad5e376 --- /dev/null +++ b/solutions/1758-minimum-changes-to-make-alternating-binary-string.js @@ -0,0 +1,31 @@ +/** + * 1758. Minimum Changes To Make Alternating Binary String + * https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/ + * Difficulty: Easy + * + * You are given a string s consisting only of the characters '0' and '1'. In one operation, you can + * change any '0' to '1' or vice versa. + * + * The string is called alternating if no two adjacent characters are equal. For example, the string + * "010" is alternating, while the string "0100" is not. + * + * Return the minimum number of operations needed to make s alternating. + */ + +/** + * @param {string} s + * @return {number} + */ +var minOperations = function(s) { + let changesToZeroStart = 0; + let changesToOneStart = 0; + + for (let i = 0; i < s.length; i++) { + const expectedZeroStart = i % 2 === 0 ? '0' : '1'; + const expectedOneStart = i % 2 === 0 ? '1' : '0'; + if (s[i] !== expectedZeroStart) changesToZeroStart++; + if (s[i] !== expectedOneStart) changesToOneStart++; + } + + return Math.min(changesToZeroStart, changesToOneStart); +}; From ae02d4ac1841ad0fecdcb4dd718cff9f469895f5 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 28 Apr 2025 21:36:52 -0500 Subject: [PATCH 020/495] Add solution #1759 --- README.md | 3 +- ...9-count-number-of-homogenous-substrings.js | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 solutions/1759-count-number-of-homogenous-substrings.js diff --git a/README.md b/README.md index 52a6bfc8..7546dc27 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,524 LeetCode solutions in JavaScript +# 1,525 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1354,6 +1354,7 @@ 1754|[Largest Merge Of Two Strings](./solutions/1754-largest-merge-of-two-strings.js)|Medium| 1755|[Closest Subsequence Sum](./solutions/1755-closest-subsequence-sum.js)|Hard| 1758|[Minimum Changes To Make Alternating Binary String](./solutions/1758-minimum-changes-to-make-alternating-binary-string.js)|Easy| +1759|[Count Number of Homogenous Substrings](./solutions/1759-count-number-of-homogenous-substrings.js)|Medium| 1764|[Form Array by Concatenating Subarrays of Another Array](./solutions/1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| 1765|[Map of Highest Peak](./solutions/1765-map-of-highest-peak.js)|Medium| 1768|[Merge Strings Alternately](./solutions/1768-merge-strings-alternately.js)|Easy| diff --git a/solutions/1759-count-number-of-homogenous-substrings.js b/solutions/1759-count-number-of-homogenous-substrings.js new file mode 100644 index 00000000..b6fb8fbc --- /dev/null +++ b/solutions/1759-count-number-of-homogenous-substrings.js @@ -0,0 +1,35 @@ +/** + * 1759. Count Number of Homogenous Substrings + * https://leetcode.com/problems/count-number-of-homogenous-substrings/ + * Difficulty: Medium + * + * Given a string s, return the number of homogenous substrings of s. Since the answer may be + * too large, return it modulo 109 + 7. + * + * A string is homogenous if all the characters of the string are the same. + * + * A substring is a contiguous sequence of characters within a string. + */ + +/** + * @param {string} s + * @return {number} + */ +var countHomogenous = function(s) { + const mod = 1e9 + 7; + let result = 0; + let streak = 1; + + for (let i = 1; i < s.length; i++) { + if (s[i] === s[i - 1]) { + streak++; + } else { + result = (result + (streak * (streak + 1) / 2)) % mod; + streak = 1; + } + } + + result = (result + (streak * (streak + 1) / 2)) % mod; + + return result; +}; From 99b9286f1a8a235c9816b6d3753242c91eaa1e08 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 29 Apr 2025 18:04:03 -0500 Subject: [PATCH 021/495] Add solution #1760 --- README.md | 3 +- .../1760-minimum-limit-of-balls-in-a-bag.js | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 solutions/1760-minimum-limit-of-balls-in-a-bag.js diff --git a/README.md b/README.md index 7546dc27..934b193b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,525 LeetCode solutions in JavaScript +# 1,526 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1355,6 +1355,7 @@ 1755|[Closest Subsequence Sum](./solutions/1755-closest-subsequence-sum.js)|Hard| 1758|[Minimum Changes To Make Alternating Binary String](./solutions/1758-minimum-changes-to-make-alternating-binary-string.js)|Easy| 1759|[Count Number of Homogenous Substrings](./solutions/1759-count-number-of-homogenous-substrings.js)|Medium| +1760|[Minimum Limit of Balls in a Bag](./solutions/1760-minimum-limit-of-balls-in-a-bag.js)|Medium| 1764|[Form Array by Concatenating Subarrays of Another Array](./solutions/1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| 1765|[Map of Highest Peak](./solutions/1765-map-of-highest-peak.js)|Medium| 1768|[Merge Strings Alternately](./solutions/1768-merge-strings-alternately.js)|Easy| diff --git a/solutions/1760-minimum-limit-of-balls-in-a-bag.js b/solutions/1760-minimum-limit-of-balls-in-a-bag.js new file mode 100644 index 00000000..f8ff3efa --- /dev/null +++ b/solutions/1760-minimum-limit-of-balls-in-a-bag.js @@ -0,0 +1,45 @@ +/** + * 1760. Minimum Limit of Balls in a Bag + * https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/ + * Difficulty: Medium + * + * You are given an integer array nums where the ith bag contains nums[i] balls. You are also + * given an integer maxOperations. + * + * You can perform the following operation at most maxOperations times: + * - Take any bag of balls and divide it into two new bags with a positive number of balls. + * - For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags + * of 2 and 3 balls. + * + * Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after + * the operations. + * + * Return the minimum possible penalty after performing the operations. + */ + +/** + * @param {number[]} nums + * @param {number} maxOperations + * @return {number} + */ +var minimumSize = function(nums, maxOperations) { + let left = 1; + let right = Math.max(...nums); + + while (left < right) { + const mid = Math.floor((left + right) / 2); + let operations = 0; + + for (const num of nums) { + operations += Math.ceil(num / mid) - 1; + } + + if (operations <= maxOperations) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; +}; From 09603d5424703018d9e18e5a3633357b17b054e0 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 29 Apr 2025 18:05:29 -0500 Subject: [PATCH 022/495] Add solution #1761 --- README.md | 3 +- ...m-degree-of-a-connected-trio-in-a-graph.js | 49 +++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 solutions/1761-minimum-degree-of-a-connected-trio-in-a-graph.js diff --git a/README.md b/README.md index 934b193b..623b25ce 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,526 LeetCode solutions in JavaScript +# 1,527 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1356,6 +1356,7 @@ 1758|[Minimum Changes To Make Alternating Binary String](./solutions/1758-minimum-changes-to-make-alternating-binary-string.js)|Easy| 1759|[Count Number of Homogenous Substrings](./solutions/1759-count-number-of-homogenous-substrings.js)|Medium| 1760|[Minimum Limit of Balls in a Bag](./solutions/1760-minimum-limit-of-balls-in-a-bag.js)|Medium| +1761|[Minimum Degree of a Connected Trio in a Graph](./solutions/1761-minimum-degree-of-a-connected-trio-in-a-graph.js)|Hard| 1764|[Form Array by Concatenating Subarrays of Another Array](./solutions/1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| 1765|[Map of Highest Peak](./solutions/1765-map-of-highest-peak.js)|Medium| 1768|[Merge Strings Alternately](./solutions/1768-merge-strings-alternately.js)|Easy| diff --git a/solutions/1761-minimum-degree-of-a-connected-trio-in-a-graph.js b/solutions/1761-minimum-degree-of-a-connected-trio-in-a-graph.js new file mode 100644 index 00000000..d913b953 --- /dev/null +++ b/solutions/1761-minimum-degree-of-a-connected-trio-in-a-graph.js @@ -0,0 +1,49 @@ +/** + * 1761. Minimum Degree of a Connected Trio in a Graph + * https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph/ + * Difficulty: Hard + * + * You are given an undirected graph. You are given an integer n which is the number of nodes in + * the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an + * undirected edge between ui and vi. + * + * A connected trio is a set of three nodes where there is an edge between every pair of them. + * + * The degree of a connected trio is the number of edges where one endpoint is in the trio, and + * the other is not. + * + * Return the minimum degree of a connected trio in the graph, or -1 if the graph has no + * connected trios. + */ + +/** + * @param {number} n + * @param {number[][]} edges + * @return {number} + */ +var minTrioDegree = function(n, edges) { + const graph = Array.from({ length: n + 1 }, () => new Set()); + const degrees = Array(n + 1).fill(0); + + for (const [u, v] of edges) { + graph[u].add(v); + graph[v].add(u); + degrees[u]++; + degrees[v]++; + } + + let minDegree = Infinity; + + for (let i = 1; i <= n; i++) { + for (const j of graph[i]) { + for (const k of graph[j]) { + if (graph[k].has(i)) { + const trioDegree = degrees[i] + degrees[j] + degrees[k] - 6; + minDegree = Math.min(minDegree, trioDegree); + } + } + } + } + + return minDegree === Infinity ? -1 : minDegree; +}; From 29a6289510144c040cb30bb30f525f254bb1207e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 29 Apr 2025 18:06:48 -0500 Subject: [PATCH 023/495] Add solution #1763 --- README.md | 3 +- solutions/1763-longest-nice-substring.js | 38 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 solutions/1763-longest-nice-substring.js diff --git a/README.md b/README.md index 623b25ce..00804036 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,527 LeetCode solutions in JavaScript +# 1,528 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1357,6 +1357,7 @@ 1759|[Count Number of Homogenous Substrings](./solutions/1759-count-number-of-homogenous-substrings.js)|Medium| 1760|[Minimum Limit of Balls in a Bag](./solutions/1760-minimum-limit-of-balls-in-a-bag.js)|Medium| 1761|[Minimum Degree of a Connected Trio in a Graph](./solutions/1761-minimum-degree-of-a-connected-trio-in-a-graph.js)|Hard| +1763|[Longest Nice Substring](./solutions/1763-longest-nice-substring.js)|Easy| 1764|[Form Array by Concatenating Subarrays of Another Array](./solutions/1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| 1765|[Map of Highest Peak](./solutions/1765-map-of-highest-peak.js)|Medium| 1768|[Merge Strings Alternately](./solutions/1768-merge-strings-alternately.js)|Easy| diff --git a/solutions/1763-longest-nice-substring.js b/solutions/1763-longest-nice-substring.js new file mode 100644 index 00000000..00495b99 --- /dev/null +++ b/solutions/1763-longest-nice-substring.js @@ -0,0 +1,38 @@ +/** + * 1763. Longest Nice Substring + * https://leetcode.com/problems/longest-nice-substring/ + * Difficulty: Easy + * + * A string s is nice if, for every letter of the alphabet that s contains, it appears both + * in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, + * and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. + * + * Given a string s, return the longest substring of s that is nice. If there are multiple, + * return the substring of the earliest occurrence. If there are none, return an empty string. + */ + +/** + * @param {string} s + * @return {string} + */ +var longestNiceSubstring = function(s) { + let longest = ''; + + for (let i = 0; i < s.length; i++) { + for (let j = i; j < s.length; j++) { + const substr = s.slice(i, j + 1); + if (substr.length <= longest.length) continue; + const chars = new Set(substr.toLowerCase().split('')); + let isNice = true; + for (const char of chars) { + if (!substr.includes(char.toLowerCase()) || !substr.includes(char.toUpperCase())) { + isNice = false; + break; + } + } + if (isNice) longest = substr; + } + } + + return longest; +}; From 32e32fa9e065689ca91568ddac8d692de6beb4c7 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 29 Apr 2025 18:08:33 -0500 Subject: [PATCH 024/495] Add solution #1766 --- README.md | 3 +- solutions/1766-tree-of-coprimes.js | 76 ++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 solutions/1766-tree-of-coprimes.js diff --git a/README.md b/README.md index 00804036..e538babe 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,528 LeetCode solutions in JavaScript +# 1,529 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1360,6 +1360,7 @@ 1763|[Longest Nice Substring](./solutions/1763-longest-nice-substring.js)|Easy| 1764|[Form Array by Concatenating Subarrays of Another Array](./solutions/1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| 1765|[Map of Highest Peak](./solutions/1765-map-of-highest-peak.js)|Medium| +1766|[Tree of Coprimes](./solutions/1766-tree-of-coprimes.js)|Hard| 1768|[Merge Strings Alternately](./solutions/1768-merge-strings-alternately.js)|Easy| 1769|[Minimum Number of Operations to Move All Balls to Each Box](./solutions/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](./solutions/1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| diff --git a/solutions/1766-tree-of-coprimes.js b/solutions/1766-tree-of-coprimes.js new file mode 100644 index 00000000..31ec7f8d --- /dev/null +++ b/solutions/1766-tree-of-coprimes.js @@ -0,0 +1,76 @@ +/** + * 1766. Tree of Coprimes + * https://leetcode.com/problems/tree-of-coprimes/ + * Difficulty: Hard + * + * There is 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. Each node has a value associated with it, + * and the root of the tree is node 0. + * + * To represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] + * represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes + * uj and vj in the tree. + * + * Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor + * of x and y. + * + * An ancestor of a node i is any other node on the shortest path from node i to the root. A node + * is not considered an ancestor of itself. + * + * Return an array ans of size n, where ans[i] is the closest ancestor to node i such that + * nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor. + */ + +/** + * @param {number[]} nums + * @param {number[][]} edges + * @return {number[]} + */ +var getCoprimes = function(nums, edges) { + const n = nums.length; + const graph = Array.from({ length: n }, () => []); + for (const [u, v] of edges) { + graph[u].push(v); + graph[v].push(u); + } + + const result = Array(n).fill(-1); + const valueDepth = Array(51).fill().map(() => []); + const visited = new Set(); + + dfs(0, 0, -1); + return result; + + function dfs(node, depth, parent) { + const val = nums[node]; + let maxDepth = -1; + let closestAncestor = -1; + + for (let i = 1; i <= 50; i++) { + if (gcd(val, i) === 1 && valueDepth[i].length) { + const [ancestor, d] = valueDepth[i].at(-1); + if (d > maxDepth) { + maxDepth = d; + closestAncestor = ancestor; + } + } + } + + result[node] = closestAncestor; + valueDepth[val].push([node, depth]); + visited.add(node); + + for (const neighbor of graph[node]) { + if (!visited.has(neighbor)) { + dfs(neighbor, depth + 1, node); + } + } + + valueDepth[val].pop(); + } + + function gcd(a, b) { + while (b) [a, b] = [b, a % b]; + return a; + } +}; From 8b816850d52e13ee1e37dcfb51802e78f0bce526 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 29 Apr 2025 18:09:47 -0500 Subject: [PATCH 025/495] Add solution #1770 --- README.md | 3 +- ...om-performing-multiplication-operations.js | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 solutions/1770-maximum-score-from-performing-multiplication-operations.js diff --git a/README.md b/README.md index e538babe..fb0f030d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,529 LeetCode solutions in JavaScript +# 1,530 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1363,6 +1363,7 @@ 1766|[Tree of Coprimes](./solutions/1766-tree-of-coprimes.js)|Hard| 1768|[Merge Strings Alternately](./solutions/1768-merge-strings-alternately.js)|Easy| 1769|[Minimum Number of Operations to Move All Balls to Each Box](./solutions/1769-minimum-number-of-operations-to-move-all-balls-to-each-box.js)|Medium| +1770|[Maximum Score from Performing Multiplication Operations](./solutions/1770-maximum-score-from-performing-multiplication-operations.js)|Hard| 1780|[Check if Number is a Sum of Powers of Three](./solutions/1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| diff --git a/solutions/1770-maximum-score-from-performing-multiplication-operations.js b/solutions/1770-maximum-score-from-performing-multiplication-operations.js new file mode 100644 index 00000000..73ec2746 --- /dev/null +++ b/solutions/1770-maximum-score-from-performing-multiplication-operations.js @@ -0,0 +1,39 @@ +/** + * 1770. Maximum Score from Performing Multiplication Operations + * https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/ + * Difficulty: Hard + * + * You are given two 0-indexed integer arrays nums and multipliers of size n and m respectively, + * where n >= m. + * + * You begin with a score of 0. You want to perform exactly m operations. On the ith operation + * (0-indexed) you will: + * - Choose one integer x from either the start or the end of the array nums. + * - Add multipliers[i] * x to your score. + * - Note that multipliers[0] corresponds to the first operation, multipliers[1] to the second + * operation, and so on. + * - Remove x from nums. + * + * Return the maximum score after performing m operations. + */ + +/** + * @param {number[]} nums + * @param {number[]} multipliers + * @return {number} + */ +var maximumScore = function(nums, multipliers) { + const m = multipliers.length; + const dp = Array.from({ length: m + 1 }, () => Array(m + 1).fill(0)); + + for (let op = m - 1; op >= 0; op--) { + for (let left = op; left >= 0; left--) { + const right = nums.length - 1 - (op - left); + const takeLeft = multipliers[op] * nums[left] + dp[op + 1][left + 1]; + const takeRight = multipliers[op] * nums[right] + dp[op + 1][left]; + dp[op][left] = Math.max(takeLeft, takeRight); + } + } + + return dp[0][0]; +}; From 183e2585cf2f5ffee6a73c038f1d97296bd74365 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 29 Apr 2025 20:51:35 -0500 Subject: [PATCH 026/495] Add solution #1771 --- README.md | 3 +- ...ize-palindrome-length-from-subsequences.js | 47 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 solutions/1771-maximize-palindrome-length-from-subsequences.js diff --git a/README.md b/README.md index fb0f030d..1e640e8b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,530 LeetCode solutions in JavaScript +# 1,531 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1364,6 +1364,7 @@ 1768|[Merge Strings Alternately](./solutions/1768-merge-strings-alternately.js)|Easy| 1769|[Minimum Number of Operations to Move All Balls to Each Box](./solutions/1769-minimum-number-of-operations-to-move-all-balls-to-each-box.js)|Medium| 1770|[Maximum Score from Performing Multiplication Operations](./solutions/1770-maximum-score-from-performing-multiplication-operations.js)|Hard| +1771|[Maximize Palindrome Length From Subsequences](./solutions/1771-maximize-palindrome-length-from-subsequences.js)|Hard| 1780|[Check if Number is a Sum of Powers of Three](./solutions/1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| diff --git a/solutions/1771-maximize-palindrome-length-from-subsequences.js b/solutions/1771-maximize-palindrome-length-from-subsequences.js new file mode 100644 index 00000000..f24d48c9 --- /dev/null +++ b/solutions/1771-maximize-palindrome-length-from-subsequences.js @@ -0,0 +1,47 @@ +/** + * 1771. Maximize Palindrome Length From Subsequences + * https://leetcode.com/problems/maximize-palindrome-length-from-subsequences/ + * Difficulty: Hard + * + * You are given two strings, word1 and word2. You want to construct a string in the following + * manner: + * - Choose some non-empty subsequence subsequence1 from word1. + * - Choose some non-empty subsequence subsequence2 from word2. + * - Concatenate the subsequences: subsequence1 + subsequence2, to make the string. + * + * Return the length of the longest palindrome that can be constructed in the described manner. + * If no palindromes can be constructed, return 0. + * + * A subsequence of a string s is a string that can be made by deleting some (possibly none) + * characters from s without changing the order of the remaining characters. + * + * A palindrome is a string that reads the same forward as well as backward. + */ + +/** + * @param {string} word1 + * @param {string} word2 + * @return {number} + */ +var longestPalindrome = function(word1, word2) { + const s = word1 + word2; + const n = s.length; + const dp = Array.from({ length: n }, () => Array(n).fill(0)); + let result = 0; + + for (let i = n - 1; i >= 0; i--) { + dp[i][i] = 1; + for (let j = i + 1; j < n; j++) { + if (s[i] === s[j]) { + dp[i][j] = dp[i + 1][j - 1] + 2; + if (i < word1.length && j >= word1.length) { + result = Math.max(result, dp[i][j]); + } + } else { + dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); + } + } + } + + return result; +}; From 1523a5894ef4360368c870c6bc2feae4987b5022 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 29 Apr 2025 20:52:59 -0500 Subject: [PATCH 027/495] Add solution #1773 --- README.md | 3 +- solutions/1773-count-items-matching-a-rule.js | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 solutions/1773-count-items-matching-a-rule.js diff --git a/README.md b/README.md index 1e640e8b..dbf8705f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,531 LeetCode solutions in JavaScript +# 1,532 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1365,6 +1365,7 @@ 1769|[Minimum Number of Operations to Move All Balls to Each Box](./solutions/1769-minimum-number-of-operations-to-move-all-balls-to-each-box.js)|Medium| 1770|[Maximum Score from Performing Multiplication Operations](./solutions/1770-maximum-score-from-performing-multiplication-operations.js)|Hard| 1771|[Maximize Palindrome Length From Subsequences](./solutions/1771-maximize-palindrome-length-from-subsequences.js)|Hard| +1773|[Count Items Matching a Rule](./solutions/1773-count-items-matching-a-rule.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./solutions/1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| diff --git a/solutions/1773-count-items-matching-a-rule.js b/solutions/1773-count-items-matching-a-rule.js new file mode 100644 index 00000000..528c7169 --- /dev/null +++ b/solutions/1773-count-items-matching-a-rule.js @@ -0,0 +1,35 @@ +/** + * 1773. Count Items Matching a Rule + * https://leetcode.com/problems/count-items-matching-a-rule/ + * Difficulty: Easy + * + * You are given an array items, where each items[i] = [typei, colori, namei] describes the type, + * color, and name of the ith item. You are also given a rule represented by two strings, + * ruleKey and ruleValue. + * + * The ith item is said to match the rule if one of the following is true: + * - ruleKey == "type" and ruleValue == typei. + * - ruleKey == "color" and ruleValue == colori. + * - ruleKey == "name" and ruleValue == namei. + * + * Return the number of items that match the given rule. + */ + +/** + * @param {string[][]} items + * @param {string} ruleKey + * @param {string} ruleValue + * @return {number} + */ +var countMatches = function(items, ruleKey, ruleValue) { + const keyIndex = { type: 0, color: 1, name: 2 }; + let result = 0; + + for (const item of items) { + if (item[keyIndex[ruleKey]] === ruleValue) { + result++; + } + } + + return result; +}; From bbbe1d3b248cd92f9dfd54155868f72789f42dac Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 29 Apr 2025 20:54:28 -0500 Subject: [PATCH 028/495] Add solution #1774 --- README.md | 3 +- solutions/1774-closest-dessert-cost.js | 55 ++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 solutions/1774-closest-dessert-cost.js diff --git a/README.md b/README.md index dbf8705f..a413edd1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,532 LeetCode solutions in JavaScript +# 1,533 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1366,6 +1366,7 @@ 1770|[Maximum Score from Performing Multiplication Operations](./solutions/1770-maximum-score-from-performing-multiplication-operations.js)|Hard| 1771|[Maximize Palindrome Length From Subsequences](./solutions/1771-maximize-palindrome-length-from-subsequences.js)|Hard| 1773|[Count Items Matching a Rule](./solutions/1773-count-items-matching-a-rule.js)|Easy| +1774|[Closest Dessert Cost](./solutions/1774-closest-dessert-cost.js)|Medium| 1780|[Check if Number is a Sum of Powers of Three](./solutions/1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| diff --git a/solutions/1774-closest-dessert-cost.js b/solutions/1774-closest-dessert-cost.js new file mode 100644 index 00000000..707d1812 --- /dev/null +++ b/solutions/1774-closest-dessert-cost.js @@ -0,0 +1,55 @@ +/** + * 1774. Closest Dessert Cost + * https://leetcode.com/problems/closest-dessert-cost/ + * Difficulty: Medium + * + * You would like to make dessert and are preparing to buy the ingredients. You have n ice + * cream base flavors and m types of toppings to choose from. You must follow these rules + * when making your dessert: + * - There must be exactly one ice cream base. + * - You can add one or more types of topping or have no toppings at all. + * - There are at most two of each type of topping. + * + * You are given three inputs: + * - baseCosts, an integer array of length n, where each baseCosts[i] represents the price of + * the ith ice cream base flavor. + * - toppingCosts, an integer array of length m, where each toppingCosts[i] is the price of + * one of the ith topping. + * - target, an integer representing your target price for dessert. + * + * You want to make a dessert with a total cost as close to target as possible. + * + * Return the closest possible cost of the dessert to target. If there are multiple, return + * the lower one. + */ + +/** + * @param {number[]} baseCosts + * @param {number[]} toppingCosts + * @param {number} target + * @return {number} + */ +var closestCost = function(baseCosts, toppingCosts, target) { + let result = Infinity; + + for (const base of baseCosts) { + exploreToppings(0, base); + } + + return result; + + function exploreToppings(index, currentCost) { + const diff = Math.abs(currentCost - target); + const prevDiff = Math.abs(result - target); + + if (diff < prevDiff || (diff === prevDiff && currentCost < result)) { + result = currentCost; + } + + if (index >= toppingCosts.length || currentCost > target) return; + + exploreToppings(index + 1, currentCost); + exploreToppings(index + 1, currentCost + toppingCosts[index]); + exploreToppings(index + 1, currentCost + 2 * toppingCosts[index]); + } +}; From 7fdef4dd2689028e9470c9ea46088424a3fdf238 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 29 Apr 2025 20:57:00 -0500 Subject: [PATCH 029/495] Add solution #1775 --- README.md | 3 +- ...rrays-with-minimum-number-of-operations.js | 65 +++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 solutions/1775-equal-sum-arrays-with-minimum-number-of-operations.js diff --git a/README.md b/README.md index a413edd1..c1838660 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,533 LeetCode solutions in JavaScript +# 1,534 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1367,6 +1367,7 @@ 1771|[Maximize Palindrome Length From Subsequences](./solutions/1771-maximize-palindrome-length-from-subsequences.js)|Hard| 1773|[Count Items Matching a Rule](./solutions/1773-count-items-matching-a-rule.js)|Easy| 1774|[Closest Dessert Cost](./solutions/1774-closest-dessert-cost.js)|Medium| +1775|[Equal Sum Arrays With Minimum Number of Operations](./solutions/1775-equal-sum-arrays-with-minimum-number-of-operations.js)|Medium| 1780|[Check if Number is a Sum of Powers of Three](./solutions/1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| diff --git a/solutions/1775-equal-sum-arrays-with-minimum-number-of-operations.js b/solutions/1775-equal-sum-arrays-with-minimum-number-of-operations.js new file mode 100644 index 00000000..8c2f068f --- /dev/null +++ b/solutions/1775-equal-sum-arrays-with-minimum-number-of-operations.js @@ -0,0 +1,65 @@ +/** + * 1775. Equal Sum Arrays With Minimum Number of Operations + * https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/ + * Difficulty: Medium + * + * You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values + * in the arrays are between 1 and 6, inclusive. + * + * In one operation, you can change any integer's value in any of the arrays to any value between + * 1 and 6, inclusive. + * + * Return the minimum number of operations required to make the sum of values in nums1 equal to + * the sum of values in nums2. Return -1 if it is not possible to make the sum of the two arrays + * equal. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var minOperations = function(nums1, nums2) { + let sum1 = nums1.reduce((a, b) => a + b, 0); + let sum2 = nums2.reduce((a, b) => a + b, 0); + + if (sum1 < sum2) { + [nums1, nums2, sum1, sum2] = [nums2, nums1, sum2, sum1]; + } + + const maxSum1 = nums1.length * 6; + const minSum1 = nums1.length; + const maxSum2 = nums2.length * 6; + const minSum2 = nums2.length; + + if (maxSum1 < minSum2 || maxSum2 < minSum1) return -1; + + let result = 0; + const gains = []; + const losses = []; + + for (const num of nums1) { + losses.push(num - 1); + } + for (const num of nums2) { + gains.push(6 - num); + } + + losses.sort((a, b) => b - a); + gains.sort((a, b) => b - a); + + let i = 0; + let j = 0; + let diff = sum1 - sum2; + + while (diff > 0 && (i < losses.length || j < gains.length)) { + const change = i < losses.length && (j >= gains.length || losses[i] >= gains[j]) + ? losses[i++] + : gains[j++]; + const take = Math.min(diff, change); + diff -= take; + result++; + } + + return result; +}; From 8bc7b9cb852f2dc38b3efae092c3d20794b48b26 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 29 Apr 2025 20:58:50 -0500 Subject: [PATCH 030/495] Add solution #1776 --- README.md | 3 +- solutions/1776-car-fleet-ii.js | 56 ++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 solutions/1776-car-fleet-ii.js diff --git a/README.md b/README.md index c1838660..98200a35 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,534 LeetCode solutions in JavaScript +# 1,535 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1368,6 +1368,7 @@ 1773|[Count Items Matching a Rule](./solutions/1773-count-items-matching-a-rule.js)|Easy| 1774|[Closest Dessert Cost](./solutions/1774-closest-dessert-cost.js)|Medium| 1775|[Equal Sum Arrays With Minimum Number of Operations](./solutions/1775-equal-sum-arrays-with-minimum-number-of-operations.js)|Medium| +1776|[Car Fleet II](./solutions/1776-car-fleet-ii.js)|Hard| 1780|[Check if Number is a Sum of Powers of Three](./solutions/1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| diff --git a/solutions/1776-car-fleet-ii.js b/solutions/1776-car-fleet-ii.js new file mode 100644 index 00000000..176303c5 --- /dev/null +++ b/solutions/1776-car-fleet-ii.js @@ -0,0 +1,56 @@ +/** + * 1776. Car Fleet II + * https://leetcode.com/problems/car-fleet-ii/ + * Difficulty: Hard + * + * There are n cars traveling at different speeds in the same direction along a one-lane road. + * You are given an array cars of length n, where cars[i] = [positioni, speedi] represents: + * - positioni is the distance between the ith car and the beginning of the road in meters. + * It is guaranteed that positioni < positioni+1. + * - speedi is the initial speed of the ith car in meters per second. + * + * For simplicity, cars can be considered as points moving along the number line. Two cars + * collide when they occupy the same position. Once a car collides with another car, they + * unite and form a single car fleet. The cars in the formed fleet will have the same position + * and the same speed, which is the initial speed of the slowest car in the fleet. + * + * Return an array answer, where answer[i] is the time, in seconds, at which the ith car + * collides with the next car, or -1 if the car does not collide with the next car. Answers + * within 10-5 of the actual answers are accepted. + */ + +/** + * @param {number[][]} cars + * @return {number[]} + */ +var getCollisionTimes = function(cars) { + const n = cars.length; + const stack = []; + const collisionTimes = Array(n).fill(-1); + + for (let i = n - 1; i >= 0; i--) { + const [pos, speed] = cars[i]; + + while (stack.length > 0) { + const j = stack[stack.length - 1]; + const [nextPos, nextSpeed] = cars[j]; + + if (speed <= nextSpeed || (collisionTimes[j] > 0 + && (nextPos - pos) / (speed - nextSpeed) >= collisionTimes[j])) { + stack.pop(); + } else { + break; + } + } + + if (stack.length > 0) { + const j = stack[stack.length - 1]; + const [nextPos, nextSpeed] = cars[j]; + collisionTimes[i] = (nextPos - pos) / (speed - nextSpeed); + } + + stack.push(i); + } + + return collisionTimes; +}; From a2af5dd55a5471e06eb0485370ef709df01989c7 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 29 Apr 2025 21:01:00 -0500 Subject: [PATCH 031/495] Add solution #1779 --- README.md | 3 +- ...int-that-has-the-same-x-or-y-coordinate.js | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 solutions/1779-find-nearest-point-that-has-the-same-x-or-y-coordinate.js diff --git a/README.md b/README.md index 98200a35..39d5f2b0 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,535 LeetCode solutions in JavaScript +# 1,536 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1369,6 +1369,7 @@ 1774|[Closest Dessert Cost](./solutions/1774-closest-dessert-cost.js)|Medium| 1775|[Equal Sum Arrays With Minimum Number of Operations](./solutions/1775-equal-sum-arrays-with-minimum-number-of-operations.js)|Medium| 1776|[Car Fleet II](./solutions/1776-car-fleet-ii.js)|Hard| +1779|[Find Nearest Point That Has the Same X or Y Coordinate](./solutions/1779-find-nearest-point-that-has-the-same-x-or-y-coordinate.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./solutions/1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| diff --git a/solutions/1779-find-nearest-point-that-has-the-same-x-or-y-coordinate.js b/solutions/1779-find-nearest-point-that-has-the-same-x-or-y-coordinate.js new file mode 100644 index 00000000..faf1f1b2 --- /dev/null +++ b/solutions/1779-find-nearest-point-that-has-the-same-x-or-y-coordinate.js @@ -0,0 +1,40 @@ +/** + * 1779. Find Nearest Point That Has the Same X or Y Coordinate + * https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/ + * Difficulty: Easy + * + * You are given two integers, x and y, which represent your current location on a Cartesian + * grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents + * that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the + * same y-coordinate as your location. + * + * Return the index (0-indexed) of the valid point with the smallest Manhattan distance from + * your current location. If there are multiple, return the valid point with the smallest index. + * If there are no valid points, return -1. + * + * The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2). + */ + +/** + * @param {number} x + * @param {number} y + * @param {number[][]} points + * @return {number} + */ +var nearestValidPoint = function(x, y, points) { + let minDistance = Infinity; + let result = -1; + + for (let i = 0; i < points.length; i++) { + const [px, py] = points[i]; + if (px === x || py === y) { + const distance = Math.abs(px - x) + Math.abs(py - y); + if (distance < minDistance) { + minDistance = distance; + result = i; + } + } + } + + return result; +}; From 2b77b3662147157c6a76415ba91f1080fc86c2e8 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 29 Apr 2025 21:02:05 -0500 Subject: [PATCH 032/495] Add solution #1781 --- README.md | 3 +- .../1781-sum-of-beauty-of-all-substrings.js | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 solutions/1781-sum-of-beauty-of-all-substrings.js diff --git a/README.md b/README.md index 39d5f2b0..658fc411 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,536 LeetCode solutions in JavaScript +# 1,537 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1371,6 +1371,7 @@ 1776|[Car Fleet II](./solutions/1776-car-fleet-ii.js)|Hard| 1779|[Find Nearest Point That Has the Same X or Y Coordinate](./solutions/1779-find-nearest-point-that-has-the-same-x-or-y-coordinate.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./solutions/1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| +1781|[Sum of Beauty of All Substrings](./solutions/1781-sum-of-beauty-of-all-substrings.js)|Medium| 1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| 1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| diff --git a/solutions/1781-sum-of-beauty-of-all-substrings.js b/solutions/1781-sum-of-beauty-of-all-substrings.js new file mode 100644 index 00000000..6c561b33 --- /dev/null +++ b/solutions/1781-sum-of-beauty-of-all-substrings.js @@ -0,0 +1,35 @@ +/** + * 1781. Sum of Beauty of All Substrings + * https://leetcode.com/problems/sum-of-beauty-of-all-substrings/ + * Difficulty: Medium + * + * The beauty of a string is the difference in frequencies between the most frequent and + * least frequent characters. + * - For example, the beauty of "abaacc" is 3 - 1 = 2. + * + * Given a string s, return the sum of beauty of all of its substrings. + */ + +/** + * @param {string} s + * @return {number} + */ +var beautySum = function(s) { + let result = 0; + + for (let i = 0; i < s.length; i++) { + const freq = new Map(); + for (let j = i; j < s.length; j++) { + freq.set(s[j], (freq.get(s[j]) || 0) + 1); + let maxFreq = 0; + let minFreq = Infinity; + for (const count of freq.values()) { + maxFreq = Math.max(maxFreq, count); + minFreq = Math.min(minFreq, count); + } + result += maxFreq - minFreq; + } + } + + return result; +}; From e246e40436fc7be88be6d95a5500f252cf0a3797 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 29 Apr 2025 21:04:00 -0500 Subject: [PATCH 033/495] Add solution #1782 --- README.md | 3 +- solutions/1782-count-pairs-of-nodes.js | 68 ++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 solutions/1782-count-pairs-of-nodes.js diff --git a/README.md b/README.md index 658fc411..16d66e50 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,537 LeetCode solutions in JavaScript +# 1,538 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1372,6 +1372,7 @@ 1779|[Find Nearest Point That Has the Same X or Y Coordinate](./solutions/1779-find-nearest-point-that-has-the-same-x-or-y-coordinate.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./solutions/1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1781|[Sum of Beauty of All Substrings](./solutions/1781-sum-of-beauty-of-all-substrings.js)|Medium| +1782|[Count Pairs Of Nodes](./solutions/1782-count-pairs-of-nodes.js)|Hard| 1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| 1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| diff --git a/solutions/1782-count-pairs-of-nodes.js b/solutions/1782-count-pairs-of-nodes.js new file mode 100644 index 00000000..d0e4f00c --- /dev/null +++ b/solutions/1782-count-pairs-of-nodes.js @@ -0,0 +1,68 @@ +/** + * 1782. Count Pairs Of Nodes + * https://leetcode.com/problems/count-pairs-of-nodes/ + * Difficulty: Hard + * + * You are given an undirected graph defined by an integer n, the number of nodes, and a 2D + * integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there + * is an undirected edge between ui and vi. You are also given an integer array queries. + * + * Let incident(a, b) be defined as the number of edges that are connected to either node a or b. + * + * The answer to the jth query is the number of pairs of nodes (a, b) that satisfy both of the + * following conditions: + * - a < b + * - incident(a, b) > queries[j] + * + * Return an array answers such that answers.length == queries.length and answers[j] is the + * answer of the jth query. + * + * Note that there can be multiple edges between the same two nodes. + */ + +/** + * @param {number} n + * @param {number[][]} edges + * @param {number[]} queries + * @return {number[]} + */ +var countPairs = function(n, edges, queries) { + const degrees = Array(n + 1).fill(0); + const edgeCounts = new Map(); + + for (const [u, v] of edges) { + degrees[u]++; + degrees[v]++; + const key = u < v ? `${u},${v}` : `${v},${u}`; + edgeCounts.set(key, (edgeCounts.get(key) || 0) + 1); + } + + const sortedDegrees = [...degrees].slice(1).sort((a, b) => a - b); + const result = Array(queries.length).fill(0); + + for (let q = 0; q < queries.length; q++) { + let total = 0; + let left = 0; + let right = n - 1; + + while (left < right) { + if (sortedDegrees[left] + sortedDegrees[right] > queries[q]) { + total += right - left; + right--; + } else { + left++; + } + } + + for (const [key, count] of edgeCounts) { + const [u, v] = key.split(',').map(Number); + if (degrees[u] + degrees[v] > queries[q] && degrees[u] + degrees[v] - count <= queries[q]) { + total--; + } + } + + result[q] = total; + } + + return result; +}; From 641cb755a89b9548ce5bcf825d9b50219f860646 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 29 Apr 2025 21:05:06 -0500 Subject: [PATCH 034/495] Add solution #1784 --- README.md | 3 ++- ...-string-has-at-most-one-segment-of-ones.js | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 solutions/1784-check-if-binary-string-has-at-most-one-segment-of-ones.js diff --git a/README.md b/README.md index 16d66e50..7182a14f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,538 LeetCode solutions in JavaScript +# 1,539 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1373,6 +1373,7 @@ 1780|[Check if Number is a Sum of Powers of Three](./solutions/1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1781|[Sum of Beauty of All Substrings](./solutions/1781-sum-of-beauty-of-all-substrings.js)|Medium| 1782|[Count Pairs Of Nodes](./solutions/1782-count-pairs-of-nodes.js)|Hard| +1784|[Check if Binary String Has at Most One Segment of Ones](./solutions/1784-check-if-binary-string-has-at-most-one-segment-of-ones.js)|Easy| 1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| 1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| diff --git a/solutions/1784-check-if-binary-string-has-at-most-one-segment-of-ones.js b/solutions/1784-check-if-binary-string-has-at-most-one-segment-of-ones.js new file mode 100644 index 00000000..4f3e3fb9 --- /dev/null +++ b/solutions/1784-check-if-binary-string-has-at-most-one-segment-of-ones.js @@ -0,0 +1,26 @@ +/** + * 1784. Check if Binary String Has at Most One Segment of Ones + * https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/ + * Difficulty: Easy + * + * Given a binary string s without leading zeros, return true if s contains at most one + * contiguous segment of ones. Otherwise, return false. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var checkOnesSegment = function(s) { + let seenZero = false; + + for (let i = 1; i < s.length; i++) { + if (s[i] === '0') { + seenZero = true; + } else if (seenZero) { + return false; + } + } + + return true; +}; From 55cd09cac6c4c7c5f1fc57bc7bbe6f5fb6cf013f Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 29 Apr 2025 21:06:11 -0500 Subject: [PATCH 035/495] Add solution #1785 --- README.md | 3 ++- ...mum-elements-to-add-to-form-a-given-sum.js | 25 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 solutions/1785-minimum-elements-to-add-to-form-a-given-sum.js diff --git a/README.md b/README.md index 7182a14f..f6f27e6b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,539 LeetCode solutions in JavaScript +# 1,540 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1374,6 +1374,7 @@ 1781|[Sum of Beauty of All Substrings](./solutions/1781-sum-of-beauty-of-all-substrings.js)|Medium| 1782|[Count Pairs Of Nodes](./solutions/1782-count-pairs-of-nodes.js)|Hard| 1784|[Check if Binary String Has at Most One Segment of Ones](./solutions/1784-check-if-binary-string-has-at-most-one-segment-of-ones.js)|Easy| +1785|[Minimum Elements to Add to Form a Given Sum](./solutions/1785-minimum-elements-to-add-to-form-a-given-sum.js)|Medium| 1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| 1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| diff --git a/solutions/1785-minimum-elements-to-add-to-form-a-given-sum.js b/solutions/1785-minimum-elements-to-add-to-form-a-given-sum.js new file mode 100644 index 00000000..7b27b2c7 --- /dev/null +++ b/solutions/1785-minimum-elements-to-add-to-form-a-given-sum.js @@ -0,0 +1,25 @@ +/** + * 1785. Minimum Elements to Add to Form a Given Sum + * https://leetcode.com/problems/minimum-elements-to-add-to-form-a-given-sum/ + * Difficulty: Medium + * + * You are given an integer array nums and two integers limit and goal. The array nums has + * an interesting property that abs(nums[i]) <= limit. + * + * Return the minimum number of elements you need to add to make the sum of the array equal + * to goal. The array must maintain its property that abs(nums[i]) <= limit. + * + * Note that abs(x) equals x if x >= 0, and -x otherwise. + */ + +/** + * @param {number[]} nums + * @param {number} limit + * @param {number} goal + * @return {number} + */ +var minElements = function(nums, limit, goal) { + const currentSum = nums.reduce((sum, num) => sum + num, 0); + const difference = Math.abs(goal - currentSum); + return Math.ceil(difference / limit); +}; From 674188b807117b8bc3c7833f83cc53b98da96c52 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 01:23:16 -0500 Subject: [PATCH 036/495] Add solution #1786 --- README.md | 3 +- ...estricted-paths-from-first-to-last-node.js | 80 +++++++++++++++++++ 2 files changed, 82 insertions(+), 1 deletion(-) create mode 100644 solutions/1786-number-of-restricted-paths-from-first-to-last-node.js diff --git a/README.md b/README.md index f6f27e6b..5f991a99 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,540 LeetCode solutions in JavaScript +# 1,541 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1375,6 +1375,7 @@ 1782|[Count Pairs Of Nodes](./solutions/1782-count-pairs-of-nodes.js)|Hard| 1784|[Check if Binary String Has at Most One Segment of Ones](./solutions/1784-check-if-binary-string-has-at-most-one-segment-of-ones.js)|Easy| 1785|[Minimum Elements to Add to Form a Given Sum](./solutions/1785-minimum-elements-to-add-to-form-a-given-sum.js)|Medium| +1786|[Number of Restricted Paths From First to Last Node](./solutions/1786-number-of-restricted-paths-from-first-to-last-node.js)|Medium| 1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| 1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| diff --git a/solutions/1786-number-of-restricted-paths-from-first-to-last-node.js b/solutions/1786-number-of-restricted-paths-from-first-to-last-node.js new file mode 100644 index 00000000..e55ddab4 --- /dev/null +++ b/solutions/1786-number-of-restricted-paths-from-first-to-last-node.js @@ -0,0 +1,80 @@ +/** + * 1786. Number of Restricted Paths From First to Last Node + * https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/ + * Difficulty: Medium + * + * There is an undirected weighted connected graph. You are given a positive integer n which + * denotes that the graph has n nodes labeled from 1 to n, and an array edges where each + * edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with + * weight equal to weighti. + * + * A path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that + * z0 = start and zk = end and there is an edge between zi and zi+1 where 0 <= i <= k-1. + * + * The distance of a path is the sum of the weights on the edges of the path. Let + * distanceToLastNode(x) denote the shortest distance of a path between node n and node x. + * A restricted path is a path that also satisfies that + * distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 <= i <= k-1. + * + * Return the number of restricted paths from node 1 to node n. Since that number may be too + * large, return it modulo 109 + 7. + */ + +/** + * @param {number} n + * @param {number[][]} edges + * @return {number} + */ +var countRestrictedPaths = function(n, edges) { + const MODULO = 1e9 + 7; + const graph = {}; + for (const [u, v, weight] of edges) { + (graph[u] ??= []).push({ edge: v, weight }); + (graph[v] ??= []).push({ edge: u, weight }); + } + + const distances = new Array(n + 1).fill(Number.MAX_SAFE_INTEGER); + distances[n] = 0; + + const NOT_VISITED = 0; + const VISITED = 1; + const IN_QUEUE = 2; + const states = new Array(n + 1).fill(NOT_VISITED); + const queue = [n]; + + while (queue.length) { + const node = queue.shift(); + states[node] = IN_QUEUE; + + for (const { edge, weight } of graph[node]) { + if (distances[node] + weight >= distances[edge]) continue; + + distances[edge] = distances[node] + weight; + + if (states[edge] === NOT_VISITED) { + queue.push(edge); + states[edge] = VISITED; + } else if (states[edge] === IN_QUEUE) { + queue.unshift(edge); + } + } + } + + const memo = new Map([[n, 1]]); + + return countPaths(1); + + function countPaths(node) { + if (memo.has(node)) return memo.get(node); + + let count = 0; + for (const { edge } of graph[node]) { + if (distances[edge] < distances[node]) { + count = (count + countPaths(edge)) % MODULO; + } + } + + memo.set(node, count); + return count; + } +}; From 14aa478cce453ee3f6762447b78414bf42665f61 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 01:29:16 -0500 Subject: [PATCH 037/495] Add solution #1787 --- README.md | 3 +- ...e-the-xor-of-all-segments-equal-to-zero.js | 51 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 solutions/1787-make-the-xor-of-all-segments-equal-to-zero.js diff --git a/README.md b/README.md index 5f991a99..6141a367 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,541 LeetCode solutions in JavaScript +# 1,542 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1376,6 +1376,7 @@ 1784|[Check if Binary String Has at Most One Segment of Ones](./solutions/1784-check-if-binary-string-has-at-most-one-segment-of-ones.js)|Easy| 1785|[Minimum Elements to Add to Form a Given Sum](./solutions/1785-minimum-elements-to-add-to-form-a-given-sum.js)|Medium| 1786|[Number of Restricted Paths From First to Last Node](./solutions/1786-number-of-restricted-paths-from-first-to-last-node.js)|Medium| +1787|[Make the XOR of All Segments Equal to Zero](./solutions/1787-make-the-xor-of-all-segments-equal-to-zero.js)|Hard| 1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| 1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| diff --git a/solutions/1787-make-the-xor-of-all-segments-equal-to-zero.js b/solutions/1787-make-the-xor-of-all-segments-equal-to-zero.js new file mode 100644 index 00000000..7817c120 --- /dev/null +++ b/solutions/1787-make-the-xor-of-all-segments-equal-to-zero.js @@ -0,0 +1,51 @@ +/** + * 1787. Make the XOR of All Segments Equal to Zero + * https://leetcode.com/problems/make-the-xor-of-all-segments-equal-to-zero/ + * Difficulty: Hard + * + * You are given an array nums and an integer k. The XOR of a segment [left, right] where + * left <= right is the XOR of all the elements with indices between left and right, + * inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right]. + * + * Return the minimum number of elements to change in the array such that the XOR of all + * segments of size k is equal to zero. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var minChanges = function(nums, k) { + const n = nums.length; + const maxVal = 1 << 10; + const groups = new Array(k).fill().map(() => new Map()); + + for (let i = 0; i < n; i++) { + groups[i % k].set(nums[i], (groups[i % k].get(nums[i]) || 0) + 1); + } + + const dp = new Array(maxVal).fill(n); + dp[0] = 0; + + for (let pos = 0; pos < k; pos++) { + const prevDp = [...dp]; + dp.fill(n); + const groupSize = Math.floor(n / k) + (pos < n % k ? 1 : 0); + const minPrev = Math.min(...prevDp); + + for (let xor = 0; xor < maxVal; xor++) { + if (prevDp[xor] === n) continue; + for (const [val, count] of groups[pos]) { + const newXor = xor ^ val; + dp[newXor] = Math.min(dp[newXor], prevDp[xor] + groupSize - count); + } + } + + for (let xor = 0; xor < maxVal; xor++) { + dp[xor] = Math.min(dp[xor], minPrev + groupSize); + } + } + + return dp[0]; +}; From bd3917b8780c1817c4cde9f6806d4c0e51c3e257 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 19:12:45 -0500 Subject: [PATCH 038/495] Add solution #1792 --- README.md | 3 +- solutions/1792-maximum-average-pass-ratio.js | 107 +++++++++++++++++++ 2 files changed, 109 insertions(+), 1 deletion(-) create mode 100644 solutions/1792-maximum-average-pass-ratio.js diff --git a/README.md b/README.md index 6141a367..6fc9f011 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,542 LeetCode solutions in JavaScript +# 1,543 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1379,6 +1379,7 @@ 1787|[Make the XOR of All Segments Equal to Zero](./solutions/1787-make-the-xor-of-all-segments-equal-to-zero.js)|Hard| 1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| +1792|[Maximum Average Pass Ratio](./solutions/1792-maximum-average-pass-ratio.js)|Medium| 1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| diff --git a/solutions/1792-maximum-average-pass-ratio.js b/solutions/1792-maximum-average-pass-ratio.js new file mode 100644 index 00000000..3ff9c5b3 --- /dev/null +++ b/solutions/1792-maximum-average-pass-ratio.js @@ -0,0 +1,107 @@ +/** + * 1792. Maximum Average Pass Ratio + * https://leetcode.com/problems/maximum-average-pass-ratio/ + * Difficulty: Medium + * + * There is a school that has classes of students and each class will be having a final exam. + * You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know + * beforehand that in the ith class, there are totali total students, but only passi number + * of students will pass the exam. + * + * You are also given an integer extraStudents. There are another extraStudents brilliant + * students that are guaranteed to pass the exam of any class they are assigned to. You want + * to assign each of the extraStudents students to a class in a way that maximizes the average + * pass ratio across all the classes. + * + * The pass ratio of a class is equal to the number of students of the class that will pass + * the exam divided by the total number of students of the class. The average pass ratio is + * the sum of pass ratios of all the classes divided by the number of the classes. + * + * Return the maximum possible average pass ratio after assigning the extraStudents students. + * Answers within 10-5 of the actual answer will be accepted. + */ + +/** +* @param {number[][]} classes +* @param {number} extraStudents +* @return {number} +*/ +var maxAverageRatio = function(classes, extraStudents) { + const maxHeap = []; + + for (const [pass, total] of classes) { + const profit = getProfit(pass, total); + maxHeap.push([profit, pass, total]); + } + + heapify(); + + for (let i = 0; i < extraStudents; i++) { + const [_, pass, total] = extractMax(); + const newPass = pass + 1; + const newTotal = total + 1; + const newProfit = getProfit(newPass, newTotal); + insert([newProfit, newPass, newTotal]); + } + + let sumRatio = 0; + for (const [_, pass, total] of maxHeap) { + sumRatio += pass / total; + } + + return sumRatio / classes.length; + + function getProfit(pass, total) { + return (pass + 1) / (total + 1) - pass / total; + } + + function heapify() { + for (let i = Math.floor(maxHeap.length / 2) - 1; i >= 0; i--) { + siftDown(i); + } + } + + function siftDown(i) { + const left = 2 * i + 1; + const right = 2 * i + 2; + let largest = i; + + if (left < maxHeap.length && maxHeap[left][0] > maxHeap[largest][0]) { + largest = left; + } + + if (right < maxHeap.length && maxHeap[right][0] > maxHeap[largest][0]) { + largest = right; + } + + if (largest !== i) { + [maxHeap[i], maxHeap[largest]] = [maxHeap[largest], maxHeap[i]]; + siftDown(largest); + } + } + + function extractMax() { + const max = maxHeap[0]; + const last = maxHeap.pop(); + + if (maxHeap.length > 0) { + maxHeap[0] = last; + siftDown(0); + } + + return max; + } + + function insert(item) { + maxHeap.push(item); + + let i = maxHeap.length - 1; + let parent = Math.floor((i - 1) / 2); + + while (i > 0 && maxHeap[i][0] > maxHeap[parent][0]) { + [maxHeap[i], maxHeap[parent]] = [maxHeap[parent], maxHeap[i]]; + i = parent; + parent = Math.floor((i - 1) / 2); + } + } +}; From 9861912d8f6cc46e9dcb646b2c5468da70a9a6dd Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 19:14:03 -0500 Subject: [PATCH 039/495] Add solution #1793 --- README.md | 3 +- .../1793-maximum-score-of-a-good-subarray.js | 42 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 solutions/1793-maximum-score-of-a-good-subarray.js diff --git a/README.md b/README.md index 6fc9f011..103c5cff 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,543 LeetCode solutions in JavaScript +# 1,544 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1380,6 +1380,7 @@ 1790|[Check if One String Swap Can Make Strings Equal](./solutions/1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| 1792|[Maximum Average Pass Ratio](./solutions/1792-maximum-average-pass-ratio.js)|Medium| +1793|[Maximum Score of a Good Subarray](./solutions/1793-maximum-score-of-a-good-subarray.js)|Hard| 1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| diff --git a/solutions/1793-maximum-score-of-a-good-subarray.js b/solutions/1793-maximum-score-of-a-good-subarray.js new file mode 100644 index 00000000..9a662c67 --- /dev/null +++ b/solutions/1793-maximum-score-of-a-good-subarray.js @@ -0,0 +1,42 @@ +/** + * 1793. Maximum Score of a Good Subarray + * https://leetcode.com/problems/maximum-score-of-a-good-subarray/ + * Difficulty: Hard + * + * You are given an array of integers nums (0-indexed) and an integer k. + * + * The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * + * (j - i + 1). A good subarray is a subarray where i <= k <= j. + * + * Return the maximum possible score of a good subarray. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var maximumScore = function(nums, k) { + let result = nums[k]; + let minimum = nums[k]; + let left = k; + let right = k; + const length = nums.length; + + while (left > 0 || right < length - 1) { + const leftValue = left > 0 ? nums[left - 1] : 0; + const rightValue = right < length - 1 ? nums[right + 1] : 0; + + if (leftValue >= rightValue) { + left--; + minimum = Math.min(minimum, leftValue); + } else { + right++; + minimum = Math.min(minimum, rightValue); + } + + result = Math.max(result, minimum * (right - left + 1)); + } + + return result; +}; From b1138c330b325b0fbace19751f2759bd1b9e1d41 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 19:15:33 -0500 Subject: [PATCH 040/495] Add solution #1796 --- README.md | 3 +- .../1796-second-largest-digit-in-a-string.js | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 solutions/1796-second-largest-digit-in-a-string.js diff --git a/README.md b/README.md index 103c5cff..8fd7f9a1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,544 LeetCode solutions in JavaScript +# 1,545 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1381,6 +1381,7 @@ 1791|[Find Center of Star Graph](./solutions/1791-find-center-of-star-graph.js)|Easy| 1792|[Maximum Average Pass Ratio](./solutions/1792-maximum-average-pass-ratio.js)|Medium| 1793|[Maximum Score of a Good Subarray](./solutions/1793-maximum-score-of-a-good-subarray.js)|Hard| +1796|[Second Largest Digit in a String](./solutions/1796-second-largest-digit-in-a-string.js)|Easy| 1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| diff --git a/solutions/1796-second-largest-digit-in-a-string.js b/solutions/1796-second-largest-digit-in-a-string.js new file mode 100644 index 00000000..196ba422 --- /dev/null +++ b/solutions/1796-second-largest-digit-in-a-string.js @@ -0,0 +1,33 @@ +/** + * 1796. Second Largest Digit in a String + * https://leetcode.com/problems/second-largest-digit-in-a-string/ + * Difficulty: Easy + * + * Given an alphanumeric string s, return the second largest numerical digit that appears in + * s, or -1 if it does not exist. + * + * An alphanumeric string is a string consisting of lowercase English letters and digits. + */ + +/** + * @param {string} s + * @return {number} + */ +var secondHighest = function(s) { + let largest = -1; + let result = -1; + + for (const char of s) { + if (/\d/.test(char)) { + const digit = parseInt(char); + if (digit > largest) { + result = largest; + largest = digit; + } else if (digit < largest && digit > result) { + result = digit; + } + } + } + + return result; +}; From e64559551e76df4202ccb9e176ad5030f782ec7d Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 19:33:26 -0500 Subject: [PATCH 041/495] Add solution #2071 --- README.md | 3 +- ...-maximum-number-of-tasks-you-can-assign.js | 79 +++++++++++++++++++ 2 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 solutions/2071-maximum-number-of-tasks-you-can-assign.js diff --git a/README.md b/README.md index 8fd7f9a1..2eb9a816 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,545 LeetCode solutions in JavaScript +# 1,546 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1410,6 +1410,7 @@ 2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| 2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| +2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| diff --git a/solutions/2071-maximum-number-of-tasks-you-can-assign.js b/solutions/2071-maximum-number-of-tasks-you-can-assign.js new file mode 100644 index 00000000..5382d5d5 --- /dev/null +++ b/solutions/2071-maximum-number-of-tasks-you-can-assign.js @@ -0,0 +1,79 @@ +/** + * 2071. Maximum Number of Tasks You Can Assign + * https://leetcode.com/problems/maximum-number-of-tasks-you-can-assign/ + * Difficulty: Hard + * + * You have n tasks and m workers. Each task has a strength requirement stored in a 0-indexed + * integer array tasks, with the ith task requiring tasks[i] strength to complete. The strength + * of each worker is stored in a 0-indexed integer array workers, with the jth worker having + * workers[j] strength. Each worker can only be assigned to a single task and must have a + * strength greater than or equal to the task's strength requirement (i.e., workers[j] >= tasks[i]). + * + * Additionally, you have pills magical pills that will increase a worker's strength by strength. + * You can decide which workers receive the magical pills, however, you may only give each worker + * at most one magical pill. + * + * Given the 0-indexed integer arrays tasks and workers and the integers pills and strength, + * return the maximum number of tasks that can be completed. + */ + +/** + * @param {number[]} tasks + * @param {number[]} workers + * @param {number} pills + * @param {number} strength + * @return {number} + */ +var maxTaskAssign = function(tasks, workers, pills, strength) { + tasks.sort((a, b) => a - b); + workers.sort((a, b) => a - b); + + const n = tasks.length; + const m = workers.length; + + let left = 0; + let right = Math.min(n, m); + + while (left < right) { + const mid = Math.floor((left + right + 1) / 2); + + if (canAssign(mid)) { + left = mid; + } else { + right = mid - 1; + } + } + + return left; + + function canAssign(k) { + const availableTasks = tasks.slice(0, k); + const availableWorkers = workers.slice(m - k); + let remainingPills = pills; + + for (let i = k - 1; i >= 0; i--) { + const task = availableTasks[i]; + + if (availableWorkers[availableWorkers.length - 1] >= task) { + availableWorkers.pop(); + continue; + } + + if (remainingPills === 0) return false; + + let found = false; + for (let j = 0; j < availableWorkers.length; j++) { + if (availableWorkers[j] + strength >= task) { + availableWorkers.splice(j, 1); + remainingPills--; + found = true; + break; + } + } + + if (!found) return false; + } + + return true; + } +}; From 9e4bca5164a8337afe3e665073f0399e813364b2 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 19:36:20 -0500 Subject: [PATCH 042/495] Add solution #1797 --- README.md | 3 +- .../1797-design-authentication-manager.js | 68 +++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 solutions/1797-design-authentication-manager.js diff --git a/README.md b/README.md index 2eb9a816..a6cac0d6 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,546 LeetCode solutions in JavaScript +# 1,547 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1382,6 +1382,7 @@ 1792|[Maximum Average Pass Ratio](./solutions/1792-maximum-average-pass-ratio.js)|Medium| 1793|[Maximum Score of a Good Subarray](./solutions/1793-maximum-score-of-a-good-subarray.js)|Hard| 1796|[Second Largest Digit in a String](./solutions/1796-second-largest-digit-in-a-string.js)|Easy| +1797|[Design Authentication Manager](./solutions/1797-design-authentication-manager.js)|Medium| 1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| diff --git a/solutions/1797-design-authentication-manager.js b/solutions/1797-design-authentication-manager.js new file mode 100644 index 00000000..e631c416 --- /dev/null +++ b/solutions/1797-design-authentication-manager.js @@ -0,0 +1,68 @@ +/** + * 1797. Design Authentication Manager + * https://leetcode.com/problems/design-authentication-manager/ + * Difficulty: Medium + * + * There is an authentication system that works with authentication tokens. For each session, + * the user will receive a new authentication token that will expire timeToLive seconds after + * the currentTime. If the token is renewed, the expiry time will be extended to expire + * timeToLive seconds after the (potentially different) currentTime. + * + * Implement the AuthenticationManager class: + * - AuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the + * timeToLive. + * - generate(string tokenId, int currentTime) generates a new token with the given tokenId + * at the given currentTime in seconds. + * - renew(string tokenId, int currentTime) renews the unexpired token with the given tokenId + * at the given currentTime in seconds. If there are no unexpired tokens with the given + * tokenId, the request is ignored, and nothing happens. + * - countUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the + * given currentTime. + * + * Note that if a token expires at time t, and another action happens on time t (renew or + * countUnexpiredTokens), the expiration takes place before the other actions. + */ + +/** + * @param {number} timeToLive + */ +var AuthenticationManager = function(timeToLive) { + this.timeToLive = timeToLive; + this.tokens = new Map(); +}; + +/** + * @param {string} tokenId + * @param {number} currentTime + * @return {void} + */ +AuthenticationManager.prototype.generate = function(tokenId, currentTime) { + this.tokens.set(tokenId, currentTime + this.timeToLive); +}; + +/** + * @param {string} tokenId + * @param {number} currentTime + * @return {void} + */ +AuthenticationManager.prototype.renew = function(tokenId, currentTime) { + if (this.tokens.has(tokenId) && this.tokens.get(tokenId) > currentTime) { + this.tokens.set(tokenId, currentTime + this.timeToLive); + } +}; + +/** + * @param {number} currentTime + * @return {number} + */ +AuthenticationManager.prototype.countUnexpiredTokens = function(currentTime) { + let count = 0; + for (const [tokenId, expiry] of this.tokens) { + if (expiry > currentTime) { + count++; + } else { + this.tokens.delete(tokenId); + } + } + return count; +}; From e213a32867e3175b441f38664c65dafc3f73bf77 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 19:37:21 -0500 Subject: [PATCH 043/495] Add solution #1798 --- README.md | 3 +- ...mber-of-consecutive-values-you-can-make.js | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 solutions/1798-maximum-number-of-consecutive-values-you-can-make.js diff --git a/README.md b/README.md index a6cac0d6..17090820 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,547 LeetCode solutions in JavaScript +# 1,548 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1383,6 +1383,7 @@ 1793|[Maximum Score of a Good Subarray](./solutions/1793-maximum-score-of-a-good-subarray.js)|Hard| 1796|[Second Largest Digit in a String](./solutions/1796-second-largest-digit-in-a-string.js)|Easy| 1797|[Design Authentication Manager](./solutions/1797-design-authentication-manager.js)|Medium| +1798|[Maximum Number of Consecutive Values You Can Make](./solutions/1798-maximum-number-of-consecutive-values-you-can-make.js)|Medium| 1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| diff --git a/solutions/1798-maximum-number-of-consecutive-values-you-can-make.js b/solutions/1798-maximum-number-of-consecutive-values-you-can-make.js new file mode 100644 index 00000000..0c91d2de --- /dev/null +++ b/solutions/1798-maximum-number-of-consecutive-values-you-can-make.js @@ -0,0 +1,30 @@ +/** + * 1798. Maximum Number of Consecutive Values You Can Make + * https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make/ + * Difficulty: Medium + * + * You are given an integer array coins of length n which represents the n coins that you + * own. The value of the ith coin is coins[i]. You can make some value x if you can choose + * some of your n coins such that their values sum up to x. + * + * Return the maximum number of consecutive integer values that you can make with your coins + * starting from and including 0. + * + * Note that you may have multiple coins of the same value. + */ + +/** + * @param {number[]} coins + * @return {number} + */ +var getMaximumConsecutive = function(coins) { + let maxReachable = 0; + + coins.sort((a, b) => a - b); + for (const coin of coins) { + if (coin > maxReachable + 1) break; + maxReachable += coin; + } + + return maxReachable + 1; +}; From e4f5c5c38d6d4bef1830167496167356ef8af237 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 19:39:01 -0500 Subject: [PATCH 044/495] Add solution #1799 --- README.md | 3 +- .../1799-maximize-score-after-n-operations.js | 59 +++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 solutions/1799-maximize-score-after-n-operations.js diff --git a/README.md b/README.md index 17090820..a8cd5000 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,548 LeetCode solutions in JavaScript +# 1,549 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1384,6 +1384,7 @@ 1796|[Second Largest Digit in a String](./solutions/1796-second-largest-digit-in-a-string.js)|Easy| 1797|[Design Authentication Manager](./solutions/1797-design-authentication-manager.js)|Medium| 1798|[Maximum Number of Consecutive Values You Can Make](./solutions/1798-maximum-number-of-consecutive-values-you-can-make.js)|Medium| +1799|[Maximize Score After N Operations](./solutions/1799-maximize-score-after-n-operations.js)|Hard| 1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| diff --git a/solutions/1799-maximize-score-after-n-operations.js b/solutions/1799-maximize-score-after-n-operations.js new file mode 100644 index 00000000..eb7a2e3b --- /dev/null +++ b/solutions/1799-maximize-score-after-n-operations.js @@ -0,0 +1,59 @@ +/** + * 1799. Maximize Score After N Operations + * https://leetcode.com/problems/maximize-score-after-n-operations/ + * Difficulty: Hard + * + * You are given nums, an array of positive integers of size 2 * n. You must perform n operations + * on this array. + * + * In the ith operation (1-indexed), you will: + * - Choose two elements, x and y. + * - Receive a score of i * gcd(x, y). + * - Remove x and y from nums. + * + * Return the maximum score you can receive after performing n operations. + * + * The function gcd(x, y) is the greatest common divisor of x and y. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxScore = function(nums) { + const n = nums.length; + const pairsGcd = Array(n).fill().map(() => Array(n).fill(0)); + for (let i = 0; i < n; i++) { + for (let j = i + 1; j < n; j++) { + pairsGcd[i][j] = gcd(nums[i], nums[j]); + } + } + + return solve(1, 0, {}, pairsGcd); + + function gcd(a, b) { + while (b) { + a %= b; + [a, b] = [b, a]; + } + return a; + } + + function solve(operations, mask, memo, pairsGcd) { + if (operations > nums.length / 2) return 0; + if (memo[mask] !== undefined) return memo[mask]; + + let maxScore = 0; + for (let i = 0; i < nums.length; i++) { + if (mask & (1 << i)) continue; + for (let j = i + 1; j < nums.length; j++) { + if (mask & (1 << j)) continue; + const newMask = mask | (1 << i) | (1 << j); + const score = operations * pairsGcd[i][j] + solve(operations + 1, newMask, memo, pairsGcd); + maxScore = Math.max(maxScore, score); + } + } + + return memo[mask] = maxScore; + } +}; From 0a12b13b7d1d07ffbd6750901f2fec1a77cbde51 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 19:51:34 -0500 Subject: [PATCH 045/495] Add solution #1801 --- README.md | 3 +- .../1801-number-of-orders-in-the-backlog.js | 73 +++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 solutions/1801-number-of-orders-in-the-backlog.js diff --git a/README.md b/README.md index a8cd5000..0149bef7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,549 LeetCode solutions in JavaScript +# 1,550 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1386,6 +1386,7 @@ 1798|[Maximum Number of Consecutive Values You Can Make](./solutions/1798-maximum-number-of-consecutive-values-you-can-make.js)|Medium| 1799|[Maximize Score After N Operations](./solutions/1799-maximize-score-after-n-operations.js)|Hard| 1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| +1801|[Number of Orders in the Backlog](./solutions/1801-number-of-orders-in-the-backlog.js)|Medium| 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| diff --git a/solutions/1801-number-of-orders-in-the-backlog.js b/solutions/1801-number-of-orders-in-the-backlog.js new file mode 100644 index 00000000..1c9501c0 --- /dev/null +++ b/solutions/1801-number-of-orders-in-the-backlog.js @@ -0,0 +1,73 @@ +/** + * 1801. Number of Orders in the Backlog + * https://leetcode.com/problems/number-of-orders-in-the-backlog/ + * Difficulty: Medium + * + * You are given a 2D integer array orders, where each orders[i] = [pricei, amounti, orderTypei] + * denotes that amounti orders have been placed of type orderTypei at the price pricei. + * The orderTypei is: + * - 0 if it is a batch of buy orders, or + * - 1 if it is a batch of sell orders. + * + * Note that orders[i] represents a batch of amounti independent orders with the same price and + * order type. All orders represented by orders[i] will be placed before all orders represented + * by orders[i+1] for all valid i. + * + * There is a backlog that consists of orders that have not been executed. The backlog is initially + * empty. When an order is placed, the following happens: + * - If the order is a buy order, you look at the sell order with the smallest price in the backlog. + * If that sell order's price is smaller than or equal to the current buy order's price, they will + * match and be executed, and that sell order will be removed from the backlog. Else, the buy + * order is added to the backlog. + * - Vice versa, if the order is a sell order, you look at the buy order with the largest price in + * the backlog. If that buy order's price is larger than or equal to the current sell order's + * price, they will match and be executed, and that buy order will be removed from the backlog. + * Else, the sell order is added to the backlog. + * + * Return the total amount of orders in the backlog after placing all the orders from the input. + * Since this number can be large, return it modulo 109 + 7. + */ + +/** + * @param {number[][]} orders + * @return {number} + */ +var getNumberOfBacklogOrders = function(orders) { + const MOD = 1e9 + 7; + const buyOrders = new MinPriorityQueue(); + const sellOrders = new MinPriorityQueue(); + + for (let [price, amount, type] of orders) { + if (type === 0) { + const order = { price: -price, amount, originalPrice: price, valueOf: () => -price }; + while (amount > 0 && !sellOrders.isEmpty() && sellOrders.front().price <= price) { + const sellOrder = sellOrders.dequeue(); + const matchAmount = Math.min(amount, sellOrder.amount); + amount -= matchAmount; + sellOrder.amount -= matchAmount; + if (sellOrder.amount > 0) sellOrders.enqueue(sellOrder); + } + if (amount > 0) buyOrders.enqueue({ ...order, amount }); + } else { + const order = { price, amount, valueOf: () => price }; + while (amount > 0 && !buyOrders.isEmpty() && buyOrders.front().originalPrice >= price) { + const buyOrder = buyOrders.dequeue(); + const matchAmount = Math.min(amount, buyOrder.amount); + amount -= matchAmount; + buyOrder.amount -= matchAmount; + if (buyOrder.amount > 0) buyOrders.enqueue(buyOrder); + } + if (amount > 0) sellOrders.enqueue({ ...order, amount }); + } + } + + let total = 0; + while (!buyOrders.isEmpty()) { + total = (total + buyOrders.dequeue().amount) % MOD; + } + while (!sellOrders.isEmpty()) { + total = (total + sellOrders.dequeue().amount) % MOD; + } + + return total; +}; From f3ee12f9d03eb902ec0524ab8f53df1151644774 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 20:12:36 -0500 Subject: [PATCH 046/495] Add solution #1802 --- README.md | 3 +- ...lue-at-a-given-index-in-a-bounded-array.js | 51 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 solutions/1802-maximum-value-at-a-given-index-in-a-bounded-array.js diff --git a/README.md b/README.md index 0149bef7..5dc29f16 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,550 LeetCode solutions in JavaScript +# 1,551 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1387,6 +1387,7 @@ 1799|[Maximize Score After N Operations](./solutions/1799-maximize-score-after-n-operations.js)|Hard| 1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| 1801|[Number of Orders in the Backlog](./solutions/1801-number-of-orders-in-the-backlog.js)|Medium| +1802|[Maximum Value at a Given Index in a Bounded Array](./solutions/1802-maximum-value-at-a-given-index-in-a-bounded-array.js)|Medium| 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| diff --git a/solutions/1802-maximum-value-at-a-given-index-in-a-bounded-array.js b/solutions/1802-maximum-value-at-a-given-index-in-a-bounded-array.js new file mode 100644 index 00000000..bc7fba1a --- /dev/null +++ b/solutions/1802-maximum-value-at-a-given-index-in-a-bounded-array.js @@ -0,0 +1,51 @@ +/** + * 1802. Maximum Value at a Given Index in a Bounded Array + * https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/ + * Difficulty: Medium + * + * You are given three positive integers: n, index, and maxSum. You want to construct an array + * nums (0-indexed) that satisfies the following conditions: + * - nums.length == n + * - nums[i] is a positive integer where 0 <= i < n. + * - abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1. + * - The sum of all the elements of nums does not exceed maxSum. + * - nums[index] is maximized. + * + * Return nums[index] of the constructed array. + * + * Note that abs(x) equals x if x >= 0, and -x otherwise. + */ + +/** + * @param {number} n + * @param {number} index + * @param {number} maxSum + * @return {number} + */ +var maxValue = function(n, index, maxSum) { + function minSumRequired(peak) { + const leftCount = Math.min(index, peak - 1); + const rightCount = Math.min(n - index - 1, peak - 1); + let sum = peak; + sum += (peak - 1 + peak - leftCount) * leftCount / 2; + sum += (peak - 1 + peak - rightCount) * rightCount / 2; + sum += (index - leftCount) + (n - index - 1 - rightCount); + return sum; + } + + let low = 1; + let high = maxSum; + let result = 1; + + while (low <= high) { + const mid = Math.floor((low + high) / 2); + if (minSumRequired(mid) <= maxSum) { + result = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + + return result; +}; From 2d9105ec00b69ce14de05a26642f5a3a567c95bd Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 20:16:41 -0500 Subject: [PATCH 047/495] Add solution #1803 --- README.md | 3 +- .../1803-count-pairs-with-xor-in-a-range.js | 67 +++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 solutions/1803-count-pairs-with-xor-in-a-range.js diff --git a/README.md b/README.md index 5dc29f16..7abff49c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,551 LeetCode solutions in JavaScript +# 1,552 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1388,6 +1388,7 @@ 1800|[Maximum Ascending Subarray Sum](./solutions/1800-maximum-ascending-subarray-sum.js)|Easy| 1801|[Number of Orders in the Backlog](./solutions/1801-number-of-orders-in-the-backlog.js)|Medium| 1802|[Maximum Value at a Given Index in a Bounded Array](./solutions/1802-maximum-value-at-a-given-index-in-a-bounded-array.js)|Medium| +1803|[Count Pairs With XOR in a Range](./solutions/1803-count-pairs-with-xor-in-a-range.js)|Hard| 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| diff --git a/solutions/1803-count-pairs-with-xor-in-a-range.js b/solutions/1803-count-pairs-with-xor-in-a-range.js new file mode 100644 index 00000000..1912bf08 --- /dev/null +++ b/solutions/1803-count-pairs-with-xor-in-a-range.js @@ -0,0 +1,67 @@ +/** + * 1803. Count Pairs With XOR in a Range + * https://leetcode.com/problems/count-pairs-with-xor-in-a-range/ + * Difficulty: Hard + * + * Given a (0-indexed) integer array nums and two integers low and high, return the number + * of nice pairs. + * + * A nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR + * nums[j]) <= high. + */ + +/** + * @param {number[]} nums + * @param {number} low + * @param {number} high + * @return {number} + */ +var countPairs = function(nums, low, high) { + const root = new TrieNode(); + let total = 0; + + for (const num of nums) { + total += countPairsInRange(num, high, root) - countPairsInRange(num, low - 1, root); + insert(num, root); + } + + return total; +}; + +class TrieNode { + constructor() { + this.children = [null, null]; + this.count = 0; + } +} + +function countPairsInRange(num, limit, root, depth = 14) { + let count = 0; + let node = root; + for (let i = depth; i >= 0 && node; i--) { + const numBit = (num >> i) & 1; + const limitBit = (limit >> i) & 1; + if (limitBit === 0) { + node = node.children[numBit]; + } else { + if (node.children[numBit]) { + count += node.children[numBit].count; + } + node = node.children[numBit ^ 1]; + } + } + return count + (node ? node.count : 0); +} + +function insert(num, root) { + let node = root; + for (let i = 14; i >= 0; i--) { + const bit = (num >> i) & 1; + if (!node.children[bit]) { + node.children[bit] = new TrieNode(); + } + node = node.children[bit]; + node.count++; + } +} + From d3c53fe43372864cff247dfa7bcf0ebb9967faeb Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 20:20:47 -0500 Subject: [PATCH 048/495] Add solution #1805 --- README.md | 3 +- ...umber-of-different-integers-in-a-string.js | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 solutions/1805-number-of-different-integers-in-a-string.js diff --git a/README.md b/README.md index 7abff49c..b7f40dcf 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,552 LeetCode solutions in JavaScript +# 1,553 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1389,6 +1389,7 @@ 1801|[Number of Orders in the Backlog](./solutions/1801-number-of-orders-in-the-backlog.js)|Medium| 1802|[Maximum Value at a Given Index in a Bounded Array](./solutions/1802-maximum-value-at-a-given-index-in-a-bounded-array.js)|Medium| 1803|[Count Pairs With XOR in a Range](./solutions/1803-count-pairs-with-xor-in-a-range.js)|Hard| +1805|[Number of Different Integers in a String](./solutions/1805-number-of-different-integers-in-a-string.js)|Easy| 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| diff --git a/solutions/1805-number-of-different-integers-in-a-string.js b/solutions/1805-number-of-different-integers-in-a-string.js new file mode 100644 index 00000000..61b6f693 --- /dev/null +++ b/solutions/1805-number-of-different-integers-in-a-string.js @@ -0,0 +1,40 @@ +/** + * 1805. Number of Different Integers in a String + * https://leetcode.com/problems/number-of-different-integers-in-a-string/ + * Difficulty: Easy + * + * You are given a string word that consists of digits and lowercase English letters. + * + * You will replace every non-digit character with a space. For example, "a123bc34d8ef34" + * will become " 123 34 8 34". Notice that you are left with some integers that are + * separated by at least one space: "123", "34", "8", and "34". + * + * Return the number of different integers after performing the replacement operations on word. + * + * Two integers are considered different if their decimal representations without any leading + * zeros are different. + */ + +/** + * @param {string} word + * @return {number} + */ +var numDifferentIntegers = function(word) { + const uniqueIntegers = new Set(); + let currentNum = ''; + + for (const char of word) { + if (/\d/.test(char)) { + currentNum += char; + } else if (currentNum) { + uniqueIntegers.add(String(BigInt(currentNum))); + currentNum = ''; + } + } + + if (currentNum) { + uniqueIntegers.add(String(BigInt(currentNum))); + } + + return uniqueIntegers.size; +}; From 3c3e4ffe4032fb50d936e3d35d0e30987e4770ad Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 20:22:26 -0500 Subject: [PATCH 049/495] Add solution #1806 --- README.md | 3 +- ...perations-to-reinitialize-a-permutation.js | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 solutions/1806-minimum-number-of-operations-to-reinitialize-a-permutation.js diff --git a/README.md b/README.md index b7f40dcf..281048bd 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,553 LeetCode solutions in JavaScript +# 1,554 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1390,6 +1390,7 @@ 1802|[Maximum Value at a Given Index in a Bounded Array](./solutions/1802-maximum-value-at-a-given-index-in-a-bounded-array.js)|Medium| 1803|[Count Pairs With XOR in a Range](./solutions/1803-count-pairs-with-xor-in-a-range.js)|Hard| 1805|[Number of Different Integers in a String](./solutions/1805-number-of-different-integers-in-a-string.js)|Easy| +1806|[Minimum Number of Operations to Reinitialize a Permutation](./solutions/1806-minimum-number-of-operations-to-reinitialize-a-permutation.js)|Medium| 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| diff --git a/solutions/1806-minimum-number-of-operations-to-reinitialize-a-permutation.js b/solutions/1806-minimum-number-of-operations-to-reinitialize-a-permutation.js new file mode 100644 index 00000000..5ba88490 --- /dev/null +++ b/solutions/1806-minimum-number-of-operations-to-reinitialize-a-permutation.js @@ -0,0 +1,37 @@ +/** + * 1806. Minimum Number of Operations to Reinitialize a Permutation + * https://leetcode.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation/ + * Difficulty: Medium + * + * You are given an even integer n. You initially have a permutation perm of size n where + * perm[i] == i (0-indexed). + * + * In one operation, you will create a new array arr, and for each i: + * - If i % 2 == 0, then arr[i] = perm[i / 2]. + * - If i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2]. + * + * You will then assign arr to perm. + * + * Return the minimum non-zero number of operations you need to perform on perm to return the + * permutation to its initial value. + */ + +/** + * @param {number} n + * @return {number} + */ +var reinitializePermutation = function(n) { + let currentIndex = 1; + let result = 0; + + do { + if (currentIndex % 2 === 0) { + currentIndex = currentIndex / 2; + } else { + currentIndex = n / 2 + (currentIndex - 1) / 2; + } + result++; + } while (currentIndex !== 1); + + return result; +}; From a27a4e6099e83fc66e916f49c45b06e3330d223b Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 20:25:10 -0500 Subject: [PATCH 050/495] Add solution #1807 --- README.md | 3 +- ...-evaluate-the-bracket-pairs-of-a-string.js | 51 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 solutions/1807-evaluate-the-bracket-pairs-of-a-string.js diff --git a/README.md b/README.md index 281048bd..b3bda01a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,554 LeetCode solutions in JavaScript +# 1,555 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1391,6 +1391,7 @@ 1803|[Count Pairs With XOR in a Range](./solutions/1803-count-pairs-with-xor-in-a-range.js)|Hard| 1805|[Number of Different Integers in a String](./solutions/1805-number-of-different-integers-in-a-string.js)|Easy| 1806|[Minimum Number of Operations to Reinitialize a Permutation](./solutions/1806-minimum-number-of-operations-to-reinitialize-a-permutation.js)|Medium| +1807|[Evaluate the Bracket Pairs of a String](./solutions/1807-evaluate-the-bracket-pairs-of-a-string.js)|Medium| 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| diff --git a/solutions/1807-evaluate-the-bracket-pairs-of-a-string.js b/solutions/1807-evaluate-the-bracket-pairs-of-a-string.js new file mode 100644 index 00000000..7fffdc33 --- /dev/null +++ b/solutions/1807-evaluate-the-bracket-pairs-of-a-string.js @@ -0,0 +1,51 @@ +/** + * 1807. Evaluate the Bracket Pairs of a String + * https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/ + * Difficulty: Medium + * + * You are given a string s that contains some bracket pairs, with each pair containing + * a non-empty key. + * + * - For example, in the string "(name)is(age)yearsold", there are two bracket pairs that contain + * the keys "name" and "age". + * + * You know the values of a wide range of keys. This is represented by a 2D string array knowledge + * where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei. + * + * You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that + * contains some key keyi, you will: + * - Replace keyi and the bracket pair with the key's corresponding valuei. + * - If you do not know the value of the key, you will replace keyi and the bracket pair with a + * question mark "?" (without the quotation marks). + * + * Each key will appear at most once in your knowledge. There will not be any nested brackets in s. + * + * Return the resulting string after evaluating all of the bracket pairs. + */ + +/** + * @param {string} s + * @param {string[][]} knowledge + * @return {string} + */ +var evaluate = function(s, knowledge) { + const keyValueMap = new Map(knowledge); + let result = ''; + let i = 0; + + while (i < s.length) { + if (s[i] === '(') { + i++; + let key = ''; + while (i < s.length && s[i] !== ')') { + key += s[i++]; + } + result += keyValueMap.get(key) || '?'; + i++; + } else { + result += s[i++]; + } + } + + return result; +}; From 3da1a2eab079654068c4c4436c75124cc634093f Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:32:43 -0500 Subject: [PATCH 051/495] Add solution #1808 --- README.md | 3 +- .../1808-maximize-number-of-nice-divisors.js | 48 +++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 solutions/1808-maximize-number-of-nice-divisors.js diff --git a/README.md b/README.md index b3bda01a..0ed1f86c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,555 LeetCode solutions in JavaScript +# 1,556 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1392,6 +1392,7 @@ 1805|[Number of Different Integers in a String](./solutions/1805-number-of-different-integers-in-a-string.js)|Easy| 1806|[Minimum Number of Operations to Reinitialize a Permutation](./solutions/1806-minimum-number-of-operations-to-reinitialize-a-permutation.js)|Medium| 1807|[Evaluate the Bracket Pairs of a String](./solutions/1807-evaluate-the-bracket-pairs-of-a-string.js)|Medium| +1808|[Maximize Number of Nice Divisors](./solutions/1808-maximize-number-of-nice-divisors.js)|Hard| 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| diff --git a/solutions/1808-maximize-number-of-nice-divisors.js b/solutions/1808-maximize-number-of-nice-divisors.js new file mode 100644 index 00000000..49f3697a --- /dev/null +++ b/solutions/1808-maximize-number-of-nice-divisors.js @@ -0,0 +1,48 @@ +/** + * 1808. Maximize Number of Nice Divisors + * https://leetcode.com/problems/maximize-number-of-nice-divisors/ + * Difficulty: Hard + * + * You are given a positive integer primeFactors. You are asked to construct a positive + * integer n that satisfies the following conditions: + * - The number of prime factors of n (not necessarily distinct) is at most primeFactors. + * - The number of nice divisors of n is maximized. Note that a divisor of n is nice if it + * is divisible by every prime factor of n. For example, if n = 12, then its prime factors + * are [2,2,3], then 6 and 12 are nice divisors, while 3 and 4 are not. + * + * Return the number of nice divisors of n. Since that number can be too large, return it + * modulo 109 + 7. + * + * Note that a prime number is a natural number greater than 1 that is not a product of two + * smaller natural numbers. The prime factors of a number n is a list of prime numbers such + * that their product equals n. + */ + +/** + * @param {number} primeFactors + * @return {number} + */ +var maxNiceDivisors = function(primeFactors) { + const MOD = 1e9 + 7; + + if (primeFactors <= 3) return primeFactors; + + const quotient = Math.floor(primeFactors / 3); + const remainder = primeFactors % 3; + + if (remainder === 0) return power(3, quotient); + if (remainder === 1) return (power(3, quotient - 1) * 4) % MOD; + + return (power(3, quotient) * 2) % MOD; + + function power(base, exponent) { + let result = BigInt(1); + base = BigInt(base); + while (exponent > 0) { + if (exponent & 1) result = (result * base) % BigInt(MOD); + base = (base * base) % BigInt(MOD); + exponent >>= 1; + } + return Number(result); + } +}; From 87ffa93e76dc7dde60a319a70fa323e631994eb0 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:34:44 -0500 Subject: [PATCH 052/495] Add solution #1813 --- README.md | 3 +- solutions/1813-sentence-similarity-iii.js | 46 +++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 solutions/1813-sentence-similarity-iii.js diff --git a/README.md b/README.md index 0ed1f86c..bd46a49e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,556 LeetCode solutions in JavaScript +# 1,557 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1394,6 +1394,7 @@ 1807|[Evaluate the Bracket Pairs of a String](./solutions/1807-evaluate-the-bracket-pairs-of-a-string.js)|Medium| 1808|[Maximize Number of Nice Divisors](./solutions/1808-maximize-number-of-nice-divisors.js)|Hard| 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| +1813|[Sentence Similarity III](./solutions/1813-sentence-similarity-iii.js)|Medium| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| diff --git a/solutions/1813-sentence-similarity-iii.js b/solutions/1813-sentence-similarity-iii.js new file mode 100644 index 00000000..872cea74 --- /dev/null +++ b/solutions/1813-sentence-similarity-iii.js @@ -0,0 +1,46 @@ +/** + * 1813. Sentence Similarity III + * https://leetcode.com/problems/sentence-similarity-iii/ + * Difficulty: Medium + * + * You are given two strings sentence1 and sentence2, each representing a sentence composed of + * words. A sentence is a list of words that are separated by a single space with no leading + * or trailing spaces. Each word consists of only uppercase and lowercase English characters. + * + * Two sentences s1 and s2 are considered similar if it is possible to insert an arbitrary + * sentence (possibly empty) inside one of these sentences such that the two sentences become + * equal. Note that the inserted sentence must be separated from existing words by spaces. + * + * For example: + * - s1 = "Hello Jane" and s2 = "Hello my name is Jane" can be made equal by inserting "my name is" + * between "Hello" and "Jane" in s1. + * - s1 = "Frog cool" and s2 = "Frogs are cool" are not similar, since although there is a sentence + * "s are" inserted into s1, it is not separated from "Frog" by a space. + * + * Given two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are + * similar. Otherwise, return false. + */ + +/** + * @param {string} sentence1 + * @param {string} sentence2 + * @return {boolean} + */ +var areSentencesSimilar = function(sentence1, sentence2) { + let words1 = sentence1.split(' '); + let words2 = sentence2.split(' '); + if (words1.length < words2.length) [words1, words2] = [words2, words1]; + + let prefixLength = 0; + while (prefixLength < words2.length && words1[prefixLength] === words2[prefixLength]) { + prefixLength++; + } + + let suffixLength = 0; + while (suffixLength < words2.length - prefixLength + && words1[words1.length - 1 - suffixLength] === words2[words2.length - 1 - suffixLength]) { + suffixLength++; + } + + return prefixLength + suffixLength >= words2.length; +}; From 37c847f0c05d632044b636c095d0606fa65dc452 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:36:20 -0500 Subject: [PATCH 053/495] Add solution #1814 --- README.md | 3 +- .../1814-count-nice-pairs-in-an-array.js | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 solutions/1814-count-nice-pairs-in-an-array.js diff --git a/README.md b/README.md index bd46a49e..b2a1b511 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,557 LeetCode solutions in JavaScript +# 1,558 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1395,6 +1395,7 @@ 1808|[Maximize Number of Nice Divisors](./solutions/1808-maximize-number-of-nice-divisors.js)|Hard| 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| 1813|[Sentence Similarity III](./solutions/1813-sentence-similarity-iii.js)|Medium| +1814|[Count Nice Pairs in an Array](./solutions/1814-count-nice-pairs-in-an-array.js)|Medium| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| diff --git a/solutions/1814-count-nice-pairs-in-an-array.js b/solutions/1814-count-nice-pairs-in-an-array.js new file mode 100644 index 00000000..f8db6cc5 --- /dev/null +++ b/solutions/1814-count-nice-pairs-in-an-array.js @@ -0,0 +1,37 @@ +/** + * 1814. Count Nice Pairs in an Array + * https://leetcode.com/problems/count-nice-pairs-in-an-array/ + * Difficulty: Medium + * + * You are given an array nums that consists of non-negative integers. Let us define rev(x) + * as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. + * A pair of indices (i, j) is nice if it satisfies all of the following conditions: + * - 0 <= i < j < nums.length + * - nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) + * + * Return the number of nice pairs of indices. Since that number can be too large, return it + * modulo 109 + 7. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var countNicePairs = function(nums) { + const MOD = 1e9 + 7; + const map = new Map(); + let result = 0; + + for (const num of nums) { + const diff = num - reverseNumber(num); + const count = map.get(diff) || 0; + result = (result + count) % MOD; + map.set(diff, count + 1); + } + + return result; + + function reverseNumber(num) { + return Number(String(num).split('').reverse().join('')); + } +}; From 217db874b2c44af227f41ae24912bdd20147d614 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:38:24 -0500 Subject: [PATCH 054/495] Add solution #1815 --- README.md | 3 +- ...m-number-of-groups-getting-fresh-donuts.js | 59 +++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 solutions/1815-maximum-number-of-groups-getting-fresh-donuts.js diff --git a/README.md b/README.md index b2a1b511..891f2324 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,558 LeetCode solutions in JavaScript +# 1,559 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1396,6 +1396,7 @@ 1812|[Determine Color of a Chessboard Square](./solutions/1812-determine-color-of-a-chessboard-square.js)|Easy| 1813|[Sentence Similarity III](./solutions/1813-sentence-similarity-iii.js)|Medium| 1814|[Count Nice Pairs in an Array](./solutions/1814-count-nice-pairs-in-an-array.js)|Medium| +1815|[Maximum Number of Groups Getting Fresh Donuts](./solutions/1815-maximum-number-of-groups-getting-fresh-donuts.js)|Hard| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| diff --git a/solutions/1815-maximum-number-of-groups-getting-fresh-donuts.js b/solutions/1815-maximum-number-of-groups-getting-fresh-donuts.js new file mode 100644 index 00000000..fcd73dc8 --- /dev/null +++ b/solutions/1815-maximum-number-of-groups-getting-fresh-donuts.js @@ -0,0 +1,59 @@ +/** + * 1815. Maximum Number of Groups Getting Fresh Donuts + * https://leetcode.com/problems/maximum-number-of-groups-getting-fresh-donuts/ + * Difficulty: Hard + * + * There is a donuts shop that bakes donuts in batches of batchSize. They have a rule where they + * must serve all of the donuts of a batch before serving any donuts of the next batch. You are + * given an integer batchSize and an integer array groups, where groups[i] denotes that there is + * a group of groups[i] customers that will visit the shop. Each customer will get exactly one + * donut. + * + * When a group visits the shop, all customers of the group must be served before serving any + * of the following groups. A group will be happy if they all get fresh donuts. That is, the + * first customer of the group does not receive a donut that was left over from the previous group. + * + * You can freely rearrange the ordering of the groups. Return the maximum possible number of + * happy groups after rearranging the groups. + */ + +/** + * @param {number} batchSize + * @param {number[]} groups + * @return {number} + */ +var maxHappyGroups = function(batchSize, groups) { + const remainders = new Array(batchSize).fill(0); + let result = 0; + + for (const size of groups) { + remainders[size % batchSize]++; + } + + result += remainders[0]; + remainders[0] = 0; + + return result + findMaxHappy(remainders, 0); + + function findMaxHappy(remainders, leftover, memo = new Map()) { + const key = remainders.join(',') + ',' + leftover; + if (memo.has(key)) return memo.get(key); + + let maxHappy = 0; + for (let i = 1; i < batchSize; i++) { + if (remainders[i] === 0) continue; + remainders[i]--; + + let current = 0; + if (leftover === 0) current = 1; + maxHappy = Math.max( + maxHappy, current + findMaxHappy(remainders, (leftover + i) % batchSize, memo) + ); + + remainders[i]++; + } + + memo.set(key, maxHappy); + return maxHappy; + } +}; From 9b478ed487c7ce44e39cb0c1a9856a32c1ea1dbf Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:39:48 -0500 Subject: [PATCH 055/495] Add solution #1816 --- README.md | 3 ++- solutions/1816-truncate-sentence.js | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 solutions/1816-truncate-sentence.js diff --git a/README.md b/README.md index 891f2324..d049d2e1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,559 LeetCode solutions in JavaScript +# 1,560 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1397,6 +1397,7 @@ 1813|[Sentence Similarity III](./solutions/1813-sentence-similarity-iii.js)|Medium| 1814|[Count Nice Pairs in an Array](./solutions/1814-count-nice-pairs-in-an-array.js)|Medium| 1815|[Maximum Number of Groups Getting Fresh Donuts](./solutions/1815-maximum-number-of-groups-getting-fresh-donuts.js)|Hard| +1816|[Truncate Sentence](./solutions/1816-truncate-sentence.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| diff --git a/solutions/1816-truncate-sentence.js b/solutions/1816-truncate-sentence.js new file mode 100644 index 00000000..d0d91e32 --- /dev/null +++ b/solutions/1816-truncate-sentence.js @@ -0,0 +1,22 @@ +/** + * 1816. Truncate Sentence + * https://leetcode.com/problems/truncate-sentence/ + * Difficulty: Easy + * + * A sentence is a list of words that are separated by a single space with no leading or + * trailing spaces. Each of the words consists of only uppercase and lowercase English + * letters (no punctuation). + * - For example, "Hello World", "HELLO", and "hello world hello world" are all sentences. + * + * You are given a sentence s and an integer k. You want to truncate s such that it contains + * only the first k words. Return s after truncating it. + */ + +/** + * @param {string} s + * @param {number} k + * @return {string} + */ +var truncateSentence = function(s, k) { + return s.split(' ').slice(0, k).join(' '); +}; From d978725127fb38e1c94e371d1683b73cb13afc82 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:41:43 -0500 Subject: [PATCH 056/495] Add solution #1818 --- README.md | 3 +- .../1818-minimum-absolute-sum-difference.js | 51 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 solutions/1818-minimum-absolute-sum-difference.js diff --git a/README.md b/README.md index d049d2e1..0bb003d4 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,560 LeetCode solutions in JavaScript +# 1,561 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1399,6 +1399,7 @@ 1815|[Maximum Number of Groups Getting Fresh Donuts](./solutions/1815-maximum-number-of-groups-getting-fresh-donuts.js)|Hard| 1816|[Truncate Sentence](./solutions/1816-truncate-sentence.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| +1818|[Minimum Absolute Sum Difference](./solutions/1818-minimum-absolute-sum-difference.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| diff --git a/solutions/1818-minimum-absolute-sum-difference.js b/solutions/1818-minimum-absolute-sum-difference.js new file mode 100644 index 00000000..fb1cc1dc --- /dev/null +++ b/solutions/1818-minimum-absolute-sum-difference.js @@ -0,0 +1,51 @@ +/** + * 1818. Minimum Absolute Sum Difference + * https://leetcode.com/problems/minimum-absolute-sum-difference/ + * Difficulty: Medium + * + * You are given two positive integer arrays nums1 and nums2, both of length n. + * + * The absolute sum difference of arrays nums1 and nums2 is defined as the sum of + * |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed). + * + * You can replace at most one element of nums1 with any other element in nums1 to minimize + * the absolute sum difference. + * + * Return the minimum absolute sum difference after replacing at most one element in the + * array nums1. Since the answer may be large, return it modulo 109 + 7. + * + * |x| is defined as: + * - x if x >= 0, or + * - -x if x < 0. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var minAbsoluteSumDiff = function(nums1, nums2) { + const MOD = 1e9 + 7; + const sortedNums1 = [...nums1].sort((a, b) => a - b); + let totalDiff = 0; + let maxReduction = 0; + + for (let i = 0; i < nums1.length; i++) { + const currentDiff = Math.abs(nums1[i] - nums2[i]); + totalDiff = (totalDiff + currentDiff) % MOD; + + let left = 0; + let right = nums1.length - 1; + while (left <= right) { + const mid = Math.floor((left + right) / 2); + const newDiff = Math.abs(sortedNums1[mid] - nums2[i]); + const reduction = currentDiff - newDiff; + maxReduction = Math.max(maxReduction, reduction); + + if (sortedNums1[mid] < nums2[i]) left = mid + 1; + else right = mid - 1; + } + } + + return (totalDiff - maxReduction + MOD) % MOD; +}; From b64675cfd9ac1c49e84e76540cbdd6bb28842e81 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:42:54 -0500 Subject: [PATCH 057/495] Add solution #1819 --- README.md | 3 +- ...9-number-of-different-subsequences-gcds.js | 48 +++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 solutions/1819-number-of-different-subsequences-gcds.js diff --git a/README.md b/README.md index 0bb003d4..0915110a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,561 LeetCode solutions in JavaScript +# 1,562 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1400,6 +1400,7 @@ 1816|[Truncate Sentence](./solutions/1816-truncate-sentence.js)|Easy| 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| 1818|[Minimum Absolute Sum Difference](./solutions/1818-minimum-absolute-sum-difference.js)|Medium| +1819|[Number of Different Subsequences GCDs](./solutions/1819-number-of-different-subsequences-gcds.js)|Hard| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| diff --git a/solutions/1819-number-of-different-subsequences-gcds.js b/solutions/1819-number-of-different-subsequences-gcds.js new file mode 100644 index 00000000..04842fef --- /dev/null +++ b/solutions/1819-number-of-different-subsequences-gcds.js @@ -0,0 +1,48 @@ +/** + * 1819. Number of Different Subsequences GCDs + * https://leetcode.com/problems/number-of-different-subsequences-gcds/ + * Difficulty: Hard + * + * You are given an array nums that consists of positive integers. + * + * The GCD of a sequence of numbers is defined as the greatest integer that divides all the + * numbers in the sequence evenly. + * - For example, the GCD of the sequence [4,6,16] is 2. + * + * 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]. + * + * Return the number of different GCDs among all non-empty subsequences of nums. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var countDifferentSubsequenceGCDs = function(nums) { + const maxNum = Math.max(...nums); + const exists = new Array(maxNum + 1).fill(false); + let result = 0; + + function gcd(a, b) { + while (b) [a, b] = [b, a % b]; + return a; + } + + for (const num of nums) { + exists[num] = true; + } + + for (let i = 1; i <= maxNum; i++) { + let currentGcd = 0; + for (let j = i; j <= maxNum; j += i) { + if (exists[j]) { + currentGcd = currentGcd ? gcd(currentGcd, j) : j; + } + } + if (currentGcd === i) result++; + } + + return result; +}; From b67a16ad53942851115a079499e22f07cf385ade Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:43:48 -0500 Subject: [PATCH 058/495] Add solution #1822 --- README.md | 3 +- .../1822-sign-of-the-product-of-an-array.js | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 solutions/1822-sign-of-the-product-of-an-array.js diff --git a/README.md b/README.md index 0915110a..9841b8bd 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,562 LeetCode solutions in JavaScript +# 1,563 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1401,6 +1401,7 @@ 1817|[Finding the Users Active Minutes](./solutions/1817-finding-the-users-active-minutes.js)|Medium| 1818|[Minimum Absolute Sum Difference](./solutions/1818-minimum-absolute-sum-difference.js)|Medium| 1819|[Number of Different Subsequences GCDs](./solutions/1819-number-of-different-subsequences-gcds.js)|Hard| +1822|[Sign of the Product of an Array](./solutions/1822-sign-of-the-product-of-an-array.js)|Easy| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| diff --git a/solutions/1822-sign-of-the-product-of-an-array.js b/solutions/1822-sign-of-the-product-of-an-array.js new file mode 100644 index 00000000..f235ea51 --- /dev/null +++ b/solutions/1822-sign-of-the-product-of-an-array.js @@ -0,0 +1,29 @@ +/** + * 1822. Sign of the Product of an Array + * https://leetcode.com/problems/sign-of-the-product-of-an-array/ + * Difficulty: Easy + * + * Implement a function signFunc(x) that returns: + * - 1 if x is positive. + * - -1 if x is negative. + * - 0 if x is equal to 0. + * + * You are given an integer array nums. Let product be the product of all values in the array nums. + * + * Return signFunc(product). + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var arraySign = function(nums) { + let negativeCount = 0; + + for (const num of nums) { + if (num === 0) return 0; + if (num < 0) negativeCount++; + } + + return negativeCount % 2 === 0 ? 1 : -1; +}; From 486e2c55c6dd13518a7ad9cd3d4d1346e6e04884 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:45:09 -0500 Subject: [PATCH 059/495] Add solution #1823 --- README.md | 3 +- ...23-find-the-winner-of-the-circular-game.js | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 solutions/1823-find-the-winner-of-the-circular-game.js diff --git a/README.md b/README.md index 9841b8bd..1a84a629 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,563 LeetCode solutions in JavaScript +# 1,564 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1402,6 +1402,7 @@ 1818|[Minimum Absolute Sum Difference](./solutions/1818-minimum-absolute-sum-difference.js)|Medium| 1819|[Number of Different Subsequences GCDs](./solutions/1819-number-of-different-subsequences-gcds.js)|Hard| 1822|[Sign of the Product of an Array](./solutions/1822-sign-of-the-product-of-an-array.js)|Easy| +1823|[Find the Winner of the Circular Game](./solutions/1823-find-the-winner-of-the-circular-game.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| diff --git a/solutions/1823-find-the-winner-of-the-circular-game.js b/solutions/1823-find-the-winner-of-the-circular-game.js new file mode 100644 index 00000000..3138d5bb --- /dev/null +++ b/solutions/1823-find-the-winner-of-the-circular-game.js @@ -0,0 +1,36 @@ +/** + * 1823. Find the Winner of the Circular Game + * https://leetcode.com/problems/find-the-winner-of-the-circular-game/ + * Difficulty: Medium + * + * There are n friends that are playing a game. The friends are sitting in a circle and are + * numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith + * friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the + * nth friend brings you to the 1st friend. + * + * The rules of the game are as follows: + * 1. Start at the 1st friend. + * 2. Count the next k friends in the clockwise direction including the friend you started at. + * The counting wraps around the circle and may count some friends more than once. + * 3. The last friend you counted leaves the circle and loses the game. + * 4. If there is still more than one friend in the circle, go back to step 2 starting from the + * friend immediately clockwise of the friend who just lost and repeat. + * 5. Else, the last friend in the circle wins the game. + * + * Given the number of friends, n, and an integer k, return the winner of the game. + */ + +/** + * @param {number} n + * @param {number} k + * @return {number} + */ +var findTheWinner = function(n, k) { + let winner = 0; + + for (let i = 1; i <= n; i++) { + winner = (winner + k) % i; + } + + return winner + 1; +}; From 9f97e10a2a78e79e93bb9064fa4635f1a1d93ef4 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:56:45 -0500 Subject: [PATCH 060/495] Add solution #1824 --- README.md | 3 +- solutions/1824-minimum-sideway-jumps.js | 55 +++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 solutions/1824-minimum-sideway-jumps.js diff --git a/README.md b/README.md index 1a84a629..425f40b6 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,564 LeetCode solutions in JavaScript +# 1,565 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1403,6 +1403,7 @@ 1819|[Number of Different Subsequences GCDs](./solutions/1819-number-of-different-subsequences-gcds.js)|Hard| 1822|[Sign of the Product of an Array](./solutions/1822-sign-of-the-product-of-an-array.js)|Easy| 1823|[Find the Winner of the Circular Game](./solutions/1823-find-the-winner-of-the-circular-game.js)|Medium| +1824|[Minimum Sideway Jumps](./solutions/1824-minimum-sideway-jumps.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| diff --git a/solutions/1824-minimum-sideway-jumps.js b/solutions/1824-minimum-sideway-jumps.js new file mode 100644 index 00000000..e4eb60d3 --- /dev/null +++ b/solutions/1824-minimum-sideway-jumps.js @@ -0,0 +1,55 @@ +/** + * 1824. Minimum Sideway Jumps + * https://leetcode.com/problems/minimum-sideway-jumps/ + * Difficulty: Medium + * + * There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog + * starts at point 0 in the second lane and wants to jump to point n. However, there could be + * obstacles along the way. + * + * You are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) + * describes an obstacle on the lane obstacles[i] at point i. If obstacles[i] == 0, there are no + * obstacles at point i. There will be at most one obstacle in the 3 lanes at each point. + * - For example, if obstacles[2] == 1, then there is an obstacle on lane 1 at point 2. + * + * The frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle + * on the lane at point i + 1. To avoid obstacles, the frog can also perform a side jump to jump + * to another lane (even if they are not adjacent) at the same point if there is no obstacle on + * the new lane. + * - For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. + * + * Return the minimum number of side jumps the frog needs to reach any lane at point n starting + * from lane 2 at point 0. + * + * Note: There will be no obstacles on points 0 and n. + */ + +/** + * @param {number[]} obstacles + * @return {number} + */ +var minSideJumps = function(obstacles) { + const n = obstacles.length; + let dp = [1, 0, 1]; + + for (let i = 1; i < n; i++) { + const currentObstacle = obstacles[i]; + const nextDp = [Infinity, Infinity, Infinity]; + + for (let lane = 1; lane <= 3; lane++) { + if (lane === currentObstacle) continue; + + nextDp[lane - 1] = dp[lane - 1]; + + for (let fromLane = 1; fromLane <= 3; fromLane++) { + if (fromLane !== lane && fromLane !== currentObstacle) { + nextDp[lane - 1] = Math.min(nextDp[lane - 1], dp[fromLane - 1] + 1); + } + } + } + + dp = nextDp; + } + + return Math.min(...dp); +}; From 02d73d6cb995b4a2aeefddceb94d8302753e6d84 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 09:23:15 -0500 Subject: [PATCH 061/495] Add solution #1825 --- README.md | 3 +- solutions/1825-finding-mk-average.js | 93 ++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 1 deletion(-) create mode 100644 solutions/1825-finding-mk-average.js diff --git a/README.md b/README.md index 425f40b6..fab4f2d2 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,565 LeetCode solutions in JavaScript +# 1,566 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1404,6 +1404,7 @@ 1822|[Sign of the Product of an Array](./solutions/1822-sign-of-the-product-of-an-array.js)|Easy| 1823|[Find the Winner of the Circular Game](./solutions/1823-find-the-winner-of-the-circular-game.js)|Medium| 1824|[Minimum Sideway Jumps](./solutions/1824-minimum-sideway-jumps.js)|Medium| +1825|[Finding MK Average](./solutions/1825-finding-mk-average.js)|Hard| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| diff --git a/solutions/1825-finding-mk-average.js b/solutions/1825-finding-mk-average.js new file mode 100644 index 00000000..ddc2b83e --- /dev/null +++ b/solutions/1825-finding-mk-average.js @@ -0,0 +1,93 @@ +/** + * 1825. Finding MK Average + * https://leetcode.com/problems/finding-mk-average/ + * Difficulty: Hard + * + * You are given two integers, m and k, and a stream of integers. You are tasked to implement a data + * structure that calculates the MKAverage for the stream. + * + * The MKAverage can be calculated using these steps: + * - If the number of the elements in the stream is less than m you should consider the MKAverage to + * be -1. Otherwise, copy the last m elements of the stream to a separate container. + * - Remove the smallest k elements and the largest k elements from the container. + * - Calculate the average value for the rest of the elements rounded down to the nearest integer. + * + * Implement the MKAverage class: + * - MKAverage(int m, int k) Initializes the MKAverage object with an empty stream and the two + * integers m and k. + * - void addElement(int num) Inserts a new element num into the stream. + * - int calculateMKAverage() Calculates and returns the MKAverage for the current stream rounded + * down to the nearest integer. + */ + +/** + * @param {number} m + * @param {number} k + */ +var MKAverage = function(m, k) { + this.m = m; + this.k = k; + this.stream = []; + this.sortedStream = []; + this.sum = 0; +}; + +/** + * @param {number} num + * @return {void} + */ +MKAverage.prototype.addElement = function(num) { + this.stream.push(num); + + const insertIndex = this.findInsertPosition(num); + this.sortedStream.splice(insertIndex, 0, num); + this.sum += num; + + if (this.stream.length > this.m) { + const oldestElement = this.stream.shift(); + const oldestIndex = this.sortedStream.indexOf(oldestElement); + this.sortedStream.splice(oldestIndex, 1); + this.sum -= oldestElement; + } +}; + +/** + * @return {number} + */ +MKAverage.prototype.calculateMKAverage = function() { + if (this.stream.length < this.m) { + return -1; + } + + let adjustedSum = this.sum; + + for (let i = 0; i < this.k; i++) { + adjustedSum -= this.sortedStream[i]; + } + for (let i = this.sortedStream.length - this.k; i < this.sortedStream.length; i++) { + adjustedSum -= this.sortedStream[i]; + } + + return Math.floor(adjustedSum / (this.m - 2 * this.k)); +}; + +/** + * Helper method to find insert position using binary search + * @param {number} num + * @return {number} + */ +MKAverage.prototype.findInsertPosition = function(num) { + let left = 0; + let right = this.sortedStream.length - 1; + + while (left <= right) { + const mid = Math.floor((left + right) / 2); + if (this.sortedStream[mid] < num) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return left; +}; From b6cd33fa944a7a52bdba4ffd9432ca8ee9c0a671 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 09:25:05 -0500 Subject: [PATCH 062/495] Add solution #1827 --- README.md | 3 +- ...operations-to-make-the-array-increasing.js | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 solutions/1827-minimum-operations-to-make-the-array-increasing.js diff --git a/README.md b/README.md index fab4f2d2..ccf28dce 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,566 LeetCode solutions in JavaScript +# 1,567 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1405,6 +1405,7 @@ 1823|[Find the Winner of the Circular Game](./solutions/1823-find-the-winner-of-the-circular-game.js)|Medium| 1824|[Minimum Sideway Jumps](./solutions/1824-minimum-sideway-jumps.js)|Medium| 1825|[Finding MK Average](./solutions/1825-finding-mk-average.js)|Hard| +1827|[Minimum Operations to Make the Array Increasing](./solutions/1827-minimum-operations-to-make-the-array-increasing.js)|Easy| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| diff --git a/solutions/1827-minimum-operations-to-make-the-array-increasing.js b/solutions/1827-minimum-operations-to-make-the-array-increasing.js new file mode 100644 index 00000000..5eef57d6 --- /dev/null +++ b/solutions/1827-minimum-operations-to-make-the-array-increasing.js @@ -0,0 +1,35 @@ +/** + * 1827. Minimum Operations to Make the Array Increasing + * https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing/ + * Difficulty: Easy + * + * You are given an integer array nums (0-indexed). In one operation, you can choose an + * element of the array and increment it by 1. + * - For example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3]. + * + * Return the minimum number of operations needed to make nums strictly increasing. + * + * An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. + * An array of length 1 is trivially strictly increasing. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var minOperations = function(nums) { + let result = 0; + let previousValue = nums[0]; + + for (let i = 1; i < nums.length; i++) { + if (nums[i] <= previousValue) { + const requiredValue = previousValue + 1; + result += requiredValue - nums[i]; + previousValue = requiredValue; + } else { + previousValue = nums[i]; + } + } + + return result; +}; From 57219d21e3b1dcc488d9081757b311da2aa30581 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 09:25:57 -0500 Subject: [PATCH 063/495] Add solution #1828 --- README.md | 3 +- ...ies-on-number-of-points-inside-a-circle.js | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 solutions/1828-queries-on-number-of-points-inside-a-circle.js diff --git a/README.md b/README.md index ccf28dce..00436041 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,567 LeetCode solutions in JavaScript +# 1,568 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1406,6 +1406,7 @@ 1824|[Minimum Sideway Jumps](./solutions/1824-minimum-sideway-jumps.js)|Medium| 1825|[Finding MK Average](./solutions/1825-finding-mk-average.js)|Hard| 1827|[Minimum Operations to Make the Array Increasing](./solutions/1827-minimum-operations-to-make-the-array-increasing.js)|Easy| +1828|[Queries on Number of Points Inside a Circle](./solutions/1828-queries-on-number-of-points-inside-a-circle.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| diff --git a/solutions/1828-queries-on-number-of-points-inside-a-circle.js b/solutions/1828-queries-on-number-of-points-inside-a-circle.js new file mode 100644 index 00000000..bfc1e4b8 --- /dev/null +++ b/solutions/1828-queries-on-number-of-points-inside-a-circle.js @@ -0,0 +1,38 @@ +/** + * 1828. Queries on Number of Points Inside a Circle + * https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle/ + * Difficulty: Medium + * + * You are given an array points where points[i] = [xi, yi] is the coordinates of the ith + * point on a 2D plane. Multiple points can have the same coordinates. + * + * You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle + * centered at (xj, yj) with a radius of rj. + * + * For each query queries[j], compute the number of points inside the jth circle. Points on + * the border of the circle are considered inside. + * + * Return an array answer, where answer[j] is the answer to the jth query. + */ + +/** + * @param {number[][]} points + * @param {number[][]} queries + * @return {number[]} + */ +var countPoints = function(points, queries) { + const result = []; + + for (const [centerX, centerY, radius] of queries) { + let pointsInside = 0; + for (const [pointX, pointY] of points) { + const distance = Math.sqrt((centerX - pointX) ** 2 + (centerY - pointY) ** 2); + if (distance <= radius) { + pointsInside++; + } + } + result.push(pointsInside); + } + + return result; +}; From a6bc314bfc9cb9189f11f15e0c088fa47a5ee179 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 09:27:02 -0500 Subject: [PATCH 064/495] Add solution #1829 --- README.md | 3 +- solutions/1829-maximum-xor-for-each-query.js | 36 ++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 solutions/1829-maximum-xor-for-each-query.js diff --git a/README.md b/README.md index 00436041..e443e22a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,568 LeetCode solutions in JavaScript +# 1,569 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1407,6 +1407,7 @@ 1825|[Finding MK Average](./solutions/1825-finding-mk-average.js)|Hard| 1827|[Minimum Operations to Make the Array Increasing](./solutions/1827-minimum-operations-to-make-the-array-increasing.js)|Easy| 1828|[Queries on Number of Points Inside a Circle](./solutions/1828-queries-on-number-of-points-inside-a-circle.js)|Medium| +1829|[Maximum XOR for Each Query](./solutions/1829-maximum-xor-for-each-query.js)|Medium| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| diff --git a/solutions/1829-maximum-xor-for-each-query.js b/solutions/1829-maximum-xor-for-each-query.js new file mode 100644 index 00000000..43a867f6 --- /dev/null +++ b/solutions/1829-maximum-xor-for-each-query.js @@ -0,0 +1,36 @@ +/** + * 1829. Maximum XOR for Each Query + * https://leetcode.com/problems/maximum-xor-for-each-query/ + * Difficulty: Medium + * + * You are given a sorted array nums of n non-negative integers and an integer maximumBit. + * You want to perform the following query n times: + * - Find a non-negative integer k < 2maximumBit such that nums[0] XOR nums[1] XOR ... XOR + * nums[nums.length-1] XOR k is maximized. k is the answer to the ith query. + * - Remove the last element from the current array nums. + * + * Return an array answer, where answer[i] is the answer to the ith query. + */ + +/** + * @param {number[]} nums + * @param {number} maximumBit + * @return {number[]} + */ +var getMaximumXor = function(nums, maximumBit) { + const result = []; + let currentXor = 0; + const maxValue = (1 << maximumBit) - 1; + + for (const num of nums) { + currentXor ^= num; + } + + for (let i = nums.length - 1; i >= 0; i--) { + const optimalK = currentXor ^ maxValue; + result.push(optimalK); + currentXor ^= nums[i]; + } + + return result; +}; From 5ad84b57e213edb2ea08fb1434ba5445aa992045 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 09:29:52 -0500 Subject: [PATCH 065/495] Add solution #1830 --- README.md | 3 +- ...ber-of-operations-to-make-string-sorted.js | 71 +++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 solutions/1830-minimum-number-of-operations-to-make-string-sorted.js diff --git a/README.md b/README.md index e443e22a..3979ce08 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,569 LeetCode solutions in JavaScript +# 1,570 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1408,6 +1408,7 @@ 1827|[Minimum Operations to Make the Array Increasing](./solutions/1827-minimum-operations-to-make-the-array-increasing.js)|Easy| 1828|[Queries on Number of Points Inside a Circle](./solutions/1828-queries-on-number-of-points-inside-a-circle.js)|Medium| 1829|[Maximum XOR for Each Query](./solutions/1829-maximum-xor-for-each-query.js)|Medium| +1830|[Minimum Number of Operations to Make String Sorted](./solutions/1830-minimum-number-of-operations-to-make-string-sorted.js)|Hard| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| diff --git a/solutions/1830-minimum-number-of-operations-to-make-string-sorted.js b/solutions/1830-minimum-number-of-operations-to-make-string-sorted.js new file mode 100644 index 00000000..51cbb535 --- /dev/null +++ b/solutions/1830-minimum-number-of-operations-to-make-string-sorted.js @@ -0,0 +1,71 @@ +/** + * 1830. Minimum Number of Operations to Make String Sorted + * https://leetcode.com/problems/minimum-number-of-operations-to-make-string-sorted/ + * Difficulty: Hard + * + * You are given a string s (0-indexed). You are asked to perform the following operation on + * s until you get a sorted string: + * 1. Find the largest index i such that 1 <= i < s.length and s[i] < s[i - 1]. + * 2. Find the largest index j such that i <= j < s.length and s[k] < s[i - 1] for all the + * possible values of k in the range [i, j] inclusive. + * 3. Swap the two characters at indices i - 1 and j. + * 4. Reverse the suffix starting at index i. + * + * Return the number of operations needed to make the string sorted. Since the answer can be too + * large, return it modulo 109 + 7. + */ + +/** + * @param {string} s + * @return {number} + */ +var makeStringSorted = function(s) { + const MOD = 1e9 + 7; + const length = s.length; + const factorials = new Array(length + 1).fill(1n); + const inverses = new Array(length + 1).fill(1n); + + for (let i = 2; i <= length; i++) { + factorials[i] = (factorials[i - 1] * BigInt(i)) % BigInt(MOD); + } + + for (let i = 1; i <= length; i++) { + inverses[i] = modInverse(factorials[i], BigInt(MOD)); + } + + let result = 0n; + const charCounts = new Array(26).fill(0); + for (let i = length - 1; i >= 0; i--) { + const charIndex = s.charCodeAt(i) - 97; + charCounts[charIndex]++; + let smallerChars = 0; + for (let j = 0; j < charIndex; j++) { + smallerChars += charCounts[j]; + } + let totalPermutations = factorials[length - i - 1]; + for (const count of charCounts) { + totalPermutations = (totalPermutations * inverses[count]) % BigInt(MOD); + } + result = (result + BigInt(smallerChars) * totalPermutations) % BigInt(MOD); + } + + return Number(result); + + function modInverse(a, m) { + const m0 = m; + let q; + let x0 = 0n; + let x1 = 1n; + while (a > 1n) { + q = a / m; + [a, m] = [m, a % m]; + [x0, x1] = [x1 - q * x0, x0]; + } + return x1 < 0n ? x1 + m0 : x1; + } + + function combinations(n, k) { + if (k < 0 || k > n) return 0n; + return (factorials[n] * inverses[k] % BigInt(MOD)) * inverses[n - k] % BigInt(MOD); + } +}; From d2c69724ce38658d646756d3a6746068482fb351 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 09:44:05 -0500 Subject: [PATCH 066/495] Add solution #1834 --- README.md | 3 +- solutions/1834-single-threaded-cpu.js | 51 +++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 solutions/1834-single-threaded-cpu.js diff --git a/README.md b/README.md index 3979ce08..9d2ebba2 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,570 LeetCode solutions in JavaScript +# 1,571 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1411,6 +1411,7 @@ 1830|[Minimum Number of Operations to Make String Sorted](./solutions/1830-minimum-number-of-operations-to-make-string-sorted.js)|Hard| 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| +1834|[Single-Threaded CPU](./solutions/1834-single-threaded-cpu.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1834-single-threaded-cpu.js b/solutions/1834-single-threaded-cpu.js new file mode 100644 index 00000000..e07dd7dc --- /dev/null +++ b/solutions/1834-single-threaded-cpu.js @@ -0,0 +1,51 @@ +/** + * 1834. Single-Threaded CPU + * https://leetcode.com/problems/single-threaded-cpu/ + * Difficulty: Medium + * + * You are given n tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, + * where tasks[i] = [enqueueTimei, processingTimei] means that the ith task will be available + * to process at enqueueTimei and will take processingTimei to finish processing. + * + * You have a single-threaded CPU that can process at most one task at a time and will act in + * the following way: + * - If the CPU is idle and there are no available tasks to process, the CPU remains idle. + * - If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest + * processing time. If multiple tasks have the same shortest processing time, it will choose the + * task with the smallest index. + * - Once a task is started, the CPU will process the entire task without stopping. + * - The CPU can finish a task then start a new one instantly. + * + * Return the order in which the CPU will process the tasks. + */ + +/** + * @param {number[][]} tasks + * @return {number[]} + */ +var getOrder = function(tasks) { + const indexedTasks = tasks.map(([enqueue, process], index) => ({ enqueue, process, index })) + .sort((a, b) => a.enqueue - b.enqueue); + + const result = []; + const availableTasks = new PriorityQueue((a, b) => a.process - b.process || a.index - b.index); + let currentTime = indexedTasks[0].enqueue; + let taskIndex = 0; + + while (result.length < tasks.length) { + while (taskIndex < tasks.length && indexedTasks[taskIndex].enqueue <= currentTime) { + availableTasks.push(indexedTasks[taskIndex]); + taskIndex++; + } + + if (availableTasks.size() > 0) { + const task = availableTasks.pop(); + result.push(task.index); + currentTime += task.process; + } else { + currentTime = indexedTasks[taskIndex].enqueue; + } + } + + return result; +}; From f3fa12cacb098ef4e75c8a291b76104238b4b2e0 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 09:45:14 -0500 Subject: [PATCH 067/495] Add solution #1835 --- README.md | 3 +- ...5-find-xor-sum-of-all-pairs-bitwise-and.js | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 solutions/1835-find-xor-sum-of-all-pairs-bitwise-and.js diff --git a/README.md b/README.md index 9d2ebba2..2cc94660 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,571 LeetCode solutions in JavaScript +# 1,572 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1412,6 +1412,7 @@ 1832|[Check if the Sentence Is Pangram](./solutions/1832-check-if-the-sentence-is-pangram.js)|Easy| 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| 1834|[Single-Threaded CPU](./solutions/1834-single-threaded-cpu.js)|Medium| +1835|[Find XOR Sum of All Pairs Bitwise AND](./solutions/1835-find-xor-sum-of-all-pairs-bitwise-and.js)|Hard| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1835-find-xor-sum-of-all-pairs-bitwise-and.js b/solutions/1835-find-xor-sum-of-all-pairs-bitwise-and.js new file mode 100644 index 00000000..f57b405d --- /dev/null +++ b/solutions/1835-find-xor-sum-of-all-pairs-bitwise-and.js @@ -0,0 +1,37 @@ +/** + * 1835. Find XOR Sum of All Pairs Bitwise AND + * https://leetcode.com/problems/find-xor-sum-of-all-pairs-bitwise-and/ + * Difficulty: Hard + * + * The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one + * element, then its XOR sum will be equal to this element. + * - For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR + * sum of [3] is equal to 3. + * + * You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers. + * + * Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) + * pair where 0 <= i < arr1.length and 0 <= j < arr2.length. + * + * Return the XOR sum of the aforementioned list. + */ + +/** + * @param {number[]} arr1 + * @param {number[]} arr2 + * @return {number} + */ +var getXORSum = function(arr1, arr2) { + let xor1 = 0; + let xor2 = 0; + + for (const num of arr1) { + xor1 ^= num; + } + + for (const num of arr2) { + xor2 ^= num; + } + + return xor1 & xor2; +}; From fc984b3a60a51fd9566fea6cad0d2645f55eda5c Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 09:46:01 -0500 Subject: [PATCH 068/495] Add solution #1837 --- README.md | 3 ++- solutions/1837-sum-of-digits-in-base-k.js | 27 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 solutions/1837-sum-of-digits-in-base-k.js diff --git a/README.md b/README.md index 2cc94660..e71e370a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,572 LeetCode solutions in JavaScript +# 1,573 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1413,6 +1413,7 @@ 1833|[Maximum Ice Cream Bars](./solutions/1833-maximum-ice-cream-bars.js)|Medium| 1834|[Single-Threaded CPU](./solutions/1834-single-threaded-cpu.js)|Medium| 1835|[Find XOR Sum of All Pairs Bitwise AND](./solutions/1835-find-xor-sum-of-all-pairs-bitwise-and.js)|Hard| +1837|[Sum of Digits in Base K](./solutions/1837-sum-of-digits-in-base-k.js)|Easy| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1837-sum-of-digits-in-base-k.js b/solutions/1837-sum-of-digits-in-base-k.js new file mode 100644 index 00000000..48223a4d --- /dev/null +++ b/solutions/1837-sum-of-digits-in-base-k.js @@ -0,0 +1,27 @@ +/** + * 1837. Sum of Digits in Base K + * https://leetcode.com/problems/sum-of-digits-in-base-k/ + * Difficulty: Easy + * + * Given an integer n (in base 10) and a base k, return the sum of the digits of n after + * converting n from base 10 to base k. + * + * After converting, each digit should be interpreted as a base 10 number, and the sum should + * be returned in base 10. + */ + +/** + * @param {number} n + * @param {number} k + * @return {number} + */ +var sumBase = function(n, k) { + let digitSum = 0; + + while (n > 0) { + digitSum += n % k; + n = Math.floor(n / k); + } + + return digitSum; +}; From 530fb126806f16a30051ccf5437959c4f574faa3 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 09:47:00 -0500 Subject: [PATCH 069/495] Add solution #1838 --- README.md | 3 +- ...-frequency-of-the-most-frequent-element.js | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 solutions/1838-frequency-of-the-most-frequent-element.js diff --git a/README.md b/README.md index e71e370a..73edcf2a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,573 LeetCode solutions in JavaScript +# 1,574 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1414,6 +1414,7 @@ 1834|[Single-Threaded CPU](./solutions/1834-single-threaded-cpu.js)|Medium| 1835|[Find XOR Sum of All Pairs Bitwise AND](./solutions/1835-find-xor-sum-of-all-pairs-bitwise-and.js)|Hard| 1837|[Sum of Digits in Base K](./solutions/1837-sum-of-digits-in-base-k.js)|Easy| +1838|[Frequency of the Most Frequent Element](./solutions/1838-frequency-of-the-most-frequent-element.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1838-frequency-of-the-most-frequent-element.js b/solutions/1838-frequency-of-the-most-frequent-element.js new file mode 100644 index 00000000..d13b8eb2 --- /dev/null +++ b/solutions/1838-frequency-of-the-most-frequent-element.js @@ -0,0 +1,36 @@ +/** + * 1838. Frequency of the Most Frequent Element + * https://leetcode.com/problems/frequency-of-the-most-frequent-element/ + * Difficulty: Medium + * + * The frequency of an element is the number of times it occurs in an array. + * + * You are given an integer array nums and an integer k. In one operation, you can choose + * an index of nums and increment the element at that index by 1. + * + * Return the maximum possible frequency of an element after performing at most k operations. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var maxFrequency = function(nums, k) { + nums.sort((a, b) => a - b); + + let result = 0; + let currentSum = 0; + let left = 0; + + for (let right = 0; right < nums.length; right++) { + currentSum += nums[right]; + while (currentSum + k < nums[right] * (right - left + 1)) { + currentSum -= nums[left]; + left++; + } + result = Math.max(result, right - left + 1); + } + + return result; +}; From 3eeab1b341ac0b398a059d9a7d47b5c5678855e2 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 09:48:24 -0500 Subject: [PATCH 070/495] Add solution #1839 --- README.md | 3 +- ...ongest-substring-of-all-vowels-in-order.js | 43 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 solutions/1839-longest-substring-of-all-vowels-in-order.js diff --git a/README.md b/README.md index 73edcf2a..e1b1d47a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,574 LeetCode solutions in JavaScript +# 1,575 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1415,6 +1415,7 @@ 1835|[Find XOR Sum of All Pairs Bitwise AND](./solutions/1835-find-xor-sum-of-all-pairs-bitwise-and.js)|Hard| 1837|[Sum of Digits in Base K](./solutions/1837-sum-of-digits-in-base-k.js)|Easy| 1838|[Frequency of the Most Frequent Element](./solutions/1838-frequency-of-the-most-frequent-element.js)|Medium| +1839|[Longest Substring Of All Vowels in Order](./solutions/1839-longest-substring-of-all-vowels-in-order.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1839-longest-substring-of-all-vowels-in-order.js b/solutions/1839-longest-substring-of-all-vowels-in-order.js new file mode 100644 index 00000000..343f0279 --- /dev/null +++ b/solutions/1839-longest-substring-of-all-vowels-in-order.js @@ -0,0 +1,43 @@ +/** + * 1839. Longest Substring Of All Vowels in Order + * https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/ + * Difficulty: Medium + * + * A string is considered beautiful if it satisfies the following conditions: + * - Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it. + * - The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's + * before 'i's, etc.). + * + * For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but "uaeio", "aeoiu", + * and "aaaeeeooo" are not beautiful. + * + * Given a string word consisting of English vowels, return the length of the longest beautiful + * substring of word. If no such substring exists, return 0. + * + * A substring is a contiguous sequence of characters in a string. + */ + +/** + * @param {string} word + * @return {number} + */ +var longestBeautifulSubstring = function(word) { + let result = 0; + let start = 0; + let vowelCount = 1; + + for (let i = 1; i < word.length; i++) { + if (word[i] < word[i - 1]) { + start = i; + vowelCount = 1; + } else if (word[i] > word[i - 1]) { + vowelCount++; + } + + if (vowelCount === 5) { + result = Math.max(result, i - start + 1); + } + } + + return result; +}; From cfcd277fdc67174e1f43360656c4d6b139dde4ab Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 17:19:49 -0500 Subject: [PATCH 071/495] Add solution #1840 --- README.md | 3 +- solutions/1840-maximum-building-height.js | 60 +++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 solutions/1840-maximum-building-height.js diff --git a/README.md b/README.md index e1b1d47a..3ed8dc04 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,575 LeetCode solutions in JavaScript +# 1,576 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1416,6 +1416,7 @@ 1837|[Sum of Digits in Base K](./solutions/1837-sum-of-digits-in-base-k.js)|Easy| 1838|[Frequency of the Most Frequent Element](./solutions/1838-frequency-of-the-most-frequent-element.js)|Medium| 1839|[Longest Substring Of All Vowels in Order](./solutions/1839-longest-substring-of-all-vowels-in-order.js)|Medium| +1840|[Maximum Building Height](./solutions/1840-maximum-building-height.js)|Hard| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1840-maximum-building-height.js b/solutions/1840-maximum-building-height.js new file mode 100644 index 00000000..d77cdd46 --- /dev/null +++ b/solutions/1840-maximum-building-height.js @@ -0,0 +1,60 @@ +/** + * 1840. Maximum Building Height + * https://leetcode.com/problems/maximum-building-height/ + * Difficulty: Hard + * + * You want to build n new buildings in a city. The new buildings will be built in a line + * and are labeled from 1 to n. + * + * However, there are city restrictions on the heights of the new buildings: + * - The height of each building must be a non-negative integer. + * - The height of the first building must be 0. + * - The height difference between any two adjacent buildings cannot exceed 1. + * + * Additionally, there are city restrictions on the maximum height of specific buildings. + * These restrictions are given as a 2D integer array restrictions where + * restrictions[i] = [idi, maxHeighti] indicates that building idi must have a height + * less than or equal to maxHeighti. + * + * It is guaranteed that each building will appear at most once in restrictions, and building + * 1 will not be in restrictions. + * + * Return the maximum possible height of the tallest building. + */ + +/** + * @param {number} n + * @param {number[][]} restrictions + * @return {number} + */ +var maxBuilding = function(n, restrictions) { + restrictions.push([1, 0], [n, n - 1]); + restrictions.sort((a, b) => a[0] - b[0]); + + const length = restrictions.length; + + for (let i = 1; i < length; i++) { + const [currId, currHeight] = restrictions[i]; + const [prevId, prevHeight] = restrictions[i - 1]; + restrictions[i][1] = Math.min(currHeight, prevHeight + (currId - prevId)); + } + + for (let i = length - 2; i >= 0; i--) { + const [currId, currHeight] = restrictions[i]; + const [nextId, nextHeight] = restrictions[i + 1]; + restrictions[i][1] = Math.min(currHeight, nextHeight + (nextId - currId)); + } + + let maxHeight = 0; + + for (let i = 1; i < length; i++) { + const [leftId, leftHeight] = restrictions[i - 1]; + const [rightId, rightHeight] = restrictions[i]; + const distance = rightId - leftId; + const heightDiff = Math.abs(rightHeight - leftHeight); + const peakHeight = Math.max(leftHeight, rightHeight) + Math.floor((distance - heightDiff) / 2); + maxHeight = Math.max(maxHeight, peakHeight); + } + + return maxHeight; +}; From 2af24b48671649bd11d251f79e14fd4e22ec12db Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 17:21:25 -0500 Subject: [PATCH 072/495] Add solution #1844 --- README.md | 3 +- ...1844-replace-all-digits-with-characters.js | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 solutions/1844-replace-all-digits-with-characters.js diff --git a/README.md b/README.md index 3ed8dc04..d9a42a67 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,576 LeetCode solutions in JavaScript +# 1,577 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1417,6 +1417,7 @@ 1838|[Frequency of the Most Frequent Element](./solutions/1838-frequency-of-the-most-frequent-element.js)|Medium| 1839|[Longest Substring Of All Vowels in Order](./solutions/1839-longest-substring-of-all-vowels-in-order.js)|Medium| 1840|[Maximum Building Height](./solutions/1840-maximum-building-height.js)|Hard| +1844|[Replace All Digits with Characters](./solutions/1844-replace-all-digits-with-characters.js)|Easy| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1844-replace-all-digits-with-characters.js b/solutions/1844-replace-all-digits-with-characters.js new file mode 100644 index 00000000..c5efb48c --- /dev/null +++ b/solutions/1844-replace-all-digits-with-characters.js @@ -0,0 +1,39 @@ +/** + * 1844. Replace All Digits with Characters + * https://leetcode.com/problems/replace-all-digits-with-characters/ + * Difficulty: Easy + * + * You are given a 0-indexed string s that has lowercase English letters in its even indices and + * digits in its odd indices. + * + * You must perform an operation shift(c, x), where c is a character and x is a digit, that returns + * the xth character after c. + * - For example, shift('a', 5) = 'f' and shift('x', 0) = 'x'. + * + * For every odd index i, you want to replace the digit s[i] with the result of the + * shift(s[i-1], s[i]) operation. + * + * Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never + * exceed 'z'. + * + * Note that shift(c, x) is not a preloaded function, but an operation to be implemented as part + * of the solution. + */ + +/** + * @param {string} s + * @return {string} + */ +var replaceDigits = function(s) { + const result = s.split(''); + + for (let i = 1; i < s.length; i += 2) { + result[i] = shiftChar(s[i - 1], s[i]); + } + + return result.join(''); + + function shiftChar(char, shift) { + return String.fromCharCode(char.charCodeAt(0) + parseInt(shift)); + } +}; From 4541813ea715c2cc23ec9a26318fa222be3f17c8 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 17:23:53 -0500 Subject: [PATCH 073/495] Add solution #1845 --- README.md | 3 +- solutions/1845-seat-reservation-manager.js | 44 ++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 solutions/1845-seat-reservation-manager.js diff --git a/README.md b/README.md index d9a42a67..63e0a77b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,577 LeetCode solutions in JavaScript +# 1,578 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1418,6 +1418,7 @@ 1839|[Longest Substring Of All Vowels in Order](./solutions/1839-longest-substring-of-all-vowels-in-order.js)|Medium| 1840|[Maximum Building Height](./solutions/1840-maximum-building-height.js)|Hard| 1844|[Replace All Digits with Characters](./solutions/1844-replace-all-digits-with-characters.js)|Easy| +1845|[Seat Reservation Manager](./solutions/1845-seat-reservation-manager.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1845-seat-reservation-manager.js b/solutions/1845-seat-reservation-manager.js new file mode 100644 index 00000000..53bc7edd --- /dev/null +++ b/solutions/1845-seat-reservation-manager.js @@ -0,0 +1,44 @@ +/** + * 1845. Seat Reservation Manager + * https://leetcode.com/problems/seat-reservation-manager/ + * Difficulty: Medium + * + * Design a system that manages the reservation state of n seats that are numbered from 1 to n. + * + * Implement the SeatManager class: + * - SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from + * 1 to n. All seats are initially available. + * - int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its + * number. + * - void unreserve(int seatNumber) Unreserves the seat with the given seatNumber. + */ + +/** + * @param {number} n + */ +var SeatManager = function(n) { + this.nextAvailable = 1; + this.unreservedSeats = new Set(); +}; + +/** + * @return {number} + */ +SeatManager.prototype.reserve = function() { + if (this.unreservedSeats.size > 0) { + const minSeat = Math.min(...this.unreservedSeats); + if (minSeat < this.nextAvailable) { + this.unreservedSeats.delete(minSeat); + return minSeat; + } + } + return this.nextAvailable++; +}; + +/** + * @param {number} seatNumber + * @return {void} + */ +SeatManager.prototype.unreserve = function(seatNumber) { + this.unreservedSeats.add(seatNumber); +}; From 5e633dc2867f9fae1d79746a2d12e123a02e3d1e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 17:25:14 -0500 Subject: [PATCH 074/495] Add solution #1846 --- README.md | 3 +- ...lement-after-decreasing-and-rearranging.js | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 solutions/1846-maximum-element-after-decreasing-and-rearranging.js diff --git a/README.md b/README.md index 63e0a77b..928ff2fc 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,578 LeetCode solutions in JavaScript +# 1,579 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1419,6 +1419,7 @@ 1840|[Maximum Building Height](./solutions/1840-maximum-building-height.js)|Hard| 1844|[Replace All Digits with Characters](./solutions/1844-replace-all-digits-with-characters.js)|Easy| 1845|[Seat Reservation Manager](./solutions/1845-seat-reservation-manager.js)|Medium| +1846|[Maximum Element After Decreasing and Rearranging](./solutions/1846-maximum-element-after-decreasing-and-rearranging.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1846-maximum-element-after-decreasing-and-rearranging.js b/solutions/1846-maximum-element-after-decreasing-and-rearranging.js new file mode 100644 index 00000000..266a8dc1 --- /dev/null +++ b/solutions/1846-maximum-element-after-decreasing-and-rearranging.js @@ -0,0 +1,36 @@ +/** + * 1846. Maximum Element After Decreasing and Rearranging + * https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/ + * Difficulty: Medium + * + * You are given an array of positive integers arr. Perform some operations (possibly none) on + * arr so that it satisfies these conditions: + * - The value of the first element in arr must be 1. + * - The absolute difference between any 2 adjacent elements must be less than or equal to 1. + * In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length + * (0-indexed). abs(x) is the absolute value of x. + * + * There are 2 types of operations that you can perform any number of times: + * - Decrease the value of any element of arr to a smaller positive integer. + * - Rearrange the elements of arr to be in any order. + * + * Return the maximum possible value of an element in arr after performing the operations to + * satisfy the conditions. + */ + +/** + * @param {number[]} arr + * @return {number} + */ +var maximumElementAfterDecrementingAndRearranging = function(arr) { + arr.sort((a, b) => a - b); + let maxPossible = 1; + + for (let i = 1; i < arr.length; i++) { + if (arr[i] > maxPossible) { + maxPossible++; + } + } + + return maxPossible; +}; From e2ec06d65585e8fae51368df849519024df11f13 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 17:28:46 -0500 Subject: [PATCH 075/495] Add solution #1847 --- README.md | 3 +- solutions/1847-closest-room.js | 83 ++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 solutions/1847-closest-room.js diff --git a/README.md b/README.md index 928ff2fc..fbb2d155 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,579 LeetCode solutions in JavaScript +# 1,580 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1420,6 +1420,7 @@ 1844|[Replace All Digits with Characters](./solutions/1844-replace-all-digits-with-characters.js)|Easy| 1845|[Seat Reservation Manager](./solutions/1845-seat-reservation-manager.js)|Medium| 1846|[Maximum Element After Decreasing and Rearranging](./solutions/1846-maximum-element-after-decreasing-and-rearranging.js)|Medium| +1847|[Closest Room](./solutions/1847-closest-room.js)|Hard| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1847-closest-room.js b/solutions/1847-closest-room.js new file mode 100644 index 00000000..49963145 --- /dev/null +++ b/solutions/1847-closest-room.js @@ -0,0 +1,83 @@ +/** + * 1847. Closest Room + * https://leetcode.com/problems/closest-room/ + * Difficulty: Hard + * + * There is a hotel with n rooms. The rooms are represented by a 2D integer array rooms where + * rooms[i] = [roomIdi, sizei] denotes that there is a room with room number roomIdi and size + * equal to sizei. Each roomIdi is guaranteed to be unique. + * + * You are also given k queries in a 2D array queries where queries[j] = [preferredj, minSizej]. + * The answer to the jth query is the room number id of a room such that: + * - The room has a size of at least minSizej, and + * - abs(id - preferredj) is minimized, where abs(x) is the absolute value of x. + * + * If there is a tie in the absolute difference, then use the room with the smallest such id. + * If there is no such room, the answer is -1. + * + * Return an array answer of length k where answer[j] contains the answer to the jth query. + */ + +/** + * @param {number[][]} rooms + * @param {number[][]} queries + * @return {number[]} + */ +var closestRoom = function(rooms, queries) { + rooms.sort((a, b) => b[1] - a[1]); + const sortedQueries = queries + .map((q, i) => [q[0], q[1], i]) + .sort((a, b) => b[1] - a[1]); + + const result = new Array(queries.length).fill(-1); + const roomIds = []; + let roomIndex = 0; + + for (const [preferred, minSize, queryIndex] of sortedQueries) { + while (roomIndex < rooms.length && rooms[roomIndex][1] >= minSize) { + insertSorted(rooms[roomIndex][0]); + roomIndex++; + } + + result[queryIndex] = findClosestId(preferred); + } + + return result; + + function insertSorted(id) { + let left = 0; + let right = roomIds.length; + while (left < right) { + const mid = Math.floor((left + right) / 2); + if (roomIds[mid] < id) left = mid + 1; + else right = mid; + } + roomIds.splice(left, 0, id); + } + + function findClosestId(target) { + if (!roomIds.length) return -1; + + let left = 0; + let right = roomIds.length - 1; + let closest = roomIds[0]; + let minDiff = Math.abs(closest - target); + + while (left <= right) { + const mid = Math.floor((left + right) / 2); + const id = roomIds[mid]; + const diff = Math.abs(id - target); + + if (diff < minDiff || (diff === minDiff && id < closest)) { + minDiff = diff; + closest = id; + } + + if (id < target) left = mid + 1; + else if (id > target) right = mid - 1; + else break; + } + + return closest; + } +}; From 46375fcdae181e2a48b495936163335f180157b0 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 17:30:02 -0500 Subject: [PATCH 076/495] Add solution #1848 --- README.md | 3 +- ...-minimum-distance-to-the-target-element.js | 32 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 solutions/1848-minimum-distance-to-the-target-element.js diff --git a/README.md b/README.md index fbb2d155..8c164385 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,580 LeetCode solutions in JavaScript +# 1,581 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1421,6 +1421,7 @@ 1845|[Seat Reservation Manager](./solutions/1845-seat-reservation-manager.js)|Medium| 1846|[Maximum Element After Decreasing and Rearranging](./solutions/1846-maximum-element-after-decreasing-and-rearranging.js)|Medium| 1847|[Closest Room](./solutions/1847-closest-room.js)|Hard| +1848|[Minimum Distance to the Target Element](./solutions/1848-minimum-distance-to-the-target-element.js)|Easy| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1848-minimum-distance-to-the-target-element.js b/solutions/1848-minimum-distance-to-the-target-element.js new file mode 100644 index 00000000..567427d2 --- /dev/null +++ b/solutions/1848-minimum-distance-to-the-target-element.js @@ -0,0 +1,32 @@ +/** + * 1848. Minimum Distance to the Target Element + * https://leetcode.com/problems/minimum-distance-to-the-target-element/ + * Difficulty: Easy + * + * Given an integer array nums (0-indexed) and two integers target and start, find an index i + * such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute + * value of x. + * + * Return abs(i - start). + * + * It is guaranteed that target exists in nums. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @param {number} start + * @return {number} + */ +var getMinDistance = function(nums, target, start) { + let result = Infinity; + + for (let i = 0; i < nums.length; i++) { + if (nums[i] === target) { + const distance = Math.abs(i - start); + result = Math.min(result, distance); + } + } + + return result; +}; From 0bb4341299d01889d938e4a38d66309b86863f46 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 17:31:46 -0500 Subject: [PATCH 077/495] Add solution #1849 --- README.md | 3 +- ...ring-into-descending-consecutive-values.js | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 solutions/1849-splitting-a-string-into-descending-consecutive-values.js diff --git a/README.md b/README.md index 8c164385..86c62950 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,581 LeetCode solutions in JavaScript +# 1,582 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1422,6 +1422,7 @@ 1846|[Maximum Element After Decreasing and Rearranging](./solutions/1846-maximum-element-after-decreasing-and-rearranging.js)|Medium| 1847|[Closest Room](./solutions/1847-closest-room.js)|Hard| 1848|[Minimum Distance to the Target Element](./solutions/1848-minimum-distance-to-the-target-element.js)|Easy| +1849|[Splitting a String Into Descending Consecutive Values](./solutions/1849-splitting-a-string-into-descending-consecutive-values.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1849-splitting-a-string-into-descending-consecutive-values.js b/solutions/1849-splitting-a-string-into-descending-consecutive-values.js new file mode 100644 index 00000000..d993db28 --- /dev/null +++ b/solutions/1849-splitting-a-string-into-descending-consecutive-values.js @@ -0,0 +1,50 @@ +/** + * 1849. Splitting a String Into Descending Consecutive Values + * https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/ + * Difficulty: Medium + * + * You are given a string s that consists of only digits. + * + * Check if we can split s into two or more non-empty substrings such that the numerical values of + * the substrings are in descending order and the difference between numerical values of every two + * adjacent substrings is equal to 1. + * - For example, the string s = "0090089" can be split into ["0090", "089"] with numerical values + * [90,89]. The values are in descending order and adjacent values differ by 1, so this way is + * valid. + * - Another example, the string s = "001" can be split into ["0", "01"], ["00", "1"], or + * ["0", "0", "1"]. However all the ways are invalid because they have numerical values + * [0,1], [0,1], and [0,0,1] respectively, all of which are not in descending order. + * + * Return true if it is possible to split s as described above, or false otherwise. + * + * A substring is a contiguous sequence of characters in a string. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var splitString = function(s) { + let firstValue = 0; + for (let i = 0; i < s.length - 1; i++) { + firstValue = firstValue * 10 + parseInt(s[i]); + if (trySplit(i + 1, firstValue)) return true; + } + + return false; + + function trySplit(index, prevValue) { + if (index === s.length) return true; + + let currentValue = 0; + for (let i = index; i < s.length; i++) { + currentValue = currentValue * 10 + parseInt(s[i]); + if (currentValue >= prevValue) break; + if (prevValue - currentValue === 1 && trySplit(i + 1, currentValue)) { + return true; + } + } + + return false; + } +}; From 9b2cd933f5c93abb576482e17a3c1753ad5f7440 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 17:33:23 -0500 Subject: [PATCH 078/495] Add solution #1850 --- README.md | 3 +- ...-swaps-to-reach-the-kth-smallest-number.js | 70 +++++++++++++++++++ 2 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 solutions/1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number.js diff --git a/README.md b/README.md index 86c62950..9b4e35ed 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,582 LeetCode solutions in JavaScript +# 1,583 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1423,6 +1423,7 @@ 1847|[Closest Room](./solutions/1847-closest-room.js)|Hard| 1848|[Minimum Distance to the Target Element](./solutions/1848-minimum-distance-to-the-target-element.js)|Easy| 1849|[Splitting a String Into Descending Consecutive Values](./solutions/1849-splitting-a-string-into-descending-consecutive-values.js)|Medium| +1850|[Minimum Adjacent Swaps to Reach the Kth Smallest Number](./solutions/1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number.js b/solutions/1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number.js new file mode 100644 index 00000000..d4853138 --- /dev/null +++ b/solutions/1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number.js @@ -0,0 +1,70 @@ +/** + * 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number + * https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/ + * Difficulty: Medium + * + * You are given a string num, representing a large integer, and an integer k. + * + * We call some integer wonderful if it is a permutation of the digits in num and is greater in + * value than num. There can be many wonderful integers. However, we only care about the + * smallest-valued ones. + * - For example, when num = "5489355142": + * - The 1st smallest wonderful integer is "5489355214". + * - The 2nd smallest wonderful integer is "5489355241". + * - The 3rd smallest wonderful integer is "5489355412". + * - The 4th smallest wonderful integer is "5489355421". + * + * Return the minimum number of adjacent digit swaps that needs to be applied to num to reach + * the kth smallest wonderful integer. + * + * The tests are generated in such a way that kth smallest wonderful integer exists. + */ + +/** + * @param {string} num + * @param {number} k + * @return {number} + */ +var getMinSwaps = function(num, k) { + const original = num.split(''); + const target = num.split(''); + + for (let i = 0; i < k; i++) { + nextPermutation(target); + } + + let result = 0; + for (let i = 0; i < original.length; i++) { + if (original[i] !== target[i]) { + let j = i + 1; + while (j < original.length && original[j] !== target[i]) j++; + while (j > i) { + [original[j], original[j - 1]] = [original[j - 1], original[j]]; + result++; + j--; + } + } + } + + return result; + + function nextPermutation(arr) { + let i = arr.length - 2; + while (i >= 0 && arr[i] >= arr[i + 1]) i--; + if (i < 0) return false; + + let j = arr.length - 1; + while (arr[j] <= arr[i]) j--; + + [arr[i], arr[j]] = [arr[j], arr[i]]; + + let left = i + 1; + let right = arr.length - 1; + while (left < right) { + [arr[left], arr[right]] = [arr[right], arr[left]]; + left++; + right--; + } + return true; + } +}; From 89cdf855273a42ea24563c0022d926853c0b1e92 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 17:37:23 -0500 Subject: [PATCH 079/495] Add solution #1851 --- README.md | 3 +- ...-minimum-interval-to-include-each-query.js | 49 +++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 solutions/1851-minimum-interval-to-include-each-query.js diff --git a/README.md b/README.md index 9b4e35ed..61972224 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,583 LeetCode solutions in JavaScript +# 1,584 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1424,6 +1424,7 @@ 1848|[Minimum Distance to the Target Element](./solutions/1848-minimum-distance-to-the-target-element.js)|Easy| 1849|[Splitting a String Into Descending Consecutive Values](./solutions/1849-splitting-a-string-into-descending-consecutive-values.js)|Medium| 1850|[Minimum Adjacent Swaps to Reach the Kth Smallest Number](./solutions/1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number.js)|Medium| +1851|[Minimum Interval to Include Each Query](./solutions/1851-minimum-interval-to-include-each-query.js)|Hard| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1851-minimum-interval-to-include-each-query.js b/solutions/1851-minimum-interval-to-include-each-query.js new file mode 100644 index 00000000..a81d82ea --- /dev/null +++ b/solutions/1851-minimum-interval-to-include-each-query.js @@ -0,0 +1,49 @@ +/** + * 1851. Minimum Interval to Include Each Query + * https://leetcode.com/problems/minimum-interval-to-include-each-query/ + * Difficulty: Hard + * + * You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes + * the ith interval starting at lefti and ending at righti (inclusive). The size of an interval + * is defined as the number of integers it contains, or more formally righti - lefti + 1. + * + * You are also given an integer array queries. The answer to the jth query is the size of the + * smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, + * the answer is -1. + * + * Return an array containing the answers to the queries. + */ + +/** + * @param {number[][]} intervals + * @param {number[]} queries + * @return {number[]} + */ +var minInterval = function(intervals, queries) { + intervals.sort((a, b) => a[0] - b[0]); + const sortedQueries = queries + .map((q, i) => [q, i]) + .sort((a, b) => a[0] - b[0]); + + const activeIntervals = new PriorityQueue((a, b) => a[0] - b[0]); + const result = new Array(queries.length).fill(-1); + let intervalIndex = 0; + + for (const [queryValue, queryIndex] of sortedQueries) { + while (intervalIndex < intervals.length && intervals[intervalIndex][0] <= queryValue) { + const [start, end] = intervals[intervalIndex]; + activeIntervals.enqueue([end - start + 1, end]); + intervalIndex++; + } + + while (!activeIntervals.isEmpty() && activeIntervals.front()?.[1] < queryValue) { + activeIntervals.dequeue(); + } + + if (!activeIntervals.isEmpty()) { + result[queryIndex] = activeIntervals.front()[0]; + } + } + + return result; +}; From ceabb1100979f2b6d03c0766d2b0d0e0c4a2159b Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 17:38:36 -0500 Subject: [PATCH 080/495] Add solution #1854 --- README.md | 3 +- solutions/1854-maximum-population-year.js | 42 +++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 solutions/1854-maximum-population-year.js diff --git a/README.md b/README.md index 61972224..7b35612c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,584 LeetCode solutions in JavaScript +# 1,585 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1425,6 +1425,7 @@ 1849|[Splitting a String Into Descending Consecutive Values](./solutions/1849-splitting-a-string-into-descending-consecutive-values.js)|Medium| 1850|[Minimum Adjacent Swaps to Reach the Kth Smallest Number](./solutions/1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number.js)|Medium| 1851|[Minimum Interval to Include Each Query](./solutions/1851-minimum-interval-to-include-each-query.js)|Hard| +1854|[Maximum Population Year](./solutions/1854-maximum-population-year.js)|Easy| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1854-maximum-population-year.js b/solutions/1854-maximum-population-year.js new file mode 100644 index 00000000..9ea9aec0 --- /dev/null +++ b/solutions/1854-maximum-population-year.js @@ -0,0 +1,42 @@ +/** + * 1854. Maximum Population Year + * https://leetcode.com/problems/maximum-population-year/ + * Difficulty: Easy + * + * You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the + * birth and death years of the ith person. + * + * The population of some year x is the number of people alive during that year. The ith person + * is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note + * that the person is not counted in the year that they die. + * + * Return the earliest year with the maximum population. + */ + +/** + * @param {number[][]} logs + * @return {number} + */ +var maximumPopulation = function(logs) { + const populationChanges = new Array(101).fill(0); + const baseYear = 1950; + + for (const [birth, death] of logs) { + populationChanges[birth - baseYear]++; + populationChanges[death - baseYear]--; + } + + let maxPopulation = 0; + let currentPopulation = 0; + let result = baseYear; + + for (let i = 0; i < populationChanges.length; i++) { + currentPopulation += populationChanges[i]; + if (currentPopulation > maxPopulation) { + maxPopulation = currentPopulation; + result = baseYear + i; + } + } + + return result; +}; From 2a5b6031b728a95664978a0396121fe879810a0d Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 19:04:39 -0500 Subject: [PATCH 081/495] Add solution #1855 --- README.md | 3 +- ...ximum-distance-between-a-pair-of-values.js | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 solutions/1855-maximum-distance-between-a-pair-of-values.js diff --git a/README.md b/README.md index 7b35612c..0d97b75b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,585 LeetCode solutions in JavaScript +# 1,586 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1426,6 +1426,7 @@ 1850|[Minimum Adjacent Swaps to Reach the Kth Smallest Number](./solutions/1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number.js)|Medium| 1851|[Minimum Interval to Include Each Query](./solutions/1851-minimum-interval-to-include-each-query.js)|Hard| 1854|[Maximum Population Year](./solutions/1854-maximum-population-year.js)|Easy| +1855|[Maximum Distance Between a Pair of Values](./solutions/1855-maximum-distance-between-a-pair-of-values.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1855-maximum-distance-between-a-pair-of-values.js b/solutions/1855-maximum-distance-between-a-pair-of-values.js new file mode 100644 index 00000000..d94af4d5 --- /dev/null +++ b/solutions/1855-maximum-distance-between-a-pair-of-values.js @@ -0,0 +1,35 @@ +/** + * 1855. Maximum Distance Between a Pair of Values + * https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/ + * Difficulty: Medium + * + * You are given two non-increasing 0-indexed integer arrays nums2 and nums2. + * + * A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, + * is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i. + * + * Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0. + * + * An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var maxDistance = function(nums1, nums2) { + let result = 0; + let left = 0; + + for (let right = 0; right < nums2.length; right++) { + while (left < nums1.length && nums1[left] > nums2[right]) { + left++; + } + if (left <= right && left < nums1.length) { + result = Math.max(result, right - left); + } + } + + return result; +}; From 43e13bd9361bd660a03aa64b625867df9b3944d5 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 19:06:37 -0500 Subject: [PATCH 082/495] Add solution #1856 --- README.md | 3 +- .../1856-maximum-subarray-min-product.js | 47 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 solutions/1856-maximum-subarray-min-product.js diff --git a/README.md b/README.md index 0d97b75b..eb529b26 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,586 LeetCode solutions in JavaScript +# 1,587 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1427,6 +1427,7 @@ 1851|[Minimum Interval to Include Each Query](./solutions/1851-minimum-interval-to-include-each-query.js)|Hard| 1854|[Maximum Population Year](./solutions/1854-maximum-population-year.js)|Easy| 1855|[Maximum Distance Between a Pair of Values](./solutions/1855-maximum-distance-between-a-pair-of-values.js)|Medium| +1856|[Maximum Subarray Min-Product](./solutions/1856-maximum-subarray-min-product.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1856-maximum-subarray-min-product.js b/solutions/1856-maximum-subarray-min-product.js new file mode 100644 index 00000000..02a5f6bc --- /dev/null +++ b/solutions/1856-maximum-subarray-min-product.js @@ -0,0 +1,47 @@ +/** + * 1856. Maximum Subarray Min-Product + * https://leetcode.com/problems/maximum-subarray-min-product/ + * Difficulty: Medium + * + * The min-product of an array is equal to the minimum value in the array multiplied by + * the array's sum. + * - For example, the array [3,2,5] (minimum value is 2) has a min-product of + * 2 * (3+2+5) = 2 * 10 = 20. + * + * Given an array of integers nums, return the maximum min-product of any non-empty + * subarray of nums. Since the answer may be large, return it modulo 109 + 7. + * + * Note that the min-product should be maximized before performing the modulo operation. + * Testcases are generated such that the maximum min-product without modulo will fit in + * a 64-bit signed integer. + * + * A subarray is a contiguous part of an array. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxSumMinProduct = function(nums) { + const modulo = 1000000007n; + const stack = []; + const prefixSums = [0n]; + let maxMinProduct = 0n; + + for (let i = 0; i < nums.length; i++) { + prefixSums.push(prefixSums[i] + BigInt(nums[i])); + } + + for (let right = 0; right <= nums.length; right++) { + const current = right < nums.length ? BigInt(nums[right]) : 0n; + while (stack.length && stack[stack.length - 1].value > current) { + const { index, value } = stack.pop(); + const left = stack.length ? stack[stack.length - 1].index + 1 : 0; + const subarraySum = prefixSums[right] - prefixSums[left]; + maxMinProduct = maxMinProduct > value * subarraySum ? maxMinProduct : value * subarraySum; + } + stack.push({ index: right, value: current }); + } + + return Number(maxMinProduct % modulo); +}; From dd702a9611fb7374403940f9ee58bd574238657b Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 19:07:41 -0500 Subject: [PATCH 083/495] Add solution #1857 --- README.md | 3 +- ...largest-color-value-in-a-directed-graph.js | 60 +++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 solutions/1857-largest-color-value-in-a-directed-graph.js diff --git a/README.md b/README.md index eb529b26..1a76cb90 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,587 LeetCode solutions in JavaScript +# 1,588 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1428,6 +1428,7 @@ 1854|[Maximum Population Year](./solutions/1854-maximum-population-year.js)|Easy| 1855|[Maximum Distance Between a Pair of Values](./solutions/1855-maximum-distance-between-a-pair-of-values.js)|Medium| 1856|[Maximum Subarray Min-Product](./solutions/1856-maximum-subarray-min-product.js)|Medium| +1857|[Largest Color Value in a Directed Graph](./solutions/1857-largest-color-value-in-a-directed-graph.js)|Hard| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1857-largest-color-value-in-a-directed-graph.js b/solutions/1857-largest-color-value-in-a-directed-graph.js new file mode 100644 index 00000000..c592996b --- /dev/null +++ b/solutions/1857-largest-color-value-in-a-directed-graph.js @@ -0,0 +1,60 @@ +/** + * 1857. Largest Color Value in a Directed Graph + * https://leetcode.com/problems/largest-color-value-in-a-directed-graph/ + * Difficulty: Hard + * + * There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1. + * + * You are given a string colors where colors[i] is a lowercase English letter representing the + * color of the ith node in this graph (0-indexed). You are also given a 2D array edges where + * edges[j] = [aj, bj] indicates that there is a directed edge from node aj to node bj. + * + * A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there + * is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the + * number of nodes that are colored the most frequently occurring color along that path. + * + * Return the largest color value of any valid path in the given graph, or -1 if the graph + * contains a cycle. + */ + +/** + * @param {string} colors + * @param {number[][]} edges + * @return {number} + */ +var largestPathValue = function(colors, edges) { + const nodeCount = colors.length; + const adjacencyList = Array.from({ length: nodeCount }, () => []); + const inDegree = new Array(nodeCount).fill(0); + const colorCounts = Array.from({ length: nodeCount }, () => new Array(26).fill(0)); + const queue = []; + let maxColorValue = 0; + let processedNodes = 0; + + for (const [from, to] of edges) { + adjacencyList[from].push(to); + inDegree[to]++; + } + + for (let i = 0; i < nodeCount; i++) { + if (inDegree[i] === 0) queue.push(i); + } + + while (queue.length) { + const current = queue.shift(); + processedNodes++; + const colorIndex = colors.charCodeAt(current) - 97; + colorCounts[current][colorIndex]++; + + for (const next of adjacencyList[current]) { + for (let i = 0; i < 26; i++) { + colorCounts[next][i] = Math.max(colorCounts[next][i], colorCounts[current][i]); + } + if (--inDegree[next] === 0) queue.push(next); + } + + maxColorValue = Math.max(maxColorValue, ...colorCounts[current]); + } + + return processedNodes === nodeCount ? maxColorValue : -1; +}; From 6b10860285fde7e4ae88b55b1485baa86c5127d1 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 19:09:16 -0500 Subject: [PATCH 084/495] Add solution #1859 --- README.md | 3 ++- solutions/1859-sorting-the-sentence.js | 32 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 solutions/1859-sorting-the-sentence.js diff --git a/README.md b/README.md index 1a76cb90..4e7abc29 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,588 LeetCode solutions in JavaScript +# 1,589 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1429,6 +1429,7 @@ 1855|[Maximum Distance Between a Pair of Values](./solutions/1855-maximum-distance-between-a-pair-of-values.js)|Medium| 1856|[Maximum Subarray Min-Product](./solutions/1856-maximum-subarray-min-product.js)|Medium| 1857|[Largest Color Value in a Directed Graph](./solutions/1857-largest-color-value-in-a-directed-graph.js)|Hard| +1859|[Sorting the Sentence](./solutions/1859-sorting-the-sentence.js)|Easy| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1859-sorting-the-sentence.js b/solutions/1859-sorting-the-sentence.js new file mode 100644 index 00000000..d2d9c81f --- /dev/null +++ b/solutions/1859-sorting-the-sentence.js @@ -0,0 +1,32 @@ +/** + * 1859. Sorting the Sentence + * https://leetcode.com/problems/sorting-the-sentence/ + * Difficulty: Easy + * + * A sentence is a list of words that are separated by a single space with no leading or trailing + * spaces. Each word consists of lowercase and uppercase English letters. + * + * A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging + * the words in the sentence. + * - For example, the sentence "This is a sentence" can be shuffled as "sentence4 a3 is2 This1" or + * "is2 sentence4 This1 a3". + * + * Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original + * sentence. + */ + +/** + * @param {string} s + * @return {string} + */ +var sortSentence = function(s) { + const words = s.split(' '); + const sortedWords = new Array(words.length); + + for (const word of words) { + const position = parseInt(word.slice(-1)) - 1; + sortedWords[position] = word.slice(0, -1); + } + + return sortedWords.join(' '); +}; From b855113a453c112d50af5e74063c1c9df5029339 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 19:11:00 -0500 Subject: [PATCH 085/495] Add solution #1860 --- README.md | 3 +- solutions/1860-incremental-memory-leak.js | 41 +++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 solutions/1860-incremental-memory-leak.js diff --git a/README.md b/README.md index 4e7abc29..8ad29a3e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,589 LeetCode solutions in JavaScript +# 1,590 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1430,6 +1430,7 @@ 1856|[Maximum Subarray Min-Product](./solutions/1856-maximum-subarray-min-product.js)|Medium| 1857|[Largest Color Value in a Directed Graph](./solutions/1857-largest-color-value-in-a-directed-graph.js)|Hard| 1859|[Sorting the Sentence](./solutions/1859-sorting-the-sentence.js)|Easy| +1860|[Incremental Memory Leak](./solutions/1860-incremental-memory-leak.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1860-incremental-memory-leak.js b/solutions/1860-incremental-memory-leak.js new file mode 100644 index 00000000..fd72b849 --- /dev/null +++ b/solutions/1860-incremental-memory-leak.js @@ -0,0 +1,41 @@ +/** + * 1860. Incremental Memory Leak + * https://leetcode.com/problems/incremental-memory-leak/ + * Difficulty: Medium + * + * You are given two integers memory1 and memory2 representing the available memory in bits on + * two memory sticks. There is currently a faulty program running that consumes an increasing + * amount of memory every second. + * + * At the ith second (starting from 1), i bits of memory are allocated to the stick with more + * available memory (or from the first memory stick if both have the same available memory). + * If neither stick has at least i bits of available memory, the program crashes. + * + * Return an array containing [crashTime, memory1crash, memory2crash], where crashTime is the + * time (in seconds) when the program crashed and memory1crash and memory2crash are the + * available bits of memory in the first and second sticks respectively. + */ + +/** + * @param {number} memory1 + * @param {number} memory2 + * @return {number[]} + */ +var memLeak = function(memory1, memory2) { + let time = 1; + let stick1 = memory1; + let stick2 = memory2; + + while (time <= stick1 || time <= stick2) { + if (stick1 >= stick2) { + if (stick1 < time) break; + stick1 -= time; + } else { + if (stick2 < time) break; + stick2 -= time; + } + time++; + } + + return [time, stick1, stick2]; +}; From 01c6f484aff39fc6997927b67e7faad05e491a82 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 19:13:51 -0500 Subject: [PATCH 086/495] Add solution #1861 --- README.md | 3 +- solutions/1861-rotating-the-box.js | 46 ++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 solutions/1861-rotating-the-box.js diff --git a/README.md b/README.md index 8ad29a3e..4f9f3852 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,590 LeetCode solutions in JavaScript +# 1,591 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1431,6 +1431,7 @@ 1857|[Largest Color Value in a Directed Graph](./solutions/1857-largest-color-value-in-a-directed-graph.js)|Hard| 1859|[Sorting the Sentence](./solutions/1859-sorting-the-sentence.js)|Easy| 1860|[Incremental Memory Leak](./solutions/1860-incremental-memory-leak.js)|Medium| +1861|[Rotating the Box](./solutions/1861-rotating-the-box.js)|Medium| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1861-rotating-the-box.js b/solutions/1861-rotating-the-box.js new file mode 100644 index 00000000..0b874c74 --- /dev/null +++ b/solutions/1861-rotating-the-box.js @@ -0,0 +1,46 @@ +/** + * 1861. Rotating the Box + * https://leetcode.com/problems/rotating-the-box/ + * Difficulty: Medium + * + * You are given an m x n matrix of characters boxGrid representing a side-view of a box. + * Each cell of the box is one of the following: + * - A stone '#' + * - A stationary obstacle '*' + * - Empty '.' + * + * The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. + * Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. + * Gravity does not affect the obstacles' positions, and the inertia from the box's rotation + * does not affect the stones' horizontal positions. + * + * It is guaranteed that each stone in boxGrid rests on an obstacle, another stone, or the + * bottom of the box. + * + * Return an n x m matrix representing the box after the rotation described above. + */ + +/** + * @param {character[][]} boxGrid + * @return {character[][]} + */ +var rotateTheBox = function(boxGrid) { + const rows = boxGrid.length; + const cols = boxGrid[0].length; + const result = Array.from({ length: cols }, () => new Array(rows).fill('.')); + + for (let row = 0; row < rows; row++) { + let freePosition = cols - 1; + for (let col = cols - 1; col >= 0; col--) { + if (boxGrid[row][col] === '*') { + result[col][rows - 1 - row] = '*'; + freePosition = col - 1; + } else if (boxGrid[row][col] === '#') { + result[freePosition][rows - 1 - row] = '#'; + freePosition--; + } + } + } + + return result; +}; From d75684541d6de34753517225d4fa1d3e3879b5d6 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 19:15:13 -0500 Subject: [PATCH 087/495] Add solution #1862 --- README.md | 3 +- solutions/1862-sum-of-floored-pairs.js | 44 ++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 solutions/1862-sum-of-floored-pairs.js diff --git a/README.md b/README.md index 4f9f3852..4522ffa7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,591 LeetCode solutions in JavaScript +# 1,592 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1432,6 +1432,7 @@ 1859|[Sorting the Sentence](./solutions/1859-sorting-the-sentence.js)|Easy| 1860|[Incremental Memory Leak](./solutions/1860-incremental-memory-leak.js)|Medium| 1861|[Rotating the Box](./solutions/1861-rotating-the-box.js)|Medium| +1862|[Sum of Floored Pairs](./solutions/1862-sum-of-floored-pairs.js)|Hard| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| diff --git a/solutions/1862-sum-of-floored-pairs.js b/solutions/1862-sum-of-floored-pairs.js new file mode 100644 index 00000000..4d470c3c --- /dev/null +++ b/solutions/1862-sum-of-floored-pairs.js @@ -0,0 +1,44 @@ +/** + * 1862. Sum of Floored Pairs + * https://leetcode.com/problems/sum-of-floored-pairs/ + * Difficulty: Hard + * + * Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of + * indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return + * it modulo 109 + 7. + * + * The floor() function returns the integer part of the division. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var sumOfFlooredPairs = function(nums) { + const modulo = 1e9 + 7; + const maxValue = Math.max(...nums); + const frequency = new Array(maxValue + 1).fill(0); + const prefixSum = new Array(maxValue + 1).fill(0); + let result = 0; + + for (const num of nums) { + frequency[num]++; + } + + for (let i = 1; i <= maxValue; i++) { + prefixSum[i] = prefixSum[i - 1] + frequency[i]; + } + + for (let i = 1; i <= maxValue; i++) { + if (frequency[i] === 0) continue; + for (let divisor = i; divisor <= maxValue; divisor += i) { + const quotient = Math.floor(divisor / i); + const count = ( + prefixSum[Math.min(maxValue, divisor + i - 1)] - prefixSum[divisor - 1] + ) % modulo; + result = (result + quotient * frequency[i] * count) % modulo; + } + } + + return result; +}; From 3afd87b6cfce219746820c2248ba02885819becf Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 19:16:11 -0500 Subject: [PATCH 088/495] Add solution #1864 --- README.md | 3 +- ...s-to-make-the-binary-string-alternating.js | 49 +++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 solutions/1864-minimum-number-of-swaps-to-make-the-binary-string-alternating.js diff --git a/README.md b/README.md index 4522ffa7..cc5fff8b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,592 LeetCode solutions in JavaScript +# 1,593 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1434,6 +1434,7 @@ 1861|[Rotating the Box](./solutions/1861-rotating-the-box.js)|Medium| 1862|[Sum of Floored Pairs](./solutions/1862-sum-of-floored-pairs.js)|Hard| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| +1864|[Minimum Number of Swaps to Make the Binary String Alternating](./solutions/1864-minimum-number-of-swaps-to-make-the-binary-string-alternating.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| diff --git a/solutions/1864-minimum-number-of-swaps-to-make-the-binary-string-alternating.js b/solutions/1864-minimum-number-of-swaps-to-make-the-binary-string-alternating.js new file mode 100644 index 00000000..28378e0b --- /dev/null +++ b/solutions/1864-minimum-number-of-swaps-to-make-the-binary-string-alternating.js @@ -0,0 +1,49 @@ +/** + * 1864. Minimum Number of Swaps to Make the Binary String Alternating + * https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/ + * Difficulty: Medium + * + * Given a binary string s, return the minimum number of character swaps to make it alternating, + * or -1 if it is impossible. + * + * The string is called alternating if no two adjacent characters are equal. For example, the + * strings "010" and "1010" are alternating, while the string "0100" is not. + * + * Any two characters may be swapped, even if they are not adjacent. + */ + +/** + * @param {string} s + * @return {number} + */ +var minSwaps = function(s) { + const length = s.length; + let ones = 0; + let zeros = 0; + + for (const char of s) { + if (char === '1') ones++; + else zeros++; + } + + if (Math.abs(ones - zeros) > 1) return -1; + + let mismatchesStartWithZero = 0; + let mismatchesStartWithOne = 0; + + for (let i = 0; i < length; i++) { + if (i % 2 === 0) { + if (s[i] !== '0') mismatchesStartWithZero++; + if (s[i] !== '1') mismatchesStartWithOne++; + } else { + if (s[i] !== '1') mismatchesStartWithZero++; + if (s[i] !== '0') mismatchesStartWithOne++; + } + } + + if (ones === zeros) { + return Math.min(mismatchesStartWithZero, mismatchesStartWithOne) >> 1; + } + + return (ones > zeros ? mismatchesStartWithOne : mismatchesStartWithZero) >> 1; +}; From d456f16433cffdfcbd1dd1dae89c4a0e400295b3 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 19:17:42 -0500 Subject: [PATCH 089/495] Add solution #1865 --- README.md | 3 +- .../1865-finding-pairs-with-a-certain-sum.js | 60 +++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 solutions/1865-finding-pairs-with-a-certain-sum.js diff --git a/README.md b/README.md index cc5fff8b..7c44fb33 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,593 LeetCode solutions in JavaScript +# 1,594 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1435,6 +1435,7 @@ 1862|[Sum of Floored Pairs](./solutions/1862-sum-of-floored-pairs.js)|Hard| 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1864|[Minimum Number of Swaps to Make the Binary String Alternating](./solutions/1864-minimum-number-of-swaps-to-make-the-binary-string-alternating.js)|Medium| +1865|[Finding Pairs With a Certain Sum](./solutions/1865-finding-pairs-with-a-certain-sum.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| diff --git a/solutions/1865-finding-pairs-with-a-certain-sum.js b/solutions/1865-finding-pairs-with-a-certain-sum.js new file mode 100644 index 00000000..9a100a1b --- /dev/null +++ b/solutions/1865-finding-pairs-with-a-certain-sum.js @@ -0,0 +1,60 @@ +/** + * 1865. Finding Pairs With a Certain Sum + * https://leetcode.com/problems/finding-pairs-with-a-certain-sum/ + * Difficulty: Medium + * + * You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure + * that supports queries of two types: + * 1. Add a positive integer to an element of a given index in the array nums2. + * 2. Count the number of pairs (i, j) such that nums1[i] + nums2[j] equals a given + * value (0 <= i < nums1.length and 0 <= j < nums2.length). + * + * Implement the FindSumPairs class: + * - FindSumPairs(int[] nums1, int[] nums2) Initializes the FindSumPairs object with two integer + * arrays nums1 and nums2. + * - void add(int index, int val) Adds val to nums2[index], i.e., apply nums2[index] += val. + * - int count(int tot) Returns the number of pairs (i, j) such that nums1[i] + nums2[j] == tot. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + */ +var FindSumPairs = function(nums1, nums2) { + this.firstArray = nums1; + this.secondArray = nums2; + this.frequency = new Map(); + + for (const num of nums2) { + this.frequency.set(num, (this.frequency.get(num) || 0) + 1); + } +}; + +/** + * @param {number} index + * @param {number} val + * @return {void} + */ +FindSumPairs.prototype.add = function(index, val) { + const oldValue = this.secondArray[index]; + this.secondArray[index] += val; + const newValue = this.secondArray[index]; + + this.frequency.set(oldValue, this.frequency.get(oldValue) - 1); + this.frequency.set(newValue, (this.frequency.get(newValue) || 0) + 1); +}; + +/** + * @param {number} tot + * @return {number} + */ +FindSumPairs.prototype.count = function(tot) { + let result = 0; + + for (const num of this.firstArray) { + const complement = tot - num; + result += this.frequency.get(complement) || 0; + } + + return result; +}; From c0b859a8378f3933ca1ee6dda95089bc1f2c6487 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 19:19:01 -0500 Subject: [PATCH 090/495] Add solution #1866 --- README.md | 3 +- ...-rearrange-sticks-with-k-sticks-visible.js | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 solutions/1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible.js diff --git a/README.md b/README.md index 7c44fb33..e6b43063 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,594 LeetCode solutions in JavaScript +# 1,595 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1436,6 +1436,7 @@ 1863|[Sum of All Subset XOR Totals](./solutions/1863-sum-of-all-subset-xor-totals.js)|Easy| 1864|[Minimum Number of Swaps to Make the Binary String Alternating](./solutions/1864-minimum-number-of-swaps-to-make-the-binary-string-alternating.js)|Medium| 1865|[Finding Pairs With a Certain Sum](./solutions/1865-finding-pairs-with-a-certain-sum.js)|Medium| +1866|[Number of Ways to Rearrange Sticks With K Sticks Visible](./solutions/1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible.js)|Hard| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| diff --git a/solutions/1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible.js b/solutions/1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible.js new file mode 100644 index 00000000..3a2ffed6 --- /dev/null +++ b/solutions/1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible.js @@ -0,0 +1,37 @@ +/** + * 1866. Number of Ways to Rearrange Sticks With K Sticks Visible + * https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/ + * Difficulty: Hard + * + * There are n uniquely-sized sticks whose lengths are integers from 1 to n. You want to arrange + * the sticks such that exactly k sticks are visible from the left. A stick is visible from the + * left if there are no longer sticks to the left of it. + * - For example, if the sticks are arranged [1,3,2,5,4], then the sticks with lengths 1, 3, + * and 5 are visible from the left. + * + * Given n and k, return the number of such arrangements. Since the answer may be large, return + * it modulo 109 + 7. + */ + +/** + * @param {number} n + * @param {number} k + * @return {number} + */ +var rearrangeSticks = function(n, k) { + const modulo = 1e9 + 7; + const dp = Array.from({ length: n + 1 }, () => new Array(k + 1).fill(0)); + dp[0][0] = 1; + + for (let sticks = 1; sticks <= n; sticks++) { + for (let visible = 0; visible <= k; visible++) { + if (visible > sticks) continue; + if (visible > 0) { + dp[sticks][visible] = (dp[sticks][visible] + dp[sticks - 1][visible - 1]) % modulo; + } + dp[sticks][visible] = (dp[sticks][visible] + dp[sticks - 1][visible] * (sticks - 1)) % modulo; + } + } + + return dp[n][k]; +}; From bcd23198ec8edf4c791f56078617a65fb8db3901 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 20:37:55 -0500 Subject: [PATCH 091/495] Add solution #1869 --- README.md | 3 +- ...-contiguous-segments-of-ones-than-zeros.js | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 solutions/1869-longer-contiguous-segments-of-ones-than-zeros.js diff --git a/README.md b/README.md index e6b43063..aecb93da 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,595 LeetCode solutions in JavaScript +# 1,596 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1437,6 +1437,7 @@ 1864|[Minimum Number of Swaps to Make the Binary String Alternating](./solutions/1864-minimum-number-of-swaps-to-make-the-binary-string-alternating.js)|Medium| 1865|[Finding Pairs With a Certain Sum](./solutions/1865-finding-pairs-with-a-certain-sum.js)|Medium| 1866|[Number of Ways to Rearrange Sticks With K Sticks Visible](./solutions/1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible.js)|Hard| +1869|[Longer Contiguous Segments of Ones than Zeros](./solutions/1869-longer-contiguous-segments-of-ones-than-zeros.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| diff --git a/solutions/1869-longer-contiguous-segments-of-ones-than-zeros.js b/solutions/1869-longer-contiguous-segments-of-ones-than-zeros.js new file mode 100644 index 00000000..bc6acf26 --- /dev/null +++ b/solutions/1869-longer-contiguous-segments-of-ones-than-zeros.js @@ -0,0 +1,38 @@ +/** + * 1869. Longer Contiguous Segments of Ones than Zeros + * https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros/ + * Difficulty: Easy + * + * Given a binary string s, return true if the longest contiguous segment of 1's is strictly + * longer than the longest contiguous segment of 0's in s, or return false otherwise. + * - For example, in s = "110100010" the longest continuous segment of 1s has length 2, and the + * longest continuous segment of 0s has length 3. + * + * Note that if there are no 0's, then the longest continuous segment of 0's is considered to + * have a length 0. The same applies if there is no 1's. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var checkZeroOnes = function(s) { + let maxOnes = 0; + let maxZeros = 0; + let currentOnes = 0; + let currentZeros = 0; + + for (const char of s) { + if (char === '1') { + currentOnes++; + currentZeros = 0; + maxOnes = Math.max(maxOnes, currentOnes); + } else { + currentZeros++; + currentOnes = 0; + maxZeros = Math.max(maxZeros, currentZeros); + } + } + + return maxOnes > maxZeros; +}; From 0ee57b10e6f6888ed92c491d26892034438de257 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 20:39:24 -0500 Subject: [PATCH 092/495] Add solution #1870 --- README.md | 3 +- .../1870-minimum-speed-to-arrive-on-time.js | 54 +++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 solutions/1870-minimum-speed-to-arrive-on-time.js diff --git a/README.md b/README.md index aecb93da..b901373b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,596 LeetCode solutions in JavaScript +# 1,597 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1438,6 +1438,7 @@ 1865|[Finding Pairs With a Certain Sum](./solutions/1865-finding-pairs-with-a-certain-sum.js)|Medium| 1866|[Number of Ways to Rearrange Sticks With K Sticks Visible](./solutions/1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible.js)|Hard| 1869|[Longer Contiguous Segments of Ones than Zeros](./solutions/1869-longer-contiguous-segments-of-ones-than-zeros.js)|Easy| +1870|[Minimum Speed to Arrive on Time](./solutions/1870-minimum-speed-to-arrive-on-time.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| diff --git a/solutions/1870-minimum-speed-to-arrive-on-time.js b/solutions/1870-minimum-speed-to-arrive-on-time.js new file mode 100644 index 00000000..fd7633a5 --- /dev/null +++ b/solutions/1870-minimum-speed-to-arrive-on-time.js @@ -0,0 +1,54 @@ +/** + * 1870. Minimum Speed to Arrive on Time + * https://leetcode.com/problems/minimum-speed-to-arrive-on-time/ + * Difficulty: Medium + * + * You are given a floating-point number hour, representing the amount of time you have to reach + * the office. To commute to the office, you must take n trains in sequential order. You are also + * given an integer array dist of length n, where dist[i] describes the distance (in kilometers) + * of the ith train ride. + * + * Each train can only depart at an integer hour, so you may need to wait in between each train + * ride. + * - For example, if the 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours + * before you can depart on the 2nd train ride at the 2 hour mark. + * + * Return the minimum positive integer speed (in kilometers per hour) that all the trains must + * travel at for you to reach the office on time, or -1 if it is impossible to be on time. + * + * Tests are generated such that the answer will not exceed 107 and hour will have at most two + * digits after the decimal point. + */ + +/** + * @param {number[]} dist + * @param {number} hour + * @return {number} + */ +var minSpeedOnTime = function(dist, hour) { + const trainCount = dist.length; + if (Math.ceil(trainCount - 1) > hour) return -1; + + let minSpeed = 1; + let maxSpeed = 10000000; + let result = -1; + + while (minSpeed <= maxSpeed) { + const midSpeed = (minSpeed + maxSpeed) >> 1; + let totalTime = 0; + + for (let i = 0; i < trainCount - 1; i++) { + totalTime += Math.ceil(dist[i] / midSpeed); + } + totalTime += dist[trainCount - 1] / midSpeed; + + if (totalTime <= hour) { + result = midSpeed; + maxSpeed = midSpeed - 1; + } else { + minSpeed = midSpeed + 1; + } + } + + return result; +}; From af6d382a8a1db0b78b06900d71d8fc6dd1c6dcd0 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 20:42:10 -0500 Subject: [PATCH 093/495] Add solution #1871 --- README.md | 3 ++- solutions/1871-jump-game-vii.js | 44 +++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 solutions/1871-jump-game-vii.js diff --git a/README.md b/README.md index b901373b..112ce77a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,597 LeetCode solutions in JavaScript +# 1,598 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1439,6 +1439,7 @@ 1866|[Number of Ways to Rearrange Sticks With K Sticks Visible](./solutions/1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible.js)|Hard| 1869|[Longer Contiguous Segments of Ones than Zeros](./solutions/1869-longer-contiguous-segments-of-ones-than-zeros.js)|Easy| 1870|[Minimum Speed to Arrive on Time](./solutions/1870-minimum-speed-to-arrive-on-time.js)|Medium| +1871|[Jump Game VII](./solutions/1871-jump-game-vii.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| diff --git a/solutions/1871-jump-game-vii.js b/solutions/1871-jump-game-vii.js new file mode 100644 index 00000000..92a47cc2 --- /dev/null +++ b/solutions/1871-jump-game-vii.js @@ -0,0 +1,44 @@ +/** + * 1871. Jump Game VII + * https://leetcode.com/problems/jump-game-vii/ + * Difficulty: Medium + * + * You are given a 0-indexed binary string s and two integers minJump and maxJump. In the + * beginning, you are standing at index 0, which is equal to '0'. You can move from index + * i to index j if the following conditions are fulfilled: + * - i + minJump <= j <= min(i + maxJump, s.length - 1), and + * - s[j] == '0'. + * + * Return true if you can reach index s.length - 1 in s, or false otherwise. + */ + +/** + * @param {string} s + * @param {number} minJump + * @param {number} maxJump + * @return {boolean} + */ +var canReach = function(s, minJump, maxJump) { + const length = s.length; + const reachable = new Array(length).fill(false); + reachable[0] = true; + const queue = [0]; + let farthest = 0; + + while (queue.length) { + const current = queue.shift(); + const start = current + minJump; + const end = Math.min(current + maxJump, length - 1); + + for (let next = Math.max(start, farthest + 1); next <= end; next++) { + if (s[next] === '0' && !reachable[next]) { + reachable[next] = true; + queue.push(next); + if (next === length - 1) return true; + } + } + farthest = Math.max(farthest, end); + } + + return false; +}; From 180aaec8ab380854885991b4230c6216023c744d Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 20:43:36 -0500 Subject: [PATCH 094/495] Add solution #1872 --- README.md | 3 ++- solutions/1872-stone-game-viii.js | 42 +++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 solutions/1872-stone-game-viii.js diff --git a/README.md b/README.md index 112ce77a..3b9fd395 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,598 LeetCode solutions in JavaScript +# 1,599 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1440,6 +1440,7 @@ 1869|[Longer Contiguous Segments of Ones than Zeros](./solutions/1869-longer-contiguous-segments-of-ones-than-zeros.js)|Easy| 1870|[Minimum Speed to Arrive on Time](./solutions/1870-minimum-speed-to-arrive-on-time.js)|Medium| 1871|[Jump Game VII](./solutions/1871-jump-game-vii.js)|Medium| +1872|[Stone Game VIII](./solutions/1872-stone-game-viii.js)|Hard| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| diff --git a/solutions/1872-stone-game-viii.js b/solutions/1872-stone-game-viii.js new file mode 100644 index 00000000..c8e74328 --- /dev/null +++ b/solutions/1872-stone-game-viii.js @@ -0,0 +1,42 @@ +/** + * 1872. Stone Game VIII + * https://leetcode.com/problems/stone-game-viii/ + * Difficulty: Hard + * + * Alice and Bob take turns playing a game, with Alice starting first. + * + * There are n stones arranged in a row. On each player's turn, while the number of stones is more + * than one, they will do the following: + * 1. Choose an integer x > 1, and remove the leftmost x stones from the row. + * 2. Add the sum of the removed stones' values to the player's score. + * 3. Place a new stone, whose value is equal to that sum, on the left side of the row. + * + * The game stops when only one stone is left in the row. + * + * The score difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to + * maximize the score difference, and Bob's goal is the minimize the score difference. + * + * Given an integer array stones of length n where stones[i] represents the value of the ith stone + * from the left, return the score difference between Alice and Bob if they both play optimally. + */ + +/** + * @param {number[]} stones + * @return {number} + */ +var stoneGameVIII = function(stones) { + const length = stones.length; + const prefixSums = new Array(length).fill(0); + prefixSums[0] = stones[0]; + + for (let i = 1; i < length; i++) { + prefixSums[i] = prefixSums[i - 1] + stones[i]; + } + + let result = prefixSums[length - 1]; + for (let i = length - 2; i >= 1; i--) { + result = Math.max(result, prefixSums[i] - result); + } + + return result; +}; From cf96ee743a3586969a01ba6882b8db422de6e6da Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 1 May 2025 20:44:37 -0500 Subject: [PATCH 095/495] Add solution #1876 --- README.md | 3 +- ...-of-size-three-with-distinct-characters.js | 41 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 solutions/1876-substrings-of-size-three-with-distinct-characters.js diff --git a/README.md b/README.md index 3b9fd395..a182b86f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,599 LeetCode solutions in JavaScript +# 1,600 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1441,6 +1441,7 @@ 1870|[Minimum Speed to Arrive on Time](./solutions/1870-minimum-speed-to-arrive-on-time.js)|Medium| 1871|[Jump Game VII](./solutions/1871-jump-game-vii.js)|Medium| 1872|[Stone Game VIII](./solutions/1872-stone-game-viii.js)|Hard| +1876|[Substrings of Size Three with Distinct Characters](./solutions/1876-substrings-of-size-three-with-distinct-characters.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| diff --git a/solutions/1876-substrings-of-size-three-with-distinct-characters.js b/solutions/1876-substrings-of-size-three-with-distinct-characters.js new file mode 100644 index 00000000..cbe56e47 --- /dev/null +++ b/solutions/1876-substrings-of-size-three-with-distinct-characters.js @@ -0,0 +1,41 @@ +/** + * 1876. Substrings of Size Three with Distinct Characters + * https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/ + * Difficulty: Easy + * + * A string is good if there are no repeated characters. + * + * Given a string s, return the number of good substrings of length three in s. + * + * Note that if there are multiple occurrences of the same substring, every occurrence should + * be counted. + * + * A substring is a contiguous sequence of characters in a string. + */ + +/** + * @param {string} s + * @return {number} + */ +var countGoodSubstrings = function(s) { + if (s.length < 3) return 0; + + let result = 0; + const charCount = new Map(); + + for (let i = 0; i < 3; i++) { + charCount.set(s[i], (charCount.get(s[i]) || 0) + 1); + } + if (charCount.size === 3) result++; + + for (let i = 3; i < s.length; i++) { + const oldChar = s[i - 3]; + charCount.set(oldChar, charCount.get(oldChar) - 1); + if (charCount.get(oldChar) === 0) charCount.delete(oldChar); + + charCount.set(s[i], (charCount.get(s[i]) || 0) + 1); + if (charCount.size === 3) result++; + } + + return result; +}; From a94a8badf4b5cf125d78599397a4cd1e4735af14 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 11:32:11 -0500 Subject: [PATCH 096/495] Add solution #1877 --- README.md | 3 +- ...1877-minimize-maximum-pair-sum-in-array.js | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 solutions/1877-minimize-maximum-pair-sum-in-array.js diff --git a/README.md b/README.md index a182b86f..f1be5fca 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,600 LeetCode solutions in JavaScript +# 1,601 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1442,6 +1442,7 @@ 1871|[Jump Game VII](./solutions/1871-jump-game-vii.js)|Medium| 1872|[Stone Game VIII](./solutions/1872-stone-game-viii.js)|Hard| 1876|[Substrings of Size Three with Distinct Characters](./solutions/1876-substrings-of-size-three-with-distinct-characters.js)|Easy| +1877|[Minimize Maximum Pair Sum in Array](./solutions/1877-minimize-maximum-pair-sum-in-array.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| diff --git a/solutions/1877-minimize-maximum-pair-sum-in-array.js b/solutions/1877-minimize-maximum-pair-sum-in-array.js new file mode 100644 index 00000000..264d9569 --- /dev/null +++ b/solutions/1877-minimize-maximum-pair-sum-in-array.js @@ -0,0 +1,35 @@ +/** + * 1877. Minimize Maximum Pair Sum in Array + * https://leetcode.com/problems/minimize-maximum-pair-sum-in-array/ + * Difficulty: Medium + * + * The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum + * in a list of pairs. + * - For example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be + * max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8. + * + * Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that: + * - Each element of nums is in exactly one pair, and + * - The maximum pair sum is minimized. + * + * Return the minimized maximum pair sum after optimally pairing up the elements. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var minPairSum = function(nums) { + nums.sort((a, b) => a - b); + let result = 0; + let left = 0; + let right = nums.length - 1; + + while (left < right) { + result = Math.max(result, nums[left] + nums[right]); + left++; + right--; + } + + return result; +}; From f727315d667688cdcc0c5dd31c7f9890ded26b5a Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 11:33:44 -0500 Subject: [PATCH 097/495] Add solution #1878 --- README.md | 3 +- ...et-biggest-three-rhombus-sums-in-a-grid.js | 46 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 solutions/1878-get-biggest-three-rhombus-sums-in-a-grid.js diff --git a/README.md b/README.md index f1be5fca..e4a9cbda 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,601 LeetCode solutions in JavaScript +# 1,602 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1443,6 +1443,7 @@ 1872|[Stone Game VIII](./solutions/1872-stone-game-viii.js)|Hard| 1876|[Substrings of Size Three with Distinct Characters](./solutions/1876-substrings-of-size-three-with-distinct-characters.js)|Easy| 1877|[Minimize Maximum Pair Sum in Array](./solutions/1877-minimize-maximum-pair-sum-in-array.js)|Medium| +1878|[Get Biggest Three Rhombus Sums in a Grid](./solutions/1878-get-biggest-three-rhombus-sums-in-a-grid.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| diff --git a/solutions/1878-get-biggest-three-rhombus-sums-in-a-grid.js b/solutions/1878-get-biggest-three-rhombus-sums-in-a-grid.js new file mode 100644 index 00000000..f10c1b56 --- /dev/null +++ b/solutions/1878-get-biggest-three-rhombus-sums-in-a-grid.js @@ -0,0 +1,46 @@ +/** + * 1878. Get Biggest Three Rhombus Sums in a Grid + * https://leetcode.com/problems/get-biggest-three-rhombus-sums-in-a-grid/ + * Difficulty: Medium + * + * You are given an m x n integer matrix grid. + * + * A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in + * grid. The rhombus must have the shape of a square rotated 45 degrees with each of the corners + * centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding + * colored cells that should be included in each rhombus sum. + * + * Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the + * bottom right corner. + * + * Return the biggest three distinct rhombus sums in the grid in descending order. If there are + * less than three distinct values, return all of them. + */ + +/** + * @param {number[][]} grid + * @return {number[]} + */ +var getBiggestThree = function(grid) { + const rows = grid.length; + const cols = grid[0].length; + const sums = new Set(); + + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + sums.add(grid[i][j]); + for (let size = 1; size <= Math.min(i, rows - 1 - i, j, cols - 1 - j); size++) { + let rhombusSum = 0; + rhombusSum += grid[i - size][j] + grid[i + size][j] + grid[i][j - size] + grid[i][j + size]; + for (let offset = 1; offset < size; offset++) { + rhombusSum += grid[i - size + offset][j + offset] + grid[i + size - offset][j + offset]; + rhombusSum += grid[i - size + offset][j - offset] + grid[i + size - offset][j - offset]; + } + sums.add(rhombusSum); + } + } + } + + const sortedSums = [...sums].sort((a, b) => b - a); + return sortedSums.slice(0, Math.min(3, sortedSums.length)); +}; From 1876fdfc83220d583ed01d373a41fce284d5a46a Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 11:35:12 -0500 Subject: [PATCH 098/495] Add solution #1879 --- README.md | 3 +- .../1879-minimum-xor-sum-of-two-arrays.js | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 solutions/1879-minimum-xor-sum-of-two-arrays.js diff --git a/README.md b/README.md index e4a9cbda..aabf6bb7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,602 LeetCode solutions in JavaScript +# 1,603 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1444,6 +1444,7 @@ 1876|[Substrings of Size Three with Distinct Characters](./solutions/1876-substrings-of-size-three-with-distinct-characters.js)|Easy| 1877|[Minimize Maximum Pair Sum in Array](./solutions/1877-minimize-maximum-pair-sum-in-array.js)|Medium| 1878|[Get Biggest Three Rhombus Sums in a Grid](./solutions/1878-get-biggest-three-rhombus-sums-in-a-grid.js)|Medium| +1879|[Minimum XOR Sum of Two Arrays](./solutions/1879-minimum-xor-sum-of-two-arrays.js)|Hard| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| diff --git a/solutions/1879-minimum-xor-sum-of-two-arrays.js b/solutions/1879-minimum-xor-sum-of-two-arrays.js new file mode 100644 index 00000000..2f7c4f61 --- /dev/null +++ b/solutions/1879-minimum-xor-sum-of-two-arrays.js @@ -0,0 +1,39 @@ +/** + * 1879. Minimum XOR Sum of Two Arrays + * https://leetcode.com/problems/minimum-xor-sum-of-two-arrays/ + * Difficulty: Hard + * + * You are given two integer arrays nums1 and nums2 of length n. + * + * The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + * + ... + (nums1[n - 1] XOR nums2[n - 1]) (0-indexed). + * - For example, the XOR sum of [1,2,3] and [3,2,1] is equal to (1 XOR 3) + (2 XOR 2) + + * (3 XOR 1) = 2 + 0 + 2 = 4. + * + * Rearrange the elements of nums2 such that the resulting XOR sum is minimized. + * + * Return the XOR sum after the rearrangement. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var minimumXORSum = function(nums1, nums2) { + const n = nums1.length; + const dp = new Array(1 << n).fill(Infinity); + dp[0] = 0; + + for (let mask = 0; mask < (1 << n); mask++) { + const usedCount = mask.toString(2).split('1').length - 1; + for (let j = 0; j < n; j++) { + if (!(mask & (1 << j))) { + const newMask = mask | (1 << j); + dp[newMask] = Math.min(dp[newMask], dp[mask] + (nums1[usedCount] ^ nums2[j])); + } + } + } + + return dp[(1 << n) - 1]; +}; From 44b73e8839c4b44cc2083a825fb3b738c89d423d Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 11:43:00 -0500 Subject: [PATCH 099/495] Add solution #1881 --- README.md | 3 +- .../1881-maximum-value-after-insertion.js | 46 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 solutions/1881-maximum-value-after-insertion.js diff --git a/README.md b/README.md index aabf6bb7..f9b8c65e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,603 LeetCode solutions in JavaScript +# 1,604 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1446,6 +1446,7 @@ 1878|[Get Biggest Three Rhombus Sums in a Grid](./solutions/1878-get-biggest-three-rhombus-sums-in-a-grid.js)|Medium| 1879|[Minimum XOR Sum of Two Arrays](./solutions/1879-minimum-xor-sum-of-two-arrays.js)|Hard| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| +1881|[Maximum Value after Insertion](./solutions/1881-maximum-value-after-insertion.js)|Medium| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| diff --git a/solutions/1881-maximum-value-after-insertion.js b/solutions/1881-maximum-value-after-insertion.js new file mode 100644 index 00000000..4ba804d7 --- /dev/null +++ b/solutions/1881-maximum-value-after-insertion.js @@ -0,0 +1,46 @@ +/** + * 1881. Maximum Value after Insertion + * https://leetcode.com/problems/maximum-value-after-insertion/ + * Difficulty: Medium + * + * You are given a very large integer n, represented as a string, and an integer digit x. + * The digits in n and the digit x are in the inclusive range [1, 9], and n may represent + * a negative number. + * + * You want to maximize n's numerical value by inserting x anywhere in the decimal representation + * of n. You cannot insert x to the left of the negative sign. + * - For example, if n = 73 and x = 6, it would be best to insert it between 7 and 3, making + * n = 763. + * - If n = -55 and x = 2, it would be best to insert it before the first 5, making n = -255. + * + * Return a string representing the maximum value of n after the insertion. + */ + +/** + * @param {string} n + * @param {number} x + * @return {string} + */ +var maxValue = function(n, x) { + const isNegative = n[0] === '-'; + const digits = n.slice(isNegative ? 1 : 0); + let result = ''; + + if (isNegative) { + for (let i = 0; i <= digits.length; i++) { + if (i === digits.length || x < parseInt(digits[i])) { + result = '-' + digits.slice(0, i) + x + digits.slice(i); + break; + } + } + } else { + for (let i = 0; i <= digits.length; i++) { + if (i === digits.length || x > parseInt(digits[i])) { + result = digits.slice(0, i) + x + digits.slice(i); + break; + } + } + } + + return result; +}; From 519af7421e24df20fa27920e1477ae954c8d8019 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 11:48:22 -0500 Subject: [PATCH 100/495] Add solution #1882 --- README.md | 3 +- solutions/1882-process-tasks-using-servers.js | 71 +++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 solutions/1882-process-tasks-using-servers.js diff --git a/README.md b/README.md index f9b8c65e..924c9658 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,604 LeetCode solutions in JavaScript +# 1,605 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1447,6 +1447,7 @@ 1879|[Minimum XOR Sum of Two Arrays](./solutions/1879-minimum-xor-sum-of-two-arrays.js)|Hard| 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1881|[Maximum Value after Insertion](./solutions/1881-maximum-value-after-insertion.js)|Medium| +1882|[Process Tasks Using Servers](./solutions/1882-process-tasks-using-servers.js)|Medium| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| diff --git a/solutions/1882-process-tasks-using-servers.js b/solutions/1882-process-tasks-using-servers.js new file mode 100644 index 00000000..e82ad99f --- /dev/null +++ b/solutions/1882-process-tasks-using-servers.js @@ -0,0 +1,71 @@ +/** + * 1882. Process Tasks Using Servers + * https://leetcode.com/problems/process-tasks-using-servers/ + * Difficulty: Medium + * + * You are given two 0-indexed integer arrays servers and tasks of lengths n and m respectively. + * servers[i] is the weight of the ith server, and tasks[j] is the time needed to process the + * jth task in seconds. + * + * Tasks are assigned to the servers using a task queue. Initially, all servers are free, and + * the queue is empty. + * + * At second j, the jth task is inserted into the queue (starting with the 0th task being inserted + * at second 0). As long as there are free servers and the queue is not empty, the task in the front + * of the queue will be assigned to a free server with the smallest weight, and in case of a tie, + * it is assigned to a free server with the smallest index. + * + * If there are no free servers and the queue is not empty, we wait until a server becomes free + * and immediately assign the next task. If multiple servers become free at the same time, then + * multiple tasks from the queue will be assigned in order of insertion following the weight and + * index priorities above. + * + * A server that is assigned task j at second t will be free again at second t + tasks[j]. + * + * Build an array ans of length m, where ans[j] is the index of the server the jth task will + * be assigned to. + * + * Return the array ans. + */ + +/** + * @param {number[]} servers + * @param {number[]} tasks + * @return {number[]} + */ +var assignTasks = function(servers, tasks) { + const serverHeap = new PriorityQueue((a, b) => a[0] * 1000000 + a[1] - (b[0] * 1000000 + b[1])); + const busyHeap = new PriorityQueue((a, b) => a[0] - b[0]); + const result = new Array(tasks.length); + + for (let i = 0; i < servers.length; i++) { + serverHeap.enqueue([servers[i], i]); + } + + let time = 0; + let taskIndex = 0; + + while (taskIndex < tasks.length) { + time = Math.max(time, taskIndex); + + while (!busyHeap.isEmpty() && busyHeap.front()[0] <= time) { + const [, weight, index] = busyHeap.dequeue(); + serverHeap.enqueue([weight, index]); + } + + while (serverHeap.size() && taskIndex < tasks.length && taskIndex <= time) { + const [weight, index] = serverHeap.dequeue(); + result[taskIndex] = index; + busyHeap.enqueue([time + tasks[taskIndex], weight, index]); + taskIndex++; + } + + if (serverHeap.isEmpty() && taskIndex < tasks.length) { + const [freeTime, weight, index] = busyHeap.dequeue(); + time = freeTime; + serverHeap.enqueue([weight, index]); + } + } + + return result; +}; From 0318ffa0180c1ab5228781b6658cc7eb89591656 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 11:54:24 -0500 Subject: [PATCH 101/495] Add solution #1883 --- README.md | 3 +- ...imum-skips-to-arrive-at-meeting-on-time.js | 66 +++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 solutions/1883-minimum-skips-to-arrive-at-meeting-on-time.js diff --git a/README.md b/README.md index 924c9658..5c3ea6a4 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,605 LeetCode solutions in JavaScript +# 1,606 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1448,6 +1448,7 @@ 1880|[Check if Word Equals Summation of Two Words](./solutions/1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1881|[Maximum Value after Insertion](./solutions/1881-maximum-value-after-insertion.js)|Medium| 1882|[Process Tasks Using Servers](./solutions/1882-process-tasks-using-servers.js)|Medium| +1883|[Minimum Skips to Arrive at Meeting On Time](./solutions/1883-minimum-skips-to-arrive-at-meeting-on-time.js)|Hard| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| diff --git a/solutions/1883-minimum-skips-to-arrive-at-meeting-on-time.js b/solutions/1883-minimum-skips-to-arrive-at-meeting-on-time.js new file mode 100644 index 00000000..23d83b18 --- /dev/null +++ b/solutions/1883-minimum-skips-to-arrive-at-meeting-on-time.js @@ -0,0 +1,66 @@ +/** + * 1883. Minimum Skips to Arrive at Meeting On Time + * https://leetcode.com/problems/minimum-skips-to-arrive-at-meeting-on-time/ + * Difficulty: Hard + * + * You are given an integer hoursBefore, the number of hours you have to travel to your meeting. + * To arrive at your meeting, you have to travel through n roads. The road lengths are given as + * an integer array dist of length n, where dist[i] describes the length of the ith road in + * kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you + * will travel at. + * + * After you travel road i, you must rest and wait for the next integer hour before you can begin + * traveling on the next road. Note that you do not have to rest after traveling the last road + * because you are already at the meeting. + * - For example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before + * traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait. + * + * However, you are allowed to skip some rests to be able to arrive on time, meaning you do not + * need to wait for the next integer hour. Note that this means you may finish traveling future + * roads at different hour marks. + * - For example, suppose traveling the first road takes 1.4 hours and traveling the second road + * takes 0.6 hours. Skipping the rest after the first road will mean you finish traveling the + * second road right at the 2 hour mark, letting you start traveling the third road immediately. + * + * Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is + * impossible. + */ + +/** + * @param {number[]} dist + * @param {number} speed + * @param {number} hoursBefore + * @return {number} + */ +var minSkips = function(dist, speed, hoursBefore) { + const n = dist.length; + const dp = Array.from({ length: n + 1 }, () => new Array(n + 1).fill(Infinity)); + dp[0][0] = 0; + + for (let i = 1; i <= n; i++) { + for (let skips = 0; skips <= i; skips++) { + if (skips < i) { + const prevTime = dp[i - 1][skips]; + if (prevTime !== Infinity) { + const time = prevTime + dist[i - 1]; + dp[i][skips] = Math.min(dp[i][skips], Math.ceil(time / speed) * speed); + } + } + if (skips > 0) { + const prevTime = dp[i - 1][skips - 1]; + if (prevTime !== Infinity) { + dp[i][skips] = Math.min(dp[i][skips], prevTime + dist[i - 1]); + } + } + } + } + + const targetTime = hoursBefore * speed; + for (let skips = 0; skips <= n; skips++) { + if (dp[n][skips] <= targetTime) { + return skips; + } + } + + return -1; +}; From 60b7f74f35d90fd3bb5475b8818c949ee7d3c38e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 11:55:50 -0500 Subject: [PATCH 102/495] Add solution #1884 --- README.md | 3 +- .../1884-egg-drop-with-2-eggs-and-n-floors.js | 42 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 solutions/1884-egg-drop-with-2-eggs-and-n-floors.js diff --git a/README.md b/README.md index 5c3ea6a4..0670094e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,606 LeetCode solutions in JavaScript +# 1,607 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1449,6 +1449,7 @@ 1881|[Maximum Value after Insertion](./solutions/1881-maximum-value-after-insertion.js)|Medium| 1882|[Process Tasks Using Servers](./solutions/1882-process-tasks-using-servers.js)|Medium| 1883|[Minimum Skips to Arrive at Meeting On Time](./solutions/1883-minimum-skips-to-arrive-at-meeting-on-time.js)|Hard| +1884|[Egg Drop With 2 Eggs and N Floors](./solutions/1884-egg-drop-with-2-eggs-and-n-floors.js)|Medium| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| diff --git a/solutions/1884-egg-drop-with-2-eggs-and-n-floors.js b/solutions/1884-egg-drop-with-2-eggs-and-n-floors.js new file mode 100644 index 00000000..4b5ccb3f --- /dev/null +++ b/solutions/1884-egg-drop-with-2-eggs-and-n-floors.js @@ -0,0 +1,42 @@ +/** + * 1884. Egg Drop With 2 Eggs and N Floors + * https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/ + * Difficulty: Medium + * + * You are given two identical eggs and you have access to a building with n floors labeled + * from 1 to n. + * + * You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor + * higher than f will break, and any egg dropped at or below floor f will not break. + * + * In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). + * If the egg breaks, you can no longer use it. However, if the egg does not break, you may + * reuse it in future moves. + * + * Return the minimum number of moves that you need to determine with certainty what the value + * of f is. + */ + +/** + * @param {number} n + * @return {number} + */ +var twoEggDrop = function(n) { + const dp = Array.from({ length: 3 }, () => new Array(n + 1).fill(Infinity)); + dp[0][0] = 0; + dp[1][0] = 0; + dp[2][0] = 0; + + for (let floors = 1; floors <= n; floors++) { + dp[1][floors] = floors; + for (let eggs = 2; eggs <= 2; eggs++) { + for (let k = 1; k <= floors; k++) { + const breaks = dp[eggs - 1][k - 1]; + const survives = dp[eggs][floors - k]; + dp[eggs][floors] = Math.min(dp[eggs][floors], 1 + Math.max(breaks, survives)); + } + } + } + + return dp[2][n]; +}; From 31dd51ae064df1b299a1a8e326f58cf71cef002e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 11:57:20 -0500 Subject: [PATCH 103/495] Add solution #1887 --- README.md | 3 +- ...ations-to-make-the-array-elements-equal.js | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 solutions/1887-reduction-operations-to-make-the-array-elements-equal.js diff --git a/README.md b/README.md index 0670094e..a503abb6 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,607 LeetCode solutions in JavaScript +# 1,608 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1451,6 +1451,7 @@ 1883|[Minimum Skips to Arrive at Meeting On Time](./solutions/1883-minimum-skips-to-arrive-at-meeting-on-time.js)|Hard| 1884|[Egg Drop With 2 Eggs and N Floors](./solutions/1884-egg-drop-with-2-eggs-and-n-floors.js)|Medium| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| +1887|[Reduction Operations to Make the Array Elements Equal](./solutions/1887-reduction-operations-to-make-the-array-elements-equal.js)|Medium| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1887-reduction-operations-to-make-the-array-elements-equal.js b/solutions/1887-reduction-operations-to-make-the-array-elements-equal.js new file mode 100644 index 00000000..d6672d7b --- /dev/null +++ b/solutions/1887-reduction-operations-to-make-the-array-elements-equal.js @@ -0,0 +1,34 @@ +/** + * 1887. Reduction Operations to Make the Array Elements Equal + * https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/ + * Difficulty: Medium + * + * Given an integer array nums, your goal is to make all elements in nums equal. To complete one + * operation, follow these steps: + * 1. Find the largest value in nums. Let its index be i (0-indexed) and its value be largest. + * If there are multiple elements with the largest value, pick the smallest i. + * 2. Find the next largest value in nums strictly smaller than largest. Let its value be + * nextLargest. + * 3. Reduce nums[i] to nextLargest. + * + * Return the number of operations to make all elements in nums equal. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var reductionOperations = function(nums) { + nums.sort((a, b) => a - b); + let result = 0; + let count = 0; + + for (let i = 1; i < nums.length; i++) { + if (nums[i] !== nums[i - 1]) { + count++; + } + result += count; + } + + return result; +}; From ea79b2b55ddaf4f6a407b71cc77e9770706e40ce Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 12:05:37 -0500 Subject: [PATCH 104/495] Add solution #1888 --- README.md | 3 +- ...s-to-make-the-binary-string-alternating.js | 47 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 solutions/1888-minimum-number-of-flips-to-make-the-binary-string-alternating.js diff --git a/README.md b/README.md index a503abb6..a93328c0 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,608 LeetCode solutions in JavaScript +# 1,609 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1452,6 +1452,7 @@ 1884|[Egg Drop With 2 Eggs and N Floors](./solutions/1884-egg-drop-with-2-eggs-and-n-floors.js)|Medium| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1887|[Reduction Operations to Make the Array Elements Equal](./solutions/1887-reduction-operations-to-make-the-array-elements-equal.js)|Medium| +1888|[Minimum Number of Flips to Make the Binary String Alternating](./solutions/1888-minimum-number-of-flips-to-make-the-binary-string-alternating.js)|Medium| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1888-minimum-number-of-flips-to-make-the-binary-string-alternating.js b/solutions/1888-minimum-number-of-flips-to-make-the-binary-string-alternating.js new file mode 100644 index 00000000..24795a9f --- /dev/null +++ b/solutions/1888-minimum-number-of-flips-to-make-the-binary-string-alternating.js @@ -0,0 +1,47 @@ +/** + * 1888. Minimum Number of Flips to Make the Binary String Alternating + * https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/ + * Difficulty: Medium + * + * You are given a binary string s. You are allowed to perform two types of operations on the + * string in any sequence: + * - Type-1: Remove the character at the start of the string s and append it to the end of + * the string. + * - Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes + * '1' and vice-versa. + * + * Return the minimum number of type-2 operations you need to perform such that s becomes + * alternating. + * + * The string is called alternating if no two adjacent characters are equal. + * + * For example, the strings "010" and "1010" are alternating, while the string "0100" is not. + */ + +/** + * @param {string} s + * @return {number} + */ +var minFlips = function(s) { + const n = s.length; + let result = n; + let flipsZeroStart = 0; + let flipsOneStart = 0; + + for (let i = 0; i < n; i++) { + if (s[i] !== (i % 2 === 0 ? '0' : '1')) flipsZeroStart++; + if (s[i] !== (i % 2 === 0 ? '1' : '0')) flipsOneStart++; + } + + result = Math.min(flipsZeroStart, flipsOneStart); + + for (let i = 0; i < n - 1; i++) { + if (s[i] !== (i % 2 === 0 ? '0' : '1')) flipsZeroStart--; + if (s[i] !== (i % 2 === 0 ? '1' : '0')) flipsOneStart--; + if (s[i] !== ((n + i) % 2 === 0 ? '0' : '1')) flipsZeroStart++; + if (s[i] !== ((n + i) % 2 === 0 ? '1' : '0')) flipsOneStart++; + result = Math.min(result, flipsZeroStart, flipsOneStart); + } + + return result; +}; From f0a0592c20505328e74adf4061dbfbdfcaa981af Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 12:09:11 -0500 Subject: [PATCH 105/495] Add solution #1889 --- README.md | 3 +- ...889-minimum-space-wasted-from-packaging.js | 82 +++++++++++++++++++ 2 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 solutions/1889-minimum-space-wasted-from-packaging.js diff --git a/README.md b/README.md index a93328c0..849a095a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,609 LeetCode solutions in JavaScript +# 1,610 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1453,6 +1453,7 @@ 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./solutions/1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1887|[Reduction Operations to Make the Array Elements Equal](./solutions/1887-reduction-operations-to-make-the-array-elements-equal.js)|Medium| 1888|[Minimum Number of Flips to Make the Binary String Alternating](./solutions/1888-minimum-number-of-flips-to-make-the-binary-string-alternating.js)|Medium| +1889|[Minimum Space Wasted From Packaging](./solutions/1889-minimum-space-wasted-from-packaging.js)|Hard| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1889-minimum-space-wasted-from-packaging.js b/solutions/1889-minimum-space-wasted-from-packaging.js new file mode 100644 index 00000000..de010d0f --- /dev/null +++ b/solutions/1889-minimum-space-wasted-from-packaging.js @@ -0,0 +1,82 @@ +/** + * 1889. Minimum Space Wasted From Packaging + * https://leetcode.com/problems/minimum-space-wasted-from-packaging/ + * Difficulty: Hard + * + * You have n packages that you are trying to place in boxes, one package in each box. There are + * m suppliers that each produce boxes of different sizes (with infinite supply). A package can + * be placed in a box if the size of the package is less than or equal to the size of the box. + * + * The package sizes are given as an integer array packages, where packages[i] is the size of the + * ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array + * of box sizes that the jth supplier produces. + * + * You want to choose a single supplier and use boxes from them such that the total wasted space + * is minimized. For each package in a box, we define the space wasted to be size of the box - size + * of the package. The total wasted space is the sum of the space wasted in all the boxes. + * - For example, if you have to fit packages with sizes [2,3,5] and the supplier offers boxes of + * sizes [4,8], you can fit the packages of size-2 and size-3 into two boxes of size-4 and the + * package with size-5 into a box of size-8. This would result in a waste + * of (4-2) + (4-3) + (8-5) = 6. + * + * Return the minimum total wasted space by choosing the box supplier optimally, or -1 if it is + * impossible to fit all the packages inside boxes. Since the answer may be large, return it + * modulo 109 + 7. + */ + +/** + * @param {number[]} packages + * @param {number[][]} boxes + * @return {number} + */ +var minWastedSpace = function(packages, boxes) { + const modulo = 1e9 + 7; + packages.sort((a, b) => a - b); + let minWaste = BigInt(2) ** BigInt(60); + const n = packages.length; + + const prefixSums = new Array(n + 1).fill(BigInt(0)); + for (let i = 0; i < n; i++) { + prefixSums[i + 1] = prefixSums[i] + BigInt(packages[i]); + } + + for (const supplier of boxes) { + supplier.sort((a, b) => a - b); + if (supplier[supplier.length - 1] < packages[n - 1]) continue; + + let waste = BigInt(0); + let packageIndex = 0; + + for (const box of supplier) { + if (packageIndex >= n) break; + const upperBound = binarySearch(packages, box, packageIndex); + if (upperBound > packageIndex) { + const count = BigInt(upperBound - packageIndex); + waste += count * BigInt(box) - (prefixSums[upperBound] - prefixSums[packageIndex]); + packageIndex = upperBound; + } + } + + if (packageIndex === n) { + minWaste = minWaste < waste ? minWaste : waste; + } + } + + return minWaste === BigInt(2) ** BigInt(60) ? -1 : Number(minWaste % BigInt(modulo)); +}; + +function binarySearch(arr, target, start) { + let left = start; + let right = arr.length; + + while (left < right) { + const mid = (left + right) >> 1; + if (arr[mid] <= target) { + left = mid + 1; + } else { + right = mid; + } + } + + return left; +} From 3a3f1f9210b147283b0fc0b9ef106e0c20ca7663 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 15:57:01 -0500 Subject: [PATCH 106/495] Add solution #1893 --- README.md | 3 +- ...all-the-integers-in-a-range-are-covered.js | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 solutions/1893-check-if-all-the-integers-in-a-range-are-covered.js diff --git a/README.md b/README.md index 849a095a..099a55df 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,610 LeetCode solutions in JavaScript +# 1,611 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1454,6 +1454,7 @@ 1887|[Reduction Operations to Make the Array Elements Equal](./solutions/1887-reduction-operations-to-make-the-array-elements-equal.js)|Medium| 1888|[Minimum Number of Flips to Make the Binary String Alternating](./solutions/1888-minimum-number-of-flips-to-make-the-binary-string-alternating.js)|Medium| 1889|[Minimum Space Wasted From Packaging](./solutions/1889-minimum-space-wasted-from-packaging.js)|Hard| +1893|[Check if All the Integers in a Range Are Covered](./solutions/1893-check-if-all-the-integers-in-a-range-are-covered.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1893-check-if-all-the-integers-in-a-range-are-covered.js b/solutions/1893-check-if-all-the-integers-in-a-range-are-covered.js new file mode 100644 index 00000000..def56b8c --- /dev/null +++ b/solutions/1893-check-if-all-the-integers-in-a-range-are-covered.js @@ -0,0 +1,35 @@ +/** + * 1893. Check if All the Integers in a Range Are Covered + * https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/ + * Difficulty: Easy + * + * You are given a 2D integer array ranges and two integers left and right. Each + * ranges[i] = [starti, endi] represents an inclusive interval between starti and endi. + * + * Return true if each integer in the inclusive range [left, right] is covered by at least + * one interval in ranges. Return false otherwise. + * + * An integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi. + */ + +/** + * @param {number[][]} ranges + * @param {number} left + * @param {number} right + * @return {boolean} + */ +var isCovered = function(ranges, left, right) { + const covered = new Array(51).fill(false); + + for (const [start, end] of ranges) { + for (let i = start; i <= end; i++) { + covered[i] = true; + } + } + + for (let i = left; i <= right; i++) { + if (!covered[i]) return false; + } + + return true; +}; From 8ebab6dad33f2e95685800b267f8277afce92f83 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 15:58:32 -0500 Subject: [PATCH 107/495] Add solution #1894 --- README.md | 3 +- ...the-student-that-will-replace-the-chalk.js | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 solutions/1894-find-the-student-that-will-replace-the-chalk.js diff --git a/README.md b/README.md index 099a55df..9eebc1e7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,611 LeetCode solutions in JavaScript +# 1,612 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1455,6 +1455,7 @@ 1888|[Minimum Number of Flips to Make the Binary String Alternating](./solutions/1888-minimum-number-of-flips-to-make-the-binary-string-alternating.js)|Medium| 1889|[Minimum Space Wasted From Packaging](./solutions/1889-minimum-space-wasted-from-packaging.js)|Hard| 1893|[Check if All the Integers in a Range Are Covered](./solutions/1893-check-if-all-the-integers-in-a-range-are-covered.js)|Easy| +1894|[Find the Student that Will Replace the Chalk](./solutions/1894-find-the-student-that-will-replace-the-chalk.js)|Medium| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1894-find-the-student-that-will-replace-the-chalk.js b/solutions/1894-find-the-student-that-will-replace-the-chalk.js new file mode 100644 index 00000000..387fd854 --- /dev/null +++ b/solutions/1894-find-the-student-that-will-replace-the-chalk.js @@ -0,0 +1,38 @@ +/** + * 1894. Find the Student that Will Replace the Chalk + * https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/ + * Difficulty: Medium + * + * There are n students in a class numbered from 0 to n - 1. The teacher will give each student + * a problem starting with the student number 0, then the student number 1, and so on until the + * teacher reaches the student number n - 1. After that, the teacher will restart the process, + * starting with the student number 0 again. + * + * You are given a 0-indexed integer array chalk and an integer k. There are initially k pieces + * of chalk. When the student number i is given a problem to solve, they will use chalk[i] + * pieces of chalk to solve that problem. However, if the current number of chalk pieces is + * strictly less than chalk[i], then the student number i will be asked to replace the chalk. + * + * Return the index of the student that will replace the chalk pieces. + */ + +/** + * @param {number[]} chalk + * @param {number} k + * @return {number} + */ +var chalkReplacer = function(chalk, k) { + let totalChalk = 0; + for (const amount of chalk) { + totalChalk += amount; + } + + k = k % totalChalk; + + for (let i = 0; i < chalk.length; i++) { + if (k < chalk[i]) return i; + k -= chalk[i]; + } + + return 0; +}; From e1c27ff7ce835a1bb18bb292553a4920e244cd4f Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 16:00:02 -0500 Subject: [PATCH 108/495] Add solution #1895 --- README.md | 3 +- solutions/1895-largest-magic-square.js | 71 ++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 solutions/1895-largest-magic-square.js diff --git a/README.md b/README.md index 9eebc1e7..be4659b1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,612 LeetCode solutions in JavaScript +# 1,613 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1456,6 +1456,7 @@ 1889|[Minimum Space Wasted From Packaging](./solutions/1889-minimum-space-wasted-from-packaging.js)|Hard| 1893|[Check if All the Integers in a Range Are Covered](./solutions/1893-check-if-all-the-integers-in-a-range-are-covered.js)|Easy| 1894|[Find the Student that Will Replace the Chalk](./solutions/1894-find-the-student-that-will-replace-the-chalk.js)|Medium| +1895|[Largest Magic Square](./solutions/1895-largest-magic-square.js)|Medium| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1895-largest-magic-square.js b/solutions/1895-largest-magic-square.js new file mode 100644 index 00000000..e23a71cc --- /dev/null +++ b/solutions/1895-largest-magic-square.js @@ -0,0 +1,71 @@ +/** + * 1895. Largest Magic Square + * https://leetcode.com/problems/largest-magic-square/ + * Difficulty: Medium + * + * A k x k magic square is a k x k grid filled with integers such that every row sum, every + * column sum, and both diagonal sums are all equal. The integers in the magic square do not + * have to be distinct. Every 1 x 1 grid is trivially a magic square. + * + * Given an m x n integer grid, return the size (i.e., the side length k) of the largest magic + * square that can be found within this grid. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var largestMagicSquare = function(grid) { + const rows = grid.length; + const cols = grid[0].length; + const rowSums = Array.from({ length: rows + 1 }, () => new Array(cols + 1).fill(0)); + const colSums = Array.from({ length: rows + 1 }, () => new Array(cols + 1).fill(0)); + + for (let i = 1; i <= rows; i++) { + for (let j = 1; j <= cols; j++) { + rowSums[i][j] = rowSums[i][j - 1] + grid[i - 1][j - 1]; + colSums[i][j] = colSums[i - 1][j] + grid[i - 1][j - 1]; + } + } + + const maxSize = 1; + for (let size = Math.min(rows, cols); size >= 2; size--) { + for (let i = size; i <= rows; i++) { + for (let j = size; j <= cols; j++) { + const rowSum = rowSums[i][j] - rowSums[i][j - size]; + let isMagic = true; + + for (let k = 1; k < size; k++) { + if (rowSums[i - k][j] - rowSums[i - k][j - size] !== rowSum) { + isMagic = false; + break; + } + } + + if (!isMagic) continue; + + for (let k = 0; k < size; k++) { + if (colSums[i][j - k] - colSums[i - size][j - k] !== rowSum) { + isMagic = false; + break; + } + } + + if (!isMagic) continue; + + let diagSum1 = 0; + let diagSum2 = 0; + for (let k = 0; k < size; k++) { + diagSum1 += grid[i - size + k][j - size + k]; + diagSum2 += grid[i - size + k][j - 1 - k]; + } + + if (diagSum1 === rowSum && diagSum2 === rowSum) { + return size; + } + } + } + } + + return maxSize; +}; From fac5770e486bca7232c1e42e1c66bf8eb2931c6d Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 16:07:58 -0500 Subject: [PATCH 109/495] Add solution #1896 --- README.md | 3 +- ...to-change-the-final-value-of-expression.js | 113 ++++++++++++++++++ 2 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 solutions/1896-minimum-cost-to-change-the-final-value-of-expression.js diff --git a/README.md b/README.md index be4659b1..03174773 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,613 LeetCode solutions in JavaScript +# 1,614 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1457,6 +1457,7 @@ 1893|[Check if All the Integers in a Range Are Covered](./solutions/1893-check-if-all-the-integers-in-a-range-are-covered.js)|Easy| 1894|[Find the Student that Will Replace the Chalk](./solutions/1894-find-the-student-that-will-replace-the-chalk.js)|Medium| 1895|[Largest Magic Square](./solutions/1895-largest-magic-square.js)|Medium| +1896|[Minimum Cost to Change the Final Value of Expression](./solutions/1896-minimum-cost-to-change-the-final-value-of-expression.js)|Hard| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1896-minimum-cost-to-change-the-final-value-of-expression.js b/solutions/1896-minimum-cost-to-change-the-final-value-of-expression.js new file mode 100644 index 00000000..1e430149 --- /dev/null +++ b/solutions/1896-minimum-cost-to-change-the-final-value-of-expression.js @@ -0,0 +1,113 @@ +/** + * 1896. Minimum Cost to Change the Final Value of Expression + * https://leetcode.com/problems/minimum-cost-to-change-the-final-value-of-expression/ + * Difficulty: Hard + * + * You are given a valid boolean expression as a string expression consisting of the + * characters '1','0','&' (bitwise AND operator),'|' (bitwise OR operator),'(', and ')'. + * - For example, "()1|1" and "(1)&()" are not valid while "1", "(((1))|(0))", and "1|(0&(1))" + * are valid expressions. + * + * Return the minimum cost to change the final value of the expression. + * - For example, if expression = "1|1|(0&0)&1", its value is + * 1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1. We want to apply operations so that the new + * expression evaluates to 0. + * + * The cost of changing the final value of an expression is the number of operations performed + * on the expression. The types of operations are described as follows: + * - Turn a '1' into a '0'. + * - Turn a '0' into a '1'. + * - Turn a '&' into a '|'. + * - Turn a '|' into a '&'. + * + * Note: '&' does not take precedence over '|' in the order of calculation. Evaluate parentheses + * first, then in left-to-right order. + */ + +/** + * @param {string} expression + * @return {number} + */ +var minOperationsToFlip = function(expression) { + const stack = []; + for (const char of expression) { + if (char === ')') { + const values = []; + while (stack.length && stack[stack.length - 1][0] !== '(') { + values.push(stack.pop()); + } + stack.pop(); + let [val1, cost1] = values.pop(); + while (values.length) { + const [op] = values.pop(); + const [val2, cost2] = values.pop(); + if (op === '&') { + if (val1 === 1 && val2 === 1) { + val1 = 1; + cost1 = Math.min(cost1, cost2); + } else if (val1 === 0 && val2 === 0) { + val1 = 0; + cost1 = Math.min(cost1 + 1, cost2 + 1); + } else { + val1 = 0; + cost1 = Math.min(cost1 + cost2, 1); + } + } else { + if (val1 === 1 && val2 === 1) { + val1 = 1; + cost1 = Math.min(cost1 + 1, cost2 + 1); + } else if (val1 === 0 && val2 === 0) { + val1 = 0; + cost1 = Math.min(cost1, cost2); + } else { + val1 = 1; + cost1 = Math.min(cost1 + cost2, 1); + } + } + } + stack.push([val1, cost1]); + } else if (char === '1') { + stack.push([1, 1]); + } else if (char === '0') { + stack.push([0, 1]); + } else { + stack.push([char]); + } + } + + const values = []; + while (stack.length) { + values.push(stack.pop()); + } + + let [val1, cost1] = values.pop(); + while (values.length) { + const [op] = values.pop(); + const [val2, cost2] = values.pop(); + if (op === '&') { + if (val1 === 1 && val2 === 1) { + val1 = 1; + cost1 = Math.min(cost1, cost2); + } else if (val1 === 0 && val2 === 0) { + val1 = 0; + cost1 = Math.min(cost1 + 1, cost2 + 1); + } else { + val1 = 0; + cost1 = Math.min(cost1 + cost2, 1); + } + } else { + if (val1 === 1 && val2 === 1) { + val1 = 1; + cost1 = Math.min(cost1 + 1, cost2 + 1); + } else if (val1 === 0 && val2 === 0) { + val1 = 0; + cost1 = Math.min(cost1, cost2); + } else { + val1 = 1; + cost1 = Math.min(cost1 + cost2, 1); + } + } + } + + return cost1; +}; From fffe2cd959e0b5305c437526724e6330737c43df Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 16:09:06 -0500 Subject: [PATCH 110/495] Add solution #1897 --- README.md | 3 +- ...te-characters-to-make-all-strings-equal.js | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 solutions/1897-redistribute-characters-to-make-all-strings-equal.js diff --git a/README.md b/README.md index 03174773..6d5d2fc4 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,614 LeetCode solutions in JavaScript +# 1,615 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1458,6 +1458,7 @@ 1894|[Find the Student that Will Replace the Chalk](./solutions/1894-find-the-student-that-will-replace-the-chalk.js)|Medium| 1895|[Largest Magic Square](./solutions/1895-largest-magic-square.js)|Medium| 1896|[Minimum Cost to Change the Final Value of Expression](./solutions/1896-minimum-cost-to-change-the-final-value-of-expression.js)|Hard| +1897|[Redistribute Characters to Make All Strings Equal](./solutions/1897-redistribute-characters-to-make-all-strings-equal.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1897-redistribute-characters-to-make-all-strings-equal.js b/solutions/1897-redistribute-characters-to-make-all-strings-equal.js new file mode 100644 index 00000000..b58b05ba --- /dev/null +++ b/solutions/1897-redistribute-characters-to-make-all-strings-equal.js @@ -0,0 +1,34 @@ +/** + * 1897. Redistribute Characters to Make All Strings Equal + * https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal/ + * Difficulty: Easy + * + * You are given an array of strings words (0-indexed). + * + * In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, + * and move any character from words[i] to any position in words[j]. + * + * Return true if you can make every string in words equal using any number of operations, and + * false otherwise. + */ + +/** + * @param {string[]} words + * @return {boolean} + */ +var makeEqual = function(words) { + const charCount = new Array(26).fill(0); + const wordCount = words.length; + + for (const word of words) { + for (const char of word) { + charCount[char.charCodeAt(0) - 97]++; + } + } + + for (const count of charCount) { + if (count % wordCount !== 0) return false; + } + + return true; +}; From c469a7785ee7ad7de2e59d9cf75456998262b8df Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 16:11:29 -0500 Subject: [PATCH 111/495] Add solution #1898 --- README.md | 3 +- ...-maximum-number-of-removable-characters.js | 51 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 solutions/1898-maximum-number-of-removable-characters.js diff --git a/README.md b/README.md index 6d5d2fc4..804049b8 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,615 LeetCode solutions in JavaScript +# 1,616 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1459,6 +1459,7 @@ 1895|[Largest Magic Square](./solutions/1895-largest-magic-square.js)|Medium| 1896|[Minimum Cost to Change the Final Value of Expression](./solutions/1896-minimum-cost-to-change-the-final-value-of-expression.js)|Hard| 1897|[Redistribute Characters to Make All Strings Equal](./solutions/1897-redistribute-characters-to-make-all-strings-equal.js)|Easy| +1898|[Maximum Number of Removable Characters](./solutions/1898-maximum-number-of-removable-characters.js)|Medium| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1898-maximum-number-of-removable-characters.js b/solutions/1898-maximum-number-of-removable-characters.js new file mode 100644 index 00000000..1a4c15fa --- /dev/null +++ b/solutions/1898-maximum-number-of-removable-characters.js @@ -0,0 +1,51 @@ +/** + * 1898. Maximum Number of Removable Characters + * https://leetcode.com/problems/maximum-number-of-removable-characters/ + * Difficulty: Medium + * + * You are given two strings s and p where p is a subsequence of s. You are also given a distinct + * 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed). + * + * You want to choose an integer k (0 <= k <= removable.length) such that, after removing k + * characters from s using the first k indices in removable, p is still a subsequence of s. + * More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then + * remove all marked characters and check if p is still a subsequence. + * + * Return the maximum k you can choose such that p is still a subsequence of s after the removals. + * + * A subsequence of a string is a new string generated from the original string with some + * characters (can be none) deleted without changing the relative order of the remaining characters. + */ + +/** + * @param {string} s + * @param {string} p + * @param {number[]} removable + * @return {number} + */ +var maximumRemovals = function(s, p, removable) { + let left = 0; + let right = removable.length; + + while (left <= right) { + const mid = (left + right) >> 1; + const removed = new Set(removable.slice(0, mid)); + let i = 0; + let j = 0; + + while (i < s.length && j < p.length) { + if (!removed.has(i) && s[i] === p[j]) { + j++; + } + i++; + } + + if (j === p.length) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return right; +}; From 474ecffebbff7c111598706095f8fba7a650789b Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 16:12:47 -0500 Subject: [PATCH 112/495] Add solution #1899 --- README.md | 3 +- ...9-merge-triplets-to-form-target-triplet.js | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 solutions/1899-merge-triplets-to-form-target-triplet.js diff --git a/README.md b/README.md index 804049b8..bb261206 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,616 LeetCode solutions in JavaScript +# 1,617 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1460,6 +1460,7 @@ 1896|[Minimum Cost to Change the Final Value of Expression](./solutions/1896-minimum-cost-to-change-the-final-value-of-expression.js)|Hard| 1897|[Redistribute Characters to Make All Strings Equal](./solutions/1897-redistribute-characters-to-make-all-strings-equal.js)|Easy| 1898|[Maximum Number of Removable Characters](./solutions/1898-maximum-number-of-removable-characters.js)|Medium| +1899|[Merge Triplets to Form Target Triplet](./solutions/1899-merge-triplets-to-form-target-triplet.js)|Medium| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1899-merge-triplets-to-form-target-triplet.js b/solutions/1899-merge-triplets-to-form-target-triplet.js new file mode 100644 index 00000000..606dacf4 --- /dev/null +++ b/solutions/1899-merge-triplets-to-form-target-triplet.js @@ -0,0 +1,40 @@ +/** + * 1899. Merge Triplets to Form Target Triplet + * https://leetcode.com/problems/merge-triplets-to-form-target-triplet/ + * Difficulty: Medium + * + * A triplet is an array of three integers. You are given a 2D integer array triplets, where + * triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array + * target = [x, y, z] that describes the triplet you want to obtain. + * + * To obtain target, you may apply the following operation on triplets any number of times + * (possibly zero): + * - Choose two indices (0-indexed) i and j (i != j) and update triplets[j] to become + * [max(ai, aj), max(bi, bj), max(ci, cj)]. + * - For example, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will + * be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5]. + * + * Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, + * or false otherwise. + */ + +/** + * @param {number[][]} triplets + * @param {number[]} target + * @return {boolean} + */ +var mergeTriplets = function(triplets, target) { + let canFormX = false; + let canFormY = false; + let canFormZ = false; + + for (const [a, b, c] of triplets) { + if (a <= target[0] && b <= target[1] && c <= target[2]) { + if (a === target[0]) canFormX = true; + if (b === target[1]) canFormY = true; + if (c === target[2]) canFormZ = true; + } + } + + return canFormX && canFormY && canFormZ; +}; From 5af0c725f4b36ce193607c9d4eb96d3c99277202 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 16:25:00 -0500 Subject: [PATCH 113/495] Add solution #1900 --- README.md | 3 +- ...and-latest-rounds-where-players-compete.js | 86 +++++++++++++++++++ 2 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 solutions/1900-the-earliest-and-latest-rounds-where-players-compete.js diff --git a/README.md b/README.md index bb261206..2e8aa985 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,617 LeetCode solutions in JavaScript +# 1,618 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1461,6 +1461,7 @@ 1897|[Redistribute Characters to Make All Strings Equal](./solutions/1897-redistribute-characters-to-make-all-strings-equal.js)|Easy| 1898|[Maximum Number of Removable Characters](./solutions/1898-maximum-number-of-removable-characters.js)|Medium| 1899|[Merge Triplets to Form Target Triplet](./solutions/1899-merge-triplets-to-form-target-triplet.js)|Medium| +1900|[The Earliest and Latest Rounds Where Players Compete](./solutions/1900-the-earliest-and-latest-rounds-where-players-compete.js)|Hard| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1900-the-earliest-and-latest-rounds-where-players-compete.js b/solutions/1900-the-earliest-and-latest-rounds-where-players-compete.js new file mode 100644 index 00000000..47d9293b --- /dev/null +++ b/solutions/1900-the-earliest-and-latest-rounds-where-players-compete.js @@ -0,0 +1,86 @@ +/** + * 1900. The Earliest and Latest Rounds Where Players Compete + * https://leetcode.com/problems/the-earliest-and-latest-rounds-where-players-compete/ + * Difficulty: Hard + * + * There is a tournament where n players are participating. The players are standing in a single row + * and are numbered from 1 to n based on their initial standing position (player 1 is the first + * player in the row, player 2 is the second player in the row, etc.). + * + * The tournament consists of multiple rounds (starting from round number 1). In each round, the ith + * player from the front of the row competes against the ith player from the end of the row, and the + * winner advances to the next round. When the number of players is odd for the current round, the + * player in the middle automatically advances to the next round. + * - For example, if the row consists of players 1, 2, 4, 6, 7 + * - Player 1 competes against player 7. + * - Player 2 competes against player 6. + * - Player 4 automatically advances to the next round. + * + * After each round is over, the winners are lined back up in the row based on the original ordering + * assigned to them initially (ascending order). + * + * The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win + * against any other player before they compete against each other. If any two other players compete + * against each other, either of them might win, and thus you may choose the outcome of this round. + * + * Given the integers n, firstPlayer, and secondPlayer, return an integer array containing two + * values, the earliest possible round number and the latest possible round number in which these + * two players will compete against each other, respectively. + */ + +/** + * @param {number} n + * @param {number} firstPlayer + * @param {number} secondPlayer + * @return {number[]} + */ +var earliestAndLatest = function(numPlayers, firstPlayer, secondPlayer) { + let minRounds = Infinity; + let maxRounds = 0; + + dfs(0, 1); + + return [minRounds, maxRounds]; + + function dfs(playersEliminated, numRounds) { + let roundResults = [playersEliminated]; + let i = 1; + let j = numPlayers; + + while (true) { + while (playersEliminated & (1 << i)) i++; + while (playersEliminated & (1 << j)) j--; + + if (i >= j) break; + + if (i === firstPlayer && j === secondPlayer) { + minRounds = Math.min(minRounds, numRounds); + maxRounds = Math.max(maxRounds, numRounds); + return; + } + + const newRoundResults = []; + + if (j !== firstPlayer && j !== secondPlayer) { + for (const roundResult of roundResults) { + newRoundResults.push(roundResult | (1 << j)); + } + } + + if (i !== firstPlayer && i !== secondPlayer) { + for (const roundResult of roundResults) { + newRoundResults.push(roundResult | (1 << i)); + } + } + + i++; + j--; + roundResults = newRoundResults; + } + + if (!roundResults.length) return; + + numRounds++; + roundResults.forEach(roundResult => dfs(roundResult, numRounds)); + } +}; From 455a24dfdfb79ab80641b645a22091a0caf9767f Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 16:26:24 -0500 Subject: [PATCH 114/495] Add solution #1901 --- README.md | 3 +- solutions/1901-find-a-peak-element-ii.js | 61 ++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 solutions/1901-find-a-peak-element-ii.js diff --git a/README.md b/README.md index 2e8aa985..c5b095af 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,618 LeetCode solutions in JavaScript +# 1,619 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1462,6 +1462,7 @@ 1898|[Maximum Number of Removable Characters](./solutions/1898-maximum-number-of-removable-characters.js)|Medium| 1899|[Merge Triplets to Form Target Triplet](./solutions/1899-merge-triplets-to-form-target-triplet.js)|Medium| 1900|[The Earliest and Latest Rounds Where Players Compete](./solutions/1900-the-earliest-and-latest-rounds-where-players-compete.js)|Hard| +1901|[Find a Peak Element II](./solutions/1901-find-a-peak-element-ii.js)|Medium| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1901-find-a-peak-element-ii.js b/solutions/1901-find-a-peak-element-ii.js new file mode 100644 index 00000000..fc0a48ca --- /dev/null +++ b/solutions/1901-find-a-peak-element-ii.js @@ -0,0 +1,61 @@ +/** + * 1901. Find a Peak Element II + * https://leetcode.com/problems/find-a-peak-element-ii/ + * Difficulty: Medium + * + * A peak element in a 2D grid is an element that is strictly greater than all of its adjacent + * neighbors to the left, right, top, and bottom. + * + * Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element + * mat[i][j] and return the length 2 array [i,j]. + * + * You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in + * each cell. + * + * You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time. + */ + +/** + * @param {number[][]} mat + * @return {number[]} + */ +var findPeakGrid = function(mat) { + const rows = mat.length; + const cols = mat[0].length; + + return binarySearch(0, rows - 1); + + function getMaxIndexInRow(row, left, right) { + let maxIndex = left; + for (let i = left; i <= right; i++) { + if (mat[row][i] > mat[row][maxIndex]) { + maxIndex = i; + } + } + return maxIndex; + } + + function binarySearch(startRow, endRow) { + if (startRow > endRow) return null; + + const midRow = Math.floor((startRow + endRow) / 2); + const maxCol = getMaxIndexInRow(midRow, 0, cols - 1); + const maxValue = mat[midRow][maxCol]; + + const topValue = midRow > 0 ? mat[midRow - 1][maxCol] : -1; + const bottomValue = midRow < rows - 1 ? mat[midRow + 1][maxCol] : -1; + const leftValue = maxCol > 0 ? mat[midRow][maxCol - 1] : -1; + const rightValue = maxCol < cols - 1 ? mat[midRow][maxCol + 1] : -1; + + if (maxValue > topValue && maxValue > bottomValue + && maxValue > leftValue && maxValue > rightValue) { + return [midRow, maxCol]; + } + + if (midRow > 0 && topValue > maxValue) { + return binarySearch(startRow, midRow - 1); + } + + return binarySearch(midRow + 1, endRow); + } +}; From 8390e0ce088e42288a1b18c0d2cd73fbe59dcb72 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 16:27:19 -0500 Subject: [PATCH 115/495] Add solution #1903 --- README.md | 3 ++- .../1903-largest-odd-number-in-string.js | 24 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 solutions/1903-largest-odd-number-in-string.js diff --git a/README.md b/README.md index c5b095af..842d5468 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,619 LeetCode solutions in JavaScript +# 1,620 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1463,6 +1463,7 @@ 1899|[Merge Triplets to Form Target Triplet](./solutions/1899-merge-triplets-to-form-target-triplet.js)|Medium| 1900|[The Earliest and Latest Rounds Where Players Compete](./solutions/1900-the-earliest-and-latest-rounds-where-players-compete.js)|Hard| 1901|[Find a Peak Element II](./solutions/1901-find-a-peak-element-ii.js)|Medium| +1903|[Largest Odd Number in String](./solutions/1903-largest-odd-number-in-string.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1903-largest-odd-number-in-string.js b/solutions/1903-largest-odd-number-in-string.js new file mode 100644 index 00000000..9914883e --- /dev/null +++ b/solutions/1903-largest-odd-number-in-string.js @@ -0,0 +1,24 @@ +/** + * 1903. Largest Odd Number in String + * https://leetcode.com/problems/largest-odd-number-in-string/ + * Difficulty: Easy + * + * You are given a string num, representing a large integer. Return the largest-valued odd + * integer (as a string) that is a non-empty substring of num, or an empty string "" if no + * odd integer exists. + * + * A substring is a contiguous sequence of characters within a string. + */ + +/** + * @param {string} num + * @return {string} + */ +var largestOddNumber = function(num) { + for (let i = num.length - 1; i >= 0; i--) { + if (parseInt(num[i]) % 2 === 1) { + return num.slice(0, i + 1); + } + } + return ''; +}; From 62417dad988ee6bdf80f04837265ecc9fc7ddcb6 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 19:26:47 -0500 Subject: [PATCH 116/495] Add solution #1904 --- README.md | 3 +- ...e-number-of-full-rounds-you-have-played.js | 47 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 solutions/1904-the-number-of-full-rounds-you-have-played.js diff --git a/README.md b/README.md index 842d5468..6da28006 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,620 LeetCode solutions in JavaScript +# 1,621 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1464,6 +1464,7 @@ 1900|[The Earliest and Latest Rounds Where Players Compete](./solutions/1900-the-earliest-and-latest-rounds-where-players-compete.js)|Hard| 1901|[Find a Peak Element II](./solutions/1901-find-a-peak-element-ii.js)|Medium| 1903|[Largest Odd Number in String](./solutions/1903-largest-odd-number-in-string.js)|Easy| +1904|[The Number of Full Rounds You Have Played](./solutions/1904-the-number-of-full-rounds-you-have-played.js)|Medium| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1904-the-number-of-full-rounds-you-have-played.js b/solutions/1904-the-number-of-full-rounds-you-have-played.js new file mode 100644 index 00000000..4c7ad2d6 --- /dev/null +++ b/solutions/1904-the-number-of-full-rounds-you-have-played.js @@ -0,0 +1,47 @@ +/** + * 1904. The Number of Full Rounds You Have Played + * https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/ + * Difficulty: Medium + * + * You are participating in an online chess tournament. There is a chess round that starts + * every 15 minutes. The first round of the day starts at 00:00, and after every 15 minutes, + * a new round starts. + * - For example, the second round starts at 00:15, the fourth round starts at 00:45, and the + * seventh round starts at 01:30. + * + * You are given two strings loginTime and logoutTime where: + * - loginTime is the time you will login to the game, and + * - logoutTime is the time you will logout from the game. + * + * If logoutTime is earlier than loginTime, this means you have played from loginTime to midnight + * and from midnight to logoutTime. + * + * Return the number of full chess rounds you have played in the tournament. + * + * Note: All the given times follow the 24-hour clock. That means the first round of the day starts + * at 00:00 and the last round of the day starts at 23:45. + */ + +/** + * @param {string} loginTime + * @param {string} logoutTime + * @return {number} + */ +var numberOfRounds = function(loginTime, logoutTime) { + let start = toMinutes(loginTime); + let end = toMinutes(logoutTime); + + if (end < start) { + end += 24 * 60; + } + + start = Math.ceil(start / 15); + end = Math.floor(end / 15); + + return Math.max(0, end - start); + + function toMinutes(time) { + const [hours, minutes] = time.split(':').map(Number); + return hours * 60 + minutes; + } +}; From 8ed80fedc7468fddb69918aba272931db6ea4896 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 19:27:59 -0500 Subject: [PATCH 117/495] Add solution #1905 --- README.md | 3 +- solutions/1905-count-sub-islands.js | 51 +++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 solutions/1905-count-sub-islands.js diff --git a/README.md b/README.md index 6da28006..7ed3f40e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,621 LeetCode solutions in JavaScript +# 1,622 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1465,6 +1465,7 @@ 1901|[Find a Peak Element II](./solutions/1901-find-a-peak-element-ii.js)|Medium| 1903|[Largest Odd Number in String](./solutions/1903-largest-odd-number-in-string.js)|Easy| 1904|[The Number of Full Rounds You Have Played](./solutions/1904-the-number-of-full-rounds-you-have-played.js)|Medium| +1905|[Count Sub Islands](./solutions/1905-count-sub-islands.js)|Medium| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1905-count-sub-islands.js b/solutions/1905-count-sub-islands.js new file mode 100644 index 00000000..d6cf98c8 --- /dev/null +++ b/solutions/1905-count-sub-islands.js @@ -0,0 +1,51 @@ +/** + * 1905. Count Sub Islands + * https://leetcode.com/problems/count-sub-islands/ + * Difficulty: Medium + * + * You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) + * and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal + * or vertical). Any cells outside of the grid are considered water cells. + * + * An island in grid2 is considered a sub-island if there is an island in grid1 that contains all + * the cells that make up this island in grid2. + * + * Return the number of islands in grid2 that are considered sub-islands. + */ + +/** + * @param {number[][]} grid1 + * @param {number[][]} grid2 + * @return {number} + */ +var countSubIslands = function(grid1, grid2) { + const rows = grid1.length; + const cols = grid1[0].length; + let result = 0; + + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + if (grid2[i][j] === 1 && isValidSubIsland(i, j)) { + result++; + } + } + } + + return result; + + function isValidSubIsland(row, col) { + if (row < 0 || row >= rows || col < 0 || col >= cols || grid2[row][col] === 0) { + return true; + } + + grid2[row][col] = 0; + let isSubIsland = grid1[row][col] === 1; + + isSubIsland &= isValidSubIsland(row - 1, col); + isSubIsland &= isValidSubIsland(row + 1, col); + isSubIsland &= isValidSubIsland(row, col - 1); + isSubIsland &= isValidSubIsland(row, col + 1); + + return isSubIsland; + } +}; From cb238cdbc47237d6a917a53708b01a6b1cb35037 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 19:29:43 -0500 Subject: [PATCH 118/495] Add solution #1906 --- README.md | 3 +- ...906-minimum-absolute-difference-queries.js | 57 +++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 solutions/1906-minimum-absolute-difference-queries.js diff --git a/README.md b/README.md index 7ed3f40e..fabbf63c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,622 LeetCode solutions in JavaScript +# 1,623 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1466,6 +1466,7 @@ 1903|[Largest Odd Number in String](./solutions/1903-largest-odd-number-in-string.js)|Easy| 1904|[The Number of Full Rounds You Have Played](./solutions/1904-the-number-of-full-rounds-you-have-played.js)|Medium| 1905|[Count Sub Islands](./solutions/1905-count-sub-islands.js)|Medium| +1906|[Minimum Absolute Difference Queries](./solutions/1906-minimum-absolute-difference-queries.js)|Medium| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1906-minimum-absolute-difference-queries.js b/solutions/1906-minimum-absolute-difference-queries.js new file mode 100644 index 00000000..62cfc15f --- /dev/null +++ b/solutions/1906-minimum-absolute-difference-queries.js @@ -0,0 +1,57 @@ +/** + * 1906. Minimum Absolute Difference Queries + * https://leetcode.com/problems/minimum-absolute-difference-queries/ + * Difficulty: Medium + * + * The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, + * where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same, the minimum + * absolute difference is -1. + * - For example, the minimum absolute difference of the array [5,2,3,7,2] is |2 - 3| = 1. Note + * that it is not 0 because a[i] and a[j] must be different. + * + * You are given an integer array nums and the array queries where queries[i] = [li, ri]. For each + * query i, compute the minimum absolute difference of the subarray nums[li...ri] containing the + * elements of nums between the 0-based indices li and ri (inclusive). + * + * Return an array ans where ans[i] is the answer to the ith query. + * + * A subarray is a contiguous sequence of elements in an array. + * + * The value of |x| is defined as: + * - x if x >= 0. + * - -x if x < 0. + */ + +/** + * @param {number[]} nums + * @param {number[][]} queries + * @return {number[]} + */ +var minDifference = function(nums, queries) { + const maxValue = 100; + const prefixCounts = new Array(nums.length + 1).fill().map(() => new Array(maxValue + 1).fill(0)); + + for (let i = 0; i < nums.length; i++) { + for (let j = 1; j <= maxValue; j++) { + prefixCounts[i + 1][j] = prefixCounts[i][j] + (nums[i] === j ? 1 : 0); + } + } + + return queries.map(([start, end]) => getMinDiff(start, end)); + + function getMinDiff(start, end) { + let minDiff = Infinity; + let prevValue = -1; + + for (let j = 1; j <= maxValue; j++) { + if (prefixCounts[end + 1][j] - prefixCounts[start][j] > 0) { + if (prevValue !== -1) { + minDiff = Math.min(minDiff, j - prevValue); + } + prevValue = j; + } + } + + return minDiff === Infinity ? -1 : minDiff; + } +}; From 78a5328428b57581dd8e3d9d30c65e38aefcd62c Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 19:31:05 -0500 Subject: [PATCH 119/495] Add solution #1909 --- README.md | 3 +- ...t-to-make-the-array-strictly-increasing.js | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 solutions/1909-remove-one-element-to-make-the-array-strictly-increasing.js diff --git a/README.md b/README.md index fabbf63c..e6e7b968 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,623 LeetCode solutions in JavaScript +# 1,624 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1467,6 +1467,7 @@ 1904|[The Number of Full Rounds You Have Played](./solutions/1904-the-number-of-full-rounds-you-have-played.js)|Medium| 1905|[Count Sub Islands](./solutions/1905-count-sub-islands.js)|Medium| 1906|[Minimum Absolute Difference Queries](./solutions/1906-minimum-absolute-difference-queries.js)|Medium| +1909|[Remove One Element to Make the Array Strictly Increasing](./solutions/1909-remove-one-element-to-make-the-array-strictly-increasing.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| diff --git a/solutions/1909-remove-one-element-to-make-the-array-strictly-increasing.js b/solutions/1909-remove-one-element-to-make-the-array-strictly-increasing.js new file mode 100644 index 00000000..3e47a059 --- /dev/null +++ b/solutions/1909-remove-one-element-to-make-the-array-strictly-increasing.js @@ -0,0 +1,33 @@ +/** + * 1909. Remove One Element to Make the Array Strictly Increasing + * https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/ + * Difficulty: Easy + * + * Given a 0-indexed integer array nums, return true if it can be made strictly increasing after + * removing exactly one element, or false otherwise. If the array is already strictly increasing, + * return true. + * + * The array nums is strictly increasing if nums[i - 1] < nums[i] for each index + * (1 <= i < nums.length). + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var canBeIncreasing = function(nums) { + for (let i = 0; i < nums.length; i++) { + if (isStrictlyIncreasing(nums, i)) return true; + } + + return false; + + function isStrictlyIncreasing(arr, skipIndex) { + for (let i = 1; i < arr.length; i++) { + if (i === skipIndex) continue; + const prev = i - 1 === skipIndex ? i - 2 : i - 1; + if (prev >= 0 && arr[i] <= arr[prev]) return false; + } + return true; + } +}; From baed64927e3f26efee5934d8e3806646ed2bfe13 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 2 May 2025 19:32:19 -0500 Subject: [PATCH 120/495] Add solution #1911 --- README.md | 3 +- ...911-maximum-alternating-subsequence-sum.js | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 solutions/1911-maximum-alternating-subsequence-sum.js diff --git a/README.md b/README.md index e6e7b968..7f523c7c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,624 LeetCode solutions in JavaScript +# 1,625 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1469,6 +1469,7 @@ 1906|[Minimum Absolute Difference Queries](./solutions/1906-minimum-absolute-difference-queries.js)|Medium| 1909|[Remove One Element to Make the Array Strictly Increasing](./solutions/1909-remove-one-element-to-make-the-array-strictly-increasing.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| +1911|[Maximum Alternating Subsequence Sum](./solutions/1911-maximum-alternating-subsequence-sum.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| 1926|[Nearest Exit from Entrance in Maze](./solutions/1926-nearest-exit-from-entrance-in-maze.js)|Medium| diff --git a/solutions/1911-maximum-alternating-subsequence-sum.js b/solutions/1911-maximum-alternating-subsequence-sum.js new file mode 100644 index 00000000..cd33635e --- /dev/null +++ b/solutions/1911-maximum-alternating-subsequence-sum.js @@ -0,0 +1,34 @@ +/** + * 1911. Maximum Alternating Subsequence Sum + * https://leetcode.com/problems/maximum-alternating-subsequence-sum/ + * Difficulty: Medium + * + * The alternating sum of a 0-indexed array is defined as the sum of the elements at even + * indices minus the sum of the elements at odd indices. + * - For example, the alternating sum of [4,2,5,3] is (4 + 5) - (2 + 3) = 4. + * + * Given an array nums, return the maximum alternating sum of any subsequence of nums (after + * reindexing the elements of the subsequence). + * + * A subsequence of an array is a new array generated from the original array by deleting some + * elements (possibly none) without changing the remaining elements' relative order. For + * example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), + * while [2,4,2] is not. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxAlternatingSum = function(nums) { + let result = 0; + let oddSum = 0; + + for (const num of nums) { + const prevEven = result; + result = Math.max(result, oddSum + num); + oddSum = Math.max(oddSum, prevEven - num); + } + + return result; +}; From 1e7ae5b9b7ba45374675041f8e37abce9ea207ba Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 01:07:30 -0500 Subject: [PATCH 121/495] Add solution #1912 --- README.md | 3 +- solutions/1912-design-movie-rental-system.js | 147 +++++++++++++++++++ 2 files changed, 149 insertions(+), 1 deletion(-) create mode 100644 solutions/1912-design-movie-rental-system.js diff --git a/README.md b/README.md index 7f523c7c..7d70aadb 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,625 LeetCode solutions in JavaScript +# 1,626 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1470,6 +1470,7 @@ 1909|[Remove One Element to Make the Array Strictly Increasing](./solutions/1909-remove-one-element-to-make-the-array-strictly-increasing.js)|Easy| 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1911|[Maximum Alternating Subsequence Sum](./solutions/1911-maximum-alternating-subsequence-sum.js)|Medium| +1912|[Design Movie Rental System](./solutions/1912-design-movie-rental-system.js)|Hard| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| 1926|[Nearest Exit from Entrance in Maze](./solutions/1926-nearest-exit-from-entrance-in-maze.js)|Medium| diff --git a/solutions/1912-design-movie-rental-system.js b/solutions/1912-design-movie-rental-system.js new file mode 100644 index 00000000..8f07b991 --- /dev/null +++ b/solutions/1912-design-movie-rental-system.js @@ -0,0 +1,147 @@ +/** + * 1912. Design Movie Rental System + * https://leetcode.com/problems/design-movie-rental-system/ + * Difficulty: Hard + * + * You have a movie renting company consisting of n shops. You want to implement a renting system + * that supports searching for, booking, and returning movies. The system should also support + * generating a report of the currently rented movies. + * + * Each movie is given as a 2D integer array entries where entries[i] = [shopi, moviei, pricei] + * indicates that there is a copy of movie moviei at shop shopi with a rental price of pricei. + * Each shop carries at most one copy of a movie moviei. + * + * The system should support the following functions: + * - Search: Finds the cheapest 5 shops that have an unrented copy of a given movie. The shops + * should be sorted by price in ascending order, and in case of a tie, the one with the smaller + * shopi should appear first. If there are less than 5 matching shops, then all of them should be + * returned. If no shop has an unrented copy, then an empty list should be returned. + * - Rent: Rents an unrented copy of a given movie from a given shop. + * - Drop: Drops off a previously rented copy of a given movie at a given shop. + * - Report: Returns the cheapest 5 rented movies (possibly of the same movie ID) as a 2D list res + * where res[j] = [shopj, moviej] describes that the jth cheapest rented movie moviej was rented + * from the shop shopj. The movies in res should be sorted by price in ascending order, and in + * case of a tie, the one with the smaller shopj should appear first, and if there is still tie, + * the one with the smaller moviej should appear first. If there are fewer than 5 rented movies, + * then all of them should be returned. If no movies are currently being rented, then an empty + * list should be returned. + * + * Implement the MovieRentingSystem class: + * - MovieRentingSystem(int n, int[][] entries) Initializes the MovieRentingSystem object with n + * shops and the movies in entries. + * - List search(int movie) Returns a list of shops that have an unrented copy of the + * given movie as described above. + * - void rent(int shop, int movie) Rents the given movie from the given shop. + * - void drop(int shop, int movie) Drops off a previously rented movie at the given shop. + * - List> report() Returns a list of cheapest rented movies as described above. + * + * Note: The test cases will be generated such that rent will only be called if the shop has an + * unrented copy of the movie, and drop will only be called if the shop had previously rented out + * the movie. + */ + +/** + * @param {number} n + * @param {number[][]} entries + */ +var MovieRentingSystem = function(n, entries) { + this.shopMovies = new Map(); + this.movieShops = new Map(); + this.rented = new PriorityQueue((a, b) => { + if (a[2] !== b[2]) return a[2] - b[2]; + if (a[0] !== b[0]) return a[0] - b[0]; + return a[1] - b[1]; + }); + this.rentedLookup = new Map(); + + for (const [shop, movie, price] of entries) { + if (!this.shopMovies.has(shop)) { + this.shopMovies.set(shop, new Map()); + } + this.shopMovies.get(shop).set(movie, price); + + if (!this.movieShops.has(movie)) { + this.movieShops.set(movie, new PriorityQueue((a, b) => { + if (a[1] !== b[1]) return a[1] - b[1]; + return a[0] - b[0]; + })); + } + this.movieShops.get(movie).enqueue([shop, price]); + } +}; + +/** + * @param {number} movie + * @return {number[]} + */ +MovieRentingSystem.prototype.search = function(movie) { + if (!this.movieShops.has(movie)) return []; + + const queue = this.movieShops.get(movie); + const result = []; + const seen = new Set(); + + while (!queue.isEmpty() && result.length < 5) { + const [shop, price] = queue.dequeue(); + if (this.shopMovies.get(shop)?.has(movie) && !seen.has(shop)) { + result.push(shop); + seen.add(shop); + } + } + + for (const shop of result) { + queue.enqueue([shop, this.shopMovies.get(shop).get(movie)]); + } + + return result; +}; + +/** + * @param {number} shop + * @param {number} movie + * @return {void} + */ +MovieRentingSystem.prototype.rent = function(shop, movie) { + const price = this.shopMovies.get(shop).get(movie); + this.shopMovies.get(shop).delete(movie); + this.rented.enqueue([shop, movie, price]); + this.rentedLookup.set(`${shop}:${movie}`, price); +}; + +/** + * @param {number} shop + * @param {number} movie + * @return {void} + */ +MovieRentingSystem.prototype.drop = function(shop, movie) { + const price = this.rentedLookup.get(`${shop}:${movie}`); + this.rentedLookup.delete(`${shop}:${movie}`); + if (!this.shopMovies.get(shop).has(movie)) { + this.shopMovies.get(shop).set(movie, price); + this.movieShops.get(movie).enqueue([shop, price]); + } +}; + +/** + * @return {number[][]} + */ +MovieRentingSystem.prototype.report = function() { + const result = []; + const seen = new Set(); + + while (!this.rented.isEmpty() && result.length < 5) { + const [shop, movie, price] = this.rented.dequeue(); + const key = `${shop}:${movie}`; + if (this.rentedLookup.has(key) && !seen.has(key)) { + result.push([shop, movie]); + seen.add(key); + } + } + + for (const [shop, movie] of result) { + const price = this.rentedLookup.get(`${shop}:${movie}`); + this.rented.enqueue([shop, movie, price]); + } + + return result; +}; From 9eccff44ed237ed52d10c7c8d428efe26a7daf27 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 01:08:30 -0500 Subject: [PATCH 122/495] Add solution #1913 --- README.md | 3 +- ...um-product-difference-between-two-pairs.js | 42 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 solutions/1913-maximum-product-difference-between-two-pairs.js diff --git a/README.md b/README.md index 7d70aadb..844f7c5e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,626 LeetCode solutions in JavaScript +# 1,627 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1471,6 +1471,7 @@ 1910|[Remove All Occurrences of a Substring](./solutions/1910-remove-all-occurrences-of-a-substring.js)|Medium| 1911|[Maximum Alternating Subsequence Sum](./solutions/1911-maximum-alternating-subsequence-sum.js)|Medium| 1912|[Design Movie Rental System](./solutions/1912-design-movie-rental-system.js)|Hard| +1913|[Maximum Product Difference Between Two Pairs](./solutions/1913-maximum-product-difference-between-two-pairs.js)|Easy| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| 1926|[Nearest Exit from Entrance in Maze](./solutions/1926-nearest-exit-from-entrance-in-maze.js)|Medium| diff --git a/solutions/1913-maximum-product-difference-between-two-pairs.js b/solutions/1913-maximum-product-difference-between-two-pairs.js new file mode 100644 index 00000000..91e73220 --- /dev/null +++ b/solutions/1913-maximum-product-difference-between-two-pairs.js @@ -0,0 +1,42 @@ +/** + * 1913. Maximum Product Difference Between Two Pairs + * https://leetcode.com/problems/maximum-product-difference-between-two-pairs/ + * Difficulty: Easy + * + * The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d). + * - For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16. + * + * Given an integer array nums, choose four distinct indices w, x, y, and z such that the product + * difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized. + * + * Return the maximum such product difference. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxProductDifference = function(nums) { + let max1 = 0; + let max2 = 0; + let min1 = Infinity; + let min2 = Infinity; + + for (const num of nums) { + if (num > max1) { + max2 = max1; + max1 = num; + } else if (num > max2) { + max2 = num; + } + + if (num < min1) { + min2 = min1; + min1 = num; + } else if (num < min2) { + min2 = num; + } + } + + return max1 * max2 - min1 * min2; +}; From 77bd1a6cd74f7b2e92750905b03a1b7118f6c729 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 01:10:14 -0500 Subject: [PATCH 123/495] Add solution #1914 --- README.md | 3 +- solutions/1914-cyclically-rotating-a-grid.js | 66 ++++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 solutions/1914-cyclically-rotating-a-grid.js diff --git a/README.md b/README.md index 844f7c5e..4c1ecc51 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,627 LeetCode solutions in JavaScript +# 1,628 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1472,6 +1472,7 @@ 1911|[Maximum Alternating Subsequence Sum](./solutions/1911-maximum-alternating-subsequence-sum.js)|Medium| 1912|[Design Movie Rental System](./solutions/1912-design-movie-rental-system.js)|Hard| 1913|[Maximum Product Difference Between Two Pairs](./solutions/1913-maximum-product-difference-between-two-pairs.js)|Easy| +1914|[Cyclically Rotating a Grid](./solutions/1914-cyclically-rotating-a-grid.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| 1926|[Nearest Exit from Entrance in Maze](./solutions/1926-nearest-exit-from-entrance-in-maze.js)|Medium| diff --git a/solutions/1914-cyclically-rotating-a-grid.js b/solutions/1914-cyclically-rotating-a-grid.js new file mode 100644 index 00000000..84724945 --- /dev/null +++ b/solutions/1914-cyclically-rotating-a-grid.js @@ -0,0 +1,66 @@ +/** + * 1914. Cyclically Rotating a Grid + * https://leetcode.com/problems/cyclically-rotating-a-grid/ + * Difficulty: Medium + * + * You are given an m x n integer matrix grid, where m and n are both even integers, and + * an integer k. + * + * The matrix is composed of several layers, which is shown in the below image, where each + * color is its own layer. + * + * A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. + * To cyclically rotate a layer once, each element in the layer will take the place of the + * adjacent element in the counter-clockwise direction. An example rotation is shown below. + */ + +/** + * @param {number[][]} grid + * @param {number} k + * @return {number[][]} + */ +var rotateGrid = function(grid, k) { + const rows = grid.length; + const cols = grid[0].length; + const result = grid.map(row => [...row]); + + for (let layer = 0; layer < Math.min(rows, cols) / 2; layer++) { + rotateLayer(layer, layer, rows - 1 - layer, cols - 1 - layer, k); + } + + return result; + + function rotateLayer(top, left, bottom, right, rotations) { + if (top >= bottom || left >= right) return; + + const perimeter = 2 * (bottom - top + right - left); + const effectiveRotations = rotations % perimeter; + if (effectiveRotations === 0) return; + + const elements = []; + for (let i = top; i <= bottom; i++) elements.push(grid[i][left]); + for (let j = left + 1; j <= right; j++) elements.push(grid[bottom][j]); + for (let i = bottom - 1; i >= top; i--) elements.push(grid[i][right]); + for (let j = right - 1; j > left; j--) elements.push(grid[top][j]); + + const offset = (perimeter - effectiveRotations) % perimeter; + let index = offset; + + for (let i = top; i <= bottom; i++) { + result[i][left] = elements[index % perimeter]; + index++; + } + for (let j = left + 1; j <= right; j++) { + result[bottom][j] = elements[index % perimeter]; + index++; + } + for (let i = bottom - 1; i >= top; i--) { + result[i][right] = elements[index % perimeter]; + index++; + } + for (let j = right - 1; j > left; j--) { + result[top][j] = elements[index % perimeter]; + index++; + } + } +}; From 867d0d1e4bde700c64ca1055a16aa245d0eef016 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 01:11:06 -0500 Subject: [PATCH 124/495] Add solution #1915 --- README.md | 3 +- .../1915-number-of-wonderful-substrings.js | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 solutions/1915-number-of-wonderful-substrings.js diff --git a/README.md b/README.md index 4c1ecc51..52fc53da 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,628 LeetCode solutions in JavaScript +# 1,629 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1473,6 +1473,7 @@ 1912|[Design Movie Rental System](./solutions/1912-design-movie-rental-system.js)|Hard| 1913|[Maximum Product Difference Between Two Pairs](./solutions/1913-maximum-product-difference-between-two-pairs.js)|Easy| 1914|[Cyclically Rotating a Grid](./solutions/1914-cyclically-rotating-a-grid.js)|Medium| +1915|[Number of Wonderful Substrings](./solutions/1915-number-of-wonderful-substrings.js)|Medium| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| 1926|[Nearest Exit from Entrance in Maze](./solutions/1926-nearest-exit-from-entrance-in-maze.js)|Medium| diff --git a/solutions/1915-number-of-wonderful-substrings.js b/solutions/1915-number-of-wonderful-substrings.js new file mode 100644 index 00000000..b9aaf680 --- /dev/null +++ b/solutions/1915-number-of-wonderful-substrings.js @@ -0,0 +1,39 @@ +/** + * 1915. Number of Wonderful Substrings + * https://leetcode.com/problems/number-of-wonderful-substrings/ + * Difficulty: Medium + * + * A wonderful string is a string where at most one letter appears an odd number of times. + * - For example, "ccjjc" and "abab" are wonderful, but "ab" is not. + * + * Given a string word that consists of the first ten lowercase English letters ('a' through + * 'j'), return the number of wonderful non-empty substrings in word. If the same substring + * appears multiple times in word, then count each occurrence separately. + * + * A substring is a contiguous sequence of characters in a string. + */ + +/** + * @param {string} word + * @return {number} + */ +var wonderfulSubstrings = function(word) { + let count = 0; + const freq = new Map([[0, 1]]); + let state = 0; + + for (const char of word) { + const bit = 1 << (char.charCodeAt(0) - 97); + state ^= bit; + + count += freq.get(state) || 0; + freq.set(state, (freq.get(state) || 0) + 1); + + for (let i = 0; i < 10; i++) { + const oddBit = state ^ (1 << i); + count += freq.get(oddBit) || 0; + } + } + + return count; +}; From f2f79a154054259ab6c5acf7e56558e1d95b991e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 01:13:37 -0500 Subject: [PATCH 125/495] Add solution #1916 --- README.md | 3 +- ...nt-ways-to-build-rooms-in-an-ant-colony.js | 71 +++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 solutions/1916-count-ways-to-build-rooms-in-an-ant-colony.js diff --git a/README.md b/README.md index 52fc53da..40262e41 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,629 LeetCode solutions in JavaScript +# 1,630 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1474,6 +1474,7 @@ 1913|[Maximum Product Difference Between Two Pairs](./solutions/1913-maximum-product-difference-between-two-pairs.js)|Easy| 1914|[Cyclically Rotating a Grid](./solutions/1914-cyclically-rotating-a-grid.js)|Medium| 1915|[Number of Wonderful Substrings](./solutions/1915-number-of-wonderful-substrings.js)|Medium| +1916|[Count Ways to Build Rooms in an Ant Colony](./solutions/1916-count-ways-to-build-rooms-in-an-ant-colony.js)|Hard| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| 1926|[Nearest Exit from Entrance in Maze](./solutions/1926-nearest-exit-from-entrance-in-maze.js)|Medium| diff --git a/solutions/1916-count-ways-to-build-rooms-in-an-ant-colony.js b/solutions/1916-count-ways-to-build-rooms-in-an-ant-colony.js new file mode 100644 index 00000000..93f715af --- /dev/null +++ b/solutions/1916-count-ways-to-build-rooms-in-an-ant-colony.js @@ -0,0 +1,71 @@ +/** + * 1916. Count Ways to Build Rooms in an Ant Colony + * https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/ + * Difficulty: Hard + * + * You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given + * the expansion plan as a 0-indexed integer array of length n, prevRoom, where prevRoom[i] + * indicates that you must build room prevRoom[i] before building room i, and these two rooms + * must be connected directly. Room 0 is already built, so prevRoom[0] = -1. The expansion plan + * is given such that once all the rooms are built, every room will be reachable from room 0. + * + * You can only build one room at a time, and you can travel freely between rooms you have + * already built only if they are connected. You can choose to build any room as long as its + * previous room is already built. + * + * Return the number of different orders you can build all the rooms in. Since the answer may + * be large, return it modulo 109 + 7. + */ + +/** + * @param {number[]} prevRoom + * @return {number} + */ +var waysToBuildRooms = function(prevRoom) { + const n = prevRoom.length; + const mod = 1e9 + 7; + const graph = Array(n).fill().map(() => []); + const factorial = Array(n + 1).fill(1n); + const invFactorial = Array(n + 1).fill(1n); + + for (let i = 1; i <= n; i++) { + factorial[i] = (factorial[i - 1] * BigInt(i)) % BigInt(mod); + } + + for (let i = 1; i <= n; i++) { + invFactorial[i] = modInverse(factorial[i], BigInt(mod)); + } + + for (let i = 1; i < n; i++) { + graph[prevRoom[i]].push(i); + } + + return Number(countSubtreeSizes(0)[1]); + + function countSubtreeSizes(node) { + let size = 1; + let result = 1n; + + for (const child of graph[node]) { + const [childSize, childResult] = countSubtreeSizes(child); + size += childSize; + result = (result * childResult * invFactorial[childSize]) % BigInt(mod); + } + + return [size, (result * factorial[size - 1]) % BigInt(mod)]; + } + + function modInverse(a, m) { + const m0 = m; + let q; + let x0 = 0n; + let x1 = 1n; + + while (a > 1n) { + q = a / m; + [a, m] = [m, a % m]; + [x0, x1] = [x1 - q * x0, x0]; + } + return x1 < 0n ? x1 + m0 : x1; + } +}; From 182e43cbd2e7b587748078320b5a530d3fcc354e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 14:56:21 -0500 Subject: [PATCH 126/495] Add solution #1921 --- README.md | 3 +- ...21-eliminate-maximum-number-of-monsters.js | 47 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 solutions/1921-eliminate-maximum-number-of-monsters.js diff --git a/README.md b/README.md index 40262e41..f5fd050d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,630 LeetCode solutions in JavaScript +# 1,631 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1476,6 +1476,7 @@ 1915|[Number of Wonderful Substrings](./solutions/1915-number-of-wonderful-substrings.js)|Medium| 1916|[Count Ways to Build Rooms in an Ant Colony](./solutions/1916-count-ways-to-build-rooms-in-an-ant-colony.js)|Hard| 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| +1921|[Eliminate Maximum Number of Monsters](./solutions/1921-eliminate-maximum-number-of-monsters.js)|Medium| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| 1926|[Nearest Exit from Entrance in Maze](./solutions/1926-nearest-exit-from-entrance-in-maze.js)|Medium| 1929|[Concatenation of Array](./solutions/1929-concatenation-of-array.js)|Easy| diff --git a/solutions/1921-eliminate-maximum-number-of-monsters.js b/solutions/1921-eliminate-maximum-number-of-monsters.js new file mode 100644 index 00000000..e9f43cd1 --- /dev/null +++ b/solutions/1921-eliminate-maximum-number-of-monsters.js @@ -0,0 +1,47 @@ +/** + * 1921. Eliminate Maximum Number of Monsters + * https://leetcode.com/problems/eliminate-maximum-number-of-monsters/ + * Difficulty: Medium + * + * You are playing a video game where you are defending your city from a group of n monsters. You + * are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in + * kilometers of the ith monster from the city. + * + * The monsters walk toward the city at a constant speed. The speed of each monster is given to + * you in an integer array speed of size n, where speed[i] is the speed of the ith monster in + * kilometers per minute. + * + * You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon + * takes one minute to charge. The weapon is fully charged at the very start. + * + * You lose when any monster reaches your city. If a monster reaches the city at the exact moment + * the weapon is fully charged, it counts as a loss, and the game ends before you can use your + * weapon. + * + * Return the maximum number of monsters that you can eliminate before you lose, or n if you can + * eliminate all the monsters before they reach the city. + */ + +/** + * @param {number[]} dist + * @param {number[]} speed + * @return {number} + */ +var eliminateMaximum = function(dist, speed) { + const n = dist.length; + const arrivalTimes = new Array(n); + + for (let i = 0; i < n; i++) { + arrivalTimes[i] = dist[i] / speed[i]; + } + + arrivalTimes.sort((a, b) => a - b); + + for (let i = 0; i < n; i++) { + if (arrivalTimes[i] <= i) { + return i; + } + } + + return n; +}; From 3d648fdabf4e199d23d0afafcf15eadb1ea34fe2 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 15:46:22 -0500 Subject: [PATCH 127/495] Add solution #1923 --- README.md | 3 +- solutions/1923-longest-common-subpath.js | 148 +++++++++++++++++++++++ 2 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 solutions/1923-longest-common-subpath.js diff --git a/README.md b/README.md index f5fd050d..f3d48655 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,631 LeetCode solutions in JavaScript +# 1,632 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1478,6 +1478,7 @@ 1920|[Build Array from Permutation](./solutions/1920-build-array-from-permutation.js)|Easy| 1921|[Eliminate Maximum Number of Monsters](./solutions/1921-eliminate-maximum-number-of-monsters.js)|Medium| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| +1923|[Longest Common Subpath](./solutions/1923-longest-common-subpath.js)|Hard| 1926|[Nearest Exit from Entrance in Maze](./solutions/1926-nearest-exit-from-entrance-in-maze.js)|Medium| 1929|[Concatenation of Array](./solutions/1929-concatenation-of-array.js)|Easy| 1930|[Unique Length-3 Palindromic Subsequences](./solutions/1930-unique-length-3-palindromic-subsequences.js)|Medium| diff --git a/solutions/1923-longest-common-subpath.js b/solutions/1923-longest-common-subpath.js new file mode 100644 index 00000000..1c2e1b0d --- /dev/null +++ b/solutions/1923-longest-common-subpath.js @@ -0,0 +1,148 @@ +/** + * 1923. Longest Common Subpath + * https://leetcode.com/problems/longest-common-subpath/ + * Difficulty: Hard + * + * There is a country of n cities numbered from 0 to n - 1. In this country, there is a road + * connecting every pair of cities. + * + * There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one + * of them will take a path consisting of some cities. Each path is represented by an integer + * array that contains the visited cities in order. The path may contain a city more than once, + * but the same city will not be listed consecutively. + * + * Given an integer n and a 2D integer array paths where paths[i] is an integer array representing + * the path of the ith friend, return the length of the longest common subpath that is shared + * by every friend's path, or 0 if there is no common subpath at all. + * + * A subpath of a path is a contiguous sequence of cities within that path. + */ + +/** + * @param {number} n + * @param {number[][]} paths + * @return {number} + */ +var longestCommonSubpath = function(n, paths) { + if (paths.length === 0) return 0; + + paths.sort((a, b) => a.length - b.length); + + let left = 0; + let right = paths[0].length; + + while (left <= right) { + const mid = Math.floor((left + right) / 2); + + if (checkCommonSubpathExists(paths, mid)) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return right; +}; + +function checkCommonSubpathExists(paths, length) { + if (length === 0) return true; + + const firstPath = paths[0]; + + if (firstPath.length < length) return false; + + const prime = 1000000007; + const base = 100003; + + let highestPower = 1; + for (let i = 0; i < length - 1; i++) { + highestPower = (highestPower * base) % prime; + } + + let hashToPositions = new Map(); + + let hash = 0; + for (let i = 0; i < length; i++) { + hash = (hash * base + firstPath[i]) % prime; + } + + if (!hashToPositions.has(hash)) { + hashToPositions.set(hash, []); + } + hashToPositions.get(hash).push(0); + + for (let i = 1; i <= firstPath.length - length; i++) { + hash = ((hash - firstPath[i - 1] * highestPower % prime + prime) + % prime * base + firstPath[i + length - 1]) % prime; + + if (!hashToPositions.has(hash)) { + hashToPositions.set(hash, []); + } + hashToPositions.get(hash).push(i); + } + + for (let pathIdx = 1; pathIdx < paths.length; pathIdx++) { + const path = paths[pathIdx]; + + if (path.length < length) return false; + + const newHashToPositions = new Map(); + hash = 0; + for (let i = 0; i < length; i++) { + hash = (hash * base + path[i]) % prime; + } + + if (hashToPositions.has(hash)) { + const positions = hashToPositions.get(hash); + for (const pos of positions) { + let isMatch = true; + for (let j = 0; j < length; j++) { + if (firstPath[pos + j] !== path[j]) { + isMatch = false; + break; + } + } + + if (isMatch) { + if (!newHashToPositions.has(hash)) { + newHashToPositions.set(hash, []); + } + newHashToPositions.get(hash).push(pos); + break; + } + } + } + + for (let i = 1; i <= path.length - length; i++) { + hash = ((hash - path[i - 1] * highestPower % prime + prime) + % prime * base + path[i + length - 1]) % prime; + + if (hashToPositions.has(hash)) { + const positions = hashToPositions.get(hash); + for (const pos of positions) { + let isMatch = true; + for (let j = 0; j < length; j++) { + if (firstPath[pos + j] !== path[i + j]) { + isMatch = false; + break; + } + } + + if (isMatch) { + if (!newHashToPositions.has(hash)) { + newHashToPositions.set(hash, []); + } + newHashToPositions.get(hash).push(pos); + break; + } + } + } + } + + if (newHashToPositions.size === 0) return false; + + hashToPositions = newHashToPositions; + } + + return hashToPositions.size > 0; +} From eeaddb9823034de947a074c3658d429b9a7fbe29 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 15:47:18 -0500 Subject: [PATCH 128/495] Add solution #1925 --- README.md | 3 ++- solutions/1925-count-square-sum-triples.js | 29 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 solutions/1925-count-square-sum-triples.js diff --git a/README.md b/README.md index f3d48655..c7e351b0 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,632 LeetCode solutions in JavaScript +# 1,633 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1479,6 +1479,7 @@ 1921|[Eliminate Maximum Number of Monsters](./solutions/1921-eliminate-maximum-number-of-monsters.js)|Medium| 1922|[Count Good Numbers](./solutions/1922-count-good-numbers.js)|Medium| 1923|[Longest Common Subpath](./solutions/1923-longest-common-subpath.js)|Hard| +1925|[Count Square Sum Triples](./solutions/1925-count-square-sum-triples.js)|Easy| 1926|[Nearest Exit from Entrance in Maze](./solutions/1926-nearest-exit-from-entrance-in-maze.js)|Medium| 1929|[Concatenation of Array](./solutions/1929-concatenation-of-array.js)|Easy| 1930|[Unique Length-3 Palindromic Subsequences](./solutions/1930-unique-length-3-palindromic-subsequences.js)|Medium| diff --git a/solutions/1925-count-square-sum-triples.js b/solutions/1925-count-square-sum-triples.js new file mode 100644 index 00000000..b917c4e1 --- /dev/null +++ b/solutions/1925-count-square-sum-triples.js @@ -0,0 +1,29 @@ +/** + * 1925. Count Square Sum Triples + * https://leetcode.com/problems/count-square-sum-triples/ + * Difficulty: Easy + * + * A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2. + * + * Given an integer n, return the number of square triples such that 1 <= a, b, c <= n. + */ + +/** + * @param {number} n + * @return {number} + */ +var countTriples = function(n) { + let result = 0; + + for (let a = 1; a <= n; a++) { + for (let b = 1; b <= n; b++) { + const sum = a * a + b * b; + const c = Math.sqrt(sum); + if (c <= n && Number.isInteger(c)) { + result++; + } + } + } + + return result; +}; From e9fd4530cdd1dea9fad33afdbebce06cccb40988 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 15:59:21 -0500 Subject: [PATCH 129/495] Add solution #1927 --- README.md | 3 +- solutions/1927-sum-game.js | 56 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 solutions/1927-sum-game.js diff --git a/README.md b/README.md index c7e351b0..ccbc5428 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,633 LeetCode solutions in JavaScript +# 1,634 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1481,6 +1481,7 @@ 1923|[Longest Common Subpath](./solutions/1923-longest-common-subpath.js)|Hard| 1925|[Count Square Sum Triples](./solutions/1925-count-square-sum-triples.js)|Easy| 1926|[Nearest Exit from Entrance in Maze](./solutions/1926-nearest-exit-from-entrance-in-maze.js)|Medium| +1927|[Sum Game](./solutions/1927-sum-game.js)|Medium| 1929|[Concatenation of Array](./solutions/1929-concatenation-of-array.js)|Easy| 1930|[Unique Length-3 Palindromic Subsequences](./solutions/1930-unique-length-3-palindromic-subsequences.js)|Medium| 1935|[Maximum Number of Words You Can Type](./solutions/1935-maximum-number-of-words-you-can-type.js)|Easy| diff --git a/solutions/1927-sum-game.js b/solutions/1927-sum-game.js new file mode 100644 index 00000000..178435f2 --- /dev/null +++ b/solutions/1927-sum-game.js @@ -0,0 +1,56 @@ +/** + * 1927. Sum Game + * https://leetcode.com/problems/sum-game/ + * Difficulty: Medium + * + * Alice and Bob take turns playing a game, with Alice starting first. + * + * You are given a string num of even length consisting of digits and '?' characters. On each + * turn, a player will do the following if there is still at least one '?' in num: + * 1. Choose an index i where num[i] == '?'. + * 2. Replace num[i] with any digit between '0' and '9'. + * + * The game ends when there are no more '?' characters in num. + * + * For Bob to win, the sum of the digits in the first half of num must be equal to the sum of + * the digits in the second half. For Alice to win, the sums must not be equal. + * - For example, if the game ended with num = "243801", then Bob wins because 2+4+3 = 8+0+1. + * If the game ended with num = "243803", then Alice wins because 2+4+3 != 8+0+3. + * + * Assuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win. + */ + +/** + * @param {string} num + * @return {boolean} + */ +var sumGame = function(num) { + const n = num.length; + const half = n / 2; + + let leftSum = 0; + let rightSum = 0; + let leftQuestionMarks = 0; + let rightQuestionMarks = 0; + + for (let i = 0; i < n; i++) { + if (i < half) { + if (num[i] === '?') { + leftQuestionMarks++; + } else { + leftSum += parseInt(num[i]); + } + } else { + if (num[i] === '?') { + rightQuestionMarks++; + } else { + rightSum += parseInt(num[i]); + } + } + } + + const sumDiff = leftSum - rightSum; + const diff = leftQuestionMarks - rightQuestionMarks; + + return (diff % 2 !== 0) || (sumDiff + diff * 4.5 !== 0); +}; From 42715fed879f16133c1b5f5bdada694b0ad0a3c1 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:05:15 -0500 Subject: [PATCH 130/495] Add solution #1928 --- README.md | 3 +- ...nimum-cost-to-reach-destination-in-time.js | 66 +++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 solutions/1928-minimum-cost-to-reach-destination-in-time.js diff --git a/README.md b/README.md index ccbc5428..40a0f21c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,634 LeetCode solutions in JavaScript +# 1,635 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1482,6 +1482,7 @@ 1925|[Count Square Sum Triples](./solutions/1925-count-square-sum-triples.js)|Easy| 1926|[Nearest Exit from Entrance in Maze](./solutions/1926-nearest-exit-from-entrance-in-maze.js)|Medium| 1927|[Sum Game](./solutions/1927-sum-game.js)|Medium| +1928|[Minimum Cost to Reach Destination in Time](./solutions/1928-minimum-cost-to-reach-destination-in-time.js)|Hard| 1929|[Concatenation of Array](./solutions/1929-concatenation-of-array.js)|Easy| 1930|[Unique Length-3 Palindromic Subsequences](./solutions/1930-unique-length-3-palindromic-subsequences.js)|Medium| 1935|[Maximum Number of Words You Can Type](./solutions/1935-maximum-number-of-words-you-can-type.js)|Easy| diff --git a/solutions/1928-minimum-cost-to-reach-destination-in-time.js b/solutions/1928-minimum-cost-to-reach-destination-in-time.js new file mode 100644 index 00000000..a601d545 --- /dev/null +++ b/solutions/1928-minimum-cost-to-reach-destination-in-time.js @@ -0,0 +1,66 @@ +/** + * 1928. Minimum Cost to Reach Destination in Time + * https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time/ + * Difficulty: Hard + * + * There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by + * bi-directional roads. The roads are represented as a 2D integer array edges where + * edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes + * to travel. There may be multiple roads of differing travel times connecting the same two + * cities, but no road connects a city to itself. + * + * Each time you pass through a city, you must pay a passing fee. This is represented as a + * 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars + * you must pay when you pass through city j. + * + * In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less. + * The cost of your journey is the summation of passing fees for each city that you passed + * through at some moment of your journey (including the source and destination cities). + * + * Given maxTime, edges, and passingFees, return the minimum cost to complete your journey, + * or -1 if you cannot complete it within maxTime minutes. + */ + +/** + * @param {number} maxTime + * @param {number[][]} edges + * @param {number[]} passingFees + * @return {number} + */ +var minCost = function(maxTime, edges, passingFees) { + const n = passingFees.length; + const dp = new Array(n).fill().map(() => new Array(maxTime + 1).fill(Infinity)); + dp[0][0] = passingFees[0]; + + const graph = new Array(n).fill().map(() => []); + for (const [u, v, time] of edges) { + graph[u].push([v, time]); + graph[v].push([u, time]); + } + + const pq = new PriorityQueue((a, b) => a.cost - b.cost); + pq.enqueue({ cost: passingFees[0], city: 0, time: 0 }); + + while (!pq.isEmpty()) { + const { cost, city, time } = pq.dequeue(); + if (cost > dp[city][time]) continue; + + for (const [nextCity, travelTime] of graph[city]) { + const newTime = time + travelTime; + if (newTime > maxTime) continue; + + const newCost = cost + passingFees[nextCity]; + if (newCost < dp[nextCity][newTime]) { + dp[nextCity][newTime] = newCost; + pq.enqueue({ cost: newCost, city: nextCity, time: newTime }); + } + } + } + + let minCost = Infinity; + for (let t = 0; t <= maxTime; t++) { + minCost = Math.min(minCost, dp[n - 1][t]); + } + + return minCost === Infinity ? -1 : minCost; +}; From 05fc529aad5354eafe5322d9504fb016f9808993 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:09:00 -0500 Subject: [PATCH 131/495] Add solution #1931 --- README.md | 3 +- ...ting-a-grid-with-three-different-colors.js | 72 +++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 solutions/1931-painting-a-grid-with-three-different-colors.js diff --git a/README.md b/README.md index 40a0f21c..98d7cfbb 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,635 LeetCode solutions in JavaScript +# 1,636 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1485,6 +1485,7 @@ 1928|[Minimum Cost to Reach Destination in Time](./solutions/1928-minimum-cost-to-reach-destination-in-time.js)|Hard| 1929|[Concatenation of Array](./solutions/1929-concatenation-of-array.js)|Easy| 1930|[Unique Length-3 Palindromic Subsequences](./solutions/1930-unique-length-3-palindromic-subsequences.js)|Medium| +1931|[Painting a Grid With Three Different Colors](./solutions/1931-painting-a-grid-with-three-different-colors.js)|Hard| 1935|[Maximum Number of Words You Can Type](./solutions/1935-maximum-number-of-words-you-can-type.js)|Easy| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| diff --git a/solutions/1931-painting-a-grid-with-three-different-colors.js b/solutions/1931-painting-a-grid-with-three-different-colors.js new file mode 100644 index 00000000..ef8bf15b --- /dev/null +++ b/solutions/1931-painting-a-grid-with-three-different-colors.js @@ -0,0 +1,72 @@ +/** + * 1931. Painting a Grid With Three Different Colors + * https://leetcode.com/problems/painting-a-grid-with-three-different-colors/ + * Difficulty: Hard + * + * You are given two integers m and n. Consider an m x n grid where each cell is initially white. + * You can paint each cell red, green, or blue. All cells must be painted. + * + * Return the number of ways to color the grid with no two adjacent cells having the same color. + * Since the answer can be very large, return it modulo 109 + 7. + */ + +/** + * @param {number} m + * @param {number} n + * @return {number} + */ +var colorTheGrid = function(m, n) { + const MOD = 1e9 + 7; + const colors = 3; + const validStates = generateValidStates(m, colors); + const stateCount = validStates.length; + let dp = new Array(stateCount).fill(1); + + for (let col = 1; col < n; col++) { + const nextDp = new Array(stateCount).fill(0); + for (let i = 0; i < stateCount; i++) { + for (let j = 0; j < stateCount; j++) { + if (isCompatible(validStates[i], validStates[j])) { + nextDp[j] = (nextDp[j] + dp[i]) % MOD; + } + } + } + dp = nextDp; + } + + let totalWays = 0; + for (const count of dp) { + totalWays = (totalWays + count) % MOD; + } + + return totalWays; + + function generateValidStates(rows, colors) { + const states = []; + generateStates([], rows, colors, states); + return states; + } + + function generateStates(current, rows, colors, states) { + if (current.length === rows) { + states.push([...current]); + return; + } + for (let c = 0; c < colors; c++) { + if (current.length === 0 || current[current.length - 1] !== c) { + current.push(c); + generateStates(current, rows, colors, states); + current.pop(); + } + } + } + + function isCompatible(prevState, currState) { + for (let i = 0; i < prevState.length; i++) { + if (prevState[i] === currState[i]) { + return false; + } + } + return true; + } +}; From 8a95305e509043183e81a54423dcc44a64047c8b Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:10:18 -0500 Subject: [PATCH 132/495] Add solution #1932 --- README.md | 3 +- .../1932-merge-bsts-to-create-single-bst.js | 86 +++++++++++++++++++ 2 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 solutions/1932-merge-bsts-to-create-single-bst.js diff --git a/README.md b/README.md index 98d7cfbb..1b205415 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,636 LeetCode solutions in JavaScript +# 1,637 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1486,6 +1486,7 @@ 1929|[Concatenation of Array](./solutions/1929-concatenation-of-array.js)|Easy| 1930|[Unique Length-3 Palindromic Subsequences](./solutions/1930-unique-length-3-palindromic-subsequences.js)|Medium| 1931|[Painting a Grid With Three Different Colors](./solutions/1931-painting-a-grid-with-three-different-colors.js)|Hard| +1932|[Merge BSTs to Create Single BST](./solutions/1932-merge-bsts-to-create-single-bst.js)|Hard| 1935|[Maximum Number of Words You Can Type](./solutions/1935-maximum-number-of-words-you-can-type.js)|Easy| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| diff --git a/solutions/1932-merge-bsts-to-create-single-bst.js b/solutions/1932-merge-bsts-to-create-single-bst.js new file mode 100644 index 00000000..a118a41a --- /dev/null +++ b/solutions/1932-merge-bsts-to-create-single-bst.js @@ -0,0 +1,86 @@ +/** + * 1932. Merge BSTs to Create Single BST + * https://leetcode.com/problems/merge-bsts-to-create-single-bst/ + * Difficulty: Hard + * + * You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array + * trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same + * value. In one operation, you can: + * - Select two distinct indices i and j such that the value stored at one of the leaves of + * trees[i] is equal to the root value of trees[j]. + * - Replace the leaf node in trees[i] with trees[j]. + * - Remove trees[j] from trees. + * + * Return the root of the resulting BST if it is possible to form a valid BST after + * performing n - 1 operations, or null if it is impossible to create a valid BST. + * + * A BST (binary search tree) is a binary tree where each node satisfies the following property: + * - Every node in the node's left subtree has a value strictly less than the node's value. + * - Every node in the node's right subtree has a value strictly greater than the node's value. + * + * A leaf is a node that has 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[]} trees + * @return {TreeNode} + */ +var canMerge = function(trees) { + const valueToTree = new Map(); + const leafValues = new Set(); + const inDegree = new Map(); + + for (const tree of trees) { + valueToTree.set(tree.val, tree); + if (tree.left) leafValues.add(tree.left.val); + if (tree.right) leafValues.add(tree.right.val); + } + + let root = null; + for (const tree of trees) { + if (!leafValues.has(tree.val)) { + if (root) return null; + root = tree; + } + if (tree.left) inDegree.set(tree.left.val, (inDegree.get(tree.left.val) || 0) + 1); + if (tree.right) inDegree.set(tree.right.val, (inDegree.get(tree.right.val) || 0) + 1); + } + + if (!root) return null; + + const merged = mergeTrees(root, valueToTree, inDegree); + if (!merged || valueToTree.size > 1 || !isValidBST(merged, -Infinity, Infinity)) { + return null; + } + + return merged; + + function mergeTrees(node, valueToTree, inDegree) { + if (!node) return node; + + if (!node.left && !node.right && valueToTree.has(node.val) && inDegree.get(node.val) === 1) { + const tree = valueToTree.get(node.val); + if (tree === node) return node; + valueToTree.delete(node.val); + return mergeTrees(tree, valueToTree, inDegree); + } + + node.left = mergeTrees(node.left, valueToTree, inDegree); + node.right = mergeTrees(node.right, valueToTree, inDegree); + return node; + } + + function isValidBST(node, min, max) { + if (!node) return true; + if (node.val <= min || node.val >= max) return false; + return isValidBST(node.left, min, node.val) && isValidBST(node.right, node.val, max); + } +}; From e533e5b38eda345df3faffb5be1ed3b61bb09d7e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:11:23 -0500 Subject: [PATCH 133/495] Add solution #1936 --- README.md | 3 +- solutions/1936-add-minimum-number-of-rungs.js | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 solutions/1936-add-minimum-number-of-rungs.js diff --git a/README.md b/README.md index 1b205415..fb1ba9d0 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,637 LeetCode solutions in JavaScript +# 1,638 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1488,6 +1488,7 @@ 1931|[Painting a Grid With Three Different Colors](./solutions/1931-painting-a-grid-with-three-different-colors.js)|Hard| 1932|[Merge BSTs to Create Single BST](./solutions/1932-merge-bsts-to-create-single-bst.js)|Hard| 1935|[Maximum Number of Words You Can Type](./solutions/1935-maximum-number-of-words-you-can-type.js)|Easy| +1936|[Add Minimum Number of Rungs](./solutions/1936-add-minimum-number-of-rungs.js)|Medium| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1936-add-minimum-number-of-rungs.js b/solutions/1936-add-minimum-number-of-rungs.js new file mode 100644 index 00000000..2dba6511 --- /dev/null +++ b/solutions/1936-add-minimum-number-of-rungs.js @@ -0,0 +1,36 @@ +/** + * 1936. Add Minimum Number of Rungs + * https://leetcode.com/problems/add-minimum-number-of-rungs/ + * Difficulty: Medium + * + * You are given a strictly increasing integer array rungs that represents the height of rungs + * on a ladder. You are currently on the floor at height 0, and you want to reach the last rung. + * + * You are also given an integer dist. You can only climb to the next highest rung if the + * distance between where you are currently at (the floor or on a rung) and the next rung is + * at most dist. You are able to insert rungs at any positive integer height if a rung is not + * already there. + * + * Return the minimum number of rungs that must be added to the ladder in order for you to climb + * to the last rung. + */ + +/** + * @param {number[]} rungs + * @param {number} dist + * @return {number} + */ +var addRungs = function(rungs, dist) { + let currentHeight = 0; + let result = 0; + + for (const rung of rungs) { + const gap = rung - currentHeight; + if (gap > dist) { + result += Math.ceil(gap / dist) - 1; + } + currentHeight = rung; + } + + return result; +}; From d1865597f79ee3a1bae3ba32e2c35c255de31d04 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:12:35 -0500 Subject: [PATCH 134/495] Add solution #1937 --- README.md | 3 +- ...1937-maximum-number-of-points-with-cost.js | 55 +++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 solutions/1937-maximum-number-of-points-with-cost.js diff --git a/README.md b/README.md index fb1ba9d0..e8cc3cbd 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,638 LeetCode solutions in JavaScript +# 1,639 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1489,6 +1489,7 @@ 1932|[Merge BSTs to Create Single BST](./solutions/1932-merge-bsts-to-create-single-bst.js)|Hard| 1935|[Maximum Number of Words You Can Type](./solutions/1935-maximum-number-of-words-you-can-type.js)|Easy| 1936|[Add Minimum Number of Rungs](./solutions/1936-add-minimum-number-of-rungs.js)|Medium| +1937|[Maximum Number of Points with Cost](./solutions/1937-maximum-number-of-points-with-cost.js)|Medium| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1937-maximum-number-of-points-with-cost.js b/solutions/1937-maximum-number-of-points-with-cost.js new file mode 100644 index 00000000..288c1888 --- /dev/null +++ b/solutions/1937-maximum-number-of-points-with-cost.js @@ -0,0 +1,55 @@ +/** + * 1937. Maximum Number of Points with Cost + * https://leetcode.com/problems/maximum-number-of-points-with-cost/ + * Difficulty: Medium + * + * You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want + * to maximize the number of points you can get from the matrix. + * + * To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) + * will add points[r][c] to your score. + * + * However, you will lose points if you pick a cell too far from the cell that you picked in + * the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking + * cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score. + * + * Return the maximum number of points you can achieve. + * + * abs(x) is defined as: + * - x for x >= 0. + * - -x for x < 0. + */ + +/** + * @param {number[][]} points + * @return {number} + */ +var maxPoints = function(points) { + const rows = points.length; + const cols = points[0].length; + let prevRow = points[0].slice(); + + for (let r = 1; r < rows; r++) { + const currRow = new Array(cols).fill(0); + const leftMax = new Array(cols).fill(0); + const rightMax = new Array(cols).fill(0); + + leftMax[0] = prevRow[0]; + for (let c = 1; c < cols; c++) { + leftMax[c] = Math.max(leftMax[c - 1] - 1, prevRow[c]); + } + + rightMax[cols - 1] = prevRow[cols - 1]; + for (let c = cols - 2; c >= 0; c--) { + rightMax[c] = Math.max(rightMax[c + 1] - 1, prevRow[c]); + } + + for (let c = 0; c < cols; c++) { + currRow[c] = points[r][c] + Math.max(leftMax[c], rightMax[c]); + } + + prevRow = currRow; + } + + return Math.max(...prevRow); +}; From b297d224072ca58528331c322f28b82fecbd3638 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:14:22 -0500 Subject: [PATCH 135/495] Add solution #1938 --- README.md | 3 +- .../1938-maximum-genetic-difference-query.js | 97 +++++++++++++++++++ 2 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 solutions/1938-maximum-genetic-difference-query.js diff --git a/README.md b/README.md index e8cc3cbd..404c144c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,639 LeetCode solutions in JavaScript +# 1,640 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1490,6 +1490,7 @@ 1935|[Maximum Number of Words You Can Type](./solutions/1935-maximum-number-of-words-you-can-type.js)|Easy| 1936|[Add Minimum Number of Rungs](./solutions/1936-add-minimum-number-of-rungs.js)|Medium| 1937|[Maximum Number of Points with Cost](./solutions/1937-maximum-number-of-points-with-cost.js)|Medium| +1938|[Maximum Genetic Difference Query](./solutions/1938-maximum-genetic-difference-query.js)|Hard| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1938-maximum-genetic-difference-query.js b/solutions/1938-maximum-genetic-difference-query.js new file mode 100644 index 00000000..e7b88f18 --- /dev/null +++ b/solutions/1938-maximum-genetic-difference-query.js @@ -0,0 +1,97 @@ +/** + * 1938. Maximum Genetic Difference Query + * https://leetcode.com/problems/maximum-genetic-difference-query/ + * Difficulty: Hard + * + * There is a rooted tree consisting of n nodes numbered 0 to n - 1. Each node's number denotes + * its unique genetic value (i.e. the genetic value of node x is x). The genetic difference + * between two genetic values is defined as the bitwise-XOR of their values. You are given + * the integer array parents, where parents[i] is the parent for node i. If node x is the root + * of the tree, then parents[x] == -1. + * + * You are also given the array queries where queries[i] = [nodei, vali]. For each query i, + * find the maximum genetic difference between vali and pi, where pi is the genetic value of + * any node that is on the path between nodei and the root (including nodei and the root). + * More formally, you want to maximize vali XOR pi. + * + * Return an array ans where ans[i] is the answer to the ith query. + */ + +/** + * @param {number[]} parents + * @param {number[][]} queries + * @return {number[]} + */ +var maxGeneticDifference = function(parents, queries) { + const n = parents.length; + const graph = Array(n).fill().map(() => []); + let root = -1; + + for (let i = 0; i < n; i++) { + if (parents[i] === -1) { + root = i; + } else { + graph[parents[i]].push(i); + } + } + + const trie = { count: 0, children: {} }; + const queryMap = Array(n).fill().map(() => []); + const result = new Array(queries.length).fill(0); + + for (let i = 0; i < queries.length; i++) { + queryMap[queries[i][0]].push([queries[i][1], i]); + } + + dfs(root); + return result; + + function insertTrie(val) { + let node = trie; + for (let bit = 17; bit >= 0; bit--) { + const b = (val >> bit) & 1; + if (!node.children[b]) { + node.children[b] = { count: 0, children: {} }; + } + node = node.children[b]; + node.count++; + } + } + + function removeTrie(val) { + let node = trie; + for (let bit = 17; bit >= 0; bit--) { + const b = (val >> bit) & 1; + node = node.children[b]; + node.count--; + } + } + + function queryTrie(val) { + let node = trie; + let maxXor = 0; + for (let bit = 17; bit >= 0; bit--) { + const b = (val >> bit) & 1; + if (node.children[1 - b]?.count > 0) { + maxXor |= (1 << bit); + node = node.children[1 - b]; + } else if (node.children[b]?.count > 0) { + node = node.children[b]; + } else { + return maxXor; + } + } + return maxXor; + } + + function dfs(node) { + insertTrie(node); + for (const [val, idx] of queryMap[node]) { + result[idx] = queryTrie(val); + } + for (const child of graph[node]) { + dfs(child); + } + removeTrie(node); + } +}; From 38f1652655091dc2d5cc4a2541781ad999f5344b Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:18:00 -0500 Subject: [PATCH 136/495] Add solution #1941 --- README.md | 3 ++- ...acters-have-equal-number-of-occurrences.js | 24 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 solutions/1941-check-if-all-characters-have-equal-number-of-occurrences.js diff --git a/README.md b/README.md index 404c144c..0e5f11a7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,640 LeetCode solutions in JavaScript +# 1,641 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1491,6 +1491,7 @@ 1936|[Add Minimum Number of Rungs](./solutions/1936-add-minimum-number-of-rungs.js)|Medium| 1937|[Maximum Number of Points with Cost](./solutions/1937-maximum-number-of-points-with-cost.js)|Medium| 1938|[Maximum Genetic Difference Query](./solutions/1938-maximum-genetic-difference-query.js)|Hard| +1941|[Check if All Characters Have Equal Number of Occurrences](./solutions/1941-check-if-all-characters-have-equal-number-of-occurrences.js)|Easy| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1941-check-if-all-characters-have-equal-number-of-occurrences.js b/solutions/1941-check-if-all-characters-have-equal-number-of-occurrences.js new file mode 100644 index 00000000..aa742eb2 --- /dev/null +++ b/solutions/1941-check-if-all-characters-have-equal-number-of-occurrences.js @@ -0,0 +1,24 @@ +/** + * 1941. Check if All Characters Have Equal Number of Occurrences + * https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/ + * Difficulty: Easy + * + * Given a string s, return true if s is a good string, or false otherwise. + * + * A string s is good if all the characters that appear in s have the same number of occurrences + * (i.e., the same frequency). + */ + +/** + * @param {string} s + * @return {boolean} + */ +var areOccurrencesEqual = function(s) { + const map = new Map(); + for (const char of s) { + map.set(char, (map.get(char) || 0) + 1); + } + + const frequencies = new Set(map.values()); + return frequencies.size === 1; +}; From e8398d642faa12a80a37f9d0abd972173e77dd31 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:19:46 -0500 Subject: [PATCH 137/495] Add solution #1943 --- README.md | 3 +- solutions/1943-describe-the-painting.js | 60 +++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 solutions/1943-describe-the-painting.js diff --git a/README.md b/README.md index 0e5f11a7..8ebef097 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,641 LeetCode solutions in JavaScript +# 1,642 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1492,6 +1492,7 @@ 1937|[Maximum Number of Points with Cost](./solutions/1937-maximum-number-of-points-with-cost.js)|Medium| 1938|[Maximum Genetic Difference Query](./solutions/1938-maximum-genetic-difference-query.js)|Hard| 1941|[Check if All Characters Have Equal Number of Occurrences](./solutions/1941-check-if-all-characters-have-equal-number-of-occurrences.js)|Easy| +1943|[Describe the Painting](./solutions/1943-describe-the-painting.js)|Medium| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1943-describe-the-painting.js b/solutions/1943-describe-the-painting.js new file mode 100644 index 00000000..3e5c287a --- /dev/null +++ b/solutions/1943-describe-the-painting.js @@ -0,0 +1,60 @@ +/** + * 1943. Describe the Painting + * https://leetcode.com/problems/describe-the-painting/ + * Difficulty: Medium + * + * There is a long and thin painting that can be represented by a number line. The painting was + * painted with multiple overlapping segments where each segment was painted with a unique color. + * You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] + * represents the half-closed segment [starti, endi) with colori as the color. + * + * The colors in the overlapping segments of the painting were mixed when it was painted. When + * two or more colors mix, they form a new color that can be represented as a set of mixed colors. + * - For example, if colors 2, 4, and 6 are mixed, then the resulting mixed color is {2,4,6}. + * + * For the sake of simplicity, you should only output the sum of the elements in the set rather + * than the full set. + * + * You want to describe the painting with the minimum number of non-overlapping half-closed + * segments of these mixed colors. These segments can be represented by the 2D array painting + * where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) + * with the mixed color sum of mixj. + * - For example, the painting created with segments = [[1,4,5],[1,7,7]] can be described by + * painting = [[1,4,12],[4,7,7]] because: + * - [1,4) is colored {5,7} (with a sum of 12) from both the first and second segments. + * - [4,7) is colored {7} from only the second segment. + * + * Return the 2D array painting describing the finished painting (excluding any parts that are + * not painted). You may return the segments in any order. + * + * A half-closed segment [a, b) is the section of the number line between points a and b including + * point a and not including point b. + */ + +/** + * @param {number[][]} segments + * @return {number[][]} + */ +var splitPainting = function(segments) { + const events = []; + for (const [start, end, color] of segments) { + events.push([start, color]); + events.push([end, -color]); + } + + events.sort((a, b) => a[0] - b[0] || a[1] - b[1]); + + const result = []; + let currentSum = 0; + let prevPoint = events[0][0]; + + for (const [point, color] of events) { + if (currentSum > 0 && point > prevPoint) { + result.push([prevPoint, point, currentSum]); + } + currentSum += color; + prevPoint = point; + } + + return result; +}; From 2664b0beef8428749d19d2086941e54206b5236e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:21:04 -0500 Subject: [PATCH 138/495] Add solution #1944 --- README.md | 3 +- ...944-number-of-visible-people-in-a-queue.js | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 solutions/1944-number-of-visible-people-in-a-queue.js diff --git a/README.md b/README.md index 8ebef097..318e960a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,642 LeetCode solutions in JavaScript +# 1,643 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1493,6 +1493,7 @@ 1938|[Maximum Genetic Difference Query](./solutions/1938-maximum-genetic-difference-query.js)|Hard| 1941|[Check if All Characters Have Equal Number of Occurrences](./solutions/1941-check-if-all-characters-have-equal-number-of-occurrences.js)|Easy| 1943|[Describe the Painting](./solutions/1943-describe-the-painting.js)|Medium| +1944|[Number of Visible People in a Queue](./solutions/1944-number-of-visible-people-in-a-queue.js)|Hard| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1944-number-of-visible-people-in-a-queue.js b/solutions/1944-number-of-visible-people-in-a-queue.js new file mode 100644 index 00000000..8297710b --- /dev/null +++ b/solutions/1944-number-of-visible-people-in-a-queue.js @@ -0,0 +1,39 @@ +/** + * 1944. Number of Visible People in a Queue + * https://leetcode.com/problems/number-of-visible-people-in-a-queue/ + * Difficulty: Hard + * + * There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right + * order. You are given an array heights of distinct integers where heights[i] represents the + * height of the ith person. + * + * A person can see another person to their right in the queue if everybody in between is + * shorter than both of them. More formally, the ith person can see the jth person + * if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]). + * + * Return an array answer of length n where answer[i] is the number of people the ith person + * can see to their right in the queue. + */ + +/** + * @param {number[]} heights + * @return {number[]} + */ +var canSeePersonsCount = function(heights) { + const n = heights.length; + const result = new Array(n).fill(0); + const stack = []; + + for (let i = n - 1; i >= 0; i--) { + while (stack.length && heights[i] > stack[stack.length - 1]) { + stack.pop(); + result[i]++; + } + if (stack.length) { + result[i]++; + } + stack.push(heights[i]); + } + + return result; +}; From ba06ca5bc9dc9edcc3a161d11b54a3cb656c73f7 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:22:26 -0500 Subject: [PATCH 139/495] Add solution #1945 --- README.md | 3 +- ...5-sum-of-digits-of-string-after-convert.js | 44 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 solutions/1945-sum-of-digits-of-string-after-convert.js diff --git a/README.md b/README.md index 318e960a..924f8d2f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,643 LeetCode solutions in JavaScript +# 1,644 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1494,6 +1494,7 @@ 1941|[Check if All Characters Have Equal Number of Occurrences](./solutions/1941-check-if-all-characters-have-equal-number-of-occurrences.js)|Easy| 1943|[Describe the Painting](./solutions/1943-describe-the-painting.js)|Medium| 1944|[Number of Visible People in a Queue](./solutions/1944-number-of-visible-people-in-a-queue.js)|Hard| +1945|[Sum of Digits of String After Convert](./solutions/1945-sum-of-digits-of-string-after-convert.js)|Easy| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1945-sum-of-digits-of-string-after-convert.js b/solutions/1945-sum-of-digits-of-string-after-convert.js new file mode 100644 index 00000000..7e6e47d1 --- /dev/null +++ b/solutions/1945-sum-of-digits-of-string-after-convert.js @@ -0,0 +1,44 @@ +/** + * 1945. Sum of Digits of String After Convert + * https://leetcode.com/problems/sum-of-digits-of-string-after-convert/ + * Difficulty: Easy + * + * You are given a string s consisting of lowercase English letters, and an integer k. Your task + * is to convert the string into an integer by a special process, and then transform it by + * summing its digits repeatedly k times. More specifically, perform the following steps: + * 1. Convert s into an integer by replacing each letter with its position in the alphabet (i.e. + * replace 'a' with 1, 'b' with 2, ..., 'z' with 26). + * 2. Transform the integer by replacing it with the sum of its digits. + * 3. Repeat the transform operation (step 2) k times in total. + * + * For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following + * operations: + * 1. Convert: "zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124 + * 2. Transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17 + * 3. Transform #2: 17 ➝ 1 + 7 ➝ 8 + * + * Return the resulting integer after performing the operations described above. + */ + +/** + * @param {string} s + * @param {number} k + * @return {number} + */ +var getLucky = function(s, k) { + let number = ''; + for (const char of s) { + number += (char.charCodeAt(0) - 96).toString(); + } + + let result = 0; + for (let i = 0; i < k; i++) { + result = 0; + for (const digit of number) { + result += parseInt(digit); + } + number = result.toString(); + } + + return result; +}; From 4becdb9264509378a24291ee17bfbadf22f7438f Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:23:28 -0500 Subject: [PATCH 140/495] Add solution #1946 --- README.md | 3 +- ...largest-number-after-mutating-substring.js | 41 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 solutions/1946-largest-number-after-mutating-substring.js diff --git a/README.md b/README.md index 924f8d2f..ff2c1d6c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,644 LeetCode solutions in JavaScript +# 1,645 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1495,6 +1495,7 @@ 1943|[Describe the Painting](./solutions/1943-describe-the-painting.js)|Medium| 1944|[Number of Visible People in a Queue](./solutions/1944-number-of-visible-people-in-a-queue.js)|Hard| 1945|[Sum of Digits of String After Convert](./solutions/1945-sum-of-digits-of-string-after-convert.js)|Easy| +1946|[Largest Number After Mutating Substring](./solutions/1946-largest-number-after-mutating-substring.js)|Medium| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1946-largest-number-after-mutating-substring.js b/solutions/1946-largest-number-after-mutating-substring.js new file mode 100644 index 00000000..f64e4db0 --- /dev/null +++ b/solutions/1946-largest-number-after-mutating-substring.js @@ -0,0 +1,41 @@ +/** + * 1946. Largest Number After Mutating Substring + * https://leetcode.com/problems/largest-number-after-mutating-substring/ + * Difficulty: Medium + * + * You are given a string num, which represents a large integer. You are also given a 0-indexed + * integer array change of length 10 that maps each digit 0-9 to another digit. More formally, + * digit d maps to digit change[d]. + * + * You may choose to mutate a single substring of num. To mutate a substring, replace each digit + * num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]). + * + * Return a string representing the largest possible integer after mutating (or choosing not to) + * a single substring of num. + * + * A substring is a contiguous sequence of characters within the string. + */ + +/** + * @param {string} num + * @param {number[]} change + * @return {string} + */ +var maximumNumber = function(num, change) { + const digits = num.split(''); + let mutated = false; + + for (let i = 0; i < digits.length; i++) { + const currentDigit = parseInt(digits[i]); + const mappedDigit = change[currentDigit]; + + if (mappedDigit > currentDigit) { + digits[i] = mappedDigit.toString(); + mutated = true; + } else if (mappedDigit < currentDigit && mutated) { + break; + } + } + + return digits.join(''); +}; From 5b1e3cf0623bb57b6f635cf32c49ecf5a6cbad0e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:25:55 -0500 Subject: [PATCH 141/495] Add solution #1947 --- README.md | 3 +- .../1947-maximum-compatibility-score-sum.js | 63 +++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 solutions/1947-maximum-compatibility-score-sum.js diff --git a/README.md b/README.md index ff2c1d6c..7d8cc6a9 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,645 LeetCode solutions in JavaScript +# 1,646 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1496,6 +1496,7 @@ 1944|[Number of Visible People in a Queue](./solutions/1944-number-of-visible-people-in-a-queue.js)|Hard| 1945|[Sum of Digits of String After Convert](./solutions/1945-sum-of-digits-of-string-after-convert.js)|Easy| 1946|[Largest Number After Mutating Substring](./solutions/1946-largest-number-after-mutating-substring.js)|Medium| +1947|[Maximum Compatibility Score Sum](./solutions/1947-maximum-compatibility-score-sum.js)|Medium| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1947-maximum-compatibility-score-sum.js b/solutions/1947-maximum-compatibility-score-sum.js new file mode 100644 index 00000000..985d1deb --- /dev/null +++ b/solutions/1947-maximum-compatibility-score-sum.js @@ -0,0 +1,63 @@ +/** + * 1947. Maximum Compatibility Score Sum + * https://leetcode.com/problems/maximum-compatibility-score-sum/ + * Difficulty: Medium + * + * There is a survey that consists of n questions where each question's answer is either 0 + * (no) or 1 (yes). + * + * The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from + * 0 to m - 1. The answers of the students are represented by a 2D integer array students + * where students[i] is an integer array that contains the answers of the ith student + * (0-indexed). The answers of the mentors are represented by a 2D integer array mentors + * where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed). + * + * Each student will be assigned to one mentor, and each mentor will have one student assigned + * to them. The compatibility score of a student-mentor pair is the number of answers that + * are the same for both the student and the mentor. + * - For example, if the student's answers were [1, 0, 1] and the mentor's answers were + * [0, 0, 1], then their compatibility score is 2 because only the second and the third + * answers are the same. + * + * You are tasked with finding the optimal student-mentor pairings to maximize the sum of the + * compatibility scores. + * + * Given students and mentors, return the maximum compatibility score sum that can be achieved. + */ + +/** + * @param {number[][]} students + * @param {number[][]} mentors + * @return {number} + */ +var maxCompatibilitySum = function(students, mentors) { + const m = students.length; + let maxScore = 0; + + backtrack(0, new Array(m).fill(false), 0); + return maxScore; + + function calculateScore(student, mentor) { + let score = 0; + for (let i = 0; i < student.length; i++) { + if (student[i] === mentor[i]) score++; + } + return score; + } + + function backtrack(studentIndex, usedMentors, currentScore) { + if (studentIndex === m) { + maxScore = Math.max(maxScore, currentScore); + return; + } + + for (let mentorIndex = 0; mentorIndex < m; mentorIndex++) { + if (!usedMentors[mentorIndex]) { + usedMentors[mentorIndex] = true; + backtrack(studentIndex + 1, usedMentors, + currentScore + calculateScore(students[studentIndex], mentors[mentorIndex])); + usedMentors[mentorIndex] = false; + } + } + } +}; From 4c2490ff2c80e81a66cdfd0540f6bfa4e1bf08a5 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:33:49 -0500 Subject: [PATCH 142/495] Add solution #1948 --- README.md | 3 +- ...1948-delete-duplicate-folders-in-system.js | 115 ++++++++++++++++++ 2 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 solutions/1948-delete-duplicate-folders-in-system.js diff --git a/README.md b/README.md index 7d8cc6a9..0ffdb8e1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,646 LeetCode solutions in JavaScript +# 1,647 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1497,6 +1497,7 @@ 1945|[Sum of Digits of String After Convert](./solutions/1945-sum-of-digits-of-string-after-convert.js)|Easy| 1946|[Largest Number After Mutating Substring](./solutions/1946-largest-number-after-mutating-substring.js)|Medium| 1947|[Maximum Compatibility Score Sum](./solutions/1947-maximum-compatibility-score-sum.js)|Medium| +1948|[Delete Duplicate Folders in System](./solutions/1948-delete-duplicate-folders-in-system.js)|Hard| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1948-delete-duplicate-folders-in-system.js b/solutions/1948-delete-duplicate-folders-in-system.js new file mode 100644 index 00000000..085f6d72 --- /dev/null +++ b/solutions/1948-delete-duplicate-folders-in-system.js @@ -0,0 +1,115 @@ +/** + * 1948. Delete Duplicate Folders in System + * https://leetcode.com/problems/delete-duplicate-folders-in-system/ + * Difficulty: Hard + * + * Due to a bug, there are many duplicate folders in a file system. You are given a 2D array + * paths, where paths[i] is an array representing an absolute path to the ith folder in the + * file system. + * - For example, ["one", "two", "three"] represents the path "/one/two/three". + * + * Two folders (not necessarily on the same level) are identical if they contain the same + * non-empty set of identical subfolders and underlying subfolder structure. The folders do + * not need to be at the root level to be identical. If two or more folders are identical, + * then mark the folders as well as all their subfolders. + * - For example, folders "/a" and "/b" in the file structure below are identical. They (as + * well as their subfolders) should all be marked: + * - /a + * - /a/x + * - /a/x/y + * - /a/z + * - /b + * - /b/x + * - /b/x/y + * - /b/z + * - However, if the file structure also included the path "/b/w", then the folders "/a" and "/b" + * would not be identical. Note that "/a/x" and "/b/x" would still be considered identical + * even with the added folder. + * + * Once all the identical folders and their subfolders have been marked, the file system will delete + * all of them. The file system only runs the deletion once, so any folders that become identical + * after the initial deletion are not deleted. + * + * Return the 2D array ans containing the paths of the remaining folders after deleting all the + * marked folders. The paths may be returned in any order. + */ + +/** + * @param {string[][]} paths + * @return {string[][]} + */ +var deleteDuplicateFolder = function(paths) { + const root = {}; + + for (const path of paths) { + let node = root; + for (const folder of path) { + if (!node[folder]) node[folder] = {}; + node = node[folder]; + } + } + + const structures = new Map(); + + const serialize = (node, path) => { + if (Object.keys(node).length === 0) return ''; + + const folders = []; + const keys = Object.keys(node); + for (const folder of keys) { + const serialized = serialize(node[folder], [...path, folder]); + if (serialized !== null) { + folders.push(`${folder}(${serialized})`); + } else { + delete node[folder]; + } + } + + folders.sort(); + const key = folders.join(''); + + if (key.length > 0) { + if (!structures.has(key)) { + structures.set(key, []); + } + structures.get(key).push(path); + } + + return key; + }; + + serialize(root, []); + + const toDelete = new Set(); + + for (const [structure, paths] of structures.entries()) { + if (paths.length > 1) { + for (const path of paths) { + toDelete.add(path.join('/')); + } + } + } + + const result = []; + + const collectPaths = (node, path) => { + const currentPath = path.join('/'); + if (toDelete.has(currentPath)) return; + + if (path.length > 0) { + result.push([...path]); + } + + const keys = Object.keys(node); + for (const folder of keys) { + collectPaths(node[folder], [...path, folder]); + } + }; + + const rootFolders = Object.keys(root); + for (const folder of rootFolders) { + collectPaths(root[folder], [folder]); + } + + return result; +}; From 21997f0072e1c59872349eababe58c5261bec577 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:35:07 -0500 Subject: [PATCH 143/495] Add solution #1952 --- README.md | 3 ++- solutions/1952-three-divisors.js | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 solutions/1952-three-divisors.js diff --git a/README.md b/README.md index 0ffdb8e1..f5d8cc7d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,647 LeetCode solutions in JavaScript +# 1,648 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1498,6 +1498,7 @@ 1946|[Largest Number After Mutating Substring](./solutions/1946-largest-number-after-mutating-substring.js)|Medium| 1947|[Maximum Compatibility Score Sum](./solutions/1947-maximum-compatibility-score-sum.js)|Medium| 1948|[Delete Duplicate Folders in System](./solutions/1948-delete-duplicate-folders-in-system.js)|Hard| +1952|[Three Divisors](./solutions/1952-three-divisors.js)|Easy| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1952-three-divisors.js b/solutions/1952-three-divisors.js new file mode 100644 index 00000000..c09cf96e --- /dev/null +++ b/solutions/1952-three-divisors.js @@ -0,0 +1,27 @@ +/** + * 1952. Three Divisors + * https://leetcode.com/problems/three-divisors/ + * Difficulty: Easy + * + * Given an integer n, return true if n has exactly three positive divisors. Otherwise, + * return false. + * + * An integer m is a divisor of n if there exists an integer k such that n = k * m. + */ + +/** + * @param {number} n + * @return {boolean} + */ +var isThree = function(n) { + let divisorCount = 0; + + for (let i = 1; i <= n; i++) { + if (n % i === 0) { + divisorCount++; + if (divisorCount > 3) return false; + } + } + + return divisorCount === 3; +}; From 3248f25d5bc5cc557cc8e3742f4b668cd91d724e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:36:33 -0500 Subject: [PATCH 144/495] Add solution #1953 --- README.md | 3 +- ...-number-of-weeks-for-which-you-can-work.js | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 solutions/1953-maximum-number-of-weeks-for-which-you-can-work.js diff --git a/README.md b/README.md index f5d8cc7d..6c0ab7ca 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,648 LeetCode solutions in JavaScript +# 1,649 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1499,6 +1499,7 @@ 1947|[Maximum Compatibility Score Sum](./solutions/1947-maximum-compatibility-score-sum.js)|Medium| 1948|[Delete Duplicate Folders in System](./solutions/1948-delete-duplicate-folders-in-system.js)|Hard| 1952|[Three Divisors](./solutions/1952-three-divisors.js)|Easy| +1953|[Maximum Number of Weeks for Which You Can Work](./solutions/1953-maximum-number-of-weeks-for-which-you-can-work.js)|Medium| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1953-maximum-number-of-weeks-for-which-you-can-work.js b/solutions/1953-maximum-number-of-weeks-for-which-you-can-work.js new file mode 100644 index 00000000..730198a0 --- /dev/null +++ b/solutions/1953-maximum-number-of-weeks-for-which-you-can-work.js @@ -0,0 +1,34 @@ +/** + * 1953. Maximum Number of Weeks for Which You Can Work + * https://leetcode.com/problems/maximum-number-of-weeks-for-which-you-can-work/ + * Difficulty: Medium + * + * There are n projects numbered from 0 to n - 1. You are given an integer array milestones where + * each milestones[i] denotes the number of milestones the ith project has. + * + * You can work on the projects following these two rules: + * - Every week, you will finish exactly one milestone of one project. You must work every week. + * - You cannot work on two milestones from the same project for two consecutive weeks. + * - Once all the milestones of all the projects are finished, or if the only milestones that you + * can work on will cause you to violate the above rules, you will stop working. Note that you + * may not be able to finish every project's milestones due to these constraints. + * + * Return the maximum number of weeks you would be able to work on the projects without violating + * the rules mentioned above. + */ + +/** + * @param {number[]} milestones + * @return {number} + */ +var numberOfWeeks = function(milestones) { + let total = 0; + let maxMilestones = 0; + + for (const count of milestones) { + total += count; + maxMilestones = Math.max(maxMilestones, count); + } + + return Math.min(total, 2 * (total - maxMilestones) + 1); +}; From 4ff217d7d19576841c9db4b40c64b0027ae87687 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 16:37:47 -0500 Subject: [PATCH 145/495] Add solution #1954 --- README.md | 3 +- ...rden-perimeter-to-collect-enough-apples.js | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 solutions/1954-minimum-garden-perimeter-to-collect-enough-apples.js diff --git a/README.md b/README.md index 6c0ab7ca..7566b5c4 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,649 LeetCode solutions in JavaScript +# 1,650 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1500,6 +1500,7 @@ 1948|[Delete Duplicate Folders in System](./solutions/1948-delete-duplicate-folders-in-system.js)|Hard| 1952|[Three Divisors](./solutions/1952-three-divisors.js)|Easy| 1953|[Maximum Number of Weeks for Which You Can Work](./solutions/1953-maximum-number-of-weeks-for-which-you-can-work.js)|Medium| +1954|[Minimum Garden Perimeter to Collect Enough Apples](./solutions/1954-minimum-garden-perimeter-to-collect-enough-apples.js)|Medium| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1954-minimum-garden-perimeter-to-collect-enough-apples.js b/solutions/1954-minimum-garden-perimeter-to-collect-enough-apples.js new file mode 100644 index 00000000..e064083c --- /dev/null +++ b/solutions/1954-minimum-garden-perimeter-to-collect-enough-apples.js @@ -0,0 +1,34 @@ +/** + * 1954. Minimum Garden Perimeter to Collect Enough Apples + * https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/ + * Difficulty: Medium + * + * In a garden represented as an infinite 2D grid, there is an apple tree planted at every + * integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| + * apples growing on it. + * + * You will buy an axis-aligned square plot of land that is centered at (0, 0). + * + * Given an integer neededApples, return the minimum perimeter of a plot such that at least + * neededApples apples are inside or on the perimeter of that plot. + * + * The value of |x| is defined as: + * - x if x >= 0 + * - -x if x < 0 + */ + +/** + * @param {number} neededApples + * @return {number} + */ +var minimumPerimeter = function(neededApples) { + let n = 0; + let totalApples = 0; + + while (totalApples < neededApples) { + n++; + totalApples = 2 * n * (n + 1) * (2 * n + 1); + } + + return 8 * n; +}; From b2fc2c323509f2cbd9d5fe5f634c8cd46377c11a Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 19:12:34 -0500 Subject: [PATCH 146/495] Add solution #1955 --- README.md | 3 +- ...55-count-number-of-special-subsequences.js | 32 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 solutions/1955-count-number-of-special-subsequences.js diff --git a/README.md b/README.md index 7566b5c4..558658a9 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,650 LeetCode solutions in JavaScript +# 1,651 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1501,6 +1501,7 @@ 1952|[Three Divisors](./solutions/1952-three-divisors.js)|Easy| 1953|[Maximum Number of Weeks for Which You Can Work](./solutions/1953-maximum-number-of-weeks-for-which-you-can-work.js)|Medium| 1954|[Minimum Garden Perimeter to Collect Enough Apples](./solutions/1954-minimum-garden-perimeter-to-collect-enough-apples.js)|Medium| +1955|[Count Number of Special Subsequences](./solutions/1955-count-number-of-special-subsequences.js)|Hard| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1955-count-number-of-special-subsequences.js b/solutions/1955-count-number-of-special-subsequences.js new file mode 100644 index 00000000..5daa07ec --- /dev/null +++ b/solutions/1955-count-number-of-special-subsequences.js @@ -0,0 +1,32 @@ +/** + * 1955. Count Number of Special Subsequences + * https://leetcode.com/problems/count-number-of-special-subsequences/ + * Difficulty: Hard + * + * A sequence is special if it consists of a positive number of 0s, followed by a positive number + * of 1s, then a positive number of 2s. + * - For example, [0,1,2] and [0,0,1,1,1,2] are special. + * - In contrast, [2,1,0], [1], and [0,1,2,0] are not special. + * + * Given an array nums (consisting of only integers 0, 1, and 2), return the number of different + * subsequences that are special. Since the answer may be very large, return it modulo 109 + 7. + * + * A subsequence of an array is a sequence that can be derived from the array by deleting some + * or no elements without changing the order of the remaining elements. Two subsequences are + * different if the set of indices chosen are different. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var countSpecialSubsequences = function(nums) { + const MOD = 1e9 + 7; + const dp = [1, 0, 0, 0]; + + for (const num of nums) { + dp[num + 1] = (dp[num + 1] * 2 % MOD + dp[num]) % MOD; + } + + return dp[3]; +}; From ea44e8396fdd81094ee3dfe27bde6cd63a1f8c42 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 19:13:36 -0500 Subject: [PATCH 147/495] Add solution #1957 --- README.md | 3 +- ...-delete-characters-to-make-fancy-string.js | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 solutions/1957-delete-characters-to-make-fancy-string.js diff --git a/README.md b/README.md index 558658a9..4dee8456 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,651 LeetCode solutions in JavaScript +# 1,652 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1502,6 +1502,7 @@ 1953|[Maximum Number of Weeks for Which You Can Work](./solutions/1953-maximum-number-of-weeks-for-which-you-can-work.js)|Medium| 1954|[Minimum Garden Perimeter to Collect Enough Apples](./solutions/1954-minimum-garden-perimeter-to-collect-enough-apples.js)|Medium| 1955|[Count Number of Special Subsequences](./solutions/1955-count-number-of-special-subsequences.js)|Hard| +1957|[Delete Characters to Make Fancy String](./solutions/1957-delete-characters-to-make-fancy-string.js)|Easy| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1957-delete-characters-to-make-fancy-string.js b/solutions/1957-delete-characters-to-make-fancy-string.js new file mode 100644 index 00000000..39c92ece --- /dev/null +++ b/solutions/1957-delete-characters-to-make-fancy-string.js @@ -0,0 +1,36 @@ +/** + * 1957. Delete Characters to Make Fancy String + * https://leetcode.com/problems/delete-characters-to-make-fancy-string/ + * Difficulty: Easy + * + * A fancy string is a string where no three consecutive characters are equal. + * + * Given a string s, delete the minimum possible number of characters from s to make + * it fancy. + * + * Return the final string after the deletion. It can be shown that the answer will + * always be unique. + */ + +/** + * @param {string} s + * @return {string} + */ +var makeFancyString = function(s) { + let result = s[0]; + let count = 1; + + for (let i = 1; i < s.length; i++) { + if (s[i] === s[i - 1]) { + if (count < 2) { + result += s[i]; + count++; + } + } else { + result += s[i]; + count = 1; + } + } + + return result; +}; From d9dd20721b5cf844bce94b9193e2e29e9dbc6259 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 19:14:50 -0500 Subject: [PATCH 148/495] Add solution #1958 --- README.md | 3 +- solutions/1958-check-if-move-is-legal.js | 54 ++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 solutions/1958-check-if-move-is-legal.js diff --git a/README.md b/README.md index 4dee8456..6c987eeb 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,652 LeetCode solutions in JavaScript +# 1,653 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1503,6 +1503,7 @@ 1954|[Minimum Garden Perimeter to Collect Enough Apples](./solutions/1954-minimum-garden-perimeter-to-collect-enough-apples.js)|Medium| 1955|[Count Number of Special Subsequences](./solutions/1955-count-number-of-special-subsequences.js)|Hard| 1957|[Delete Characters to Make Fancy String](./solutions/1957-delete-characters-to-make-fancy-string.js)|Easy| +1958|[Check if Move is Legal](./solutions/1958-check-if-move-is-legal.js)|Medium| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1958-check-if-move-is-legal.js b/solutions/1958-check-if-move-is-legal.js new file mode 100644 index 00000000..7fef6e2a --- /dev/null +++ b/solutions/1958-check-if-move-is-legal.js @@ -0,0 +1,54 @@ +/** + * 1958. Check if Move is Legal + * https://leetcode.com/problems/check-if-move-is-legal/ + * Difficulty: Medium + * + * You are given a 0-indexed 8 x 8 grid board, where board[r][c] represents the cell (r, c) on a + * game board. On the board, free cells are represented by '.', white cells are represented by + * 'W', and black cells are represented by 'B'. + * + * Each move in this game consists of choosing a free cell and changing it to the color you are + * playing as (either white or black). However, a move is only legal if, after changing it, the + * cell becomes the endpoint of a good line (horizontal, vertical, or diagonal). + * + * A good line is a line of three or more cells (including the endpoints) where the endpoints of + * the line are one color, and the remaining cells in the middle are the opposite color (no cells + * in the line are free). You can find examples for good lines in the figure below. + * + * Given two integers rMove and cMove and a character color representing the color you are playing + * as (white or black), return true if changing cell (rMove, cMove) to color color is a legal move, + * or false if it is not legal. + */ + +/** + * @param {character[][]} board + * @param {number} rMove + * @param {number} cMove + * @param {character} color + * @return {boolean} + */ +var checkMove = function(board, rMove, cMove, color) { + const opposite = color === 'B' ? 'W' : 'B'; + const directions = [ + [0, 1], [0, -1], [1, 0], [-1, 0], + [1, 1], [1, -1], [-1, 1], [-1, -1] + ]; + + for (const [dr, dc] of directions) { + let row = rMove + dr; + let col = cMove + dc; + let count = 1; + + while (row >= 0 && row < 8 && col >= 0 && col < 8 && board[row][col] === opposite) { + row += dr; + col += dc; + count++; + } + + if (count >= 2 && row >= 0 && row < 8 && col >= 0 && col < 8 && board[row][col] === color) { + return true; + } + } + + return false; +}; From c51aa48c82200cad6b0e84208c95b61b4c99ff8a Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 19:17:20 -0500 Subject: [PATCH 149/495] Add solution #1959 --- README.md | 3 +- ...space-wasted-with-k-resizing-operations.js | 54 +++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 solutions/1959-minimum-total-space-wasted-with-k-resizing-operations.js diff --git a/README.md b/README.md index 6c987eeb..178d7b95 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,653 LeetCode solutions in JavaScript +# 1,654 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1504,6 +1504,7 @@ 1955|[Count Number of Special Subsequences](./solutions/1955-count-number-of-special-subsequences.js)|Hard| 1957|[Delete Characters to Make Fancy String](./solutions/1957-delete-characters-to-make-fancy-string.js)|Easy| 1958|[Check if Move is Legal](./solutions/1958-check-if-move-is-legal.js)|Medium| +1959|[Minimum Total Space Wasted With K Resizing Operations](./solutions/1959-minimum-total-space-wasted-with-k-resizing-operations.js)|Medium| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1959-minimum-total-space-wasted-with-k-resizing-operations.js b/solutions/1959-minimum-total-space-wasted-with-k-resizing-operations.js new file mode 100644 index 00000000..9576849d --- /dev/null +++ b/solutions/1959-minimum-total-space-wasted-with-k-resizing-operations.js @@ -0,0 +1,54 @@ +/** + * 1959. Minimum Total Space Wasted With K Resizing Operations + * https://leetcode.com/problems/minimum-total-space-wasted-with-k-resizing-operations/ + * Difficulty: Medium + * + * You are currently designing a dynamic array. You are given a 0-indexed integer array nums, + * where nums[i] is the number of elements that will be in the array at time i. In addition, + * you are given an integer k, the maximum number of times you can resize the array (to any size). + * + * The size of the array at time t, sizet, must be at least nums[t] because there needs to be + * enough space in the array to hold all the elements. The space wasted at time t is defined + * as sizet - nums[t], and the total space wasted is the sum of the space wasted across every + * time t where 0 <= t < nums.length. + * + * Return the minimum total space wasted if you can resize the array at most k times. + * + * Note: The array can have any size at the start and does not count towards the number of + * resizing operations. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var minSpaceWastedKResizing = function(nums, k) { + const n = nums.length; + const dp = new Array(n + 1).fill().map(() => new Array(k + 2).fill(Infinity)); + dp[0][0] = 0; + + for (let i = 1; i <= n; i++) { + let maxVal = 0; + let sum = 0; + + for (let j = i; j > 0; j--) { + maxVal = Math.max(maxVal, nums[j - 1]); + sum += nums[j - 1]; + const waste = maxVal * (i - j + 1) - sum; + + for (let resizes = 0; resizes <= k; resizes++) { + if (dp[j - 1][resizes] !== Infinity) { + dp[i][resizes + 1] = Math.min(dp[i][resizes + 1], dp[j - 1][resizes] + waste); + } + } + } + } + + let result = Infinity; + for (let resizes = 1; resizes <= k + 1; resizes++) { + result = Math.min(result, dp[n][resizes]); + } + + return result; +}; From b4001277635bad21f3f00f3426266468e70bb465 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 3 May 2025 19:29:53 -0500 Subject: [PATCH 150/495] Add solution #1960 --- README.md | 3 +- ...he-length-of-two-palindromic-substrings.js | 67 +++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 solutions/1960-maximum-product-of-the-length-of-two-palindromic-substrings.js diff --git a/README.md b/README.md index 178d7b95..1ace0ecb 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,654 LeetCode solutions in JavaScript +# 1,655 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1505,6 +1505,7 @@ 1957|[Delete Characters to Make Fancy String](./solutions/1957-delete-characters-to-make-fancy-string.js)|Easy| 1958|[Check if Move is Legal](./solutions/1958-check-if-move-is-legal.js)|Medium| 1959|[Minimum Total Space Wasted With K Resizing Operations](./solutions/1959-minimum-total-space-wasted-with-k-resizing-operations.js)|Medium| +1960|[Maximum Product of the Length of Two Palindromic Substrings](./solutions/1960-maximum-product-of-the-length-of-two-palindromic-substrings.js)|Hard| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1960-maximum-product-of-the-length-of-two-palindromic-substrings.js b/solutions/1960-maximum-product-of-the-length-of-two-palindromic-substrings.js new file mode 100644 index 00000000..10d34b76 --- /dev/null +++ b/solutions/1960-maximum-product-of-the-length-of-two-palindromic-substrings.js @@ -0,0 +1,67 @@ +/** + * 1960. Maximum Product of the Length of Two Palindromic Substrings + * https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-substrings/ + * Difficulty: Hard + * + * You are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic + * substrings of odd length such that the product of their lengths is maximized. + * + * More formally, you want to choose four integers i, j, k, l such that + * 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l] are palindromes + * and have odd lengths. s[i...j] denotes a substring from index i to index j inclusive. + * + * Return the maximum possible product of the lengths of the two non-intersecting palindromic + * substrings. + * + * A palindrome is a string that is the same forward and backward. A substring is a contiguous + * sequence of characters in a string. + */ + +/** +* @param {string} s +* @return {number} +*/ +var maxProduct = function(s) { + const n = s.length; + const before = new Array(n).fill(0); + const after = new Array(n).fill(0); + + let center = -1; + let right = -1; + const dp = new Array(n).fill(0); + + for (let i = 0; i < n; i++) { + const radius = i <= right ? Math.min(dp[2 * center - i], right - i) : 0; + let left = i - radius; + let rt = i + radius; + + while (left >= 0 && rt < n && s[left] === s[rt]) { + before[rt] = Math.max(before[rt], rt - left + 1); + after[left] = Math.max(after[left], rt - left + 1); + left--; + rt++; + } + + dp[i] = rt - i - 1; + + if (rt - 1 > right) { + center = i; + right = rt - 1; + } + } + + for (let i = 1; i < n; i++) { + before[i] = Math.max(before[i - 1], before[i]); + } + + for (let i = n - 2; i >= 0; i--) { + after[i] = Math.max(after[i + 1], after[i]); + } + + let result = 0; + for (let i = 1; i < n; i++) { + result = Math.max(result, before[i - 1] * after[i]); + } + + return result; +}; From fc9a0b8f6a7fc4548e6e65c5683cc8e0fe9a95fa Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 00:00:30 -0500 Subject: [PATCH 151/495] Add solution #1961 --- README.md | 3 +- ...61-check-if-string-is-a-prefix-of-array.js | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 solutions/1961-check-if-string-is-a-prefix-of-array.js diff --git a/README.md b/README.md index 1ace0ecb..40373c03 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,655 LeetCode solutions in JavaScript +# 1,656 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1506,6 +1506,7 @@ 1958|[Check if Move is Legal](./solutions/1958-check-if-move-is-legal.js)|Medium| 1959|[Minimum Total Space Wasted With K Resizing Operations](./solutions/1959-minimum-total-space-wasted-with-k-resizing-operations.js)|Medium| 1960|[Maximum Product of the Length of Two Palindromic Substrings](./solutions/1960-maximum-product-of-the-length-of-two-palindromic-substrings.js)|Hard| +1961|[Check If String Is a Prefix of Array](./solutions/1961-check-if-string-is-a-prefix-of-array.js)|Easy| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1961-check-if-string-is-a-prefix-of-array.js b/solutions/1961-check-if-string-is-a-prefix-of-array.js new file mode 100644 index 00000000..68aaf4c0 --- /dev/null +++ b/solutions/1961-check-if-string-is-a-prefix-of-array.js @@ -0,0 +1,30 @@ +/** + * 1961. Check If String Is a Prefix of Array + * https://leetcode.com/problems/check-if-string-is-a-prefix-of-array/ + * Difficulty: Easy + * + * Given a string s and an array of strings words, determine whether s is a prefix string of words. + * + * A string s is a prefix string of words if s can be made by concatenating the first k strings in + * words for some positive k no larger than words.length. + * + * Return true if s is a prefix string of words, or false otherwise. + */ + +/** + * @param {string} s + * @param {string[]} words + * @return {boolean} + */ +var isPrefixString = function(s, words) { + let currentIndex = 0; + + for (const word of words) { + if (currentIndex + word.length > s.length) return false; + if (s.slice(currentIndex, currentIndex + word.length) !== word) return false; + currentIndex += word.length; + if (currentIndex === s.length) return true; + } + + return false; +}; From 9bbe0e7248ea5028e97dcee47fe1886012b03f6e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 00:02:45 -0500 Subject: [PATCH 152/495] Add solution #1963 --- README.md | 3 +- ...er-of-swaps-to-make-the-string-balanced.js | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 solutions/1963-minimum-number-of-swaps-to-make-the-string-balanced.js diff --git a/README.md b/README.md index 40373c03..3f4e6399 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,656 LeetCode solutions in JavaScript +# 1,657 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1507,6 +1507,7 @@ 1959|[Minimum Total Space Wasted With K Resizing Operations](./solutions/1959-minimum-total-space-wasted-with-k-resizing-operations.js)|Medium| 1960|[Maximum Product of the Length of Two Palindromic Substrings](./solutions/1960-maximum-product-of-the-length-of-two-palindromic-substrings.js)|Hard| 1961|[Check If String Is a Prefix of Array](./solutions/1961-check-if-string-is-a-prefix-of-array.js)|Easy| +1963|[Minimum Number of Swaps to Make the String Balanced](./solutions/1963-minimum-number-of-swaps-to-make-the-string-balanced.js)|Medium| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1963-minimum-number-of-swaps-to-make-the-string-balanced.js b/solutions/1963-minimum-number-of-swaps-to-make-the-string-balanced.js new file mode 100644 index 00000000..2f687a52 --- /dev/null +++ b/solutions/1963-minimum-number-of-swaps-to-make-the-string-balanced.js @@ -0,0 +1,37 @@ +/** + * 1963. Minimum Number of Swaps to Make the String Balanced + * https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/ + * Difficulty: Medium + * + * You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening + * brackets '[' and n / 2 closing brackets ']'. + * + * A string is called balanced if and only if: + * - It is the empty string, or + * - It can be written as AB, where both A and B are balanced strings, or + * - It can be written as [C], where C is a balanced string. + * + * You may swap the brackets at any two indices any number of times. + * + * Return the minimum number of swaps to make s balanced. + */ + +/** + * @param {string} s + * @return {number} + */ +var minSwaps = function(s) { + let imbalance = 0; + let maxImbalance = 0; + + for (const bracket of s) { + if (bracket === '[') { + imbalance--; + } else { + imbalance++; + maxImbalance = Math.max(maxImbalance, imbalance); + } + } + + return Math.ceil(maxImbalance / 2); +}; From d33a05e66757739f082b097067f8f6bd654d7158 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 00:04:50 -0500 Subject: [PATCH 153/495] Add solution #1964 --- README.md | 3 +- ...-valid-obstacle-course-at-each-position.js | 54 +++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 solutions/1964-find-the-longest-valid-obstacle-course-at-each-position.js diff --git a/README.md b/README.md index 3f4e6399..84573839 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,657 LeetCode solutions in JavaScript +# 1,658 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1508,6 +1508,7 @@ 1960|[Maximum Product of the Length of Two Palindromic Substrings](./solutions/1960-maximum-product-of-the-length-of-two-palindromic-substrings.js)|Hard| 1961|[Check If String Is a Prefix of Array](./solutions/1961-check-if-string-is-a-prefix-of-array.js)|Easy| 1963|[Minimum Number of Swaps to Make the String Balanced](./solutions/1963-minimum-number-of-swaps-to-make-the-string-balanced.js)|Medium| +1964|[Find the Longest Valid Obstacle Course at Each Position](./solutions/1964-find-the-longest-valid-obstacle-course-at-each-position.js)|Hard| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1964-find-the-longest-valid-obstacle-course-at-each-position.js b/solutions/1964-find-the-longest-valid-obstacle-course-at-each-position.js new file mode 100644 index 00000000..cafb25a7 --- /dev/null +++ b/solutions/1964-find-the-longest-valid-obstacle-course-at-each-position.js @@ -0,0 +1,54 @@ +/** + * 1964. Find the Longest Valid Obstacle Course at Each Position + * https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position/ + * Difficulty: Hard + * + * You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of + * length n, where obstacles[i] describes the height of the ith obstacle. + * + * For every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle + * course in obstacles such that: + * - You choose any number of obstacles between 0 and i inclusive. + * - You must include the ith obstacle in the course. + * - You must put the chosen obstacles in the same order as they appear in obstacles. + * - Every obstacle (except the first) is taller than or the same height as the obstacle immediately + * before it. + * + * Return an array ans of length n, where ans[i] is the length of the longest obstacle course for + * index i as described above. + */ + +/** + * @param {number[]} obstacles + * @return {number[]} + */ +var longestObstacleCourseAtEachPosition = function(obstacles) { + const n = obstacles.length; + const result = new Array(n).fill(1); + const stack = []; + + for (let i = 0; i < n; i++) { + const height = obstacles[i]; + let left = 0; + let right = stack.length; + + while (left < right) { + const mid = Math.floor((left + right) / 2); + if (stack[mid] <= height) { + left = mid + 1; + } else { + right = mid; + } + } + + if (left < stack.length) { + stack[left] = height; + } else { + stack.push(height); + } + + result[i] = left + 1; + } + + return result; +}; From a89bca620cce7bd4409090c9ab2a393903805181 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 00:05:57 -0500 Subject: [PATCH 154/495] Add solution #1967 --- README.md | 3 ++- ...rings-that-appear-as-substrings-in-word.js | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 solutions/1967-number-of-strings-that-appear-as-substrings-in-word.js diff --git a/README.md b/README.md index 84573839..2e7cc313 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,658 LeetCode solutions in JavaScript +# 1,659 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1509,6 +1509,7 @@ 1961|[Check If String Is a Prefix of Array](./solutions/1961-check-if-string-is-a-prefix-of-array.js)|Easy| 1963|[Minimum Number of Swaps to Make the String Balanced](./solutions/1963-minimum-number-of-swaps-to-make-the-string-balanced.js)|Medium| 1964|[Find the Longest Valid Obstacle Course at Each Position](./solutions/1964-find-the-longest-valid-obstacle-course-at-each-position.js)|Hard| +1967|[Number of Strings That Appear as Substrings in Word](./solutions/1967-number-of-strings-that-appear-as-substrings-in-word.js)|Easy| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1967-number-of-strings-that-appear-as-substrings-in-word.js b/solutions/1967-number-of-strings-that-appear-as-substrings-in-word.js new file mode 100644 index 00000000..b0cb45d5 --- /dev/null +++ b/solutions/1967-number-of-strings-that-appear-as-substrings-in-word.js @@ -0,0 +1,19 @@ +/** + * 1967. Number of Strings That Appear as Substrings in Word + * https://leetcode.com/problems/number-of-strings-that-appear-as-substrings-in-word/ + * Difficulty: Easy + * + * Given an array of strings patterns and a string word, return the number of strings in patterns + * that exist as a substring in word. + * + * A substring is a contiguous sequence of characters within a string. + */ + +/** + * @param {string[]} patterns + * @param {string} word + * @return {number} + */ +var numOfStrings = function(patterns, word) { + return patterns.reduce((count, pattern) => word.includes(pattern) ? count + 1 : count, 0); +}; From f641f033a2f7fda6466d1e7e51dd097500c5d787 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 00:08:32 -0500 Subject: [PATCH 155/495] Add solution #1968 --- README.md | 3 +- ...ments-not-equal-to-average-of-neighbors.js | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 solutions/1968-array-with-elements-not-equal-to-average-of-neighbors.js diff --git a/README.md b/README.md index 2e7cc313..26e94dcb 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,659 LeetCode solutions in JavaScript +# 1,660 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1510,6 +1510,7 @@ 1963|[Minimum Number of Swaps to Make the String Balanced](./solutions/1963-minimum-number-of-swaps-to-make-the-string-balanced.js)|Medium| 1964|[Find the Longest Valid Obstacle Course at Each Position](./solutions/1964-find-the-longest-valid-obstacle-course-at-each-position.js)|Hard| 1967|[Number of Strings That Appear as Substrings in Word](./solutions/1967-number-of-strings-that-appear-as-substrings-in-word.js)|Easy| +1968|[Array With Elements Not Equal to Average of Neighbors](./solutions/1968-array-with-elements-not-equal-to-average-of-neighbors.js)|Medium| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1968-array-with-elements-not-equal-to-average-of-neighbors.js b/solutions/1968-array-with-elements-not-equal-to-average-of-neighbors.js new file mode 100644 index 00000000..67994987 --- /dev/null +++ b/solutions/1968-array-with-elements-not-equal-to-average-of-neighbors.js @@ -0,0 +1,29 @@ +/** + * 1968. Array With Elements Not Equal to Average of Neighbors + * https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/ + * Difficulty: Medium + * + * You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements + * in the array such that every element in the rearranged array is not equal to the average of + * its neighbors. + * + * More formally, the rearranged array should have the property such that for every i in the + * range 1 <= i < nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i]. + * + * Return any rearrangement of nums that meets the requirements. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var rearrangeArray = function(nums) { + const result = new Array(nums.length); + nums.sort((a, b) => a - b); + + for (let i = 0, left = 0, right = nums.length - 1; i < nums.length; i++) { + result[i] = i % 2 === 0 ? nums[left++] : nums[right--]; + } + + return result; +}; From 6038173edd94cab81809309c13bea2c4ea164a68 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 00:11:24 -0500 Subject: [PATCH 156/495] Add solution #1969 --- README.md | 3 +- ...-non-zero-product-of-the-array-elements.js | 44 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 solutions/1969-minimum-non-zero-product-of-the-array-elements.js diff --git a/README.md b/README.md index 26e94dcb..f098cc07 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,660 LeetCode solutions in JavaScript +# 1,661 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1511,6 +1511,7 @@ 1964|[Find the Longest Valid Obstacle Course at Each Position](./solutions/1964-find-the-longest-valid-obstacle-course-at-each-position.js)|Hard| 1967|[Number of Strings That Appear as Substrings in Word](./solutions/1967-number-of-strings-that-appear-as-substrings-in-word.js)|Easy| 1968|[Array With Elements Not Equal to Average of Neighbors](./solutions/1968-array-with-elements-not-equal-to-average-of-neighbors.js)|Medium| +1969|[Minimum Non-Zero Product of the Array Elements](./solutions/1969-minimum-non-zero-product-of-the-array-elements.js)|Medium| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1969-minimum-non-zero-product-of-the-array-elements.js b/solutions/1969-minimum-non-zero-product-of-the-array-elements.js new file mode 100644 index 00000000..9165df8e --- /dev/null +++ b/solutions/1969-minimum-non-zero-product-of-the-array-elements.js @@ -0,0 +1,44 @@ +/** + * 1969. Minimum Non-Zero Product of the Array Elements + * https://leetcode.com/problems/minimum-non-zero-product-of-the-array-elements/ + * Difficulty: Medium + * + * You are given a positive integer p. Consider an array nums (1-indexed) that consists of the + * integers in the inclusive range [1, 2p - 1] in their binary representations. You are allowed + * to do the following operation any number of times: + * - Choose two elements x and y from nums. + * - Choose a bit in x and swap it with its corresponding bit in y. Corresponding bit refers to + * the bit that is in the same position in the other integer. + * + * For example, if x = 1101 and y = 0011, after swapping the 2nd bit from the right, we have + * x = 1111 and y = 0001. + * + * Find the minimum non-zero product of nums after performing the above operation any number + * of times. Return this product modulo 109 + 7. + * + * Note: The answer should be the minimum product before the modulo operation is done. + */ + +/** + * @param {number} p + * @return {number} + */ +var minNonZeroProduct = function(p) { + const MOD = 1000000007n; + const maxVal = (1n << BigInt(p)) - 1n; + const halfCount = (maxVal - 1n) / 2n; + const base = maxVal - 1n; + + function pow(base, exp, mod) { + let result = 1n; + base = base % mod; + while (exp > 0n) { + if (exp & 1n) result = (result * base) % mod; + base = (base * base) % mod; + exp >>= 1n; + } + return result; + } + + return Number((maxVal * pow(base, halfCount, MOD)) % MOD); +}; From 9172ee7d156e1f366ad24434e1ff79bb206819a1 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 00:12:56 -0500 Subject: [PATCH 157/495] Add solution #1970 --- README.md | 3 +- ...1970-last-day-where-you-can-still-cross.js | 78 +++++++++++++++++++ 2 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 solutions/1970-last-day-where-you-can-still-cross.js diff --git a/README.md b/README.md index f098cc07..1e483ebd 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,661 LeetCode solutions in JavaScript +# 1,662 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1512,6 +1512,7 @@ 1967|[Number of Strings That Appear as Substrings in Word](./solutions/1967-number-of-strings-that-appear-as-substrings-in-word.js)|Easy| 1968|[Array With Elements Not Equal to Average of Neighbors](./solutions/1968-array-with-elements-not-equal-to-average-of-neighbors.js)|Medium| 1969|[Minimum Non-Zero Product of the Array Elements](./solutions/1969-minimum-non-zero-product-of-the-array-elements.js)|Medium| +1970|[Last Day Where You Can Still Cross](./solutions/1970-last-day-where-you-can-still-cross.js)|Hard| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1970-last-day-where-you-can-still-cross.js b/solutions/1970-last-day-where-you-can-still-cross.js new file mode 100644 index 00000000..7b36cd06 --- /dev/null +++ b/solutions/1970-last-day-where-you-can-still-cross.js @@ -0,0 +1,78 @@ +/** + * 1970. Last Day Where You Can Still Cross + * https://leetcode.com/problems/last-day-where-you-can-still-cross/ + * Difficulty: Hard + * + * There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given + * integers row and col representing the number of rows and columns in the matrix, respectively. + * + * Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded + * with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that + * on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered + * with water (i.e., changed to 1). + * + * You want to find the last day that it is possible to walk from the top to the bottom by only + * walking on land cells. You can start from any cell in the top row and end at any cell in the + * bottom row. You can only travel in the four cardinal directions (left, right, up, and down). + * + * Return the last day where it is possible to walk from the top to the bottom by only walking + * on land cells. + */ + +/** + * @param {number} row + * @param {number} col + * @param {number[][]} cells + * @return {number} + */ +var latestDayToCross = function(row, col, cells) { + const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; + let left = 1; + let right = cells.length; + let result = 0; + + while (left <= right) { + const mid = Math.floor((left + right) / 2); + if (canCross(mid)) { + result = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + + return result; + + function canCross(day) { + const grid = new Array(row).fill().map(() => new Array(col).fill(0)); + for (let i = 0; i < day; i++) { + const [r, c] = cells[i]; + grid[r - 1][c - 1] = 1; + } + + const queue = []; + const visited = new Array(row).fill().map(() => new Array(col).fill(false)); + + for (let c = 0; c < col; c++) { + if (grid[0][c] === 0) { + queue.push([0, c]); + visited[0][c] = true; + } + } + + while (queue.length) { + const [r, c] = queue.shift(); + if (r === row - 1) return true; + + for (const [dr, dc] of directions) { + const nr = r + dr; + const nc = c + dc; + if (nr >= 0 && nr < row && nc >= 0 && nc < col && !visited[nr][nc] && grid[nr][nc] === 0) { + queue.push([nr, nc]); + visited[nr][nc] = true; + } + } + } + return false; + } +}; From 86677bd33bf32c0f17c7a724f1f811ce2d347ac5 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 00:13:58 -0500 Subject: [PATCH 158/495] Add solution #1971 --- README.md | 3 +- .../1971-find-if-path-exists-in-graph.js | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 solutions/1971-find-if-path-exists-in-graph.js diff --git a/README.md b/README.md index 1e483ebd..f22aa320 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,662 LeetCode solutions in JavaScript +# 1,663 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1513,6 +1513,7 @@ 1968|[Array With Elements Not Equal to Average of Neighbors](./solutions/1968-array-with-elements-not-equal-to-average-of-neighbors.js)|Medium| 1969|[Minimum Non-Zero Product of the Array Elements](./solutions/1969-minimum-non-zero-product-of-the-array-elements.js)|Medium| 1970|[Last Day Where You Can Still Cross](./solutions/1970-last-day-where-you-can-still-cross.js)|Hard| +1971|[Find if Path Exists in Graph](./solutions/1971-find-if-path-exists-in-graph.js)|Easy| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1971-find-if-path-exists-in-graph.js b/solutions/1971-find-if-path-exists-in-graph.js new file mode 100644 index 00000000..4b032666 --- /dev/null +++ b/solutions/1971-find-if-path-exists-in-graph.js @@ -0,0 +1,50 @@ +/** + * 1971. Find if Path Exists in Graph + * https://leetcode.com/problems/find-if-path-exists-in-graph/ + * Difficulty: Easy + * + * There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to + * n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, + * where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and + * vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an + * edge to itself. + * + * You want to determine if there is a valid path that exists from vertex source to vertex + * destination. + * + * Given edges and the integers n, source, and destination, return true if there is a valid + * path from source to destination, or false otherwise. + */ + +/** + * @param {number} n + * @param {number[][]} edges + * @param {number} source + * @param {number} destination + * @return {boolean} + */ +var validPath = function(n, edges, source, destination) { + const graph = Array.from({ length: n }, () => []); + for (const [u, v] of edges) { + graph[u].push(v); + graph[v].push(u); + } + + const visited = new Set(); + const queue = [source]; + + while (queue.length) { + const vertex = queue.shift(); + if (vertex === destination) return true; + if (visited.has(vertex)) continue; + visited.add(vertex); + + for (const neighbor of graph[vertex]) { + if (!visited.has(neighbor)) { + queue.push(neighbor); + } + } + } + + return false; +}; From 7688c986a6089165a3f33e7aa6b3c615ebc49de2 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 00:15:33 -0500 Subject: [PATCH 159/495] Add solution #1974 --- README.md | 3 +- ...e-to-type-word-using-special-typewriter.js | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 solutions/1974-minimum-time-to-type-word-using-special-typewriter.js diff --git a/README.md b/README.md index f22aa320..af6b5cdd 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,663 LeetCode solutions in JavaScript +# 1,664 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1514,6 +1514,7 @@ 1969|[Minimum Non-Zero Product of the Array Elements](./solutions/1969-minimum-non-zero-product-of-the-array-elements.js)|Medium| 1970|[Last Day Where You Can Still Cross](./solutions/1970-last-day-where-you-can-still-cross.js)|Hard| 1971|[Find if Path Exists in Graph](./solutions/1971-find-if-path-exists-in-graph.js)|Easy| +1974|[Minimum Time to Type Word Using Special Typewriter](./solutions/1974-minimum-time-to-type-word-using-special-typewriter.js)|Easy| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1974-minimum-time-to-type-word-using-special-typewriter.js b/solutions/1974-minimum-time-to-type-word-using-special-typewriter.js new file mode 100644 index 00000000..9c1641e7 --- /dev/null +++ b/solutions/1974-minimum-time-to-type-word-using-special-typewriter.js @@ -0,0 +1,34 @@ +/** + * 1974. Minimum Time to Type Word Using Special Typewriter + * https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter/ + * Difficulty: Easy + * + * There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle + * with a pointer. A character can only be typed if the pointer is pointing to that character. + * The pointer is initially pointing to the character 'a'. + * + * Each second, you may perform one of the following operations: + * - Move the pointer one character counterclockwise or clockwise. + * - Type the character the pointer is currently on. + * + * Given a string word, return the minimum number of seconds to type out the characters in word. + */ + +/** + * @param {string} word + * @return {number} + */ +var minTimeToType = function(word) { + let position = 'a'; + let result = 0; + + for (const char of word) { + const clockwise = Math.abs(char.charCodeAt(0) - position.charCodeAt(0)); + const counterclockwise = 26 - clockwise; + const moves = Math.min(clockwise, counterclockwise); + result += moves + 1; + position = char; + } + + return result; +}; From f4f38cee0f3ab5b4ccedce0a3470d94c46b41a23 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 00:16:27 -0500 Subject: [PATCH 160/495] Add solution #1975 --- README.md | 3 ++- solutions/1975-maximum-matrix-sum.js | 33 ++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 solutions/1975-maximum-matrix-sum.js diff --git a/README.md b/README.md index af6b5cdd..a08be358 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,664 LeetCode solutions in JavaScript +# 1,665 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1515,6 +1515,7 @@ 1970|[Last Day Where You Can Still Cross](./solutions/1970-last-day-where-you-can-still-cross.js)|Hard| 1971|[Find if Path Exists in Graph](./solutions/1971-find-if-path-exists-in-graph.js)|Easy| 1974|[Minimum Time to Type Word Using Special Typewriter](./solutions/1974-minimum-time-to-type-word-using-special-typewriter.js)|Easy| +1975|[Maximum Matrix Sum](./solutions/1975-maximum-matrix-sum.js)|Medium| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| diff --git a/solutions/1975-maximum-matrix-sum.js b/solutions/1975-maximum-matrix-sum.js new file mode 100644 index 00000000..92b65dd2 --- /dev/null +++ b/solutions/1975-maximum-matrix-sum.js @@ -0,0 +1,33 @@ +/** + * 1975. Maximum Matrix Sum + * https://leetcode.com/problems/maximum-matrix-sum/ + * Difficulty: Medium + * + * You are given an n x n integer matrix. You can do the following operation any number of times: + * - Choose any two adjacent elements of matrix and multiply each of them by -1. + * + * Two elements are considered adjacent if and only if they share a border. + * + * Your goal is to maximize the summation of the matrix's elements. Return the maximum sum of the + * matrix's elements using the operation mentioned above. + */ + +/** + * @param {number[][]} matrix + * @return {number} + */ +var maxMatrixSum = function(matrix) { + let totalSum = 0; + let negativeCount = 0; + let minAbs = Infinity; + + for (const row of matrix) { + for (const num of row) { + totalSum += Math.abs(num); + if (num < 0) negativeCount++; + minAbs = Math.min(minAbs, Math.abs(num)); + } + } + + return negativeCount % 2 === 0 ? totalSum : totalSum - 2 * minAbs; +}; From 4e3d96caae986df9ae979f9c9ff83a39107fe22a Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 00:29:38 -0500 Subject: [PATCH 161/495] Add solution #1977 --- README.md | 3 +- ...1977-number-of-ways-to-separate-numbers.js | 77 +++++++++++++++++++ 2 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 solutions/1977-number-of-ways-to-separate-numbers.js diff --git a/README.md b/README.md index a08be358..238f9a69 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,665 LeetCode solutions in JavaScript +# 1,666 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1517,6 +1517,7 @@ 1974|[Minimum Time to Type Word Using Special Typewriter](./solutions/1974-minimum-time-to-type-word-using-special-typewriter.js)|Easy| 1975|[Maximum Matrix Sum](./solutions/1975-maximum-matrix-sum.js)|Medium| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| +1977|[Number of Ways to Separate Numbers](./solutions/1977-number-of-ways-to-separate-numbers.js)|Hard| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| 1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium| diff --git a/solutions/1977-number-of-ways-to-separate-numbers.js b/solutions/1977-number-of-ways-to-separate-numbers.js new file mode 100644 index 00000000..6fad6b5d --- /dev/null +++ b/solutions/1977-number-of-ways-to-separate-numbers.js @@ -0,0 +1,77 @@ +/** + * 1977. Number of Ways to Separate Numbers + * https://leetcode.com/problems/number-of-ways-to-separate-numbers/ + * Difficulty: Hard + * + * You wrote down many positive integers in a string called num. However, you realized that you + * forgot to add commas to seperate the different numbers. You remember that the list of integers + * was non-decreasing and that no integer had leading zeros. + * + * Return the number of possible lists of integers that you could have written down to get the + * string num. Since the answer may be large, return it modulo 109 + 7. + */ + +/** + * @param {string} num + * @return {number} + */ +var numberOfCombinations = function(num) { + const n = num.length; + if (num[0] === '0') return 0; + + const MOD = 1e9 + 7; + const lcp = new Array(n + 1).fill().map(() => new Array(n + 1).fill(0)); + + for (let i = n - 1; i >= 0; i--) { + for (let j = n - 1; j >= 0; j--) { + if (num[i] === num[j]) { + lcp[i][j] = lcp[i + 1][j + 1] + 1; + } + } + } + + const dp = new Array(n).fill().map(() => new Array(n + 1).fill(0)); + const prefixSum = new Array(n).fill().map(() => new Array(n + 1).fill(0)); + + dp[0][1] = 1; + prefixSum[0][1] = 1; + + for (let i = 1; i < n; i++) { + for (let j = 1; j <= i; j++) { + prefixSum[i - 1][j] = (prefixSum[i - 1][j - 1] + dp[i - 1][j]) % MOD; + } + + for (let len = 1; len <= i + 1; len++) { + if (num[i - len + 1] === '0') continue; + + if (i - len < 0) { + dp[i][len] = 1; + continue; + } + + dp[i][len] = prefixSum[i - len][Math.min(i - len + 1, len)]; + + if (len <= i - len + 1) { + const start1 = i - 2 * len + 1; + const start2 = i - len + 1; + + if (!compare(start1, start2, len)) { + dp[i][len] = (dp[i][len] - dp[i - len][len] + MOD) % MOD; + } + } + } + + prefixSum[i][0] = 0; + for (let j = 1; j <= i + 1; j++) { + prefixSum[i][j] = (prefixSum[i][j - 1] + dp[i][j]) % MOD; + } + } + + return prefixSum[n - 1][n]; + + function compare(i1, i2, len) { + const commonLen = lcp[i1][i2]; + if (commonLen >= len) return true; + return i1 + commonLen < n && i2 + commonLen < n && num[i1 + commonLen] <= num[i2 + commonLen]; + } +}; From b47b95d5a99caf905a0f13c8f48cd5bca8a69974 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 00:31:09 -0500 Subject: [PATCH 162/495] Add solution #1979 --- README.md | 3 ++- ...9-find-greatest-common-divisor-of-array.js | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 solutions/1979-find-greatest-common-divisor-of-array.js diff --git a/README.md b/README.md index 238f9a69..a7e8f520 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,666 LeetCode solutions in JavaScript +# 1,667 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1518,6 +1518,7 @@ 1975|[Maximum Matrix Sum](./solutions/1975-maximum-matrix-sum.js)|Medium| 1976|[Number of Ways to Arrive at Destination](./solutions/1976-number-of-ways-to-arrive-at-destination.js)|Medium| 1977|[Number of Ways to Separate Numbers](./solutions/1977-number-of-ways-to-separate-numbers.js)|Hard| +1979|[Find Greatest Common Divisor of Array](./solutions/1979-find-greatest-common-divisor-of-array.js)|Easy| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| 1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium| diff --git a/solutions/1979-find-greatest-common-divisor-of-array.js b/solutions/1979-find-greatest-common-divisor-of-array.js new file mode 100644 index 00000000..acf2c5df --- /dev/null +++ b/solutions/1979-find-greatest-common-divisor-of-array.js @@ -0,0 +1,23 @@ +/** + * 1979. Find Greatest Common Divisor of Array + * https://leetcode.com/problems/find-greatest-common-divisor-of-array/ + * Difficulty: Easy + * + * Given an integer array nums, return the greatest common divisor of the smallest number and + * largest number in nums. + * + * The greatest common divisor of two numbers is the largest positive integer that evenly + * divides both numbers. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findGCD = function(nums) { + return gcd(Math.min(...nums), Math.max(...nums)); + + function gcd(a, b) { + return b === 0 ? a : gcd(b, a % b); + } +}; From 88c86e94c3a53ed597e30006e4c8e77c2d4ca173 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 00:32:24 -0500 Subject: [PATCH 163/495] Add solution #1981 --- README.md | 3 +- ...ence-between-target-and-chosen-elements.js | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 solutions/1981-minimize-the-difference-between-target-and-chosen-elements.js diff --git a/README.md b/README.md index a7e8f520..76266be7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,667 LeetCode solutions in JavaScript +# 1,668 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1520,6 +1520,7 @@ 1977|[Number of Ways to Separate Numbers](./solutions/1977-number-of-ways-to-separate-numbers.js)|Hard| 1979|[Find Greatest Common Divisor of Array](./solutions/1979-find-greatest-common-divisor-of-array.js)|Easy| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| +1981|[Minimize the Difference Between Target and Chosen Elements](./solutions/1981-minimize-the-difference-between-target-and-chosen-elements.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| 1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium| 2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| diff --git a/solutions/1981-minimize-the-difference-between-target-and-chosen-elements.js b/solutions/1981-minimize-the-difference-between-target-and-chosen-elements.js new file mode 100644 index 00000000..6e66a493 --- /dev/null +++ b/solutions/1981-minimize-the-difference-between-target-and-chosen-elements.js @@ -0,0 +1,45 @@ +/** + * 1981. Minimize the Difference Between Target and Chosen Elements + * https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/ + * Difficulty: Medium + * + * You are given an m x n integer matrix mat and an integer target. + * + * Choose one integer from each row in the matrix such that the absolute difference between + * target and the sum of the chosen elements is minimized. + * + * Return the minimum absolute difference. + * + * The absolute difference between two numbers a and b is the absolute value of a - b. + */ + +/** + * @param {number[][]} mat + * @param {number} target + * @return {number} + */ +var minimizeTheDifference = function(mat, target) { + const m = mat.length; + const maxSum = 70 * m; + let possibleSums = new Set([0]); + + for (const row of mat) { + const nextSums = new Set(); + for (const num of row) { + for (const sum of possibleSums) { + const newSum = sum + num; + if (newSum <= target + maxSum) { + nextSums.add(newSum); + } + } + } + possibleSums = nextSums; + } + + let result = Infinity; + for (const sum of possibleSums) { + result = Math.min(result, Math.abs(sum - target)); + } + + return result; +}; From 7693c48dea85c6290839427fb21ad9d8d2b59c15 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 00:38:52 -0500 Subject: [PATCH 164/495] Add solution #1982 --- README.md | 3 +- .../1982-find-array-given-subset-sums.js | 63 +++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 solutions/1982-find-array-given-subset-sums.js diff --git a/README.md b/README.md index 76266be7..b9dc569b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,668 LeetCode solutions in JavaScript +# 1,669 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1521,6 +1521,7 @@ 1979|[Find Greatest Common Divisor of Array](./solutions/1979-find-greatest-common-divisor-of-array.js)|Easy| 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1981|[Minimize the Difference Between Target and Chosen Elements](./solutions/1981-minimize-the-difference-between-target-and-chosen-elements.js)|Medium| +1982|[Find Array Given Subset Sums](./solutions/1982-find-array-given-subset-sums.js)|Hard| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| 1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium| 2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| diff --git a/solutions/1982-find-array-given-subset-sums.js b/solutions/1982-find-array-given-subset-sums.js new file mode 100644 index 00000000..da9ab09f --- /dev/null +++ b/solutions/1982-find-array-given-subset-sums.js @@ -0,0 +1,63 @@ +/** + * 1982. Find Array Given Subset Sums + * https://leetcode.com/problems/find-array-given-subset-sums/ + * Difficulty: Hard + * + * You are given an integer n representing the length of an unknown array that you are trying + * to recover. You are also given an array sums containing the values of all 2n subset sums of + * the unknown array (in no particular order). + * + * Return the array ans of length n representing the unknown array. If multiple answers exist, + * return any of them. + * + * An array sub is a subset of an array arr if sub can be obtained from arr by deleting some + * (possibly zero or all) elements of arr. The sum of the elements in sub is one possible + * subset sum of arr. The sum of an empty array is considered to be 0. + * + * Note: Test cases are generated such that there will always be at least one correct answer. + */ + +/** +* @param {number} n +* @param {number[]} sums +* @return {number[]} +*/ +var recoverArray = function(n, sums) { + sums.sort((a, b) => a - b); + + const result = []; + while (result.length < n) { + const diff = sums[1] - sums[0]; + + const withNum = []; + const withoutNum = []; + const freq = new Map(); + for (const sum of sums) { + freq.set(sum, (freq.get(sum) || 0) + 1); + } + + for (const sum of sums) { + if (freq.get(sum) > 0) { + freq.set(sum, freq.get(sum) - 1); + + if (freq.get(sum + diff) > 0) { + freq.set(sum + diff, freq.get(sum + diff) - 1); + withoutNum.push(sum); + withNum.push(sum + diff); + } else { + return []; + } + } + } + + if (withoutNum.includes(0)) { + result.push(diff); + sums = withoutNum; + } else { + result.push(-diff); + sums = withNum; + } + } + + return result; +}; From 4bd6143272d11ebaa57da88f5653fa85f3c7a93f Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 00:40:04 -0500 Subject: [PATCH 165/495] Add solution #1984 --- README.md | 3 +- ...-between-highest-and-lowest-of-k-scores.js | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 solutions/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js diff --git a/README.md b/README.md index b9dc569b..944b55b0 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,669 LeetCode solutions in JavaScript +# 1,670 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1522,6 +1522,7 @@ 1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium| 1981|[Minimize the Difference Between Target and Chosen Elements](./solutions/1981-minimize-the-difference-between-target-and-chosen-elements.js)|Medium| 1982|[Find Array Given Subset Sums](./solutions/1982-find-array-given-subset-sums.js)|Hard| +1984|[Minimum Difference Between Highest and Lowest of K Scores](./solutions/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js)|Easy| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| 1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium| 2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| diff --git a/solutions/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js b/solutions/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js new file mode 100644 index 00000000..889aae95 --- /dev/null +++ b/solutions/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js @@ -0,0 +1,29 @@ +/** + * 1984. Minimum Difference Between Highest and Lowest of K Scores + * https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/ + * Difficulty: Easy + * + * You are given a 0-indexed integer array nums, where nums[i] represents the score of the + * ith student. You are also given an integer k. + * + * Pick the scores of any k students from the array so that the difference between the highest + * and the lowest of the k scores is minimized. + * + * Return the minimum possible difference. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var minimumDifference = function(nums, k) { + nums.sort((a, b) => a - b); + let result = Infinity; + + for (let i = 0; i <= nums.length - k; i++) { + result = Math.min(result, nums[i + k - 1] - nums[i]); + } + + return result; +}; From 95ce1f6e7bbeb3ee89dce699e2dfcfcff5d0798c Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 16:00:57 -0500 Subject: [PATCH 166/495] Add solution #1986 --- README.md | 3 +- ...er-of-work-sessions-to-finish-the-tasks.js | 59 +++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 solutions/1986-minimum-number-of-work-sessions-to-finish-the-tasks.js diff --git a/README.md b/README.md index 944b55b0..e4fde28a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,670 LeetCode solutions in JavaScript +# 1,671 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1524,6 +1524,7 @@ 1982|[Find Array Given Subset Sums](./solutions/1982-find-array-given-subset-sums.js)|Hard| 1984|[Minimum Difference Between Highest and Lowest of K Scores](./solutions/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js)|Easy| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| +1986|[Minimum Number of Work Sessions to Finish the Tasks](./solutions/1986-minimum-number-of-work-sessions-to-finish-the-tasks.js)|Medium| 1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium| 2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| diff --git a/solutions/1986-minimum-number-of-work-sessions-to-finish-the-tasks.js b/solutions/1986-minimum-number-of-work-sessions-to-finish-the-tasks.js new file mode 100644 index 00000000..f6174274 --- /dev/null +++ b/solutions/1986-minimum-number-of-work-sessions-to-finish-the-tasks.js @@ -0,0 +1,59 @@ +/** + * 1986. Minimum Number of Work Sessions to Finish the Tasks + * https://leetcode.com/problems/minimum-number-of-work-sessions-to-finish-the-tasks/ + * Difficulty: Medium + * + * There are n tasks assigned to you. The task times are represented as an integer array tasks of + * length n, where the ith task takes tasks[i] hours to finish. A work session is when you work + * for at most sessionTime consecutive hours and then take a break. + * + * You should finish the given tasks in a way that satisfies the following conditions: + * - If you start a task in a work session, you must complete it in the same work session. + * - You can start a new task immediately after finishing the previous one. + * - You may complete the tasks in any order. + * + * Given tasks and sessionTime, return the minimum number of work sessions needed to finish all the + * tasks following the conditions above. + * + * The tests are generated such that sessionTime is greater than or equal to the maximum element + * in tasks[i]. + */ + +/** + * @param {number[]} tasks + * @param {number} sessionTime + * @return {number} + */ +var minSessions = function(tasks, sessionTime) { + const n = tasks.length; + const dp = new Array(1 << n).fill(n + 1); + dp[0] = 0; + + for (let mask = 1; mask < 1 << n; mask++) { + let time = 0; + for (let i = 0; i < n; i++) { + if (mask & (1 << i)) { + time += tasks[i]; + } + } + + for (let subset = mask; subset; subset = (subset - 1) & mask) { + if (subset === mask) continue; + let subsetTime = 0; + for (let i = 0; i < n; i++) { + if (subset & (1 << i)) { + subsetTime += tasks[i]; + } + } + if (subsetTime <= sessionTime) { + dp[mask] = Math.min(dp[mask], dp[mask ^ subset] + 1); + } + } + + if (time <= sessionTime) { + dp[mask] = 1; + } + } + + return dp[(1 << n) - 1]; +}; From bd7366516a160e21c52264d2abb6ddb523413f50 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 16:02:16 -0500 Subject: [PATCH 167/495] Add solution #1987 --- README.md | 3 +- ...1987-number-of-unique-good-subsequences.js | 41 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 solutions/1987-number-of-unique-good-subsequences.js diff --git a/README.md b/README.md index e4fde28a..10614d06 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,671 LeetCode solutions in JavaScript +# 1,672 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1525,6 +1525,7 @@ 1984|[Minimum Difference Between Highest and Lowest of K Scores](./solutions/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js)|Easy| 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| 1986|[Minimum Number of Work Sessions to Finish the Tasks](./solutions/1986-minimum-number-of-work-sessions-to-finish-the-tasks.js)|Medium| +1987|[Number of Unique Good Subsequences](./solutions/1987-number-of-unique-good-subsequences.js)|Hard| 1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium| 2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| diff --git a/solutions/1987-number-of-unique-good-subsequences.js b/solutions/1987-number-of-unique-good-subsequences.js new file mode 100644 index 00000000..e0d6651c --- /dev/null +++ b/solutions/1987-number-of-unique-good-subsequences.js @@ -0,0 +1,41 @@ +/** + * 1987. Number of Unique Good Subsequences + * https://leetcode.com/problems/number-of-unique-good-subsequences/ + * Difficulty: Hard + * + * You are given a binary string binary. A subsequence of binary is considered good if it is not + * empty and has no leading zeros (with the exception of "0"). + * + * Find the number of unique good subsequences of binary. + * - For example, if binary = "001", then all the good subsequences are ["0", "0", "1"], so the + * unique good subsequences are "0" and "1". Note that subsequences "00", "01", and "001" are + * not good because they have leading zeros. + * + * Return the number of unique good subsequences of binary. Since the answer may be very large, + * return it modulo 109 + 7. + * + * A subsequence is a sequence that can be derived from another sequence by deleting some or no + * elements without changing the order of the remaining elements. + */ + +/** + * @param {string} binary + * @return {number} + */ +var numberOfUniqueGoodSubsequences = function(binary) { + const MOD = 1e9 + 7; + let endsWithZero = 0; + let endsWithOne = 0; + let hasZero = false; + + for (const digit of binary) { + if (digit === '0') { + hasZero = true; + endsWithZero = (endsWithZero + endsWithOne) % MOD; + } else { + endsWithOne = (endsWithOne + endsWithZero + 1) % MOD; + } + } + + return (endsWithZero + endsWithOne + (hasZero ? 1 : 0)) % MOD; +}; From 2d2fe482dda9508d0dd48a9a50e1601e478e15ab Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 16:03:54 -0500 Subject: [PATCH 168/495] Add solution #1991 --- README.md | 3 +- .../1991-find-the-middle-index-in-array.js | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 solutions/1991-find-the-middle-index-in-array.js diff --git a/README.md b/README.md index 10614d06..28edc771 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,672 LeetCode solutions in JavaScript +# 1,673 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1526,6 +1526,7 @@ 1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium| 1986|[Minimum Number of Work Sessions to Finish the Tasks](./solutions/1986-minimum-number-of-work-sessions-to-finish-the-tasks.js)|Medium| 1987|[Number of Unique Good Subsequences](./solutions/1987-number-of-unique-good-subsequences.js)|Hard| +1991|[Find the Middle Index in Array](./solutions/1991-find-the-middle-index-in-array.js)|Easy| 1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium| 2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| diff --git a/solutions/1991-find-the-middle-index-in-array.js b/solutions/1991-find-the-middle-index-in-array.js new file mode 100644 index 00000000..fa993684 --- /dev/null +++ b/solutions/1991-find-the-middle-index-in-array.js @@ -0,0 +1,35 @@ +/** + * 1991. Find the Middle Index in Array + * https://leetcode.com/problems/find-the-middle-index-in-array/ + * Difficulty: Easy + * + * Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst + * all the possible ones). + * + * A middleIndex is an index where nums[0] + nums[1] + ... + + * nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]. + * + * If middleIndex == 0, the left side sum is considered to be 0. Similarly, if + * middleIndex == nums.length - 1, the right side sum is considered to be 0. + * + * Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findMiddleIndex = 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; +}; From f5d35ccf343e5375a926203945cad665c05bd004 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 16:05:33 -0500 Subject: [PATCH 169/495] Add solution #1992 --- README.md | 3 +- solutions/1992-find-all-groups-of-farmland.js | 55 +++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 solutions/1992-find-all-groups-of-farmland.js diff --git a/README.md b/README.md index 28edc771..19badc3e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,673 LeetCode solutions in JavaScript +# 1,674 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1527,6 +1527,7 @@ 1986|[Minimum Number of Work Sessions to Finish the Tasks](./solutions/1986-minimum-number-of-work-sessions-to-finish-the-tasks.js)|Medium| 1987|[Number of Unique Good Subsequences](./solutions/1987-number-of-unique-good-subsequences.js)|Hard| 1991|[Find the Middle Index in Array](./solutions/1991-find-the-middle-index-in-array.js)|Easy| +1992|[Find All Groups of Farmland](./solutions/1992-find-all-groups-of-farmland.js)|Medium| 1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium| 2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| diff --git a/solutions/1992-find-all-groups-of-farmland.js b/solutions/1992-find-all-groups-of-farmland.js new file mode 100644 index 00000000..0e39fd7f --- /dev/null +++ b/solutions/1992-find-all-groups-of-farmland.js @@ -0,0 +1,55 @@ +/** + * 1992. Find All Groups of Farmland + * https://leetcode.com/problems/find-all-groups-of-farmland/ + * Difficulty: Medium + * + * You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested + * land and a 1 represents a hectare of farmland. + * + * To keep the land organized, there are designated rectangular areas of hectares that consist + * entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, + * meaning farmland in one group is not four-directionally adjacent to another farmland in a + * different group. + * + * land can be represented by a coordinate system where the top left corner of land is (0, 0) + * and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and + * bottom right corner of each group of farmland. A group of farmland with a top left corner + * at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length + * array [r1, c1, r2, c2]. + * + * Return a 2D array containing the 4-length arrays described above for each group of farmland + * in land. If there are no groups of farmland, return an empty array. You may return the answer + * in any order. + */ + +/** + * @param {number[][]} land + * @return {number[][]} + */ +var findFarmland = function(land) { + const m = land.length; + const n = land[0].length; + const result = []; + + for (let r = 0; r < m; r++) { + for (let c = 0; c < n; c++) { + if (land[r][c] === 1) { + let r2 = r; + let c2 = c; + + while (r2 + 1 < m && land[r2 + 1][c] === 1) r2++; + while (c2 + 1 < n && land[r][c2 + 1] === 1) c2++; + + result.push([r, c, r2, c2]); + + for (let i = r; i <= r2; i++) { + for (let j = c; j <= c2; j++) { + land[i][j] = 0; + } + } + } + } + } + + return result; +}; From f0764124dc39fe4fb84b00c7c131d69fe993e78f Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 16:08:22 -0500 Subject: [PATCH 170/495] Add solution #1993 --- README.md | 3 +- solutions/1993-operations-on-tree.js | 101 +++++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 1 deletion(-) create mode 100644 solutions/1993-operations-on-tree.js diff --git a/README.md b/README.md index 19badc3e..ed21d801 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,674 LeetCode solutions in JavaScript +# 1,675 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1528,6 +1528,7 @@ 1987|[Number of Unique Good Subsequences](./solutions/1987-number-of-unique-good-subsequences.js)|Hard| 1991|[Find the Middle Index in Array](./solutions/1991-find-the-middle-index-in-array.js)|Easy| 1992|[Find All Groups of Farmland](./solutions/1992-find-all-groups-of-farmland.js)|Medium| +1993|[Operations on Tree](./solutions/1993-operations-on-tree.js)|Medium| 1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium| 2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| diff --git a/solutions/1993-operations-on-tree.js b/solutions/1993-operations-on-tree.js new file mode 100644 index 00000000..e1f5952c --- /dev/null +++ b/solutions/1993-operations-on-tree.js @@ -0,0 +1,101 @@ +/** + * 1993. Operations on Tree + * https://leetcode.com/problems/operations-on-tree/ + * Difficulty: Medium + * + * You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array + * parent where parent[i] is the parent of the ith node. The root of the tree is node 0, + * so parent[0] = -1 since it has no parent. You want to design a data structure that + * allows users to lock, unlock, and upgrade nodes in the tree. + * + * The data structure should support the following functions: + * - Lock: Locks the given node for the given user and prevents other users from locking + * the same node. You may only lock a node using this function if the node is unlocked. + * - Unlock: Unlocks the given node for the given user. You may only unlock a node using + * this function if it is currently locked by the same user. + * - Upgrade: Locks the given node for the given user and unlocks all of its descendants + * regardless of who locked it. You may only upgrade a node if all 3 conditions are true: + * - The node is unlocked, + * - It has at least one locked descendant (by any user), and + * - It does not have any locked ancestors. + * + * Implement the LockingTree class: + * - LockingTree(int[] parent) initializes the data structure with the parent array. + * - lock(int num, int user) returns true if it is possible for the user with id user to lock + * the node num, or false otherwise. If it is possible, the node num will become locked by + * the user with id user. + * - unlock(int num, int user) returns true if it is possible for the user with id user to + * unlock the node num, or false otherwise. If it is possible, the node num will become unlocked. + * - upgrade(int num, int user) returns true if it is possible for the user with id user to + * upgrade the node num, or false otherwise. If it is possible, the node num will be upgraded. + */ + +/** + * @param {number[]} parent + */ +var LockingTree = function(parent) { + this.parent = parent; + this.locked = new Map(); + this.children = new Array(parent.length).fill().map(() => []); + for (let i = 1; i < parent.length; i++) { + this.children[parent[i]].push(i); + } +}; + +/** + * @param {number} num + * @param {number} user + * @return {boolean} + */ +LockingTree.prototype.lock = function(num, user) { + if (this.locked.has(num)) return false; + this.locked.set(num, user); + return true; +}; + +/** + * @param {number} num + * @param {number} user + * @return {boolean} + */ +LockingTree.prototype.unlock = function(num, user) { + if (!this.locked.has(num) || this.locked.get(num) !== user) return false; + this.locked.delete(num); + return true; +}; + +/** + * @param {number} num + * @param {number} user + * @return {boolean} + */ +LockingTree.prototype.upgrade = function(num, user) { + if (this.locked.has(num)) return false; + + let node = num; + while (node !== -1) { + if (this.locked.has(node)) return false; + node = this.parent[node]; + } + + const descendants = []; + const queue = [num]; + let hasLockedDescendant = false; + + while (queue.length) { + const curr = queue.shift(); + if (this.locked.has(curr)) { + hasLockedDescendant = true; + descendants.push(curr); + } + queue.push(...this.children[curr]); + } + + if (!hasLockedDescendant) return false; + + for (const descendant of descendants) { + this.locked.delete(descendant); + } + this.locked.set(num, user); + return true; +}; From 172777ed5c4fe511e1003105960d282bb3a67ce8 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 16:12:57 -0500 Subject: [PATCH 171/495] Add solution #1994 --- README.md | 3 +- solutions/1994-the-number-of-good-subsets.js | 75 ++++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 solutions/1994-the-number-of-good-subsets.js diff --git a/README.md b/README.md index ed21d801..9bd50ddc 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,675 LeetCode solutions in JavaScript +# 1,676 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1529,6 +1529,7 @@ 1991|[Find the Middle Index in Array](./solutions/1991-find-the-middle-index-in-array.js)|Easy| 1992|[Find All Groups of Farmland](./solutions/1992-find-all-groups-of-farmland.js)|Medium| 1993|[Operations on Tree](./solutions/1993-operations-on-tree.js)|Medium| +1994|[The Number of Good Subsets](./solutions/1994-the-number-of-good-subsets.js)|Hard| 1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium| 2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| diff --git a/solutions/1994-the-number-of-good-subsets.js b/solutions/1994-the-number-of-good-subsets.js new file mode 100644 index 00000000..7fb63535 --- /dev/null +++ b/solutions/1994-the-number-of-good-subsets.js @@ -0,0 +1,75 @@ +/** + * 1994. The Number of Good Subsets + * https://leetcode.com/problems/the-number-of-good-subsets/ + * Difficulty: Hard + * + * You are given an integer array nums. We call a subset of nums good if its product can be + * represented as a product of one or more distinct prime numbers. + * + * - For example, if nums = [1, 2, 3, 4]: + * - [2, 3], [1, 2, 3], and [1, 3] are good subsets with products 6 = 2*3, 6 = 2*3, and 3 = 3 + * respectively. + * - [1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively. + * + * Return the number of different good subsets in nums modulo 109 + 7. + * + * A subset of nums is any array that can be obtained by deleting some (possibly none or all) + * elements from nums. Two subsets are different if and only if the chosen indices to delete + * are different. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var numberOfGoodSubsets = function(nums) { + const MOD = 1e9 + 7; + const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]; + const freq = new Array(31).fill(0); + for (const num of nums) { + freq[num]++; + } + + const dp = new Array(1 << primes.length).fill(0); + dp[0] = 1; + for (let i = 0; i < freq[1]; i++) { + dp[0] = (dp[0] * 2) % MOD; + } + + for (let num = 2; num <= 30; num++) { + if (freq[num] === 0) continue; + let mask = 0; + let valid = true; + for (let i = 0; i < primes.length; i++) { + let count = 0; + let temp = num; + while (temp % primes[i] === 0) { + count++; + temp /= primes[i]; + } + if (count > 1) { + valid = false; + break; + } + if (count === 1) { + mask |= 1 << i; + } + } + + if (!valid) continue; + + const prev = dp.slice(); + for (let j = 0; j < 1 << primes.length; j++) { + if ((j & mask) === 0) { + dp[j | mask] = (dp[j | mask] + prev[j] * freq[num]) % MOD; + } + } + } + + let result = 0; + for (let i = 1; i < 1 << primes.length; i++) { + result = (result + dp[i]) % MOD; + } + + return result; +}; From 5208f506c5064e0066df7a9907b4250ff383f6f4 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 16:15:58 -0500 Subject: [PATCH 172/495] Add solution #1995 --- README.md | 3 +- solutions/1995-count-special-quadruplets.js | 31 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 solutions/1995-count-special-quadruplets.js diff --git a/README.md b/README.md index 9bd50ddc..7c6b17d9 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,676 LeetCode solutions in JavaScript +# 1,677 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1530,6 +1530,7 @@ 1992|[Find All Groups of Farmland](./solutions/1992-find-all-groups-of-farmland.js)|Medium| 1993|[Operations on Tree](./solutions/1993-operations-on-tree.js)|Medium| 1994|[The Number of Good Subsets](./solutions/1994-the-number-of-good-subsets.js)|Hard| +1995|[Count Special Quadruplets](./solutions/1995-count-special-quadruplets.js)|Easy| 1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium| 2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| diff --git a/solutions/1995-count-special-quadruplets.js b/solutions/1995-count-special-quadruplets.js new file mode 100644 index 00000000..e37902ac --- /dev/null +++ b/solutions/1995-count-special-quadruplets.js @@ -0,0 +1,31 @@ +/** + * 1995. Count Special Quadruplets + * https://leetcode.com/problems/count-special-quadruplets/ + * Difficulty: Easy + * + * Given a 0-indexed integer array nums, return the number of distinct quadruplets + * (a, b, c, d) such that: + * - nums[a] + nums[b] + nums[c] == nums[d], and + * - a < b < c < d + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var countQuadruplets = function(nums) { + const map = new Map(); + let result = 0; + + for (let c = nums.length - 2; c >= 2; c--) { + map.set(nums[c + 1], (map.get(nums[c + 1]) || 0) + 1); + for (let a = 0; a < c - 1; a++) { + for (let b = a + 1; b < c; b++) { + const sum = nums[a] + nums[b] + nums[c]; + result += map.get(sum) || 0; + } + } + } + + return result; +}; From 3b1c655848953da715ec47a3d878ea7e769dd13f Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 16:17:58 -0500 Subject: [PATCH 173/495] Add solution #1997 --- README.md | 3 +- ...ay-where-you-have-been-in-all-the-rooms.js | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 solutions/1997-first-day-where-you-have-been-in-all-the-rooms.js diff --git a/README.md b/README.md index 7c6b17d9..18323c96 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,677 LeetCode solutions in JavaScript +# 1,678 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1532,6 +1532,7 @@ 1994|[The Number of Good Subsets](./solutions/1994-the-number-of-good-subsets.js)|Hard| 1995|[Count Special Quadruplets](./solutions/1995-count-special-quadruplets.js)|Easy| 1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium| +1997|[First Day Where You Have Been in All the Rooms](./solutions/1997-first-day-where-you-have-been-in-all-the-rooms.js)|Medium| 2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy| diff --git a/solutions/1997-first-day-where-you-have-been-in-all-the-rooms.js b/solutions/1997-first-day-where-you-have-been-in-all-the-rooms.js new file mode 100644 index 00000000..6dde2362 --- /dev/null +++ b/solutions/1997-first-day-where-you-have-been-in-all-the-rooms.js @@ -0,0 +1,36 @@ +/** + * 1997. First Day Where You Have Been in All the Rooms + * https://leetcode.com/problems/first-day-where-you-have-been-in-all-the-rooms/ + * Difficulty: Medium + * + * There are n rooms you need to visit, labeled from 0 to n - 1. Each day is labeled, starting + * from 0. You will go in and visit one room a day. + * + * Initially on day 0, you visit room 0. The order you visit the rooms for the coming days is + * determined by the following rules and a given 0-indexed array nextVisit of length n: + * - Assuming that on a day, you visit room i, + * - if you have been in room i an odd number of times (including the current visit), on the next + * day you will visit a room with a lower or equal room number specified by nextVisit[i] + * where 0 <= nextVisit[i] <= i; + * - if you have been in room i an even number of times (including the current visit), on the + * next day you will visit room (i + 1) mod n. + * + * Return the label of the first day where you have been in all the rooms. It can be shown + * that such a day exists. Since the answer may be very large, return it modulo 109 + 7. + */ + +/** + * @param {number[]} nextVisit + * @return {number} + */ +var firstDayBeenInAllRooms = function(nextVisit) { + const MOD = 1e9 + 7; + const n = nextVisit.length; + const dp = new Array(n).fill(0); + + for (let i = 1; i < n; i++) { + dp[i] = (2 * dp[i - 1] + 2 - dp[nextVisit[i - 1]] + MOD) % MOD; + } + + return dp[n - 1]; +}; From a5aeb0cabf050534d8eea75c7280e7df02fff8c7 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 16:22:06 -0500 Subject: [PATCH 174/495] Add solution #1998 --- README.md | 3 +- solutions/1998-gcd-sort-of-an-array.js | 69 ++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 solutions/1998-gcd-sort-of-an-array.js diff --git a/README.md b/README.md index 18323c96..a19594cf 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,678 LeetCode solutions in JavaScript +# 1,679 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1533,6 +1533,7 @@ 1995|[Count Special Quadruplets](./solutions/1995-count-special-quadruplets.js)|Easy| 1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium| 1997|[First Day Where You Have Been in All the Rooms](./solutions/1997-first-day-where-you-have-been-in-all-the-rooms.js)|Medium| +1998|[GCD Sort of an Array](./solutions/1998-gcd-sort-of-an-array.js)|Hard| 2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy| diff --git a/solutions/1998-gcd-sort-of-an-array.js b/solutions/1998-gcd-sort-of-an-array.js new file mode 100644 index 00000000..97bb5a39 --- /dev/null +++ b/solutions/1998-gcd-sort-of-an-array.js @@ -0,0 +1,69 @@ +/** + * 1998. GCD Sort of an Array + * https://leetcode.com/problems/gcd-sort-of-an-array/ + * Difficulty: Hard + * + * You are given an integer array nums, and you can perform the following operation any + * number of times on nums: + * - Swap the positions of two elements nums[i] and nums[j] if gcd(nums[i], nums[j]) > 1 + * where gcd(nums[i], nums[j]) is the greatest common divisor of nums[i] and nums[j]. + * + * Return true if it is possible to sort nums in non-decreasing order using the above swap + * method, or false otherwise. + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var gcdSort = function(nums) { + const maxNum = Math.max(...nums); + const parent = new Array(maxNum + 1).fill().map((_, i) => i); + const minPrime = new Array(maxNum + 1).fill(0); + for (let i = 2; i <= maxNum; i++) { + if (minPrime[i] === 0) { + for (let j = i; j <= maxNum; j += i) { + minPrime[j] = i; + } + } + } + + const groups = new Map(); + for (const num of nums) { + let curr = num; + const primes = new Set(); + while (curr > 1) { + const prime = minPrime[curr]; + primes.add(prime); + curr /= prime; + } + for (const prime of primes) { + if (!groups.has(prime)) groups.set(prime, []); + groups.get(prime).push(num); + } + } + + for (const numbers of groups.values()) { + for (let i = 1; i < numbers.length; i++) { + union(numbers[i - 1], numbers[i], parent); + } + } + + const sorted = [...nums].sort((a, b) => a - b); + for (let i = 0; i < nums.length; i++) { + if (find(nums[i], parent) !== find(sorted[i], parent)) { + return false; + } + } + + return true; + + function find(x, parent) { + if (parent[x] !== x) parent[x] = find(parent[x], parent); + return parent[x]; + } + + function union(x, y, parent) { + parent[find(x, parent)] = find(y, parent); + } +}; From 2c23301a4c81ae4703b080fd4b2b43c53bc1be53 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 4 May 2025 16:23:31 -0500 Subject: [PATCH 175/495] Add solution #2001 --- README.md | 3 +- ...-of-pairs-of-interchangeable-rectangles.js | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 solutions/2001-number-of-pairs-of-interchangeable-rectangles.js diff --git a/README.md b/README.md index a19594cf..9a506882 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,679 LeetCode solutions in JavaScript +# 1,680 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1535,6 +1535,7 @@ 1997|[First Day Where You Have Been in All the Rooms](./solutions/1997-first-day-where-you-have-been-in-all-the-rooms.js)|Medium| 1998|[GCD Sort of an Array](./solutions/1998-gcd-sort-of-an-array.js)|Hard| 2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| +2001|[Number of Pairs of Interchangeable Rectangles](./solutions/2001-number-of-pairs-of-interchangeable-rectangles.js)|Medium| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy| 2017|[Grid Game](./solutions/2017-grid-game.js)|Medium| diff --git a/solutions/2001-number-of-pairs-of-interchangeable-rectangles.js b/solutions/2001-number-of-pairs-of-interchangeable-rectangles.js new file mode 100644 index 00000000..89f2611e --- /dev/null +++ b/solutions/2001-number-of-pairs-of-interchangeable-rectangles.js @@ -0,0 +1,38 @@ +/** + * 2001. Number of Pairs of Interchangeable Rectangles + * https://leetcode.com/problems/number-of-pairs-of-interchangeable-rectangles/ + * Difficulty: Medium + * + * You are given n rectangles represented by a 0-indexed 2D integer array rectangles, + * where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle. + * + * Two rectangles i and j (i < j) are considered interchangeable if they have the same + * width-to-height ratio. More formally, two rectangles are interchangeable if + * widthi/heighti == widthj/heightj (using decimal division, not integer division). + * + * Return the number of pairs of interchangeable rectangles in rectangles. + */ + +/** + * @param {number[][]} rectangles + * @return {number} + */ +var interchangeableRectangles = function(rectangles) { + const map = new Map(); + let result = 0; + + for (const [width, height] of rectangles) { + const gcd = (a, b) => b === 0 ? a : gcd(b, a % b); + const divisor = gcd(width, height); + const ratio = `${width / divisor}/${height / divisor}`; + + if (map.has(ratio)) { + result += map.get(ratio); + map.set(ratio, map.get(ratio) + 1); + } else { + map.set(ratio, 1); + } + } + + return result; +}; From 6731205df1dadc7472e785557989e91bde06b21a Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 18:30:32 -0500 Subject: [PATCH 176/495] Add solution #2002 --- README.md | 3 +- ...-length-of-two-palindromic-subsequences.js | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 solutions/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js diff --git a/README.md b/README.md index 9a506882..3aabfff6 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,680 LeetCode solutions in JavaScript +# 1,681 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1536,6 +1536,7 @@ 1998|[GCD Sort of an Array](./solutions/1998-gcd-sort-of-an-array.js)|Hard| 2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| 2001|[Number of Pairs of Interchangeable Rectangles](./solutions/2001-number-of-pairs-of-interchangeable-rectangles.js)|Medium| +2002|[Maximum Product of the Length of Two Palindromic Subsequences](./solutions/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js)|Medium| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy| 2017|[Grid Game](./solutions/2017-grid-game.js)|Medium| diff --git a/solutions/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js b/solutions/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js new file mode 100644 index 00000000..ae489e83 --- /dev/null +++ b/solutions/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js @@ -0,0 +1,50 @@ +/** + * 2002. Maximum Product of the Length of Two Palindromic Subsequences + * https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/ + * Difficulty: Medium + * + * Given a string s, find two disjoint palindromic subsequences of s such that the product of their + * lengths is maximized. The two subsequences are disjoint if they do not both pick a character at + * the same index. + * + * Return the maximum possible product of the lengths of the two palindromic subsequences. + * + * A subsequence is a string that can be derived from another string by deleting some or no + * characters without changing the order of the remaining characters. A string is palindromic + * if it reads the same forward and backward. + */ + +/** + * @param {string} s + * @return {number} + */ +var maxProduct = function(s) { + const n = s.length; + let result = 0; + + for (let mask1 = 1; mask1 < (1 << n); mask1++) { + for (let mask2 = 1; mask2 < (1 << n); mask2++) { + if (mask1 & mask2) continue; + const len1 = isPalindrome(s, mask1); + if (len1 === 0) continue; + const len2 = isPalindrome(s, mask2); + if (len2 === 0) continue; + result = Math.max(result, len1 * len2); + } + } + + return result; + + function isPalindrome(str, mask) { + const chars = []; + for (let i = 0; i < n; i++) { + if (mask & (1 << i)) chars.push(str[i]); + } + let left = 0; + let right = chars.length - 1; + while (left < right) { + if (chars[left++] !== chars[right--]) return 0; + } + return chars.length; + } +}; From 58652032846f1feef6e989f988b5439cb8a28699 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 18:33:31 -0500 Subject: [PATCH 177/495] Add solution #2003 --- README.md | 3 +- ...t-missing-genetic-value-in-each-subtree.js | 55 +++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 solutions/2003-smallest-missing-genetic-value-in-each-subtree.js diff --git a/README.md b/README.md index 3aabfff6..6cb763d8 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,681 LeetCode solutions in JavaScript +# 1,682 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1537,6 +1537,7 @@ 2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy| 2001|[Number of Pairs of Interchangeable Rectangles](./solutions/2001-number-of-pairs-of-interchangeable-rectangles.js)|Medium| 2002|[Maximum Product of the Length of Two Palindromic Subsequences](./solutions/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js)|Medium| +2003|[Smallest Missing Genetic Value in Each Subtree](./solutions/2003-smallest-missing-genetic-value-in-each-subtree.js)|Hard| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy| 2017|[Grid Game](./solutions/2017-grid-game.js)|Medium| diff --git a/solutions/2003-smallest-missing-genetic-value-in-each-subtree.js b/solutions/2003-smallest-missing-genetic-value-in-each-subtree.js new file mode 100644 index 00000000..f57b89d8 --- /dev/null +++ b/solutions/2003-smallest-missing-genetic-value-in-each-subtree.js @@ -0,0 +1,55 @@ +/** + * 2003. Smallest Missing Genetic Value in Each Subtree + * https://leetcode.com/problems/smallest-missing-genetic-value-in-each-subtree/ + * Difficulty: Hard + * + * There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a + * 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is + * the root, parents[0] == -1. + * + * There are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. + * You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for + * node i. + * + * Return an array ans of length n where ans[i] is the smallest genetic value that is missing + * from the subtree rooted at node i. + * + * The subtree rooted at a node x contains node x and all of its descendant nodes. + */ + +/** + * @param {number[]} parents + * @param {number[]} nums + * @return {number[]} + */ +var smallestMissingValueSubtree = function(parents, nums) { + const n = parents.length; + const result = new Array(n).fill(1); + const children = Array.from({ length: n }, () => []); + const seen = new Set(); + let maxMissing = 1; + + for (let i = 1; i < n; i++) { + children[parents[i]].push(i); + } + + const nodeWithOne = nums.indexOf(1); + if (nodeWithOne === -1) return result; + + let current = nodeWithOne; + while (current !== -1) { + const stack = [current]; + while (stack.length) { + const node = stack.pop(); + seen.add(nums[node]); + for (const child of children[node]) { + if (!seen.has(nums[child])) stack.push(child); + } + } + while (seen.has(maxMissing)) maxMissing++; + result[current] = maxMissing; + current = parents[current]; + } + + return result; +}; From cf7a7ca4a667c96e842537779fffd6184165e783 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 18:34:55 -0500 Subject: [PATCH 178/495] Add solution #2006 --- README.md | 3 +- ...ber-of-pairs-with-absolute-difference-k.js | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 solutions/2006-count-number-of-pairs-with-absolute-difference-k.js diff --git a/README.md b/README.md index 6cb763d8..8b937066 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,682 LeetCode solutions in JavaScript +# 1,683 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1538,6 +1538,7 @@ 2001|[Number of Pairs of Interchangeable Rectangles](./solutions/2001-number-of-pairs-of-interchangeable-rectangles.js)|Medium| 2002|[Maximum Product of the Length of Two Palindromic Subsequences](./solutions/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js)|Medium| 2003|[Smallest Missing Genetic Value in Each Subtree](./solutions/2003-smallest-missing-genetic-value-in-each-subtree.js)|Hard| +2006|[Count Number of Pairs With Absolute Difference K](./solutions/2006-count-number-of-pairs-with-absolute-difference-k.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy| 2017|[Grid Game](./solutions/2017-grid-game.js)|Medium| diff --git a/solutions/2006-count-number-of-pairs-with-absolute-difference-k.js b/solutions/2006-count-number-of-pairs-with-absolute-difference-k.js new file mode 100644 index 00000000..022c9b4d --- /dev/null +++ b/solutions/2006-count-number-of-pairs-with-absolute-difference-k.js @@ -0,0 +1,29 @@ +/** + * 2006. Count Number of Pairs With Absolute Difference K + * https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/ + * Difficulty: Easy + * + * Given an integer array nums and an integer k, return the number of pairs (i, j) where + * i < j such that |nums[i] - nums[j]| == k. + * + * The value of |x| is defined as: + * - x if x >= 0. + * - -x if x < 0. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var countKDifference = function(nums, k) { + const map = new Map(); + let result = 0; + + for (const num of nums) { + result += (map.get(num - k) || 0) + (map.get(num + k) || 0); + map.set(num, (map.get(num) || 0) + 1); + } + + return result; +}; From 5c5158d456e3839004eef0b633816d4614a53579 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 18:35:49 -0500 Subject: [PATCH 179/495] Add solution #2007 --- README.md | 3 +- ...-find-original-array-from-doubled-array.js | 42 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 solutions/2007-find-original-array-from-doubled-array.js diff --git a/README.md b/README.md index 8b937066..ab6d34a7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,683 LeetCode solutions in JavaScript +# 1,684 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1539,6 +1539,7 @@ 2002|[Maximum Product of the Length of Two Palindromic Subsequences](./solutions/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js)|Medium| 2003|[Smallest Missing Genetic Value in Each Subtree](./solutions/2003-smallest-missing-genetic-value-in-each-subtree.js)|Hard| 2006|[Count Number of Pairs With Absolute Difference K](./solutions/2006-count-number-of-pairs-with-absolute-difference-k.js)|Easy| +2007|[Find Original Array From Doubled Array](./solutions/2007-find-original-array-from-doubled-array.js)|Medium| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy| 2017|[Grid Game](./solutions/2017-grid-game.js)|Medium| diff --git a/solutions/2007-find-original-array-from-doubled-array.js b/solutions/2007-find-original-array-from-doubled-array.js new file mode 100644 index 00000000..ca1d1357 --- /dev/null +++ b/solutions/2007-find-original-array-from-doubled-array.js @@ -0,0 +1,42 @@ +/** + * 2007. Find Original Array From Doubled Array + * https://leetcode.com/problems/find-original-array-from-doubled-array/ + * Difficulty: Medium + * + * An integer array original is transformed into a doubled array changed by appending twice the + * value of every element in original, and then randomly shuffling the resulting array. + * + * Given an array changed, return original if changed is a doubled array. If changed is not a + * doubled array, return an empty array. The elements in original may be returned in any order. + */ + +/** + * @param {number[]} changed + * @return {number[]} + */ +var findOriginalArray = function(changed) { + if (changed.length % 2 !== 0) return []; + + const frequency = new Map(); + const result = []; + + changed.sort((a, b) => a - b); + + for (const num of changed) { + frequency.set(num, (frequency.get(num) || 0) + 1); + } + + for (const num of changed) { + if (frequency.get(num) === 0) continue; + + frequency.set(num, frequency.get(num) - 1); + + const doubled = num * 2; + if (!frequency.has(doubled) || frequency.get(doubled) === 0) return []; + + frequency.set(doubled, frequency.get(doubled) - 1); + result.push(num); + } + + return result; +}; From 07de3a7998dfe970ccf10caa408146c1c152efec Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 18:37:11 -0500 Subject: [PATCH 180/495] Add solution #2008 --- README.md | 3 +- solutions/2008-maximum-earnings-from-taxi.js | 43 ++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 solutions/2008-maximum-earnings-from-taxi.js diff --git a/README.md b/README.md index ab6d34a7..f27d094c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,684 LeetCode solutions in JavaScript +# 1,685 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1540,6 +1540,7 @@ 2003|[Smallest Missing Genetic Value in Each Subtree](./solutions/2003-smallest-missing-genetic-value-in-each-subtree.js)|Hard| 2006|[Count Number of Pairs With Absolute Difference K](./solutions/2006-count-number-of-pairs-with-absolute-difference-k.js)|Easy| 2007|[Find Original Array From Doubled Array](./solutions/2007-find-original-array-from-doubled-array.js)|Medium| +2008|[Maximum Earnings From Taxi](./solutions/2008-maximum-earnings-from-taxi.js)|Medium| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy| 2017|[Grid Game](./solutions/2017-grid-game.js)|Medium| diff --git a/solutions/2008-maximum-earnings-from-taxi.js b/solutions/2008-maximum-earnings-from-taxi.js new file mode 100644 index 00000000..fd7cbaac --- /dev/null +++ b/solutions/2008-maximum-earnings-from-taxi.js @@ -0,0 +1,43 @@ +/** + * 2008. Maximum Earnings From Taxi + * https://leetcode.com/problems/maximum-earnings-from-taxi/ + * Difficulty: Medium + * + * There are n points on a road you are driving your taxi on. The n points on the road are + * labeled from 1 to n in the direction you are going, and you want to drive from point 1 + * to point n to make money by picking up passengers. You cannot change the direction of the taxi. + * + * The passengers are represented by a 0-indexed 2D integer array rides, where + * rides[i] = [starti, endi, tipi] denotes the ith passenger requesting a ride from point + * starti to point endi who is willing to give a tipi dollar tip. + * + * For each passenger i you pick up, you earn endi - starti + tipi dollars. You may only drive + * at most one passenger at a time. + * + * Given n and rides, return the maximum number of dollars you can earn by picking up the + * passengers optimally. + * + * Note: You may drop off a passenger and pick up a different passenger at the same point. + */ + +/** + * @param {number} n + * @param {number[][]} rides + * @return {number} + */ +var maxTaxiEarnings = function(n, rides) { + rides.sort((a, b) => a[1] - b[1]); + const dp = new Array(n + 1).fill(0); + let rideIndex = 0; + + for (let point = 1; point <= n; point++) { + dp[point] = dp[point - 1]; + while (rideIndex < rides.length && rides[rideIndex][1] === point) { + const [start, end, tip] = rides[rideIndex]; + dp[point] = Math.max(dp[point], dp[start] + (end - start + tip)); + rideIndex++; + } + } + + return dp[n]; +}; From 48c9a3467d79848492981addedd081db0c2e9422 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 18:38:44 -0500 Subject: [PATCH 181/495] Add solution #2009 --- README.md | 3 +- ...-of-operations-to-make-array-continuous.js | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 solutions/2009-minimum-number-of-operations-to-make-array-continuous.js diff --git a/README.md b/README.md index f27d094c..8bc25eef 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,685 LeetCode solutions in JavaScript +# 1,686 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1541,6 +1541,7 @@ 2006|[Count Number of Pairs With Absolute Difference K](./solutions/2006-count-number-of-pairs-with-absolute-difference-k.js)|Easy| 2007|[Find Original Array From Doubled Array](./solutions/2007-find-original-array-from-doubled-array.js)|Medium| 2008|[Maximum Earnings From Taxi](./solutions/2008-maximum-earnings-from-taxi.js)|Medium| +2009|[Minimum Number of Operations to Make Array Continuous](./solutions/2009-minimum-number-of-operations-to-make-array-continuous.js)|Hard| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy| 2017|[Grid Game](./solutions/2017-grid-game.js)|Medium| diff --git a/solutions/2009-minimum-number-of-operations-to-make-array-continuous.js b/solutions/2009-minimum-number-of-operations-to-make-array-continuous.js new file mode 100644 index 00000000..d4cd063e --- /dev/null +++ b/solutions/2009-minimum-number-of-operations-to-make-array-continuous.js @@ -0,0 +1,36 @@ +/** + * 2009. Minimum Number of Operations to Make Array Continuous + * https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/ + * Difficulty: Hard + * + * You are given an integer array nums. In one operation, you can replace any element in nums + * with any integer. + * + * nums is considered continuous if both of the following conditions are fulfilled: + * - All elements in nums are unique. + * - The difference between the maximum element and the minimum element in nums equals + * nums.length - 1. + * + * For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous. + * + * Return the minimum number of operations to make nums continuous. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var minOperations = function(nums) { + const n = nums.length; + const uniqueNums = [...new Set(nums)].sort((a, b) => a - b); + let result = n; + + for (let i = 0, j = 0; i < uniqueNums.length; i++) { + while (j < uniqueNums.length && uniqueNums[j] - uniqueNums[i] <= n - 1) { + j++; + } + result = Math.min(result, n - (j - i)); + } + + return result; +}; From 89f97765a0beb61be3def0b620c268a0b747f802 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 18:39:49 -0500 Subject: [PATCH 182/495] Add solution #2012 --- README.md | 3 +- solutions/2012-sum-of-beauty-in-the-array.js | 42 ++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 solutions/2012-sum-of-beauty-in-the-array.js diff --git a/README.md b/README.md index 8bc25eef..8d529a54 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,686 LeetCode solutions in JavaScript +# 1,687 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1543,6 +1543,7 @@ 2008|[Maximum Earnings From Taxi](./solutions/2008-maximum-earnings-from-taxi.js)|Medium| 2009|[Minimum Number of Operations to Make Array Continuous](./solutions/2009-minimum-number-of-operations-to-make-array-continuous.js)|Hard| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| +2012|[Sum of Beauty in the Array](./solutions/2012-sum-of-beauty-in-the-array.js)|Medium| 2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy| 2017|[Grid Game](./solutions/2017-grid-game.js)|Medium| 2027|[Minimum Moves to Convert String](./solutions/2027-minimum-moves-to-convert-string.js)|Easy| diff --git a/solutions/2012-sum-of-beauty-in-the-array.js b/solutions/2012-sum-of-beauty-in-the-array.js new file mode 100644 index 00000000..957da790 --- /dev/null +++ b/solutions/2012-sum-of-beauty-in-the-array.js @@ -0,0 +1,42 @@ +/** + * 2012. Sum of Beauty in the Array + * https://leetcode.com/problems/sum-of-beauty-in-the-array/ + * Difficulty: Medium + * + * You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) + * the beauty of nums[i] equals: + * - 2, if nums[j] < nums[i] < nums[k], for all 0 <= j < i and for all i < k <= nums.length - 1. + * - 1, if nums[i - 1] < nums[i] < nums[i + 1], and the previous condition is not satisfied. + * - 0, if none of the previous conditions holds. + * + * Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var sumOfBeauties = function(nums) { + const n = nums.length; + let result = 0; + const leftMax = new Array(n).fill(nums[0]); + const rightMin = new Array(n).fill(nums[n - 1]); + + for (let i = 1; i < n; i++) { + leftMax[i] = Math.max(leftMax[i - 1], nums[i - 1]); + } + + for (let i = n - 2; i >= 0; i--) { + rightMin[i] = Math.min(rightMin[i + 1], nums[i + 1]); + } + + for (let i = 1; i < n - 1; i++) { + if (leftMax[i] < nums[i] && nums[i] < rightMin[i]) { + result += 2; + } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { + result += 1; + } + } + + return result; +}; From bf7f191f5a889d190f51f35265dbbdab085721c1 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 18:43:31 -0500 Subject: [PATCH 183/495] Add solution #2013 --- README.md | 3 +- solutions/2013-detect-squares.js | 54 ++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 solutions/2013-detect-squares.js diff --git a/README.md b/README.md index 8d529a54..8554d5f9 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,687 LeetCode solutions in JavaScript +# 1,688 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1544,6 +1544,7 @@ 2009|[Minimum Number of Operations to Make Array Continuous](./solutions/2009-minimum-number-of-operations-to-make-array-continuous.js)|Hard| 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| 2012|[Sum of Beauty in the Array](./solutions/2012-sum-of-beauty-in-the-array.js)|Medium| +2013|[Detect Squares](./solutions/2013-detect-squares.js)|Medium| 2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy| 2017|[Grid Game](./solutions/2017-grid-game.js)|Medium| 2027|[Minimum Moves to Convert String](./solutions/2027-minimum-moves-to-convert-string.js)|Easy| diff --git a/solutions/2013-detect-squares.js b/solutions/2013-detect-squares.js new file mode 100644 index 00000000..606076c3 --- /dev/null +++ b/solutions/2013-detect-squares.js @@ -0,0 +1,54 @@ +/** + * 2013. Detect Squares + * https://leetcode.com/problems/detect-squares/ + * Difficulty: Medium + * + * You are given a stream of points on the X-Y plane. Design an algorithm that: + * - Adds new points from the stream into a data structure. Duplicate points are allowed and should + * be treated as different points. + * - Given a query point, counts the number of ways to choose three points from the data structure + * such that the three points and the query point form an axis-aligned square with positive area. + * + * An axis-aligned square is a square whose edges are all the same length and are either parallel + * or perpendicular to the x-axis and y-axis. + * + * Implement the DetectSquares class: + * - DetectSquares() Initializes the object with an empty data structure. + * - void add(int[] point) Adds a new point point = [x, y] to the data structure. + * - int count(int[] point) Counts the number of ways to form axis-aligned squares with point + * point = [x, y] as described above. + */ + +var DetectSquares = function() { + this.points = new Map(); +}; + +/** + * @param {number[]} point + * @return {void} + */ +DetectSquares.prototype.add = function(point) { + const [x, y] = point; + const key = `${x},${y}`; + this.points.set(key, (this.points.get(key) || 0) + 1); +}; + +/** + * @param {number[]} point + * @return {number} + */ +DetectSquares.prototype.count = function(point) { + const [x, y] = point; + let result = 0; + + for (const [key, count] of this.points) { + const [px, py] = key.split(',').map(Number); + if (px === x || py === y || Math.abs(px - x) !== Math.abs(py - y)) continue; + + const point1 = `${x},${py}`; + const point2 = `${px},${y}`; + result += count * (this.points.get(point1) || 0) * (this.points.get(point2) || 0); + } + + return result; +}; From ed4df82d44fb42f5595ddd3d9c047e08966d6a5e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 18:45:20 -0500 Subject: [PATCH 184/495] Add solution #2014 --- README.md | 3 +- ...14-longest-subsequence-repeated-k-times.js | 64 +++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 solutions/2014-longest-subsequence-repeated-k-times.js diff --git a/README.md b/README.md index 8554d5f9..e3568a61 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,688 LeetCode solutions in JavaScript +# 1,689 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1545,6 +1545,7 @@ 2011|[Final Value of Variable After Performing Operations](./solutions/2011-final-value-of-variable-after-performing-operations.js)|Easy| 2012|[Sum of Beauty in the Array](./solutions/2012-sum-of-beauty-in-the-array.js)|Medium| 2013|[Detect Squares](./solutions/2013-detect-squares.js)|Medium| +2014|[Longest Subsequence Repeated k Times](./solutions/2014-longest-subsequence-repeated-k-times.js)|Hard| 2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy| 2017|[Grid Game](./solutions/2017-grid-game.js)|Medium| 2027|[Minimum Moves to Convert String](./solutions/2027-minimum-moves-to-convert-string.js)|Easy| diff --git a/solutions/2014-longest-subsequence-repeated-k-times.js b/solutions/2014-longest-subsequence-repeated-k-times.js new file mode 100644 index 00000000..ec575695 --- /dev/null +++ b/solutions/2014-longest-subsequence-repeated-k-times.js @@ -0,0 +1,64 @@ +/** + * 2014. Longest Subsequence Repeated k Times + * https://leetcode.com/problems/longest-subsequence-repeated-k-times/ + * Difficulty: Hard + * + * You are given a string s of length n, and an integer k. You are tasked to find the longest + * subsequence repeated k times in string s. + * + * A subsequence is a string that can be derived from another string by deleting some or no + * characters without changing the order of the remaining characters. + * + * A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, + * where seq * k represents a string constructed by concatenating seq k times. + * - For example, "bba" is repeated 2 times in the string "bababcba", because the string + * "bbabba", constructed by concatenating "bba" 2 times, is a subsequence of the + * string "bababcba". + * + * Return the longest subsequence repeated k times in string s. If multiple such subsequences + * are found, return the lexicographically largest one. If there is no such subsequence, + * return an empty string. + */ + +/** + * @param {string} s + * @param {number} k + * @return {string} + */ +var longestSubsequenceRepeatedK = function(s, k) { + const n = s.length; + const freq = new Array(26).fill(0); + for (const char of s) { + freq[char.charCodeAt(0) - 97]++; + } + + let candidates = ''; + for (let i = 0; i < 26; i++) { + const count = Math.floor(freq[i] / k); + candidates += String.fromCharCode(97 + i).repeat(count); + } + + function canFormSubsequence(seq) { + let j = 0; + for (let i = 0; i < n && j < seq.length * k; i++) { + if (s[i] === seq[j % seq.length]) j++; + } + return j >= seq.length * k; + } + + let result = ''; + backtrack('', candidates); + return result; + + function backtrack(curr, remaining) { + if (curr.length > result.length || (curr.length === result.length && curr > result)) { + if (canFormSubsequence(curr)) result = curr; + } + if (!remaining) return; + + for (let i = remaining.length - 1; i >= 0; i--) { + const nextChar = remaining[i]; + backtrack(curr + nextChar, remaining.slice(0, i) + remaining.slice(i + 1)); + } + } +}; From 635885bda60d8f8aee5c09f618a82f8cc0aa207f Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 18:47:06 -0500 Subject: [PATCH 185/495] Add solution #2018 --- README.md | 3 +- ...heck-if-word-can-be-placed-in-crossword.js | 66 +++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 solutions/2018-check-if-word-can-be-placed-in-crossword.js diff --git a/README.md b/README.md index e3568a61..6e9ddcdc 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,689 LeetCode solutions in JavaScript +# 1,690 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1548,6 +1548,7 @@ 2014|[Longest Subsequence Repeated k Times](./solutions/2014-longest-subsequence-repeated-k-times.js)|Hard| 2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy| 2017|[Grid Game](./solutions/2017-grid-game.js)|Medium| +2018|[Check if Word Can Be Placed In Crossword](./solutions/2018-check-if-word-can-be-placed-in-crossword.js)|Medium| 2027|[Minimum Moves to Convert String](./solutions/2027-minimum-moves-to-convert-string.js)|Easy| 2033|[Minimum Operations to Make a Uni-Value Grid](./solutions/2033-minimum-operations-to-make-a-uni-value-grid.js)|Medium| 2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| diff --git a/solutions/2018-check-if-word-can-be-placed-in-crossword.js b/solutions/2018-check-if-word-can-be-placed-in-crossword.js new file mode 100644 index 00000000..0a22bd5c --- /dev/null +++ b/solutions/2018-check-if-word-can-be-placed-in-crossword.js @@ -0,0 +1,66 @@ +/** + * 2018. Check if Word Can Be Placed In Crossword + * https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/ + * Difficulty: Medium + * + * You are given an m x n matrix board, representing the current state of a crossword puzzle. + * The crossword contains lowercase English letters (from solved words), ' ' to represent any + * empty cells, and '#' to represent any blocked cells. + * + * A word can be placed horizontally (left to right or right to left) or vertically (top to + * bottom or bottom to top) in the board if: + * - It does not occupy a cell containing the character '#'. + * - The cell each letter is placed in must either be ' ' (empty) or match the letter already + * on the board. + * - There must not be any empty cells ' ' or other lowercase letters directly left or right + * of the word if the word was placed horizontally. + * - There must not be any empty cells ' ' or other lowercase letters directly above or below + * the word if the word was placed vertically. + * + * Given a string word, return true if word can be placed in board, or false otherwise. + */ + +/** + * @param {character[][]} board + * @param {string} word + * @return {boolean} + */ +var placeWordInCrossword = function(board, word) { + const rows = board.length; + const cols = board[0].length; + const wordLen = word.length; + + function canPlace(row, col, dr, dc) { + for (let i = 0; i < wordLen; i++) { + const r = row + i * dr; + const c = col + i * dc; + if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] === '#') return false; + if (board[r][c] !== ' ' && board[r][c] !== word[i]) return false; + } + + const beforeR = row - dr; + const beforeC = col - dc; + const afterR = row + wordLen * dr; + const afterC = col + wordLen * dc; + + if ((beforeR >= 0 && beforeR < rows && beforeC >= 0 + && beforeC < cols && board[beforeR][beforeC] !== '#') + || (afterR >= 0 && afterR < rows && afterC >= 0 + && afterC < cols && board[afterR][afterC] !== '#')) { + return false; + } + + return true; + } + + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + if (canPlace(r, c, 0, 1) || canPlace(r, c, 0, -1) + || canPlace(r, c, 1, 0) || canPlace(r, c, -1, 0)) { + return true; + } + } + } + + return false; +}; From 3811e5e8ece8a698e9b3534a4b664e46e65e1c3a Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 18:58:30 -0500 Subject: [PATCH 186/495] Add solution #2019 --- README.md | 3 +- ...ore-of-students-solving-math-expression.js | 72 +++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 solutions/2019-the-score-of-students-solving-math-expression.js diff --git a/README.md b/README.md index 6e9ddcdc..7d580045 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,690 LeetCode solutions in JavaScript +# 1,691 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1549,6 +1549,7 @@ 2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy| 2017|[Grid Game](./solutions/2017-grid-game.js)|Medium| 2018|[Check if Word Can Be Placed In Crossword](./solutions/2018-check-if-word-can-be-placed-in-crossword.js)|Medium| +2019|[The Score of Students Solving Math Expression](./solutions/2019-the-score-of-students-solving-math-expression.js)|Hard| 2027|[Minimum Moves to Convert String](./solutions/2027-minimum-moves-to-convert-string.js)|Easy| 2033|[Minimum Operations to Make a Uni-Value Grid](./solutions/2033-minimum-operations-to-make-a-uni-value-grid.js)|Medium| 2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| diff --git a/solutions/2019-the-score-of-students-solving-math-expression.js b/solutions/2019-the-score-of-students-solving-math-expression.js new file mode 100644 index 00000000..b4391da2 --- /dev/null +++ b/solutions/2019-the-score-of-students-solving-math-expression.js @@ -0,0 +1,72 @@ +/** + * 2019. The Score of Students Solving Math Expression + * https://leetcode.com/problems/the-score-of-students-solving-math-expression/ + * Difficulty: Hard + * + * You are given a string s that contains digits 0-9, addition symbols '+', and multiplication + * symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). + * This expression was given to n elementary school students. The students were instructed to + * get the answer of the expression by following this order of operations: + * 1. Compute multiplication, reading from left to right; Then, + * 2. Compute addition, reading from left to right. + * + * You are given an integer array answers of length n, which are the submitted answers of the + * students in no particular order. You are asked to grade the answers, by following these rules: + * - If an answer equals the correct answer of the expression, this student will be rewarded + * 5 points; + * - Otherwise, if the answer could be interpreted as if the student applied the operators in + * the wrong order but had correct arithmetic, this student will be rewarded 2 points; + * - Otherwise, this student will be rewarded 0 points. + * + * Return the sum of the points of the students. + */ + +/** + * @param {string} s + * @param {number[]} answers + * @return {number} + */ +var scoreOfStudents = function(s, answers) { + const correct = eval(s.replace(/(\d)([*+])/g, '$1 $2 ')); + + const n = s.length; + const dp = new Map(); + + function compute(start, end) { + const key = `${start},${end}`; + if (dp.has(key)) return dp.get(key); + + const results = new Set(); + if (start === end) { + results.add(Number(s[start])); + dp.set(key, results); + return results; + } + + for (let i = start + 1; i < end; i += 2) { + const leftResults = compute(start, i - 1); + const rightResults = compute(i + 1, end); + const op = s[i]; + + for (const left of leftResults) { + for (const right of rightResults) { + const val = op === '+' ? left + right : left * right; + if (val <= 1000) results.add(val); + } + } + } + + dp.set(key, results); + return results; + } + + const wrongAnswers = compute(0, n - 1); + let result = 0; + + for (const answer of answers) { + if (answer === correct) result += 5; + else if (wrongAnswers.has(answer)) result += 2; + } + + return result; +}; From 9e5a6bf74d6305580062f37f9b3e1427509f0b40 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 18:59:31 -0500 Subject: [PATCH 187/495] Add solution #2022 --- README.md | 3 +- .../2022-convert-1d-array-into-2d-array.js | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 solutions/2022-convert-1d-array-into-2d-array.js diff --git a/README.md b/README.md index 7d580045..cec620ea 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,691 LeetCode solutions in JavaScript +# 1,692 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1550,6 +1550,7 @@ 2017|[Grid Game](./solutions/2017-grid-game.js)|Medium| 2018|[Check if Word Can Be Placed In Crossword](./solutions/2018-check-if-word-can-be-placed-in-crossword.js)|Medium| 2019|[The Score of Students Solving Math Expression](./solutions/2019-the-score-of-students-solving-math-expression.js)|Hard| +2022|[Convert 1D Array Into 2D Array](./solutions/2022-convert-1d-array-into-2d-array.js)|Easy| 2027|[Minimum Moves to Convert String](./solutions/2027-minimum-moves-to-convert-string.js)|Easy| 2033|[Minimum Operations to Make a Uni-Value Grid](./solutions/2033-minimum-operations-to-make-a-uni-value-grid.js)|Medium| 2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| diff --git a/solutions/2022-convert-1d-array-into-2d-array.js b/solutions/2022-convert-1d-array-into-2d-array.js new file mode 100644 index 00000000..a550b710 --- /dev/null +++ b/solutions/2022-convert-1d-array-into-2d-array.js @@ -0,0 +1,33 @@ +/** + * 2022. Convert 1D Array Into 2D Array + * https://leetcode.com/problems/convert-1d-array-into-2d-array/ + * Difficulty: Easy + * + * You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, + * m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n + * columns using all the elements from original. + * + * The elements from indices 0 to n - 1 (inclusive) of original should form the first row + * of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should + * form the second row of the constructed 2D array, and so on. + * + * Return an m x n 2D array constructed according to the above procedure, or an empty 2D array + * if it is impossible. + */ + +/** + * @param {number[]} original + * @param {number} m + * @param {number} n + * @return {number[][]} + */ +var construct2DArray = function(original, m, n) { + if (original.length !== m * n) return []; + + const result = []; + for (let i = 0; i < m; i++) { + result.push(original.slice(i * n, (i + 1) * n)); + } + + return result; +}; From 9f0110d8e34e82caf6e0a117e2f851f6367bf420 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 19:00:37 -0500 Subject: [PATCH 188/495] Add solution #2023 --- README.md | 3 +- ...ings-with-concatenation-equal-to-target.js | 32 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 solutions/2023-number-of-pairs-of-strings-with-concatenation-equal-to-target.js diff --git a/README.md b/README.md index cec620ea..805e1b80 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,692 LeetCode solutions in JavaScript +# 1,693 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1551,6 +1551,7 @@ 2018|[Check if Word Can Be Placed In Crossword](./solutions/2018-check-if-word-can-be-placed-in-crossword.js)|Medium| 2019|[The Score of Students Solving Math Expression](./solutions/2019-the-score-of-students-solving-math-expression.js)|Hard| 2022|[Convert 1D Array Into 2D Array](./solutions/2022-convert-1d-array-into-2d-array.js)|Easy| +2023|[Number of Pairs of Strings With Concatenation Equal to Target](./solutions/2023-number-of-pairs-of-strings-with-concatenation-equal-to-target.js)|Medium| 2027|[Minimum Moves to Convert String](./solutions/2027-minimum-moves-to-convert-string.js)|Easy| 2033|[Minimum Operations to Make a Uni-Value Grid](./solutions/2033-minimum-operations-to-make-a-uni-value-grid.js)|Medium| 2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| diff --git a/solutions/2023-number-of-pairs-of-strings-with-concatenation-equal-to-target.js b/solutions/2023-number-of-pairs-of-strings-with-concatenation-equal-to-target.js new file mode 100644 index 00000000..f2e98de0 --- /dev/null +++ b/solutions/2023-number-of-pairs-of-strings-with-concatenation-equal-to-target.js @@ -0,0 +1,32 @@ +/** + * 2023. Number of Pairs of Strings With Concatenation Equal to Target + * https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/ + * Difficulty: Medium + * + * Given an array of digit strings nums and a digit string target, return the number of pairs of + * indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target. + */ + +/** + * @param {string[]} nums + * @param {string} target + * @return {number} + */ +var numOfPairs = function(nums, target) { + const map = new Map(); + let result = 0; + + for (const num of nums) { + if (target.startsWith(num)) { + const suffix = target.slice(num.length); + result += map.get(suffix) || 0; + } + if (target.endsWith(num)) { + const prefix = target.slice(0, target.length - num.length); + result += map.get(prefix) || 0; + } + map.set(num, (map.get(num) || 0) + 1); + } + + return result; +}; From 2968e760d8a370c370a4dbbda5cc3ea6be7f2c29 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 19:02:01 -0500 Subject: [PATCH 189/495] Add solution #2024 --- README.md | 3 +- .../2024-maximize-the-confusion-of-an-exam.js | 43 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 solutions/2024-maximize-the-confusion-of-an-exam.js diff --git a/README.md b/README.md index 805e1b80..d8e20aa2 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,693 LeetCode solutions in JavaScript +# 1,694 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1552,6 +1552,7 @@ 2019|[The Score of Students Solving Math Expression](./solutions/2019-the-score-of-students-solving-math-expression.js)|Hard| 2022|[Convert 1D Array Into 2D Array](./solutions/2022-convert-1d-array-into-2d-array.js)|Easy| 2023|[Number of Pairs of Strings With Concatenation Equal to Target](./solutions/2023-number-of-pairs-of-strings-with-concatenation-equal-to-target.js)|Medium| +2024|[Maximize the Confusion of an Exam](./solutions/2024-maximize-the-confusion-of-an-exam.js)|Medium| 2027|[Minimum Moves to Convert String](./solutions/2027-minimum-moves-to-convert-string.js)|Easy| 2033|[Minimum Operations to Make a Uni-Value Grid](./solutions/2033-minimum-operations-to-make-a-uni-value-grid.js)|Medium| 2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| diff --git a/solutions/2024-maximize-the-confusion-of-an-exam.js b/solutions/2024-maximize-the-confusion-of-an-exam.js new file mode 100644 index 00000000..f79d25b1 --- /dev/null +++ b/solutions/2024-maximize-the-confusion-of-an-exam.js @@ -0,0 +1,43 @@ +/** + * 2024. Maximize the Confusion of an Exam + * https://leetcode.com/problems/maximize-the-confusion-of-an-exam/ + * Difficulty: Medium + * + * A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting + * false. He wants to confuse the students by maximizing the number of consecutive questions with + * the same answer (multiple trues or multiple falses in a row). + * + * You are given a string answerKey, where answerKey[i] is the original answer to the ith question. + * In addition, you are given an integer k, the maximum number of times you may perform the + * following operation: + * - Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F'). + * + * Return the maximum number of consecutive 'T's or 'F's in the answer key after performing the + * operation at most k times. + */ + +/** + * @param {string} answerKey + * @param {number} k + * @return {number} + */ +var maxConsecutiveAnswers = function(answerKey, k) { + const flipsLeft = k; + const count = { T: 0, F: 0 }; + let result = 0; + let left = 0; + + for (let right = 0; right < answerKey.length; right++) { + count[answerKey[right]]++; + const maxCount = Math.max(count.T, count.F); + + while (right - left + 1 - maxCount > flipsLeft) { + count[answerKey[left]]--; + left++; + } + + result = Math.max(result, right - left + 1); + } + + return result; +}; From ec82cc1cd8998ee3fd3605ea266006ef8457656f Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 19:15:12 -0500 Subject: [PATCH 190/495] Add solution #2025 --- README.md | 3 +- ...um-number-of-ways-to-partition-an-array.js | 57 +++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 solutions/2025-maximum-number-of-ways-to-partition-an-array.js diff --git a/README.md b/README.md index d8e20aa2..b5a5776b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,694 LeetCode solutions in JavaScript +# 1,695 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1553,6 +1553,7 @@ 2022|[Convert 1D Array Into 2D Array](./solutions/2022-convert-1d-array-into-2d-array.js)|Easy| 2023|[Number of Pairs of Strings With Concatenation Equal to Target](./solutions/2023-number-of-pairs-of-strings-with-concatenation-equal-to-target.js)|Medium| 2024|[Maximize the Confusion of an Exam](./solutions/2024-maximize-the-confusion-of-an-exam.js)|Medium| +2025|[Maximum Number of Ways to Partition an Array](./solutions/2025-maximum-number-of-ways-to-partition-an-array.js)|Hard| 2027|[Minimum Moves to Convert String](./solutions/2027-minimum-moves-to-convert-string.js)|Easy| 2033|[Minimum Operations to Make a Uni-Value Grid](./solutions/2033-minimum-operations-to-make-a-uni-value-grid.js)|Medium| 2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| diff --git a/solutions/2025-maximum-number-of-ways-to-partition-an-array.js b/solutions/2025-maximum-number-of-ways-to-partition-an-array.js new file mode 100644 index 00000000..2e28cd39 --- /dev/null +++ b/solutions/2025-maximum-number-of-ways-to-partition-an-array.js @@ -0,0 +1,57 @@ +/** + * 2025. Maximum Number of Ways to Partition an Array + * https://leetcode.com/problems/maximum-number-of-ways-to-partition-an-array/ + * Difficulty: Hard + * + * You are given a 0-indexed integer array nums of length n. The number of ways to partition + * nums is the number of pivot indices that satisfy both conditions: + * - 1 <= pivot < n + * - nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1] + * + * You are also given an integer k. You can choose to change the value of one element of nums to + * k, or to leave the array unchanged. + * + * Return the maximum possible number of ways to partition nums to satisfy both conditions after + * changing at most one element. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var waysToPartition = function(nums, k) { + const n = nums.length; + const prefixSums = [nums[0]]; + const leftDiffs = new Map(); + const rightDiffs = new Map(); + + for (let i = 1; i < n; i++) { + prefixSums[i] = prefixSums[i - 1] + nums[i]; + const diff = prefixSums[i - 1]; + rightDiffs.set(diff, (rightDiffs.get(diff) || 0) + 1); + } + + const totalSum = prefixSums[n - 1]; + let result = totalSum % 2 === 0 ? (rightDiffs.get(totalSum / 2) || 0) : 0; + + for (let i = 0; i < n; i++) { + const delta = k - nums[i]; + const newTotalSum = totalSum + delta; + + if (newTotalSum % 2 === 0) { + const targetSum = newTotalSum / 2; + const waysFromLeft = leftDiffs.get(targetSum) || 0; + const waysFromRight = rightDiffs.get(targetSum - delta) || 0; + result = Math.max(result, waysFromLeft + waysFromRight); + } + + if (i < n - 1) { + const currentDiff = prefixSums[i]; + leftDiffs.set(currentDiff, (leftDiffs.get(currentDiff) || 0) + 1); + rightDiffs.set(currentDiff, rightDiffs.get(currentDiff) - 1); + } + } + + return result; +}; From 46e8823025ce2531a88cbaa118d2015ac280bc8e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 19:18:26 -0500 Subject: [PATCH 191/495] Add solution #2028 --- README.md | 3 +- solutions/2028-find-missing-observations.js | 49 +++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 solutions/2028-find-missing-observations.js diff --git a/README.md b/README.md index b5a5776b..b0ff4c3e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,695 LeetCode solutions in JavaScript +# 1,696 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1555,6 +1555,7 @@ 2024|[Maximize the Confusion of an Exam](./solutions/2024-maximize-the-confusion-of-an-exam.js)|Medium| 2025|[Maximum Number of Ways to Partition an Array](./solutions/2025-maximum-number-of-ways-to-partition-an-array.js)|Hard| 2027|[Minimum Moves to Convert String](./solutions/2027-minimum-moves-to-convert-string.js)|Easy| +2028|[Find Missing Observations](./solutions/2028-find-missing-observations.js)|Medium| 2033|[Minimum Operations to Make a Uni-Value Grid](./solutions/2033-minimum-operations-to-make-a-uni-value-grid.js)|Medium| 2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| diff --git a/solutions/2028-find-missing-observations.js b/solutions/2028-find-missing-observations.js new file mode 100644 index 00000000..29296fbc --- /dev/null +++ b/solutions/2028-find-missing-observations.js @@ -0,0 +1,49 @@ +/** + * 2028. Find Missing Observations + * https://leetcode.com/problems/find-missing-observations/ + * Difficulty: Medium + * + * You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n + * of the observations went missing, and you only have the observations of m rolls. + * Fortunately, you have also calculated the average value of the n + m rolls. + * + * You are given an integer array rolls of length m where rolls[i] is the value of the ith + * observation. You are also given the two integers mean and n. + * + * Return an array of length n containing the missing observations such that the average + * value of the n + m rolls is exactly mean. If there are multiple valid answers, return + * any of them. If no such array exists, return an empty array. + * + * The average value of a set of k numbers is the sum of the numbers divided by k. + * + * Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m. + */ + +/** + * @param {number[]} rolls + * @param {number} mean + * @param {number} n + * @return {number[]} + */ +var missingRolls = function(rolls, mean, n) { + const totalRolls = rolls.length + n; + const targetSum = mean * totalRolls; + const currentSum = rolls.reduce((sum, roll) => sum + roll, 0); + const missingSum = targetSum - currentSum; + + if (missingSum < n || missingSum > 6 * n) return []; + + const baseValue = Math.floor(missingSum / n); + const remainder = missingSum % n; + const result = []; + + for (let i = 0; i < n; i++) { + if (i < remainder) { + result.push(baseValue + 1); + } else { + result.push(baseValue); + } + } + + return result; +}; From f0ab9762e92ffd17cbfd31ba537673e7ec62c4b4 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 19:19:28 -0500 Subject: [PATCH 192/495] Add solution #2029 --- README.md | 3 ++- solutions/2029-stone-game-ix.js | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 solutions/2029-stone-game-ix.js diff --git a/README.md b/README.md index b0ff4c3e..80e246ad 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,696 LeetCode solutions in JavaScript +# 1,697 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1556,6 +1556,7 @@ 2025|[Maximum Number of Ways to Partition an Array](./solutions/2025-maximum-number-of-ways-to-partition-an-array.js)|Hard| 2027|[Minimum Moves to Convert String](./solutions/2027-minimum-moves-to-convert-string.js)|Easy| 2028|[Find Missing Observations](./solutions/2028-find-missing-observations.js)|Medium| +2029|[Stone Game IX](./solutions/2029-stone-game-ix.js)|Medium| 2033|[Minimum Operations to Make a Uni-Value Grid](./solutions/2033-minimum-operations-to-make-a-uni-value-grid.js)|Medium| 2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| diff --git a/solutions/2029-stone-game-ix.js b/solutions/2029-stone-game-ix.js new file mode 100644 index 00000000..31ea3bb8 --- /dev/null +++ b/solutions/2029-stone-game-ix.js @@ -0,0 +1,33 @@ +/** + * 2029. Stone Game IX + * https://leetcode.com/problems/stone-game-ix/ + * Difficulty: Medium + * + * Alice and Bob continue their games with stones. There is a row of n stones, and each stone has + * an associated value. You are given an integer array stones, where stones[i] is the value of the + * ith stone. + * + * Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any + * stone from stones. The player who removes a stone loses if the sum of the values of all + * removed stones is divisible by 3. Bob will win automatically if there are no remaining stones + * (even if it is Alice's turn). + * + * Assuming both players play optimally, return true if Alice wins and false if Bob wins. + */ + +/** + * @param {number[]} stones + * @return {boolean} + */ +var stoneGameIX = function(stones) { + const remainderCount = [0, 0, 0]; + for (const stone of stones) { + remainderCount[stone % 3]++; + } + + if (remainderCount[0] % 2 === 0) { + return remainderCount[1] >= 1 && remainderCount[2] >= 1; + } + + return Math.abs(remainderCount[1] - remainderCount[2]) > 2; +}; From 5e5bab83024d0bc37475e98dce05798e2c7e1743 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 19:32:17 -0500 Subject: [PATCH 193/495] Add solution #2030 --- README.md | 3 +- ...ubsequence-with-occurrences-of-a-letter.js | 83 +++++++++++++++++++ 2 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 solutions/2030-smallest-k-length-subsequence-with-occurrences-of-a-letter.js diff --git a/README.md b/README.md index 80e246ad..1ed8524b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,697 LeetCode solutions in JavaScript +# 1,698 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1557,6 +1557,7 @@ 2027|[Minimum Moves to Convert String](./solutions/2027-minimum-moves-to-convert-string.js)|Easy| 2028|[Find Missing Observations](./solutions/2028-find-missing-observations.js)|Medium| 2029|[Stone Game IX](./solutions/2029-stone-game-ix.js)|Medium| +2030|[Smallest K-Length Subsequence With Occurrences of a Letter](./solutions/2030-smallest-k-length-subsequence-with-occurrences-of-a-letter.js)|Hard| 2033|[Minimum Operations to Make a Uni-Value Grid](./solutions/2033-minimum-operations-to-make-a-uni-value-grid.js)|Medium| 2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| diff --git a/solutions/2030-smallest-k-length-subsequence-with-occurrences-of-a-letter.js b/solutions/2030-smallest-k-length-subsequence-with-occurrences-of-a-letter.js new file mode 100644 index 00000000..9e3f916b --- /dev/null +++ b/solutions/2030-smallest-k-length-subsequence-with-occurrences-of-a-letter.js @@ -0,0 +1,83 @@ +/** + * 2030. Smallest K-Length Subsequence With Occurrences of a Letter + * https://leetcode.com/problems/smallest-k-length-subsequence-with-occurrences-of-a-letter/ + * Difficulty: Hard + * + * You are given a string s, an integer k, a letter letter, and an integer repetition. + * + * Return the lexicographically smallest subsequence of s of length k that has the letter + * letter appear at least repetition times. The test cases are generated so that the letter + * appears in s at least repetition times. + * + * A subsequence is a string that can be derived from another string by deleting some or no + * characters without changing the order of the remaining characters. + * + * A string a is lexicographically smaller than a string b if in the first position where a + * and b differ, string a has a letter that appears earlier in the alphabet than the + * corresponding letter in b. + */ + +/** + * @param {string} s + * @param {number} k + * @param {character} letter + * @param {number} repetition + * @return {string} + */ +var smallestSubsequence = function(s, k, letter, repetition) { + const n = s.length; + let letterTotal = 0; + for (let i = 0; i < n; i++) { + if (s[i] === letter) letterTotal++; + } + + const stack = []; + let stackLetterCount = 0; + let remainingCount = letterTotal; + + for (let i = 0; i < n; i++) { + const char = s[i]; + + if (char === letter) { + remainingCount--; + } + + while ( + stack.length > 0 && stack[stack.length - 1] > char && stack.length - 1 + (n - i) >= k + && (stack[stack.length - 1] !== letter || stackLetterCount + remainingCount > repetition) + ) { + if (stack[stack.length - 1] === letter) { + stackLetterCount--; + } + stack.pop(); + } + + if (stack.length < k) { + if (char === letter) { + stackLetterCount++; + } + + const neededLetters = repetition - stackLetterCount; + const remainingPositions = k - stack.length - 1; + if (char === letter || remainingPositions >= neededLetters) { + stack.push(char); + } + } + } + + if (stackLetterCount < repetition) { + let missingLetters = repetition - stackLetterCount; + const result = [...stack]; + + for (let i = k - 1; i >= 0 && missingLetters > 0; i--) { + if (result[i] !== letter) { + result[i] = letter; + missingLetters--; + } + } + + return result.join(''); + } + + return stack.join(''); +}; From b9f8785518bfd88a650e47b61d5c0def2a63ced0 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 19:33:14 -0500 Subject: [PATCH 194/495] Add solution #2032 --- README.md | 3 ++- solutions/2032-two-out-of-three.js | 41 ++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 solutions/2032-two-out-of-three.js diff --git a/README.md b/README.md index 1ed8524b..e7818ed7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,698 LeetCode solutions in JavaScript +# 1,699 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1558,6 +1558,7 @@ 2028|[Find Missing Observations](./solutions/2028-find-missing-observations.js)|Medium| 2029|[Stone Game IX](./solutions/2029-stone-game-ix.js)|Medium| 2030|[Smallest K-Length Subsequence With Occurrences of a Letter](./solutions/2030-smallest-k-length-subsequence-with-occurrences-of-a-letter.js)|Hard| +2032|[Two Out of Three](./solutions/2032-two-out-of-three.js)|Easy| 2033|[Minimum Operations to Make a Uni-Value Grid](./solutions/2033-minimum-operations-to-make-a-uni-value-grid.js)|Medium| 2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| diff --git a/solutions/2032-two-out-of-three.js b/solutions/2032-two-out-of-three.js new file mode 100644 index 00000000..566e6033 --- /dev/null +++ b/solutions/2032-two-out-of-three.js @@ -0,0 +1,41 @@ +/** + * 2032. Two Out of Three + * https://leetcode.com/problems/two-out-of-three/ + * Difficulty: Easy + * + * Given three integer arrays nums1, nums2, and nums3, return a distinct array containing all + * the values that are present in at least two out of the three arrays. You may return the + * values in any order. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @param {number[]} nums3 + * @return {number[]} + */ +var twoOutOfThree = function(nums1, nums2, nums3) { + const set1 = new Set(nums1); + const set2 = new Set(nums2); + const set3 = new Set(nums3); + const count = new Map(); + + for (const num of set1) { + count.set(num, (count.get(num) || 0) + 1); + } + + for (const num of set2) { + count.set(num, (count.get(num) || 0) + 1); + } + + for (const num of set3) { + count.set(num, (count.get(num) || 0) + 1); + } + + const result = []; + for (const [num, freq] of count) { + if (freq >= 2) result.push(num); + } + + return result; +}; From f71ce9101a48154e13806be794344560046026a0 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 5 May 2025 19:38:22 -0500 Subject: [PATCH 195/495] Add solution #2035 --- README.md | 3 +- ...o-two-arrays-to-minimize-sum-difference.js | 93 +++++++++++++++++++ 2 files changed, 95 insertions(+), 1 deletion(-) create mode 100644 solutions/2035-partition-array-into-two-arrays-to-minimize-sum-difference.js diff --git a/README.md b/README.md index e7818ed7..950bd14e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,699 LeetCode solutions in JavaScript +# 1,700 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1560,6 +1560,7 @@ 2030|[Smallest K-Length Subsequence With Occurrences of a Letter](./solutions/2030-smallest-k-length-subsequence-with-occurrences-of-a-letter.js)|Hard| 2032|[Two Out of Three](./solutions/2032-two-out-of-three.js)|Easy| 2033|[Minimum Operations to Make a Uni-Value Grid](./solutions/2033-minimum-operations-to-make-a-uni-value-grid.js)|Medium| +2035|[Partition Array Into Two Arrays to Minimize Sum Difference](./solutions/2035-partition-array-into-two-arrays-to-minimize-sum-difference.js)|Hard| 2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| 2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| diff --git a/solutions/2035-partition-array-into-two-arrays-to-minimize-sum-difference.js b/solutions/2035-partition-array-into-two-arrays-to-minimize-sum-difference.js new file mode 100644 index 00000000..1f3266b1 --- /dev/null +++ b/solutions/2035-partition-array-into-two-arrays-to-minimize-sum-difference.js @@ -0,0 +1,93 @@ +/** + * 2035. Partition Array Into Two Arrays to Minimize Sum Difference + * https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/ + * Difficulty: Hard + * + * You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays + * of length n to minimize the absolute difference of the sums of the arrays. To partition nums, + * put each element of nums into one of the two arrays. + * + * Return the minimum possible absolute difference. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var minimumDifference = function(nums) { + const n = nums.length / 2; + let result = Infinity; + const totalSum = nums.reduce((sum, num) => sum + num, 0); + const firstHalfSubsets = new Map(); + + for (let mask = 0; mask < (1 << n); mask++) { + let size = 0; + let subsetSum = 0; + + for (let i = 0; i < n; i++) { + if ((mask & (1 << i)) !== 0) { + size++; + subsetSum += nums[i]; + } + } + + if (!firstHalfSubsets.has(size)) { + firstHalfSubsets.set(size, []); + } + firstHalfSubsets.get(size).push(subsetSum); + } + + for (const [size, sums] of firstHalfSubsets) { + sums.sort((a, b) => a - b); + } + + for (let mask = 0; mask < (1 << n); mask++) { + let size = 0; + let secondHalfSum = 0; + + for (let i = 0; i < n; i++) { + if ((mask & (1 << i)) !== 0) { + size++; + secondHalfSum += nums[n + i]; + } + } + + const complementSize = n - size; + const firstHalfSums = firstHalfSubsets.get(complementSize); + const target = (totalSum - 2 * secondHalfSum) / 2; + const closestIndex = binarySearch(firstHalfSums, target); + + if (closestIndex < firstHalfSums.length) { + result = Math.min( + result, Math.abs(totalSum - 2 * (secondHalfSum + firstHalfSums[closestIndex])) + ); + } + + if (closestIndex > 0) { + result = Math.min( + result, Math.abs(totalSum - 2 * (secondHalfSum + firstHalfSums[closestIndex - 1])) + ); + } + } + + return result; +}; + +function binarySearch(arr, target) { + let left = 0; + let right = arr.length - 1; + + if (right < 0) return 0; + + while (left < right) { + const mid = Math.floor((left + right) / 2); + + if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid; + } + } + + return left; +} From 4bee36ce7d239657f816f8aea68e0b738901e9ed Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 6 May 2025 00:55:27 -0500 Subject: [PATCH 196/495] Add solution #2038 --- README.md | 3 +- ...es-if-both-neighbors-are-the-same-color.js | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 solutions/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js diff --git a/README.md b/README.md index 950bd14e..45e2f805 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,700 LeetCode solutions in JavaScript +# 1,701 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1562,6 +1562,7 @@ 2033|[Minimum Operations to Make a Uni-Value Grid](./solutions/2033-minimum-operations-to-make-a-uni-value-grid.js)|Medium| 2035|[Partition Array Into Two Arrays to Minimize Sum Difference](./solutions/2035-partition-array-into-two-arrays-to-minimize-sum-difference.js)|Hard| 2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| +2038|[Remove Colored Pieces if Both Neighbors are the Same Color](./solutions/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js)|Medium| 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| 2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| diff --git a/solutions/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js b/solutions/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js new file mode 100644 index 00000000..7a42cfcb --- /dev/null +++ b/solutions/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js @@ -0,0 +1,38 @@ +/** + * 2038. Remove Colored Pieces if Both Neighbors are the Same Color + * https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/ + * Difficulty: Medium + * + * There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. + * You are given a string colors of length n where colors[i] is the color of the ith piece. + * + * Alice and Bob are playing a game where they take alternating turns removing pieces from the + * line. In this game, Alice moves first. + * - Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored + * 'A'. She is not allowed to remove pieces that are colored 'B'. + * - Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored + * 'B'. He is not allowed to remove pieces that are colored 'A'. + * - Alice and Bob cannot remove pieces from the edge of the line. + * - If a player cannot make a move on their turn, that player loses and the other player wins. + * + * Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins. + */ + +/** + * @param {string} colors + * @return {boolean} + */ +var winnerOfGame = function(colors) { + let aliceMoves = 0; + let bobMoves = 0; + + for (let i = 1; i < colors.length - 1; i++) { + if (colors[i] === 'A' && colors[i - 1] === 'A' && colors[i + 1] === 'A') { + aliceMoves++; + } else if (colors[i] === 'B' && colors[i - 1] === 'B' && colors[i + 1] === 'B') { + bobMoves++; + } + } + + return aliceMoves > bobMoves; +}; From fb018a360746460e2b3392a36c8badffe37b3add Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 6 May 2025 00:58:07 -0500 Subject: [PATCH 197/495] Add solution #2039 --- README.md | 3 +- ...-the-time-when-the-network-becomes-idle.js | 71 +++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 solutions/2039-the-time-when-the-network-becomes-idle.js diff --git a/README.md b/README.md index 45e2f805..0e36cc05 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,701 LeetCode solutions in JavaScript +# 1,702 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1563,6 +1563,7 @@ 2035|[Partition Array Into Two Arrays to Minimize Sum Difference](./solutions/2035-partition-array-into-two-arrays-to-minimize-sum-difference.js)|Hard| 2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| 2038|[Remove Colored Pieces if Both Neighbors are the Same Color](./solutions/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js)|Medium| +2039|[The Time When the Network Becomes Idle](./solutions/2039-the-time-when-the-network-becomes-idle.js)|Medium| 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| 2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| diff --git a/solutions/2039-the-time-when-the-network-becomes-idle.js b/solutions/2039-the-time-when-the-network-becomes-idle.js new file mode 100644 index 00000000..38287340 --- /dev/null +++ b/solutions/2039-the-time-when-the-network-becomes-idle.js @@ -0,0 +1,71 @@ +/** + * 2039. The Time When the Network Becomes Idle + * https://leetcode.com/problems/the-time-when-the-network-becomes-idle/ + * Difficulty: Medium + * + * There is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array + * edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui + * and vi, and they can pass any number of messages to each other directly in one second. + * You are also given a 0-indexed integer array patience of length n. + * + * All servers are connected, i.e., a message can be passed from one server to any other + * server(s) directly or indirectly through the message channels. + * + * The server labeled 0 is the master server. The rest are data servers. Each data server + * needs to send its message to the master server for processing and wait for a reply. + * Messages move between servers optimally, so every message takes the least amount of + * time to arrive at the master server. The master server will process all newly arrived + * messages instantly and send a reply to the originating server via the reversed path + * the message had gone through. + * + * At the beginning of second 0, each data server sends its message to be processed. Starting + * from second 1, at the beginning of every second, each data server will check if it has + * received a reply to the message it sent (including any newly arrived replies) from the + * master server: + * - If it has not, it will resend the message periodically. The data server i will resend + * the message every patience[i] second(s), i.e., the data server i will resend the message + * if patience[i] second(s) have elapsed since the last time the message was sent from this + * server. + * - Otherwise, no more resending will occur from this server. + * + * The network becomes idle when there are no messages passing between servers or arriving + * at servers. + * + * Return the earliest second starting from which the network becomes idle. + */ + +/** + * @param {number[][]} edges + * @param {number[]} patience + * @return {number} + */ +var networkBecomesIdle = function(edges, patience) { + const n = patience.length; + const adjList = Array.from({ length: n }, () => []); + for (const [u, v] of edges) { + adjList[u].push(v); + adjList[v].push(u); + } + + const distances = new Array(n).fill(Infinity); + distances[0] = 0; + const queue = [0]; + let maxTime = 0; + + while (queue.length) { + const curr = queue.shift(); + for (const next of adjList[curr]) { + if (distances[next] === Infinity) { + distances[next] = distances[curr] + 1; + queue.push(next); + if (next !== 0) { + const roundTrip = 2 * distances[next]; + const lastSent = Math.floor((roundTrip - 1) / patience[next]) * patience[next]; + maxTime = Math.max(maxTime, lastSent + roundTrip); + } + } + } + } + + return maxTime + 1; +}; From 7ad2c640c4bba88eccb945b3361f58cb8189f150 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 6 May 2025 00:59:58 -0500 Subject: [PATCH 198/495] Add solution #2040 --- README.md | 3 +- ...h-smallest-product-of-two-sorted-arrays.js | 53 +++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 solutions/2040-kth-smallest-product-of-two-sorted-arrays.js diff --git a/README.md b/README.md index 0e36cc05..415ac4e1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,702 LeetCode solutions in JavaScript +# 1,703 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1564,6 +1564,7 @@ 2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| 2038|[Remove Colored Pieces if Both Neighbors are the Same Color](./solutions/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js)|Medium| 2039|[The Time When the Network Becomes Idle](./solutions/2039-the-time-when-the-network-becomes-idle.js)|Medium| +2040|[Kth Smallest Product of Two Sorted Arrays](./solutions/2040-kth-smallest-product-of-two-sorted-arrays.js)|Hard| 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| 2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| diff --git a/solutions/2040-kth-smallest-product-of-two-sorted-arrays.js b/solutions/2040-kth-smallest-product-of-two-sorted-arrays.js new file mode 100644 index 00000000..80a4da8c --- /dev/null +++ b/solutions/2040-kth-smallest-product-of-two-sorted-arrays.js @@ -0,0 +1,53 @@ +/** + * 2040. Kth Smallest Product of Two Sorted Arrays + * https://leetcode.com/problems/kth-smallest-product-of-two-sorted-arrays/ + * Difficulty: Hard + * + * Given two sorted 0-indexed integer arrays nums1 and nums2 as well as an integer k, return + * the kth (1-based) smallest product of nums1[i] * nums2[j] where 0 <= i < nums1.length + * and 0 <= j < nums2.length. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @param {number} k + * @return {number} + */ +var kthSmallestProduct = function(nums1, nums2, k) { + function countProducts(maxProduct) { + let count = 0; + for (const num1 of nums1) { + let left = 0; + let right = nums2.length; + + if (num1 >= 0) { + while (left < right) { + const mid = Math.floor((left + right) / 2); + if (num1 * nums2[mid] <= maxProduct) left = mid + 1; + else right = mid; + } + count += left; + } else { + while (left < right) { + const mid = Math.floor((left + right) / 2); + if (num1 * nums2[mid] <= maxProduct) right = mid; + else left = mid + 1; + } + count += nums2.length - left; + } + } + return count; + } + + let low = -(10 ** 10); + let high = 10 ** 10; + + while (low < high) { + const mid = Math.floor((low + high) / 2); + if (countProducts(mid) >= k) high = mid; + else low = mid + 1; + } + + return low; +}; From 81c0c8e1d61f2d71b71d484dbf864664b2a84b41 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 6 May 2025 01:01:37 -0500 Subject: [PATCH 199/495] Add solution #2042 --- README.md | 3 +- ...-if-numbers-are-ascending-in-a-sentence.js | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 solutions/2042-check-if-numbers-are-ascending-in-a-sentence.js diff --git a/README.md b/README.md index 415ac4e1..ab4e5e9a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,703 LeetCode solutions in JavaScript +# 1,704 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1565,6 +1565,7 @@ 2038|[Remove Colored Pieces if Both Neighbors are the Same Color](./solutions/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js)|Medium| 2039|[The Time When the Network Becomes Idle](./solutions/2039-the-time-when-the-network-becomes-idle.js)|Medium| 2040|[Kth Smallest Product of Two Sorted Arrays](./solutions/2040-kth-smallest-product-of-two-sorted-arrays.js)|Hard| +2042|[Check if Numbers Are Ascending in a Sentence](./solutions/2042-check-if-numbers-are-ascending-in-a-sentence.js)|Easy| 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| 2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| diff --git a/solutions/2042-check-if-numbers-are-ascending-in-a-sentence.js b/solutions/2042-check-if-numbers-are-ascending-in-a-sentence.js new file mode 100644 index 00000000..5b91979b --- /dev/null +++ b/solutions/2042-check-if-numbers-are-ascending-in-a-sentence.js @@ -0,0 +1,29 @@ +/** + * 2042. Check if Numbers Are Ascending in a Sentence + * https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence/ + * Difficulty: Easy + * + * A sentence is a list of tokens separated by a single space with no leading or trailing spaces. + * Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a + * word consisting of lowercase English letters. + * - For example, "a puppy has 2 eyes 4 legs" is a sentence with seven tokens: "2" and "4" are + * numbers and the other tokens such as "puppy" are words. + * + * Given a string s representing a sentence, you need to check if all the numbers in s are strictly + * increasing from left to right (i.e., other than the last number, each number is strictly smaller + * than the number on its right in s). + * + * Return true if so, or false otherwise. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var areNumbersAscending = function(s) { + const numbers = s.split(' ').filter(token => !isNaN(token)).map(Number); + for (let i = 1; i < numbers.length; i++) { + if (numbers[i] <= numbers[i - 1]) return false; + } + return true; +}; From ddfd211a527a9e12bef6afd4f7bacfa052a5f2ba Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Tue, 6 May 2025 01:03:36 -0500 Subject: [PATCH 200/495] Add solution #2043 --- README.md | 3 +- solutions/2043-simple-bank-system.js | 71 ++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 solutions/2043-simple-bank-system.js diff --git a/README.md b/README.md index ab4e5e9a..b871b641 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,704 LeetCode solutions in JavaScript +# 1,705 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1566,6 +1566,7 @@ 2039|[The Time When the Network Becomes Idle](./solutions/2039-the-time-when-the-network-becomes-idle.js)|Medium| 2040|[Kth Smallest Product of Two Sorted Arrays](./solutions/2040-kth-smallest-product-of-two-sorted-arrays.js)|Hard| 2042|[Check if Numbers Are Ascending in a Sentence](./solutions/2042-check-if-numbers-are-ascending-in-a-sentence.js)|Easy| +2043|[Simple Bank System](./solutions/2043-simple-bank-system.js)|Medium| 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| 2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| diff --git a/solutions/2043-simple-bank-system.js b/solutions/2043-simple-bank-system.js new file mode 100644 index 00000000..3cb80cb1 --- /dev/null +++ b/solutions/2043-simple-bank-system.js @@ -0,0 +1,71 @@ +/** + * 2043. Simple Bank System + * https://leetcode.com/problems/simple-bank-system/ + * Difficulty: Medium + * + * You have been tasked with writing a program for a popular bank that will automate all its + * incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered + * from 1 to n. The initial balance of each account is stored in a 0-indexed integer array + * balance, with the (i + 1)th account having an initial balance of balance[i]. + * + * Execute all the valid transactions. A transaction is valid if: + * - The given account number(s) are between 1 and n, and + * - The amount of money withdrawn or transferred from is less than or equal to the balance + * of the account. + * + * Implement the Bank class: + * - Bank(long[] balance) Initializes the object with the 0-indexed integer array balance. + * - boolean transfer(int account1, int account2, long money) Transfers money dollars from the + * account numbered account1 to the account numbered account2. Return true if the transaction + * was successful, false otherwise. + * - boolean deposit(int account, long money) Deposit money dollars into the account numbered + * account. Return true if the transaction was successful, false otherwise. + * - boolean withdraw(int account, long money) Withdraw money dollars from the account numbered + * account. Return true if the transaction was successful, false otherwise. + */ + +/** + * @param {number[]} balance + */ +var Bank = function(balance) { + this.accounts = balance; +}; + +/** + * @param {number} account1 + * @param {number} account2 + * @param {number} money + * @return {boolean} + */ +Bank.prototype.transfer = function(account1, account2, money) { + if (account1 > this.accounts.length || account2 > this.accounts.length) return false; + if (this.accounts[account1 - 1] < money) return false; + + this.accounts[account1 - 1] -= money; + this.accounts[account2 - 1] += money; + return true; +}; + +/** + * @param {number} account + * @param {number} money + * @return {boolean} + */ +Bank.prototype.deposit = function(account, money) { + if (account > this.accounts.length) return false; + + this.accounts[account - 1] += money; + return true; +}; + +/** + * @param {number} account + * @param {number} money + * @return {boolean} + */ +Bank.prototype.withdraw = function(account, money) { + if (account > this.accounts.length || this.accounts[account - 1] < money) return false; + + this.accounts[account - 1] -= money; + return true; +}; From 1e35b13ea8afcfd9acb2d46b9fecce1e7c452a4f Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 8 May 2025 12:47:55 -0400 Subject: [PATCH 201/495] Add solution #3342 --- README.md | 3 +- ...find-minimum-time-to-reach-last-room-ii.js | 57 +++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 solutions/3342-find-minimum-time-to-reach-last-room-ii.js diff --git a/README.md b/README.md index b871b641..e29d5404 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,705 LeetCode solutions in JavaScript +# 1,706 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1699,6 +1699,7 @@ 3223|[Minimum Length of String After Operations](./solutions/3223-minimum-length-of-string-after-operations.js)|Medium| 3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard| 3306|[Count of Substrings Containing Every Vowel and K Consonants II](./solutions/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js)|Medium| +3342|[Find Minimum Time to Reach Last Room II](./solutions/3342-find-minimum-time-to-reach-last-room-ii.js)|Medium| 3356|[Zero Array Transformation II](./solutions/3356-zero-array-transformation-ii.js)|Medium| 3375|[Minimum Operations to Make Array Values Equal to K](./solutions/3375-minimum-operations-to-make-array-values-equal-to-k.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./solutions/3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| diff --git a/solutions/3342-find-minimum-time-to-reach-last-room-ii.js b/solutions/3342-find-minimum-time-to-reach-last-room-ii.js new file mode 100644 index 00000000..24c9fc5a --- /dev/null +++ b/solutions/3342-find-minimum-time-to-reach-last-room-ii.js @@ -0,0 +1,57 @@ +/** + * 3342. Find Minimum Time to Reach Last Room II + * https://leetcode.com/problems/find-minimum-time-to-reach-last-room-ii/ + * Difficulty: Medium + * + * There is a dungeon with n x m rooms arranged as a grid. + * + * You are given a 2D array moveTime of size n x m, where moveTime[i][j] represents the minimum + * time in seconds when you can start moving to that room. You start from the room (0, 0) at + * time t = 0 and can move to an adjacent room. Moving between adjacent rooms takes one + * second for one move and two seconds for the next, alternating between the two. + * + * Return the minimum time to reach the room (n - 1, m - 1). + * + * Two rooms are adjacent if they share a common wall, either horizontally or vertically. + */ + +/** + * @param {number[][]} moveTime + * @return {number} + */ +var minTimeToReach = function(moveTime) { + const rows = moveTime.length; + const cols = moveTime[0].length; + const distances = Array.from({ length: rows }, () => new Array(cols).fill(Infinity)); + const pq = new PriorityQueue((a, b) => a[0] - b[0]); + pq.enqueue([0, 0, 0, 0]); + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; + + distances[0][0] = 0; + + while (!pq.isEmpty()) { + const [time, row, col, moveCount] = pq.dequeue(); + + if (row === rows - 1 && col === cols - 1) return time; + + if (time > distances[row][col]) continue; + + for (const [dr, dc] of directions) { + const newRow = row + dr; + const newCol = col + dc; + + if (newRow < 0 || newRow >= rows || newCol < 0 || newCol >= cols) continue; + + const moveCost = moveCount % 2 === 0 ? 1 : 2; + const startTime = Math.max(time, moveTime[newRow][newCol]); + const newTime = startTime + moveCost; + + if (newTime < distances[newRow][newCol]) { + distances[newRow][newCol] = newTime; + pq.enqueue([newTime, newRow, newCol, moveCount + 1]); + } + } + } + + return distances[rows - 1][cols - 1]; +}; From b927d90c859cd5aff236e797542b992d62a0562f Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 8 May 2025 12:50:55 -0400 Subject: [PATCH 202/495] Add solution #2044 --- README.md | 3 +- ...nt-number-of-maximum-bitwise-or-subsets.js | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 solutions/2044-count-number-of-maximum-bitwise-or-subsets.js diff --git a/README.md b/README.md index e29d5404..98b41d57 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,706 LeetCode solutions in JavaScript +# 1,707 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1567,6 +1567,7 @@ 2040|[Kth Smallest Product of Two Sorted Arrays](./solutions/2040-kth-smallest-product-of-two-sorted-arrays.js)|Hard| 2042|[Check if Numbers Are Ascending in a Sentence](./solutions/2042-check-if-numbers-are-ascending-in-a-sentence.js)|Easy| 2043|[Simple Bank System](./solutions/2043-simple-bank-system.js)|Medium| +2044|[Count Number of Maximum Bitwise-OR Subsets](./solutions/2044-count-number-of-maximum-bitwise-or-subsets.js)|Medium| 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| 2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| diff --git a/solutions/2044-count-number-of-maximum-bitwise-or-subsets.js b/solutions/2044-count-number-of-maximum-bitwise-or-subsets.js new file mode 100644 index 00000000..c318115a --- /dev/null +++ b/solutions/2044-count-number-of-maximum-bitwise-or-subsets.js @@ -0,0 +1,34 @@ +/** + * 2044. Count Number of Maximum Bitwise-OR Subsets + * https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/ + * Difficulty: Medium + * + * Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return + * the number of different non-empty subsets with the maximum bitwise OR. + * + * An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) + * elements of b. Two subsets are considered different if the indices of the elements chosen are + * different. + * + * The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] (0-indexed). + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var countMaxOrSubsets = function(nums) { + const maxOr = nums.reduce((or, num) => or | num, 0); + let count = 0; + + backtrack(0, 0); + + return count; + + function backtrack(index, currentOr) { + if (currentOr === maxOr) count++; + for (let i = index; i < nums.length; i++) { + backtrack(i + 1, currentOr | nums[i]); + } + } +}; From 57cfa88a290eda3917cb90f74155026c91416660 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 8 May 2025 12:55:09 -0400 Subject: [PATCH 203/495] Add solution #2045 --- README.md | 3 +- ...econd-minimum-time-to-reach-destination.js | 67 +++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 solutions/2045-second-minimum-time-to-reach-destination.js diff --git a/README.md b/README.md index 98b41d57..5f46f613 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,707 LeetCode solutions in JavaScript +# 1,708 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1568,6 +1568,7 @@ 2042|[Check if Numbers Are Ascending in a Sentence](./solutions/2042-check-if-numbers-are-ascending-in-a-sentence.js)|Easy| 2043|[Simple Bank System](./solutions/2043-simple-bank-system.js)|Medium| 2044|[Count Number of Maximum Bitwise-OR Subsets](./solutions/2044-count-number-of-maximum-bitwise-or-subsets.js)|Medium| +2045|[Second Minimum Time to Reach Destination](./solutions/2045-second-minimum-time-to-reach-destination.js)|Hard| 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| 2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| diff --git a/solutions/2045-second-minimum-time-to-reach-destination.js b/solutions/2045-second-minimum-time-to-reach-destination.js new file mode 100644 index 00000000..522eabab --- /dev/null +++ b/solutions/2045-second-minimum-time-to-reach-destination.js @@ -0,0 +1,67 @@ +/** + * 2045. Second Minimum Time to Reach Destination + * https://leetcode.com/problems/second-minimum-time-to-reach-destination/ + * Difficulty: Hard + * + * A city is represented as a bi-directional connected graph with n vertices where each vertex + * is labeled from 1 to n (inclusive). The edges in the graph are represented as a 2D integer + * array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex + * ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has + * an edge to itself. The time taken to traverse any edge is time minutes. + * + * Each vertex has a traffic signal which changes its color from green to red and vice versa + * every change minutes. All signals change at the same time. You can enter a vertex at any + * time, but can leave a vertex only when the signal is green. You cannot wait at a vertex + * if the signal is green. + * + * The second minimum value is defined as the smallest value strictly larger than the minimum value. + * - For example the second minimum value of [2, 3, 4] is 3, and the second minimum value of + * [2, 2, 4] is 4. + * + * Given n, edges, time, and change, return the second minimum time it will take to go from + * vertex 1 to vertex n. + */ + +/** + * @param {number} n + * @param {number[][]} edges + * @param {number} time + * @param {number} change + * @return {number} + */ +var secondMinimum = function(n, edges, time, change) { + const adjList = Array.from({ length: n + 1 }, () => []); + for (const [u, v] of edges) { + adjList[u].push(v); + adjList[v].push(u); + } + + const distances = Array.from({ length: n + 1 }, () => [Infinity, Infinity]); + const queue = [[1, 0]]; + distances[1][0] = 0; + + while (queue.length) { + const [node, currTime] = queue.shift(); + + for (const next of adjList[node]) { + const signalCycle = Math.floor(currTime / change); + const isGreen = signalCycle % 2 === 0; + let nextTime = currTime + time; + + if (!isGreen) { + nextTime = (signalCycle + 1) * change + time; + } + + if (nextTime < distances[next][0]) { + distances[next][1] = distances[next][0]; + distances[next][0] = nextTime; + queue.push([next, nextTime]); + } else if (nextTime > distances[next][0] && nextTime < distances[next][1]) { + distances[next][1] = nextTime; + queue.push([next, nextTime]); + } + } + } + + return distances[n][1]; +}; From 356288021f4caf24f16c8af9645527ad5b9f67a8 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 8 May 2025 13:17:02 -0400 Subject: [PATCH 204/495] Add solution #2048 --- README.md | 3 +- ...ext-greater-numerically-balanced-number.js | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 solutions/2048-next-greater-numerically-balanced-number.js diff --git a/README.md b/README.md index 5f46f613..bb07c5c9 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,708 LeetCode solutions in JavaScript +# 1,709 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1570,6 +1570,7 @@ 2044|[Count Number of Maximum Bitwise-OR Subsets](./solutions/2044-count-number-of-maximum-bitwise-or-subsets.js)|Medium| 2045|[Second Minimum Time to Reach Destination](./solutions/2045-second-minimum-time-to-reach-destination.js)|Hard| 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| +2048|[Next Greater Numerically Balanced Number](./solutions/2048-next-greater-numerically-balanced-number.js)|Medium| 2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| diff --git a/solutions/2048-next-greater-numerically-balanced-number.js b/solutions/2048-next-greater-numerically-balanced-number.js new file mode 100644 index 00000000..523a302a --- /dev/null +++ b/solutions/2048-next-greater-numerically-balanced-number.js @@ -0,0 +1,39 @@ +/** + * 2048. Next Greater Numerically Balanced Number + * https://leetcode.com/problems/next-greater-numerically-balanced-number/ + * Difficulty: Medium + * + * An integer x is numerically balanced if for every digit d in the number x, there are exactly + * d occurrences of that digit in x. + * + * Given an integer n, return the smallest numerically balanced number strictly greater than n. + */ + +/** + * @param {number} n + * @return {number} + */ +var nextBeautifulNumber = function(n) { + let candidate = n + 1; + while (candidate <= 10000000) { + if (isBalanced(candidate)) return candidate; + candidate++; + } + + return -1; + + function isBalanced(num) { + const freq = new Array(10).fill(0); + const str = num.toString(); + + for (const digit of str) { + freq[digit]++; + } + + for (const digit of str) { + if (freq[digit] !== parseInt(digit)) return false; + } + + return true; + } +}; From d08444365adf7958dd8c9203aa2b652b9d0002a3 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Thu, 8 May 2025 13:45:23 -0400 Subject: [PATCH 205/495] Add solution #2049 --- README.md | 3 +- ...2049-count-nodes-with-the-highest-score.js | 61 +++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 solutions/2049-count-nodes-with-the-highest-score.js diff --git a/README.md b/README.md index bb07c5c9..8befe0aa 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,709 LeetCode solutions in JavaScript +# 1,710 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1571,6 +1571,7 @@ 2045|[Second Minimum Time to Reach Destination](./solutions/2045-second-minimum-time-to-reach-destination.js)|Hard| 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| 2048|[Next Greater Numerically Balanced Number](./solutions/2048-next-greater-numerically-balanced-number.js)|Medium| +2049|[Count Nodes With the Highest Score](./solutions/2049-count-nodes-with-the-highest-score.js)|Medium| 2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| diff --git a/solutions/2049-count-nodes-with-the-highest-score.js b/solutions/2049-count-nodes-with-the-highest-score.js new file mode 100644 index 00000000..1f13961e --- /dev/null +++ b/solutions/2049-count-nodes-with-the-highest-score.js @@ -0,0 +1,61 @@ +/** + * 2049. Count Nodes With the Highest Score + * https://leetcode.com/problems/count-nodes-with-the-highest-score/ + * Difficulty: Medium + * + * There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. + * You are given a 0-indexed integer array parents representing the tree, where parents[i] is the + * parent of node i. Since node 0 is the root, parents[0] == -1. + * + * Each node has a score. To find the score of a node, consider if the node and the edges connected + * to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree + * is the number of the nodes in it. The score of the node is the product of the sizes of all + * those subtrees. + * + * Return the number of nodes that have the highest score. + */ + +/** + * @param {number[]} parents + * @return {number} + */ +var countHighestScoreNodes = function(parents) { + const n = parents.length; + const children = Array.from({ length: n }, () => []); + for (let i = 1; i < n; i++) { + children[parents[i]].push(i); + } + + const sizes = new Array(n).fill(0); + let maxScore = 0n; + let maxScoreCount = 0; + + calculateSize(0); + + return maxScoreCount; + + function calculateSize(node) { + let leftSize = 0; + let rightSize = 0; + + if (children[node].length > 0) leftSize = calculateSize(children[node][0]); + if (children[node].length > 1) rightSize = calculateSize(children[node][1]); + + sizes[node] = leftSize + rightSize + 1; + + let score = 1n; + if (leftSize > 0) score *= BigInt(leftSize); + if (rightSize > 0) score *= BigInt(rightSize); + const parentSize = n - sizes[node]; + if (parentSize > 0) score *= BigInt(parentSize); + + if (score > maxScore) { + maxScore = score; + maxScoreCount = 1; + } else if (score === maxScore) { + maxScoreCount++; + } + + return sizes[node]; + } +}; From d4ff52fa602c31c2e6383219e025e721f0f00700 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Fri, 9 May 2025 00:04:27 -0400 Subject: [PATCH 206/495] Add solution #3343 --- README.md | 3 +- ...3-count-number-of-balanced-permutations.js | 70 +++++++++++++++++++ 2 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 solutions/3343-count-number-of-balanced-permutations.js diff --git a/README.md b/README.md index 8befe0aa..65937f18 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,710 LeetCode solutions in JavaScript +# 1,711 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1704,6 +1704,7 @@ 3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard| 3306|[Count of Substrings Containing Every Vowel and K Consonants II](./solutions/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js)|Medium| 3342|[Find Minimum Time to Reach Last Room II](./solutions/3342-find-minimum-time-to-reach-last-room-ii.js)|Medium| +3343|[Count Number of Balanced Permutations](./solutions/3343-count-number-of-balanced-permutations.js)|Hard| 3356|[Zero Array Transformation II](./solutions/3356-zero-array-transformation-ii.js)|Medium| 3375|[Minimum Operations to Make Array Values Equal to K](./solutions/3375-minimum-operations-to-make-array-values-equal-to-k.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./solutions/3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| diff --git a/solutions/3343-count-number-of-balanced-permutations.js b/solutions/3343-count-number-of-balanced-permutations.js new file mode 100644 index 00000000..0e27eae1 --- /dev/null +++ b/solutions/3343-count-number-of-balanced-permutations.js @@ -0,0 +1,70 @@ +/** + * 3343. Count Number of Balanced Permutations + * https://leetcode.com/problems/count-number-of-balanced-permutations/ + * Difficulty: Hard + * + * You are given a string num. A string of digits is called balanced if the sum of the digits + * at even indices is equal to the sum of the digits at odd indices. + * + * Return the number of distinct permutations of num that are balanced. + * + * Since the answer may be very large, return it modulo 109 + 7. + * + * A permutation is a rearrangement of all the characters of a string. + */ + +/** + * @param {string} num + * @return {number} + */ +var countBalancedPermutations = function(num) { + const MOD = 1e9 + 7; + const n = num.length; + const digitCounts = new Array(10).fill(0); + let totalSum = 0; + + for (const char of num) { + const digit = parseInt(char); + digitCounts[digit]++; + totalSum += digit; + } + + if (totalSum % 2) return 0; + + const memo = new Map(); + + function combination(n, r) { + if (r > n) return 0; + if (r === 0 || r === n) return 1; + if (r > n - r) r = n - r; + + let result = 1n; + for (let i = 0; i < r; i++) { + result = result * BigInt(n - i) / BigInt(i + 1); + } + return Number(result % BigInt(MOD)); + } + + function exploreDigits(digit, oddSlots, evenSlots, targetBalance) { + if (oddSlots === 0 && evenSlots === 0 && targetBalance === 0) return 1; + if (digit < 0 || oddSlots < 0 || evenSlots < 0 || targetBalance < 0) return 0; + + const key = `${digit},${oddSlots},${evenSlots},${targetBalance}`; + if (memo.has(key)) return memo.get(key); + + let result = 0; + for (let oddCount = 0; oddCount <= digitCounts[digit]; oddCount++) { + const evenCount = digitCounts[digit] - oddCount; + const ways = (BigInt(combination(oddSlots, oddCount)) + * BigInt(combination(evenSlots, evenCount))) % BigInt(MOD); + const next = BigInt(exploreDigits(digit - 1, oddSlots - oddCount, + evenSlots - evenCount, targetBalance - digit * oddCount)); + result = (result + Number((ways * next) % BigInt(MOD))) % MOD; + } + + memo.set(key, result); + return result; + } + + return exploreDigits(9, n - Math.floor(n / 2), Math.floor(n / 2), totalSum / 2); +}; From 82f22ada1065f977ccb2926843c8c126cf68280b Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 10 May 2025 17:21:55 -0500 Subject: [PATCH 207/495] Add solution #2918 --- README.md | 3 +- ...sum-of-two-arrays-after-replacing-zeros.js | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 solutions/2918-minimum-equal-sum-of-two-arrays-after-replacing-zeros.js diff --git a/README.md b/README.md index 65937f18..4b48861d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,711 LeetCode solutions in JavaScript +# 1,712 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1685,6 +1685,7 @@ 2845|[Count of Interesting Subarrays](./solutions/2845-count-of-interesting-subarrays.js)|Medium| 2873|[Maximum Value of an Ordered Triplet I](./solutions/2873-maximum-value-of-an-ordered-triplet-i.js)|Easy| 2874|[Maximum Value of an Ordered Triplet II](./solutions/2874-maximum-value-of-an-ordered-triplet-ii.js)|Medium| +2918|[Minimum Equal Sum of Two Arrays After Replacing Zeros](./solutions/2918-minimum-equal-sum-of-two-arrays-after-replacing-zeros.js)|Medium| 2948|[Make Lexicographically Smallest Array by Swapping Elements](./solutions/2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium| 2962|[Count Subarrays Where Max Element Appears at Least K Times](./solutions/2962-count-subarrays-where-max-element-appears-at-least-k-times.js)|Medium| 2965|[Find Missing and Repeated Values](./solutions/2965-find-missing-and-repeated-values.js)|Easy| diff --git a/solutions/2918-minimum-equal-sum-of-two-arrays-after-replacing-zeros.js b/solutions/2918-minimum-equal-sum-of-two-arrays-after-replacing-zeros.js new file mode 100644 index 00000000..15ea4af7 --- /dev/null +++ b/solutions/2918-minimum-equal-sum-of-two-arrays-after-replacing-zeros.js @@ -0,0 +1,40 @@ +/** + * 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros + * https://leetcode.com/problems/minimum-equal-sum-of-two-arrays-after-replacing-zeros/ + * Difficulty: Medium + * + * You are given two arrays nums1 and nums2 consisting of positive integers. + * + * You have to replace all the 0's in both arrays with strictly positive integers such that the + * sum of elements of both arrays becomes equal. + * + * Return the minimum equal sum you can obtain, or -1 if it is impossible. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var minSum = function(nums1, nums2) { + let sum1 = 0; + let zeros1 = 0; + for (const num of nums1) { + sum1 += num; + if (num === 0) zeros1++; + } + + let sum2 = 0; + let zeros2 = 0; + for (const num of nums2) { + sum2 += num; + if (num === 0) zeros2++; + } + + const minSum1 = sum1 + zeros1; + const minSum2 = sum2 + zeros2; + + if (minSum1 > sum2 && zeros2 === 0 || minSum2 > sum1 && zeros1 === 0) return -1; + + return Math.max(minSum1, minSum2); +}; From 3ae6f4387dbc0cf3a14566cab43d7b9c73e238d1 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 10 May 2025 17:24:26 -0500 Subject: [PATCH 208/495] Add solution #3341 --- README.md | 3 +- ...-find-minimum-time-to-reach-last-room-i.js | 55 +++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 solutions/3341-find-minimum-time-to-reach-last-room-i.js diff --git a/README.md b/README.md index 4b48861d..c946ba63 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,712 LeetCode solutions in JavaScript +# 1,713 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1704,6 +1704,7 @@ 3223|[Minimum Length of String After Operations](./solutions/3223-minimum-length-of-string-after-operations.js)|Medium| 3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard| 3306|[Count of Substrings Containing Every Vowel and K Consonants II](./solutions/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js)|Medium| +3341|[Find Minimum Time to Reach Last Room I](./solutions/3341-find-minimum-time-to-reach-last-room-i.js)|Medium| 3342|[Find Minimum Time to Reach Last Room II](./solutions/3342-find-minimum-time-to-reach-last-room-ii.js)|Medium| 3343|[Count Number of Balanced Permutations](./solutions/3343-count-number-of-balanced-permutations.js)|Hard| 3356|[Zero Array Transformation II](./solutions/3356-zero-array-transformation-ii.js)|Medium| diff --git a/solutions/3341-find-minimum-time-to-reach-last-room-i.js b/solutions/3341-find-minimum-time-to-reach-last-room-i.js new file mode 100644 index 00000000..fae5957b --- /dev/null +++ b/solutions/3341-find-minimum-time-to-reach-last-room-i.js @@ -0,0 +1,55 @@ +/** + * 3341. Find Minimum Time to Reach Last Room I + * https://leetcode.com/problems/find-minimum-time-to-reach-last-room-i/ + * Difficulty: Medium + * + * There is a dungeon with n x m rooms arranged as a grid. + * + * You are given a 2D array moveTime of size n x m, where moveTime[i][j] represents the minimum + * time in seconds when you can start moving to that room. You start from the room (0, 0) at + * time t = 0 and can move to an adjacent room. Moving between adjacent rooms takes exactly + * one second. + * + * Return the minimum time to reach the room (n - 1, m - 1). + * + * Two rooms are adjacent if they share a common wall, either horizontally or vertically. + */ + +/** + * @param {number[][]} moveTime + * @return {number} + */ +var minTimeToReach = function(moveTime) { + const rows = moveTime.length; + const cols = moveTime[0].length; + const distances = Array.from({ length: rows }, () => new Array(cols).fill(Infinity)); + const pq = new PriorityQueue((a, b) => a[0] - b[0]); + pq.enqueue([0, 0, 0]); + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; + + distances[0][0] = 0; + + while (!pq.isEmpty()) { + const [time, row, col] = pq.dequeue(); + + if (row === rows - 1 && col === cols - 1) return time; + + if (time > distances[row][col]) continue; + + for (const [dr, dc] of directions) { + const newRow = row + dr; + const newCol = col + dc; + + if (newRow < 0 || newRow >= rows || newCol < 0 || newCol >= cols) continue; + + const newTime = Math.max(time, moveTime[newRow][newCol]) + 1; + + if (newTime < distances[newRow][newCol]) { + distances[newRow][newCol] = newTime; + pq.enqueue([newTime, newRow, newCol]); + } + } + } + + return distances[rows - 1][cols - 1]; +}; From 8d0eb2b36a3e5fbf0528afe1bb99801eac72a256 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 10 May 2025 18:20:12 -0500 Subject: [PATCH 209/495] Add solution #2050 --- README.md | 3 +- solutions/2050-parallel-courses-iii.js | 61 ++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 solutions/2050-parallel-courses-iii.js diff --git a/README.md b/README.md index c946ba63..cca2c3bd 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,713 LeetCode solutions in JavaScript +# 1,714 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1572,6 +1572,7 @@ 2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy| 2048|[Next Greater Numerically Balanced Number](./solutions/2048-next-greater-numerically-balanced-number.js)|Medium| 2049|[Count Nodes With the Highest Score](./solutions/2049-count-nodes-with-the-highest-score.js)|Medium| +2050|[Parallel Courses III](./solutions/2050-parallel-courses-iii.js)|Hard| 2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| diff --git a/solutions/2050-parallel-courses-iii.js b/solutions/2050-parallel-courses-iii.js new file mode 100644 index 00000000..62cdec65 --- /dev/null +++ b/solutions/2050-parallel-courses-iii.js @@ -0,0 +1,61 @@ +/** + * 2050. Parallel Courses III + * https://leetcode.com/problems/parallel-courses-iii/ + * Difficulty: Hard + * + * You are given an integer n, which indicates that there are n courses labeled from 1 to n. + * You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] + * denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite + * relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes + * how many months it takes to complete the (i+1)th course. + * + * You must find the minimum number of months needed to complete all the courses following these + * rules: + * - You may start taking a course at any time if the prerequisites are met. + * - Any number of courses can be taken at the same time. + * + * Return the minimum number of months needed to complete all the courses. + * + * Note: The test cases are generated such that it is possible to complete every course (i.e., the + * graph is a directed acyclic graph). + */ + +/** + * @param {number} n + * @param {number[][]} relations + * @param {number[]} time + * @return {number} + */ +var minimumTime = function(n, relations, time) { + const adjacencyList = Array.from({ length: n + 1 }, () => []); + const inDegree = new Array(n + 1).fill(0); + const completionTime = new Array(n + 1).fill(0); + + for (const [prev, next] of relations) { + adjacencyList[prev].push(next); + inDegree[next]++; + } + + const queue = []; + for (let i = 1; i <= n; i++) { + if (inDegree[i] === 0) { + queue.push(i); + completionTime[i] = time[i - 1]; + } + } + + while (queue.length) { + const current = queue.shift(); + for (const next of adjacencyList[current]) { + completionTime[next] = Math.max( + completionTime[next], + completionTime[current] + time[next - 1] + ); + if (--inDegree[next] === 0) { + queue.push(next); + } + } + } + + return Math.max(...completionTime); +}; From 70a134502d310b495f61850abc6506ea0777c646 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 10 May 2025 18:22:06 -0500 Subject: [PATCH 210/495] Add solution #2055 --- README.md | 3 +- solutions/2055-plates-between-candles.js | 55 ++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 solutions/2055-plates-between-candles.js diff --git a/README.md b/README.md index cca2c3bd..6ab3b938 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,714 LeetCode solutions in JavaScript +# 1,715 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1574,6 +1574,7 @@ 2049|[Count Nodes With the Highest Score](./solutions/2049-count-nodes-with-the-highest-score.js)|Medium| 2050|[Parallel Courses III](./solutions/2050-parallel-courses-iii.js)|Hard| 2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| +2055|[Plates Between Candles](./solutions/2055-plates-between-candles.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| diff --git a/solutions/2055-plates-between-candles.js b/solutions/2055-plates-between-candles.js new file mode 100644 index 00000000..347ed4ae --- /dev/null +++ b/solutions/2055-plates-between-candles.js @@ -0,0 +1,55 @@ +/** + * 2055. Plates Between Candles + * https://leetcode.com/problems/plates-between-candles/ + * Difficulty: Medium + * + * There is a long table with a line of plates and candles arranged on top of it. You are given + * a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate + * and a '|' represents a candle. + * + * You are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] + * denotes the substring s[lefti...righti] (inclusive). For each query, you need to find the + * number of plates between candles that are in the substring. A plate is considered between + * candles if there is at least one candle to its left and at least one candle to its right + * in the substring. + * - For example, s = "||**||**|*", and a query [3, 8] denotes the substring "*||**|". The number + * of plates between candles in this substring is 2, as each of the two plates has at least one + * candle in the substring to its left and right. + * + * Return an integer array answer where answer[i] is the answer to the ith query. + */ + +/** + * @param {string} s + * @param {number[][]} queries + * @return {number[]} + */ +var platesBetweenCandles = function(s, queries) { + const n = s.length; + const prefixPlates = new Array(n + 1).fill(0); + const leftCandle = new Array(n).fill(-1); + const rightCandle = new Array(n).fill(-1); + + for (let i = 0, candle = -1; i < n; i++) { + prefixPlates[i + 1] = prefixPlates[i] + (s[i] === '*' ? 1 : 0); + if (s[i] === '|') candle = i; + leftCandle[i] = candle; + } + + for (let i = n - 1, candle = -1; i >= 0; i--) { + if (s[i] === '|') candle = i; + rightCandle[i] = candle; + } + + const result = new Array(queries.length).fill(0); + for (let i = 0; i < queries.length; i++) { + const [start, end] = queries[i]; + const left = rightCandle[start]; + const right = leftCandle[end]; + if (left !== -1 && right !== -1 && left < right) { + result[i] = prefixPlates[right] - prefixPlates[left]; + } + } + + return result; +}; From 4e854b1f31a3f2713128b9bf6b731c4977562672 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 10 May 2025 18:34:25 -0500 Subject: [PATCH 211/495] Add solution #2056 --- README.md | 3 +- ...f-valid-move-combinations-on-chessboard.js | 108 ++++++++++++++++++ 2 files changed, 110 insertions(+), 1 deletion(-) create mode 100644 solutions/2056-number-of-valid-move-combinations-on-chessboard.js diff --git a/README.md b/README.md index 6ab3b938..bbc5f2c9 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,715 LeetCode solutions in JavaScript +# 1,716 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1575,6 +1575,7 @@ 2050|[Parallel Courses III](./solutions/2050-parallel-courses-iii.js)|Hard| 2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| 2055|[Plates Between Candles](./solutions/2055-plates-between-candles.js)|Medium| +2056|[Number of Valid Move Combinations On Chessboard](./solutions/2056-number-of-valid-move-combinations-on-chessboard.js)|Hard| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| diff --git a/solutions/2056-number-of-valid-move-combinations-on-chessboard.js b/solutions/2056-number-of-valid-move-combinations-on-chessboard.js new file mode 100644 index 00000000..94716f2b --- /dev/null +++ b/solutions/2056-number-of-valid-move-combinations-on-chessboard.js @@ -0,0 +1,108 @@ +/** + * 2056. Number of Valid Move Combinations On Chessboard + * https://leetcode.com/problems/number-of-valid-move-combinations-on-chessboard/ + * Difficulty: Hard + * + * There is an 8 x 8 chessboard containing n pieces (rooks, queens, or bishops). You are given a + * string array pieces of length n, where pieces[i] describes the type (rook, queen, or bishop) + * of the ith piece. In addition, you are given a 2D integer array positions also of length n, + * where positions[i] = [ri, ci] indicates that the ith piece is currently at the 1-based + * coordinate (ri, ci) on the chessboard. + * + * When making a move for a piece, you choose a destination square that the piece will travel + * toward and stop on. + * - A rook can only travel horizontally or vertically from (r, c) to the direction of (r+1, c), + * (r-1, c), (r, c+1), or (r, c-1). + * - A queen can only travel horizontally, vertically, or diagonally from (r, c) to the direction + * of (r+1, c), (r-1, c), (r, c+1), (r, c-1), (r+1, c+1), (r+1, c-1), (r-1, c+1), (r-1, c-1). + * - A bishop can only travel diagonally from (r, c) to the direction of (r+1, c+1), (r+1, c-1), + * (r-1, c+1), (r-1, c-1). + * + * You must make a move for every piece on the board simultaneously. A move combination consists of + * all the moves performed on all the given pieces. Every second, each piece will instantaneously + * travel one square towards their destination if they are not already at it. All pieces start + * traveling at the 0th second. A move combination is invalid if, at a given time, two or more + * pieces occupy the same square. + * + * Return the number of valid move combinations. + * + * Notes: + * - No two pieces will start in the same square. + * - You may choose the square a piece is already on as its destination. + * - If two pieces are directly adjacent to each other, it is valid for them to move past each other + * and swap positions in one second. + */ + +/** + * @param {string[]} pieces + * @param {number[][]} positions + * @return {number} + */ +var countCombinations = function(pieces, positions) { + const n = pieces.length; + const directions = { + rook: [[0, 1], [0, -1], [1, 0], [-1, 0]], + bishop: [[1, 1], [1, -1], [-1, 1], [-1, -1]], + queen: [[0, 1], [0, -1], [1, 0], [-1, 0], [1, 1], [1, -1], [-1, 1], [-1, -1]] + }; + + return generateCombinations(0, [], []); + + function isValidPosition(row, col) { + return row >= 1 && row <= 8 && col >= 1 && col <= 8; + } + + function simulateMoves(moves, steps) { + const current = positions.map(([r, c]) => [r, c]); + const maxSteps = Math.max(...steps); + + for (let t = 0; t <= maxSteps; t++) { + const positionsAtTime = new Set(); + for (let i = 0; i < n; i++) { + const [dr, dc] = moves[i]; + const step = Math.min(t, steps[i]); + const newRow = current[i][0] + dr * step; + const newCol = current[i][1] + dc * step; + + if (t > steps[i] && steps[i] > 0 && !isValidPosition(newRow, newCol)) continue; + + const posKey = `${newRow},${newCol}`; + if (positionsAtTime.has(posKey)) return false; + positionsAtTime.add(posKey); + } + } + + return true; + } + + function generateCombinations(index, selectedMoves, selectedSteps) { + if (index === n) { + return simulateMoves(selectedMoves, selectedSteps) ? 1 : 0; + } + + let total = 0; + const [startRow, startCol] = positions[index]; + const pieceDirections = directions[pieces[index]]; + + total += generateCombinations(index + 1, [...selectedMoves, [0, 0]], [...selectedSteps, 0]); + + for (const [dr, dc] of pieceDirections) { + let row = startRow; + let col = startCol; + let step = 0; + + while (isValidPosition(row + dr, col + dc)) { + row += dr; + col += dc; + step++; + total += generateCombinations( + index + 1, + [...selectedMoves, [dr, dc]], + [...selectedSteps, step] + ); + } + } + + return total; + } +}; From 9c8c6c83c29e0b98247fe8a70b12245454c39de7 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 10 May 2025 18:36:27 -0500 Subject: [PATCH 212/495] Add solution #2057 --- README.md | 3 ++- .../2057-smallest-index-with-equal-value.js | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 solutions/2057-smallest-index-with-equal-value.js diff --git a/README.md b/README.md index bbc5f2c9..e1c8f879 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,716 LeetCode solutions in JavaScript +# 1,717 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1576,6 +1576,7 @@ 2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium| 2055|[Plates Between Candles](./solutions/2055-plates-between-candles.js)|Medium| 2056|[Number of Valid Move Combinations On Chessboard](./solutions/2056-number-of-valid-move-combinations-on-chessboard.js)|Hard| +2057|[Smallest Index With Equal Value](./solutions/2057-smallest-index-with-equal-value.js)|Easy| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| diff --git a/solutions/2057-smallest-index-with-equal-value.js b/solutions/2057-smallest-index-with-equal-value.js new file mode 100644 index 00000000..3fe1c453 --- /dev/null +++ b/solutions/2057-smallest-index-with-equal-value.js @@ -0,0 +1,23 @@ +/** + * 2057. Smallest Index With Equal Value + * https://leetcode.com/problems/smallest-index-with-equal-value/ + * Difficulty: Easy + * + * Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod + * 10 == nums[i], or -1 if such index does not exist. + * + * x mod y denotes the remainder when x is divided by y. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var smallestEqual = function(nums) { + for (let i = 0; i < nums.length; i++) { + if (i % 10 === nums[i]) { + return i; + } + } + return -1; +}; From 20fdf445aaab9f17cdb347818a34902360b74aa6 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 10 May 2025 18:43:42 -0500 Subject: [PATCH 213/495] Add solution #2058 --- README.md | 3 +- ...number-of-nodes-between-critical-points.js | 63 +++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 solutions/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points.js diff --git a/README.md b/README.md index e1c8f879..eec96320 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,717 LeetCode solutions in JavaScript +# 1,718 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1577,6 +1577,7 @@ 2055|[Plates Between Candles](./solutions/2055-plates-between-candles.js)|Medium| 2056|[Number of Valid Move Combinations On Chessboard](./solutions/2056-number-of-valid-move-combinations-on-chessboard.js)|Hard| 2057|[Smallest Index With Equal Value](./solutions/2057-smallest-index-with-equal-value.js)|Easy| +2058|[Find the Minimum and Maximum Number of Nodes Between Critical Points](./solutions/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| diff --git a/solutions/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points.js b/solutions/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points.js new file mode 100644 index 00000000..da92ff90 --- /dev/null +++ b/solutions/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points.js @@ -0,0 +1,63 @@ +/** + * 2058. Find the Minimum and Maximum Number of Nodes Between Critical Points + * https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/ + * Difficulty: Medium + * + * A critical point in a linked list is defined as either a local maxima or a local minima. + * + * A node is a local maxima if the current node has a value strictly greater than the previous node + * and the next node. + * + * A node is a local minima if the current node has a value strictly smaller than the previous node + * and the next node. + * + * Note that a node can only be a local maxima/minima if there exists both a previous node and a + * next node. + * + * Given a linked list head, return an array of length 2 containing [minDistance, maxDistance] + * where minDistance is the minimum distance between any two distinct critical points and + * maxDistance is the maximum distance between any two distinct critical points. If there are + * fewer than two critical points, return [-1, -1]. + */ + +/** + * 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 nodesBetweenCriticalPoints = function(head) { + const criticalPositions = []; + let position = 1; + let prev = head; + let current = head.next; + + while (current.next) { + const next = current.next; + if ((current.val > prev.val && current.val > next.val) || + (current.val < prev.val && current.val < next.val)) { + criticalPositions.push(position); + } + prev = current; + current = next; + position++; + } + + if (criticalPositions.length < 2) { + return [-1, -1]; + } + + let minDistance = Infinity; + for (let i = 1; i < criticalPositions.length; i++) { + minDistance = Math.min(minDistance, criticalPositions[i] - criticalPositions[i - 1]); + } + + const maxDistance = criticalPositions[criticalPositions.length - 1] - criticalPositions[0]; + + return [minDistance, maxDistance]; +}; From f39cdf2f2219fc978eb8fffbe43322fffd26a04f Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 10 May 2025 18:45:34 -0500 Subject: [PATCH 214/495] Add solution #2059 --- README.md | 3 +- ...59-minimum-operations-to-convert-number.js | 57 +++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 solutions/2059-minimum-operations-to-convert-number.js diff --git a/README.md b/README.md index eec96320..937b78a5 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,718 LeetCode solutions in JavaScript +# 1,719 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1578,6 +1578,7 @@ 2056|[Number of Valid Move Combinations On Chessboard](./solutions/2056-number-of-valid-move-combinations-on-chessboard.js)|Hard| 2057|[Smallest Index With Equal Value](./solutions/2057-smallest-index-with-equal-value.js)|Easy| 2058|[Find the Minimum and Maximum Number of Nodes Between Critical Points](./solutions/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points.js)|Medium| +2059|[Minimum Operations to Convert Number](./solutions/2059-minimum-operations-to-convert-number.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| diff --git a/solutions/2059-minimum-operations-to-convert-number.js b/solutions/2059-minimum-operations-to-convert-number.js new file mode 100644 index 00000000..677e5de9 --- /dev/null +++ b/solutions/2059-minimum-operations-to-convert-number.js @@ -0,0 +1,57 @@ +/** + * 2059. Minimum Operations to Convert Number + * https://leetcode.com/problems/minimum-operations-to-convert-number/ + * Difficulty: Medium + * + * You are given a 0-indexed integer array nums containing distinct numbers, an integer start, + * and an integer goal. There is an integer x that is initially set to start, and you want to + * perform operations on x such that it is converted to goal. You can perform the following + * operation repeatedly on the number x: + * + * If 0 <= x <= 1000, then for any index i in the array (0 <= i < nums.length), you can set x + * to any of the following: + * - x + nums[i] + * - x - nums[i] + * - x ^ nums[i] (bitwise-XOR) + * + * Note that you can use each nums[i] any number of times in any order. Operations that set x + * to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward. + * + * Return the minimum number of operations needed to convert x = start into goal, and -1 if it + * is not possible. + */ + +/** + * @param {number[]} nums + * @param {number} start + * @param {number} goal + * @return {number} + */ +var minimumOperations = function(nums, start, goal) { + const queue = [[start, 0]]; + const visited = new Set([start]); + + while (queue.length) { + const [current, steps] = queue.shift(); + + for (const num of nums) { + const candidates = [ + current + num, + current - num, + current ^ num + ]; + + for (const next of candidates) { + if (next === goal) { + return steps + 1; + } + if (next >= 0 && next <= 1000 && !visited.has(next)) { + visited.add(next); + queue.push([next, steps + 1]); + } + } + } + } + + return -1; +}; From fafb1b6a31564b4a28fcc1f0a00cfbab9bf78091 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 10 May 2025 18:51:36 -0500 Subject: [PATCH 215/495] Add solution #2060 --- README.md | 3 +- ...string-exists-given-two-encoded-strings.js | 73 +++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 solutions/2060-check-if-an-original-string-exists-given-two-encoded-strings.js diff --git a/README.md b/README.md index 937b78a5..2cf7e444 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,719 LeetCode solutions in JavaScript +# 1,720 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1579,6 +1579,7 @@ 2057|[Smallest Index With Equal Value](./solutions/2057-smallest-index-with-equal-value.js)|Easy| 2058|[Find the Minimum and Maximum Number of Nodes Between Critical Points](./solutions/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points.js)|Medium| 2059|[Minimum Operations to Convert Number](./solutions/2059-minimum-operations-to-convert-number.js)|Medium| +2060|[Check if an Original String Exists Given Two Encoded Strings](./solutions/2060-check-if-an-original-string-exists-given-two-encoded-strings.js)|Hard| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| diff --git a/solutions/2060-check-if-an-original-string-exists-given-two-encoded-strings.js b/solutions/2060-check-if-an-original-string-exists-given-two-encoded-strings.js new file mode 100644 index 00000000..520e531e --- /dev/null +++ b/solutions/2060-check-if-an-original-string-exists-given-two-encoded-strings.js @@ -0,0 +1,73 @@ +/** + * 2060. Check if an Original String Exists Given Two Encoded Strings + * https://leetcode.com/problems/check-if-an-original-string-exists-given-two-encoded-strings/ + * Difficulty: Hard + * + * An original string, consisting of lowercase English letters, can be encoded by the following + * steps: + * - Arbitrarily split it into a sequence of some number of non-empty substrings. + * - Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its + * length (as a numeric string). + * - Concatenate the sequence as the encoded string. + * + * For example, one way to encode an original string "abcdefghijklmnop" might be: + * - Split it as a sequence: ["ab", "cdefghijklmn", "o", "p"]. + * - Choose the second and third elements to be replaced by their lengths, respectively. The + * sequence becomes ["ab", "12", "1", "p"]. + * - Concatenate the elements of the sequence to get the encoded string: "ab121p". + * + * Given two encoded strings s1 and s2, consisting of lowercase English letters and digits 1-9 + * (inclusive), return true if there exists an original string that could be encoded as both s1 + * and s2. Otherwise, return false. + * + * Note: The test cases are generated such that the number of consecutive digits in s1 and s2 + * does not exceed 3. + */ + +/** + * @param {string} s1 + * @param {string} s2 + * @return {boolean} + */ +var possiblyEquals = function(s1, s2) { + const memo = new Array(s1.length + 1).fill().map(() => new Array(s2.length + 1).fill() + .map(() => ({}))); + + function match(pos1, pos2, diff) { + if (pos1 === s1.length && pos2 === s2.length) return diff === 0; + if (memo[pos1][pos2][diff] !== undefined) return memo[pos1][pos2][diff]; + + const char1 = s1[pos1]; + const char2 = s2[pos2]; + + if (pos1 < s1.length && pos2 < s2.length && char1 === char2 && diff === 0) { + if (match(pos1 + 1, pos2 + 1, 0)) return true; + } + + if (pos1 < s1.length && isNaN(char1) && diff < 0) { + if (match(pos1 + 1, pos2, diff + 1)) return true; + } + + if (pos2 < s2.length && isNaN(char2) && diff > 0) { + if (match(pos1, pos2 + 1, diff - 1)) return true; + } + + let num = 0; + for (let i = 0; i < 3 && pos1 + i < s1.length; i++) { + if (isNaN(s1[pos1 + i])) break; + num = num * 10 + parseInt(s1[pos1 + i]); + if (match(pos1 + i + 1, pos2, diff + num)) return true; + } + + num = 0; + for (let i = 0; i < 3 && pos2 + i < s2.length; i++) { + if (isNaN(s2[pos2 + i])) break; + num = num * 10 + parseInt(s2[pos2 + i]); + if (match(pos1, pos2 + i + 1, diff - num)) return true; + } + + return memo[pos1][pos2][diff] = false; + } + + return match(0, 0, 0); +}; From 00009659372bef5e4e2e3f69f0017ef325bb75b1 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 10 May 2025 18:52:50 -0500 Subject: [PATCH 216/495] Add solution #2062 --- README.md | 3 +- ...2062-count-vowel-substrings-of-a-string.js | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 solutions/2062-count-vowel-substrings-of-a-string.js diff --git a/README.md b/README.md index 2cf7e444..aea09d23 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,720 LeetCode solutions in JavaScript +# 1,721 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1580,6 +1580,7 @@ 2058|[Find the Minimum and Maximum Number of Nodes Between Critical Points](./solutions/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points.js)|Medium| 2059|[Minimum Operations to Convert Number](./solutions/2059-minimum-operations-to-convert-number.js)|Medium| 2060|[Check if an Original String Exists Given Two Encoded Strings](./solutions/2060-check-if-an-original-string-exists-given-two-encoded-strings.js)|Hard| +2062|[Count Vowel Substrings of a String](./solutions/2062-count-vowel-substrings-of-a-string.js)|Easy| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| diff --git a/solutions/2062-count-vowel-substrings-of-a-string.js b/solutions/2062-count-vowel-substrings-of-a-string.js new file mode 100644 index 00000000..8d427ac8 --- /dev/null +++ b/solutions/2062-count-vowel-substrings-of-a-string.js @@ -0,0 +1,33 @@ +/** + * 2062. Count Vowel Substrings of a String + * https://leetcode.com/problems/count-vowel-substrings-of-a-string/ + * Difficulty: Easy + * + * A substring is a contiguous (non-empty) sequence of characters within a string. + * + * A vowel substring is a substring that only consists of vowels ('a', 'e', 'i', 'o', and 'u') + * and has all five vowels present in it. + * + * Given a string word, return the number of vowel substrings in word. + */ + +/** + * @param {string} word + * @return {number} + */ +var countVowelSubstrings = function(word) { + const vowels = new Set(['a', 'e', 'i', 'o', 'u']); + let total = 0; + + for (let start = 0; start < word.length; start++) { + const vowelCount = new Map(); + for (let end = start; end < word.length && vowels.has(word[end]); end++) { + vowelCount.set(word[end], (vowelCount.get(word[end]) || 0) + 1); + if (vowelCount.size === 5) { + total++; + } + } + } + + return total; +}; From f76162da1662e53cfa65c14cdb3a9421fab4c746 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 10 May 2025 18:53:48 -0500 Subject: [PATCH 217/495] Add solution #2063 --- README.md | 3 ++- solutions/2063-vowels-of-all-substrings.js | 30 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 solutions/2063-vowels-of-all-substrings.js diff --git a/README.md b/README.md index aea09d23..7426fe09 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,721 LeetCode solutions in JavaScript +# 1,722 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1581,6 +1581,7 @@ 2059|[Minimum Operations to Convert Number](./solutions/2059-minimum-operations-to-convert-number.js)|Medium| 2060|[Check if an Original String Exists Given Two Encoded Strings](./solutions/2060-check-if-an-original-string-exists-given-two-encoded-strings.js)|Hard| 2062|[Count Vowel Substrings of a String](./solutions/2062-count-vowel-substrings-of-a-string.js)|Easy| +2063|[Vowels of All Substrings](./solutions/2063-vowels-of-all-substrings.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| diff --git a/solutions/2063-vowels-of-all-substrings.js b/solutions/2063-vowels-of-all-substrings.js new file mode 100644 index 00000000..bde705e8 --- /dev/null +++ b/solutions/2063-vowels-of-all-substrings.js @@ -0,0 +1,30 @@ +/** + * 2063. Vowels of All Substrings + * https://leetcode.com/problems/vowels-of-all-substrings/ + * Difficulty: Medium + * + * Given a string word, return the sum of the number of vowels ('a', 'e', 'i', 'o', and 'u') in + * every substring of word. + * + * A substring is a contiguous (non-empty) sequence of characters within a string. + * + * Note: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please + * be careful during the calculations. + */ + +/** + * @param {string} word + * @return {number} + */ +var countVowels = function(word) { + const vowels = new Set(['a', 'e', 'i', 'o', 'u']); + let total = 0; + + for (let i = 0; i < word.length; i++) { + if (vowels.has(word[i])) { + total += (i + 1) * (word.length - i); + } + } + + return total; +}; From ce55ded1c26a402dd64fd791a1ec3373aa8e49ee Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 10 May 2025 18:54:56 -0500 Subject: [PATCH 218/495] Add solution #2064 --- README.md | 3 +- ...um-of-products-distributed-to-any-store.js | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 solutions/2064-minimized-maximum-of-products-distributed-to-any-store.js diff --git a/README.md b/README.md index 7426fe09..eef1c7d2 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,722 LeetCode solutions in JavaScript +# 1,723 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1582,6 +1582,7 @@ 2060|[Check if an Original String Exists Given Two Encoded Strings](./solutions/2060-check-if-an-original-string-exists-given-two-encoded-strings.js)|Hard| 2062|[Count Vowel Substrings of a String](./solutions/2062-count-vowel-substrings-of-a-string.js)|Easy| 2063|[Vowels of All Substrings](./solutions/2063-vowels-of-all-substrings.js)|Medium| +2064|[Minimized Maximum of Products Distributed to Any Store](./solutions/2064-minimized-maximum-of-products-distributed-to-any-store.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| diff --git a/solutions/2064-minimized-maximum-of-products-distributed-to-any-store.js b/solutions/2064-minimized-maximum-of-products-distributed-to-any-store.js new file mode 100644 index 00000000..b1781081 --- /dev/null +++ b/solutions/2064-minimized-maximum-of-products-distributed-to-any-store.js @@ -0,0 +1,45 @@ +/** + * 2064. Minimized Maximum of Products Distributed to Any Store + * https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/ + * Difficulty: Medium + * + * You are given an integer n indicating there are n specialty retail stores. There are m product + * types of varying amounts, which are given as a 0-indexed integer array quantities, where + * quantities[i] represents the number of products of the ith product type. + * + * You need to distribute all products to the retail stores following these rules: + * - A store can only be given at most one product type but can be given any amount of it. + * - After distribution, each store will have been given some number of products (possibly 0). + * Let x represent the maximum number of products given to any store. You want x to be as small + * as possible, i.e., you want to minimize the maximum number of products that are given to any + * store. + * + * Return the minimum possible x. + */ + +/** + * @param {number} n + * @param {number[]} quantities + * @return {number} + */ +var minimizedMaximum = function(n, quantities) { + let left = 1; + let right = Math.max(...quantities); + + while (left < right) { + const mid = Math.floor((left + right) / 2); + let storesNeeded = 0; + + for (const quantity of quantities) { + storesNeeded += Math.ceil(quantity / mid); + } + + if (storesNeeded <= n) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; +}; From 63f7d04a072ea7cfb4495ce6003f5a007f515213 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 10 May 2025 18:56:17 -0500 Subject: [PATCH 219/495] Add solution #2065 --- README.md | 3 +- .../2065-maximum-path-quality-of-a-graph.js | 59 +++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 solutions/2065-maximum-path-quality-of-a-graph.js diff --git a/README.md b/README.md index eef1c7d2..e47e518d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,723 LeetCode solutions in JavaScript +# 1,724 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1583,6 +1583,7 @@ 2062|[Count Vowel Substrings of a String](./solutions/2062-count-vowel-substrings-of-a-string.js)|Easy| 2063|[Vowels of All Substrings](./solutions/2063-vowels-of-all-substrings.js)|Medium| 2064|[Minimized Maximum of Products Distributed to Any Store](./solutions/2064-minimized-maximum-of-products-distributed-to-any-store.js)|Medium| +2065|[Maximum Path Quality of a Graph](./solutions/2065-maximum-path-quality-of-a-graph.js)|Hard| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| diff --git a/solutions/2065-maximum-path-quality-of-a-graph.js b/solutions/2065-maximum-path-quality-of-a-graph.js new file mode 100644 index 00000000..9d07048c --- /dev/null +++ b/solutions/2065-maximum-path-quality-of-a-graph.js @@ -0,0 +1,59 @@ +/** + * 2065. Maximum Path Quality of a Graph + * https://leetcode.com/problems/maximum-path-quality-of-a-graph/ + * Difficulty: Hard + * + * There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a + * 0-indexed integer array values where values[i] is the value of the ith node. You are also given + * a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there + * is an undirected edge between the nodes uj and vj, and it takes timej seconds to travel between + * the two nodes. Finally, you are given an integer maxTime. + * + * A valid path in the graph is any path that starts at node 0, ends at node 0, and takes at most + * maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid + * path is the sum of the values of the unique nodes visited in the path (each node's value is + * added at most once to the sum). + * + * Return the maximum quality of a valid path. + * + * Note: There are at most four edges connected to each node. + */ + +/** + * @param {number[]} values + * @param {number[][]} edges + * @param {number} maxTime + * @return {number} + */ +var maximalPathQuality = function(values, edges, maxTime) { + const n = values.length; + const adjList = Array.from({ length: n }, () => []); + + for (const [u, v, time] of edges) { + adjList[u].push([v, time]); + adjList[v].push([u, time]); + } + + let result = 0; + const initialVisited = new Set([0]); + + dfs(0, maxTime, values[0], initialVisited); + + return result; + + function dfs(node, timeLeft, quality, visited) { + if (timeLeft < 0) return 0; + if (node === 0) { + result = Math.max(result, quality); + } + + for (const [nextNode, travelTime] of adjList[node]) { + const newVisited = new Set(visited); + const newQuality = newVisited.has(nextNode) ? quality : quality + values[nextNode]; + newVisited.add(nextNode); + dfs(nextNode, timeLeft - travelTime, newQuality, newVisited); + } + + return result; + } +}; From 8751b63cb2d3ffb0b6c0f50c2fe958a84b597b24 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sat, 10 May 2025 18:57:20 -0500 Subject: [PATCH 220/495] Add solution #2068 --- README.md | 3 +- ...ether-two-strings-are-almost-equivalent.js | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 solutions/2068-check-whether-two-strings-are-almost-equivalent.js diff --git a/README.md b/README.md index e47e518d..6ea1771b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,724 LeetCode solutions in JavaScript +# 1,725 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1584,6 +1584,7 @@ 2063|[Vowels of All Substrings](./solutions/2063-vowels-of-all-substrings.js)|Medium| 2064|[Minimized Maximum of Products Distributed to Any Store](./solutions/2064-minimized-maximum-of-products-distributed-to-any-store.js)|Medium| 2065|[Maximum Path Quality of a Graph](./solutions/2065-maximum-path-quality-of-a-graph.js)|Hard| +2068|[Check Whether Two Strings are Almost Equivalent](./solutions/2068-check-whether-two-strings-are-almost-equivalent.js)|Easy| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| diff --git a/solutions/2068-check-whether-two-strings-are-almost-equivalent.js b/solutions/2068-check-whether-two-strings-are-almost-equivalent.js new file mode 100644 index 00000000..210aeb88 --- /dev/null +++ b/solutions/2068-check-whether-two-strings-are-almost-equivalent.js @@ -0,0 +1,29 @@ +/** + * 2068. Check Whether Two Strings are Almost Equivalent + * https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/ + * Difficulty: Easy + * + * Two strings word1 and word2 are considered almost equivalent if the differences between the + * frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3. + * + * Given two strings word1 and word2, each of length n, return true if word1 and word2 are almost + * equivalent, or false otherwise. + * + * The frequency of a letter x is the number of times it occurs in the string. + */ + +/** + * @param {string} word1 + * @param {string} word2 + * @return {boolean} + */ +var checkAlmostEquivalent = function(word1, word2) { + const map = new Array(26).fill(0); + + for (let i = 0; i < word1.length; i++) { + map[word1.charCodeAt(i) - 97]++; + map[word2.charCodeAt(i) - 97]--; + } + + return map.every(diff => Math.abs(diff) <= 3); +}; From e0cf73afc1766d3c195983ed9727350d804d663c Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 00:00:06 -0500 Subject: [PATCH 221/495] Add solution #2069 --- README.md | 3 +- solutions/2069-walking-robot-simulation-ii.js | 84 +++++++++++++++++++ 2 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 solutions/2069-walking-robot-simulation-ii.js diff --git a/README.md b/README.md index 6ea1771b..b317e107 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,725 LeetCode solutions in JavaScript +# 1,726 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1585,6 +1585,7 @@ 2064|[Minimized Maximum of Products Distributed to Any Store](./solutions/2064-minimized-maximum-of-products-distributed-to-any-store.js)|Medium| 2065|[Maximum Path Quality of a Graph](./solutions/2065-maximum-path-quality-of-a-graph.js)|Hard| 2068|[Check Whether Two Strings are Almost Equivalent](./solutions/2068-check-whether-two-strings-are-almost-equivalent.js)|Easy| +2069|[Walking Robot Simulation II](./solutions/2069-walking-robot-simulation-ii.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| diff --git a/solutions/2069-walking-robot-simulation-ii.js b/solutions/2069-walking-robot-simulation-ii.js new file mode 100644 index 00000000..e4896040 --- /dev/null +++ b/solutions/2069-walking-robot-simulation-ii.js @@ -0,0 +1,84 @@ +/** + * 2069. Walking Robot Simulation II + * https://leetcode.com/problems/walking-robot-simulation-ii/ + * Difficulty: Medium + * + * A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the + * top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal + * directions ("North", "East", "South", and "West"). A robot is initially at cell (0, 0) + * facing direction "East". + * + * The robot can be instructed to move for a specific number of steps. For each step, it does + * the following. + * 1. Attempts to move forward one cell in the direction it is facing. + * 2. If the cell the robot is moving to is out of bounds, the robot instead turns 90 degrees + * counterclockwise and retries the step. + * + * After the robot finishes moving the number of steps required, it stops and awaits the next + * instruction. + * + * Implement the Robot class: + * - Robot(int width, int height) Initializes the width x height grid with the robot at (0, 0) + * facing "East". + * - void step(int num) Instructs the robot to move forward num steps. + * - int[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y]. + * - String getDir() Returns the current direction of the robot, "North", "East", "South", or + * "West". + */ + +/** + * @param {number} width + * @param {number} height + */ +var Robot = function(width, height) { + this.width = width; + this.height = height; + this.position = [0, 0]; + this.directionIndex = 0; + this.directions = ['East', 'North', 'West', 'South']; + this.moves = [[1, 0], [0, 1], [-1, 0], [0, -1]]; + this.perimeter = 2 * (width + height - 2); +}; + +/** + * @param {number} num + * @return {void} + */ +Robot.prototype.step = function(num) { + num %= this.perimeter; + if (num === 0) num = this.perimeter; + + while (num > 0) { + const [dx, dy] = this.moves[this.directionIndex]; + const [x, y] = this.position; + let steps; + + if (this.directionIndex === 0) steps = this.width - 1 - x; + else if (this.directionIndex === 1) steps = this.height - 1 - y; + else if (this.directionIndex === 2) steps = x; + else steps = y; + + if (steps >= num) { + this.position = [x + dx * num, y + dy * num]; + num = 0; + } else { + this.position = [x + dx * steps, y + dy * steps]; + this.directionIndex = (this.directionIndex + 1) % 4; + num -= steps; + } + } +}; + +/** + * @return {number[]} + */ +Robot.prototype.getPos = function() { + return this.position; +}; + +/** + * @return {string} + */ +Robot.prototype.getDir = function() { + return this.directions[this.directionIndex]; +}; From a9e3e9e83e489bcb5acf35610e30b39e38d45a1f Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 00:00:54 -0500 Subject: [PATCH 222/495] Add solution #2070 --- README.md | 3 +- ...2070-most-beautiful-item-for-each-query.js | 54 +++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 solutions/2070-most-beautiful-item-for-each-query.js diff --git a/README.md b/README.md index b317e107..c0507a5e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,726 LeetCode solutions in JavaScript +# 1,727 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1586,6 +1586,7 @@ 2065|[Maximum Path Quality of a Graph](./solutions/2065-maximum-path-quality-of-a-graph.js)|Hard| 2068|[Check Whether Two Strings are Almost Equivalent](./solutions/2068-check-whether-two-strings-are-almost-equivalent.js)|Easy| 2069|[Walking Robot Simulation II](./solutions/2069-walking-robot-simulation-ii.js)|Medium| +2070|[Most Beautiful Item for Each Query](./solutions/2070-most-beautiful-item-for-each-query.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| diff --git a/solutions/2070-most-beautiful-item-for-each-query.js b/solutions/2070-most-beautiful-item-for-each-query.js new file mode 100644 index 00000000..1931e875 --- /dev/null +++ b/solutions/2070-most-beautiful-item-for-each-query.js @@ -0,0 +1,54 @@ +/** + * 2070. Most Beautiful Item for Each Query + * https://leetcode.com/problems/most-beautiful-item-for-each-query/ + * Difficulty: Medium + * + * You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and + * beauty of an item respectively. + * + * You are also given a 0-indexed integer array queries. For each queries[j], you want to determine + * the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item + * exists, then the answer to this query is 0. + * + * Return an array answer of the same length as queries where answer[j] is the answer to the jth + * query. + */ + +/** + * @param {number[][]} items + * @param {number[]} queries + * @return {number[]} + */ +var maximumBeauty = function(items, queries) { + items.sort((a, b) => a[0] - b[0]); + const maxBeauty = []; + let currentMax = 0; + + for (const [, beauty] of items) { + currentMax = Math.max(currentMax, beauty); + maxBeauty.push(currentMax); + } + + const result = new Array(queries.length).fill(0); + + for (let i = 0; i < queries.length; i++) { + const price = queries[i]; + let left = 0; + let right = items.length - 1; + + while (left <= right) { + const mid = Math.floor((left + right) / 2); + if (items[mid][0] <= price) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + if (right >= 0) { + result[i] = maxBeauty[right]; + } + } + + return result; +}; From 756637228f22ef034a4f23c0e4463e38fed2bbd1 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 00:02:38 -0500 Subject: [PATCH 223/495] Add solution #2074 --- README.md | 3 +- ...074-reverse-nodes-in-even-length-groups.js | 72 +++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 solutions/2074-reverse-nodes-in-even-length-groups.js diff --git a/README.md b/README.md index c0507a5e..a6b2ede9 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,727 LeetCode solutions in JavaScript +# 1,728 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1588,6 +1588,7 @@ 2069|[Walking Robot Simulation II](./solutions/2069-walking-robot-simulation-ii.js)|Medium| 2070|[Most Beautiful Item for Each Query](./solutions/2070-most-beautiful-item-for-each-query.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| +2074|[Reverse Nodes in Even Length Groups](./solutions/2074-reverse-nodes-in-even-length-groups.js)|Medium| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| diff --git a/solutions/2074-reverse-nodes-in-even-length-groups.js b/solutions/2074-reverse-nodes-in-even-length-groups.js new file mode 100644 index 00000000..2608277e --- /dev/null +++ b/solutions/2074-reverse-nodes-in-even-length-groups.js @@ -0,0 +1,72 @@ +/** + * 2074. Reverse Nodes in Even Length Groups + * https://leetcode.com/problems/reverse-nodes-in-even-length-groups/ + * Difficulty: Medium + * + * You are given the head of a linked list. + * + * The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form + * the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number + * of nodes assigned to it. In other words: + * - The 1st node is assigned to the first group. + * - The 2nd and the 3rd nodes are assigned to the second group. + * - The 4th, 5th, and 6th nodes are assigned to the third group, and so on. + * + * Note that the length of the last group may be less than or equal to 1 + the length of the second + * to last group. + * + * Reverse the nodes in each group with an even length, and return the head of the modified linked + * list. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var reverseEvenLengthGroups = function(head) { + let prevGroup = head; + let groupLength = 2; + + while (prevGroup.next) { + let count = 0; + let current = prevGroup.next; + const groupStart = current; + + while (current && count < groupLength) { + current = current.next; + count++; + } + + if (count % 2 === 0) { + prevGroup.next = reverseGroup(groupStart, count); + } + + for (let i = 0; i < count; i++) { + prevGroup = prevGroup.next; + } + + groupLength++; + } + + return head; + + function reverseGroup(start, length) { + let prev = null; + let current = start; + for (let i = 0; i < length; i++) { + const next = current.next; + current.next = prev; + prev = current; + current = next; + } + start.next = current; + return prev; + } +}; From 296c68f23ceb203b229102cdde0d693afe592d95 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 00:06:23 -0500 Subject: [PATCH 224/495] Add solution #2075 --- README.md | 3 +- .../2075-decode-the-slanted-ciphertext.js | 51 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 solutions/2075-decode-the-slanted-ciphertext.js diff --git a/README.md b/README.md index a6b2ede9..f336c7e8 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,728 LeetCode solutions in JavaScript +# 1,729 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1589,6 +1589,7 @@ 2070|[Most Beautiful Item for Each Query](./solutions/2070-most-beautiful-item-for-each-query.js)|Medium| 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2074|[Reverse Nodes in Even Length Groups](./solutions/2074-reverse-nodes-in-even-length-groups.js)|Medium| +2075|[Decode the Slanted Ciphertext](./solutions/2075-decode-the-slanted-ciphertext.js)|Medium| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| diff --git a/solutions/2075-decode-the-slanted-ciphertext.js b/solutions/2075-decode-the-slanted-ciphertext.js new file mode 100644 index 00000000..63f5a41d --- /dev/null +++ b/solutions/2075-decode-the-slanted-ciphertext.js @@ -0,0 +1,51 @@ +/** + * 2075. Decode the Slanted Ciphertext + * https://leetcode.com/problems/decode-the-slanted-ciphertext/ + * Difficulty: Medium + * + * A string originalText is encoded using a slanted transposition cipher to a string encodedText + * with the help of a matrix having a fixed number of rows rows. + * + * originalText is placed first in a top-left to bottom-right manner. + * + * The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, + * until we reach the end of originalText. The arrow indicates the order in which the cells are + * filled. All empty cells are filled with ' '. The number of columns is chosen such that the + * rightmost column will not be empty after filling in originalText. + * + * encodedText is then formed by appending all characters of the matrix in a row-wise fashion. + * + * The characters in the blue cells are appended first to encodedText, then the red cells, and so + * on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed. + * + * For example, if originalText = "cipher" and rows = 3, then we encode it in the following manner. + * + * The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the + * order in which encodedText is formed. In the above example, encodedText = "ch ie pr". + * + * Given the encoded string encodedText and number of rows rows, return the original string + * originalText. + * + * Note: originalText does not have any trailing spaces ' '. The test cases are generated such that + * there is only one possible originalText. + */ + +/** + * @param {string} encodedText + * @param {number} rows + * @return {string} + */ +var decodeCiphertext = function(encodedText, rows) { + if (rows === 1) return encodedText; + + const count = encodedText.length / rows; + let result = ''; + + for (let i = 0; i < count; i++) { + for (let row = 0; row < rows && row + i < count; row++) { + result += encodedText[row * count + i + row]; + } + } + + return result.trimEnd(); +}; From 687cd0d065d84d7691b572eaa43e152d4d8c3e3a Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 00:08:39 -0500 Subject: [PATCH 225/495] Add solution #2076 --- README.md | 3 +- ...2076-process-restricted-friend-requests.js | 70 +++++++++++++++++++ 2 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 solutions/2076-process-restricted-friend-requests.js diff --git a/README.md b/README.md index f336c7e8..43963ea0 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,729 LeetCode solutions in JavaScript +# 1,730 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1590,6 +1590,7 @@ 2071|[Maximum Number of Tasks You Can Assign](./solutions/2071-maximum-number-of-tasks-you-can-assign.js)|Hard| 2074|[Reverse Nodes in Even Length Groups](./solutions/2074-reverse-nodes-in-even-length-groups.js)|Medium| 2075|[Decode the Slanted Ciphertext](./solutions/2075-decode-the-slanted-ciphertext.js)|Medium| +2076|[Process Restricted Friend Requests](./solutions/2076-process-restricted-friend-requests.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| diff --git a/solutions/2076-process-restricted-friend-requests.js b/solutions/2076-process-restricted-friend-requests.js new file mode 100644 index 00000000..dff94d09 --- /dev/null +++ b/solutions/2076-process-restricted-friend-requests.js @@ -0,0 +1,70 @@ +/** + * 2076. Process Restricted Friend Requests + * https://leetcode.com/problems/process-restricted-friend-requests/ + * Difficulty: Hard + * + * You are given an integer n indicating the number of people in a network. Each person is + * labeled from 0 to n - 1. + * + * You are also given a 0-indexed 2D integer array restrictions, where restrictions[i] = [xi, yi] + * means that person xi and person yi cannot become friends, either directly or indirectly through + * other people. + * + * Initially, no one is friends with each other. You are given a list of friend requests as a + * 0-indexed 2D integer array requests, where requests[j] = [uj, vj] is a friend request between + * person uj and person vj. + * + * A friend request is successful if uj and vj can be friends. Each friend request is processed + * in the given order (i.e., requests[j] occurs before requests[j + 1]), and upon a successful + * request, uj and vj become direct friends for all future friend requests. + * + * Return a boolean array result, where each result[j] is true if the jth friend request is + * successful or false if it is not. + * + * Note: If uj and vj are already direct friends, the request is still successful. + */ + +/** + * @param {number} n + * @param {number[][]} restrictions + * @param {number[][]} requests + * @return {boolean[]} + */ +var friendRequests = function(n, restrictions, requests) { + const parent = Array.from({ length: n }, (_, i) => i); + const result = new Array(requests.length).fill(true); + + for (let j = 0; j < requests.length; j++) { + const [u, v] = requests[j]; + const pu = find(u); + const pv = find(v); + + let canBeFriends = true; + for (const [x, y] of restrictions) { + const px = find(x); + const py = find(y); + if ((pu === px && pv === py) || (pu === py && pv === px)) { + canBeFriends = false; + break; + } + } + + result[j] = canBeFriends; + if (canBeFriends) { + union(u, v); + } + } + + return result; + + function find(x) { + if (parent[x] !== x) { + parent[x] = find(parent[x]); + } + return parent[x]; + } + + function union(x, y) { + parent[find(x)] = find(y); + } +}; From effede67040b2fbc7c5c0cde649c2bf3b375716b Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 00:16:39 -0500 Subject: [PATCH 226/495] Add solution #2078 --- README.md | 3 +- ...o-furthest-houses-with-different-colors.js | 32 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 solutions/2078-two-furthest-houses-with-different-colors.js diff --git a/README.md b/README.md index 43963ea0..f4328fc7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,730 LeetCode solutions in JavaScript +# 1,731 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1591,6 +1591,7 @@ 2074|[Reverse Nodes in Even Length Groups](./solutions/2074-reverse-nodes-in-even-length-groups.js)|Medium| 2075|[Decode the Slanted Ciphertext](./solutions/2075-decode-the-slanted-ciphertext.js)|Medium| 2076|[Process Restricted Friend Requests](./solutions/2076-process-restricted-friend-requests.js)|Hard| +2078|[Two Furthest Houses With Different Colors](./solutions/2078-two-furthest-houses-with-different-colors.js)|Easy| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| diff --git a/solutions/2078-two-furthest-houses-with-different-colors.js b/solutions/2078-two-furthest-houses-with-different-colors.js new file mode 100644 index 00000000..9a42b696 --- /dev/null +++ b/solutions/2078-two-furthest-houses-with-different-colors.js @@ -0,0 +1,32 @@ +/** + * 2078. Two Furthest Houses With Different Colors + * https://leetcode.com/problems/two-furthest-houses-with-different-colors/ + * Difficulty: Easy + * + * There are n houses evenly lined up on the street, and each house is beautifully painted. + * You are given a 0-indexed integer array colors of length n, where colors[i] represents + * the color of the ith house. + * + * Return the maximum distance between two houses with different colors. + * + * The distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute + * value of x. + */ + +/** + * @param {number[]} colors + * @return {number} + */ +var maxDistance = function(colors) { + let result = 0; + + for (let i = 0; i < colors.length; i++) { + for (let j = i + 1; j < colors.length; j++) { + if (colors[i] !== colors[j]) { + result = Math.max(result, j - i); + } + } + } + + return result; +}; From 3ac3b0fe1088ebebc4050358a073b95a7f0aa90b Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 00:18:22 -0500 Subject: [PATCH 227/495] Add solution #2079 --- README.md | 3 ++- solutions/2079-watering-plants.js | 42 +++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 solutions/2079-watering-plants.js diff --git a/README.md b/README.md index f4328fc7..3b005494 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,731 LeetCode solutions in JavaScript +# 1,732 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1592,6 +1592,7 @@ 2075|[Decode the Slanted Ciphertext](./solutions/2075-decode-the-slanted-ciphertext.js)|Medium| 2076|[Process Restricted Friend Requests](./solutions/2076-process-restricted-friend-requests.js)|Hard| 2078|[Two Furthest Houses With Different Colors](./solutions/2078-two-furthest-houses-with-different-colors.js)|Easy| +2079|[Watering Plants](./solutions/2079-watering-plants.js)|Medium| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| diff --git a/solutions/2079-watering-plants.js b/solutions/2079-watering-plants.js new file mode 100644 index 00000000..ba77b302 --- /dev/null +++ b/solutions/2079-watering-plants.js @@ -0,0 +1,42 @@ +/** + * 2079. Watering Plants + * https://leetcode.com/problems/watering-plants/ + * Difficulty: Medium + * + * You want to water n plants in your garden with a watering can. The plants are arranged in + * a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at + * x = i. There is a river at x = -1 that you can refill your watering can at. + * + * Each plant needs a specific amount of water. You will water the plants in the following way: + * - Water the plants in order from left to right. + * - After watering the current plant, if you do not have enough water to completely water the + * next plant, return to the river to fully refill the watering can. + * - You cannot refill the watering can early. + * + * You are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis. + * + * Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water + * the ith plant needs, and an integer capacity representing the watering can capacity, return + * the number of steps needed to water all the plants. + */ + +/** + * @param {number[]} plants + * @param {number} capacity + * @return {number} + */ +var wateringPlants = function(plants, capacity) { + let water = capacity; + let result = 0; + + for (let i = 0; i < plants.length; i++) { + if (water < plants[i]) { + result += 2 * i; + water = capacity; + } + water -= plants[i]; + result++; + } + + return result; +}; From 9e1b3833ac1406b9956996118959f9c993a3c0c4 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 00:20:05 -0500 Subject: [PATCH 228/495] Add solution #2080 --- README.md | 3 +- solutions/2080-range-frequency-queries.js | 72 +++++++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 solutions/2080-range-frequency-queries.js diff --git a/README.md b/README.md index 3b005494..d4115d92 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,732 LeetCode solutions in JavaScript +# 1,733 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1593,6 +1593,7 @@ 2076|[Process Restricted Friend Requests](./solutions/2076-process-restricted-friend-requests.js)|Hard| 2078|[Two Furthest Houses With Different Colors](./solutions/2078-two-furthest-houses-with-different-colors.js)|Easy| 2079|[Watering Plants](./solutions/2079-watering-plants.js)|Medium| +2080|[Range Frequency Queries](./solutions/2080-range-frequency-queries.js)|Medium| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| diff --git a/solutions/2080-range-frequency-queries.js b/solutions/2080-range-frequency-queries.js new file mode 100644 index 00000000..32b1bb27 --- /dev/null +++ b/solutions/2080-range-frequency-queries.js @@ -0,0 +1,72 @@ +/** + * 2080. Range Frequency Queries + * https://leetcode.com/problems/range-frequency-queries/ + * Difficulty: Medium + * + * Design a data structure to find the frequency of a given value in a given subarray. + * + * The frequency of a value in a subarray is the number of occurrences of that value in + * the subarray. + * + * Implement the RangeFreqQuery class: + * - RangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed + * integer array arr. + * - int query(int left, int right, int value) Returns the frequency of value in the subarray + * arr[left...right]. + * - A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes + * the subarray that contains the elements of nums between indices left and right (inclusive). + */ + +/** + * @param {number[]} arr + */ +var RangeFreqQuery = function(arr) { + this.frequencyMap = new Map(); + + for (let i = 0; i < arr.length; i++) { + if (!this.frequencyMap.has(arr[i])) { + this.frequencyMap.set(arr[i], []); + } + this.frequencyMap.get(arr[i]).push(i); + } +}; + +/** + * @param {number} left + * @param {number} right + * @param {number} value + * @return {number} + */ +RangeFreqQuery.prototype.query = function(left, right, value) { + if (!this.frequencyMap.has(value)) return 0; + + const indices = this.frequencyMap.get(value); + let start = 0; + let end = indices.length - 1; + let leftBound = -1; + let rightBound = -1; + + while (start <= end) { + const mid = Math.floor((start + end) / 2); + if (indices[mid] >= left) { + leftBound = mid; + end = mid - 1; + } else { + start = mid + 1; + } + } + + start = 0; + end = indices.length - 1; + while (start <= end) { + const mid = Math.floor((start + end) / 2); + if (indices[mid] <= right) { + rightBound = mid; + start = mid + 1; + } else { + end = mid - 1; + } + } + + return leftBound === -1 || rightBound === -1 ? 0 : rightBound - leftBound + 1; +}; From 9aebc22ee763a33d07fec28e4a9f87c28564126c Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 00:40:09 -0500 Subject: [PATCH 229/495] Add solution #2081 --- README.md | 3 +- solutions/2081-sum-of-k-mirror-numbers.js | 105 ++++++++++++++++++++++ 2 files changed, 107 insertions(+), 1 deletion(-) create mode 100644 solutions/2081-sum-of-k-mirror-numbers.js diff --git a/README.md b/README.md index d4115d92..30ad0a61 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,733 LeetCode solutions in JavaScript +# 1,734 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1594,6 +1594,7 @@ 2078|[Two Furthest Houses With Different Colors](./solutions/2078-two-furthest-houses-with-different-colors.js)|Easy| 2079|[Watering Plants](./solutions/2079-watering-plants.js)|Medium| 2080|[Range Frequency Queries](./solutions/2080-range-frequency-queries.js)|Medium| +2081|[Sum of k-Mirror Numbers](./solutions/2081-sum-of-k-mirror-numbers.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| diff --git a/solutions/2081-sum-of-k-mirror-numbers.js b/solutions/2081-sum-of-k-mirror-numbers.js new file mode 100644 index 00000000..600d62d8 --- /dev/null +++ b/solutions/2081-sum-of-k-mirror-numbers.js @@ -0,0 +1,105 @@ +/** + * 2081. Sum of k-Mirror Numbers + * https://leetcode.com/problems/sum-of-k-mirror-numbers/ + * Difficulty: Hard + * + * A k-mirror number is a positive integer without leading zeros that reads the same both forward + * and backward in base-10 as well as in base-k. + * - For example, 9 is a 2-mirror number. The representation of 9 in base-10 and base-2 are 9 and + * 1001 respectively, which read the same both forward and backward. + * - On the contrary, 4 is not a 2-mirror number. The representation of 4 in base-2 is 100, which + * does not read the same both forward and backward. + * + * Given the base k and the number n, return the sum of the n smallest k-mirror numbers. + */ + +/** + * @param {number} k + * @param {number} n + * @return {number} + */ +var kMirror = function(k, n) { + const kMirrorNumbers = []; + let sum = 0; + let length = 1; + + while (kMirrorNumbers.length < n) { + generatePalindromes(length).forEach(num => { + if (kMirrorNumbers.length < n && isKMirror(num, k)) { + kMirrorNumbers.push(num); + sum += num; + } + }); + length++; + } + + return sum; +}; + +function toBaseK(num, k) { + if (num === 0) return '0'; + + let result = ''; + while (num > 0) { + result = (num % k) + result; + num = Math.floor(num / k); + } + + return result; +} + +function isKMirror(num, k) { + const baseKRepresentation = toBaseK(num, k); + return isPalindrome(baseKRepresentation); +} + +function isPalindrome(str) { + let left = 0; + let right = str.length - 1; + + while (left < right) { + if (str[left] !== str[right]) return false; + left++; + right--; + } + + return true; +} + +function generatePalindromes(length) { + const palindromes = []; + + if (length === 1) { + for (let i = 1; i <= 9; i++) { + palindromes.push(i); + } + return palindromes; + } + + if (length % 2 === 0) { + const half = length / 2; + const start = Math.pow(10, half - 1); + const end = Math.pow(10, half) - 1; + + for (let i = start; i <= end; i++) { + const firstHalf = i.toString(); + const secondHalf = firstHalf.split('').reverse().join(''); + palindromes.push(parseInt(firstHalf + secondHalf)); + } + } else { + const half = Math.floor(length / 2); + const start = Math.pow(10, half); + const end = Math.pow(10, half + 1) - 1; + + for (let i = start; i <= end; i++) { + const withoutMiddle = Math.floor(i / 10); + const middle = i % 10; + const firstHalf = withoutMiddle.toString(); + const secondHalf = firstHalf.split('').reverse().join(''); + palindromes.push(parseInt(firstHalf + middle + secondHalf)); + } + } + + return palindromes; +} + From 6174e00775db410d97e6f01958af06b35142bd85 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 00:41:54 -0500 Subject: [PATCH 230/495] Add solution #2086 --- README.md | 3 +- ...er-of-food-buckets-to-feed-the-hamsters.js | 43 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 solutions/2086-minimum-number-of-food-buckets-to-feed-the-hamsters.js diff --git a/README.md b/README.md index 30ad0a61..7976e60f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,734 LeetCode solutions in JavaScript +# 1,735 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1596,6 +1596,7 @@ 2080|[Range Frequency Queries](./solutions/2080-range-frequency-queries.js)|Medium| 2081|[Sum of k-Mirror Numbers](./solutions/2081-sum-of-k-mirror-numbers.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| +2086|[Minimum Number of Food Buckets to Feed the Hamsters](./solutions/2086-minimum-number-of-food-buckets-to-feed-the-hamsters.js)|Medium| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| diff --git a/solutions/2086-minimum-number-of-food-buckets-to-feed-the-hamsters.js b/solutions/2086-minimum-number-of-food-buckets-to-feed-the-hamsters.js new file mode 100644 index 00000000..5cda9132 --- /dev/null +++ b/solutions/2086-minimum-number-of-food-buckets-to-feed-the-hamsters.js @@ -0,0 +1,43 @@ +/** + * 2086. Minimum Number of Food Buckets to Feed the Hamsters + * https://leetcode.com/problems/minimum-number-of-food-buckets-to-feed-the-hamsters/ + * Difficulty: Medium + * + * You are given a 0-indexed string hamsters where hamsters[i] is either: + * - 'H' indicating that there is a hamster at index i, or + * - '.' indicating that index i is empty. + * + * You will add some number of food buckets at the empty indices in order to feed the hamsters. + * A hamster can be fed if there is at least one food bucket to its left or to its right. More + * formally, a hamster at index i can be fed if you place a food bucket at index i - 1 and/or + * at index i + 1. + * + * Return the minimum number of food buckets you should place at empty indices to feed all the + * hamsters or -1 if it is impossible to feed all of them. + */ + +/** + * @param {string} hamsters + * @return {number} + */ +var minimumBuckets = function(hamsters) { + const n = hamsters.length; + let result = 0; + + for (let i = 0; i < n; i++) { + if (hamsters[i] === 'H') { + if (i > 0 && hamsters[i - 1] === 'B') continue; + if (i < n - 1 && hamsters[i + 1] === '.') { + result++; + hamsters = hamsters.slice(0, i + 1) + 'B' + hamsters.slice(i + 2); + } else if (i > 0 && hamsters[i - 1] === '.') { + result++; + hamsters = hamsters.slice(0, i - 1) + 'B' + hamsters.slice(i); + } else { + return -1; + } + } + } + + return result; +}; From ae31f45925f2ac24332aba809c84bccc51246315 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 12:04:25 -0500 Subject: [PATCH 231/495] Add solution #2087 --- README.md | 3 +- ...um-cost-homecoming-of-a-robot-in-a-grid.js | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 solutions/2087-minimum-cost-homecoming-of-a-robot-in-a-grid.js diff --git a/README.md b/README.md index 7976e60f..11720dc6 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,735 LeetCode solutions in JavaScript +# 1,736 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1597,6 +1597,7 @@ 2081|[Sum of k-Mirror Numbers](./solutions/2081-sum-of-k-mirror-numbers.js)|Hard| 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2086|[Minimum Number of Food Buckets to Feed the Hamsters](./solutions/2086-minimum-number-of-food-buckets-to-feed-the-hamsters.js)|Medium| +2087|[Minimum Cost Homecoming of a Robot in a Grid](./solutions/2087-minimum-cost-homecoming-of-a-robot-in-a-grid.js)|Medium| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| diff --git a/solutions/2087-minimum-cost-homecoming-of-a-robot-in-a-grid.js b/solutions/2087-minimum-cost-homecoming-of-a-robot-in-a-grid.js new file mode 100644 index 00000000..8fde0697 --- /dev/null +++ b/solutions/2087-minimum-cost-homecoming-of-a-robot-in-a-grid.js @@ -0,0 +1,45 @@ +/** + * 2087. Minimum Cost Homecoming of a Robot in a Grid + * https://leetcode.com/problems/minimum-cost-homecoming-of-a-robot-in-a-grid/ + * Difficulty: Medium + * + * There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right + * cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates + * that initially, a robot is at the cell (startrow, startcol). You are also given an integer array + * homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, + * homecol). + * + * The robot needs to go to its home. It can move one cell in four directions: left, right, up, + * or down, and it can not move outside the boundary. Every move incurs some cost. You are further + * given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n. + * - If the robot moves up or down into a cell whose row is r, then this move costs rowCosts[r]. + * - If the robot moves left or right into a cell whose column is c, then this move costs + * colCosts[c]. + * + * Return the minimum total cost for this robot to return home. + */ + +/** + * @param {number[]} startPos + * @param {number[]} homePos + * @param {number[]} rowCosts + * @param {number[]} colCosts + * @return {number} + */ +var minCost = function(startPos, homePos, rowCosts, colCosts) { + let result = 0; + const [startRow, startCol] = startPos; + const [homeRow, homeCol] = homePos; + + const rowStep = startRow < homeRow ? 1 : -1; + for (let row = startRow + rowStep; row !== homeRow + rowStep; row += rowStep) { + result += rowCosts[row]; + } + + const colStep = startCol < homeCol ? 1 : -1; + for (let col = startCol + colStep; col !== homeCol + colStep; col += colStep) { + result += colCosts[col]; + } + + return result; +}; From afd3cd562988d280df65c8bc571ac7ec70926c46 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 12:06:39 -0500 Subject: [PATCH 232/495] Add solution #2088 --- README.md | 3 +- .../2088-count-fertile-pyramids-in-a-land.js | 71 +++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 solutions/2088-count-fertile-pyramids-in-a-land.js diff --git a/README.md b/README.md index 11720dc6..beee4424 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,736 LeetCode solutions in JavaScript +# 1,737 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1598,6 +1598,7 @@ 2085|[Count Common Words With One Occurrence](./solutions/2085-count-common-words-with-one-occurrence.js)|Easy| 2086|[Minimum Number of Food Buckets to Feed the Hamsters](./solutions/2086-minimum-number-of-food-buckets-to-feed-the-hamsters.js)|Medium| 2087|[Minimum Cost Homecoming of a Robot in a Grid](./solutions/2087-minimum-cost-homecoming-of-a-robot-in-a-grid.js)|Medium| +2088|[Count Fertile Pyramids in a Land](./solutions/2088-count-fertile-pyramids-in-a-land.js)|Hard| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| diff --git a/solutions/2088-count-fertile-pyramids-in-a-land.js b/solutions/2088-count-fertile-pyramids-in-a-land.js new file mode 100644 index 00000000..0780710b --- /dev/null +++ b/solutions/2088-count-fertile-pyramids-in-a-land.js @@ -0,0 +1,71 @@ +/** + * 2088. Count Fertile Pyramids in a Land + * https://leetcode.com/problems/count-fertile-pyramids-in-a-land/ + * Difficulty: Hard + * + * A farmer has a rectangular grid of land with m rows and n columns that can be divided into + * unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0). + * All cells outside the grid are considered barren. + * + * A pyramidal plot of land can be defined as a set of cells with the following criteria: + * 1. The number of cells in the set has to be greater than 1 and all cells must be fertile. + * 2. The apex of a pyramid is the topmost cell of the pyramid. The height of a pyramid is the + * number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. + * Then, the plot comprises of cells (i, j) where r <= i <= r + h - 1 and + * c - (i - r) <= j <= c + (i - r). + * + * An inverse pyramidal plot of land can be defined as a set of cells with similar criteria: + * 1. The number of cells in the set has to be greater than 1 and all cells must be fertile. + * 2. The apex of an inverse pyramid is the bottommost cell of the inverse pyramid. The height + * of an inverse pyramid is the number of rows it covers. Let (r, c) be the apex of the + * pyramid, and its height be h. Then, the plot comprises of cells (i, j) where + * r - h + 1 <= i <= r and c - (r - i) <= j <= c + (r - i). + * + * Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. + * Black cells indicate fertile cells. + * + * Given a 0-indexed m x n binary matrix grid representing the farmland, return the total number + * of pyramidal and inverse pyramidal plots that can be found in grid. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var countPyramids = function(grid) { + const rows = grid.length; + const cols = grid[0].length; + let result = 0; + + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + if (grid[i][j] === 1) { + result += countPyramidAt(i, j, false); + result += countPyramidAt(i, j, true); + } + } + } + + return result; + + function countPyramidAt(row, col, isInverse) { + let height = 0; + for (let h = 1; ; h++) { + const r = isInverse ? row - h : row + h; + if (r < 0 || r >= rows) break; + const left = col - h; + const right = col + h; + if (left < 0 || right >= cols) break; + let valid = true; + for (let j = left; j <= right; j++) { + if (grid[r][j] === 0) { + valid = false; + break; + } + } + if (!valid) break; + height++; + } + return height; + } +}; From e7b6bc6f9faced76d2eb870711237cea6b70f732 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 12:07:46 -0500 Subject: [PATCH 233/495] Add solution #2089 --- README.md | 3 +- ...find-target-indices-after-sorting-array.js | 32 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 solutions/2089-find-target-indices-after-sorting-array.js diff --git a/README.md b/README.md index beee4424..1c66a2c3 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,737 LeetCode solutions in JavaScript +# 1,738 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1599,6 +1599,7 @@ 2086|[Minimum Number of Food Buckets to Feed the Hamsters](./solutions/2086-minimum-number-of-food-buckets-to-feed-the-hamsters.js)|Medium| 2087|[Minimum Cost Homecoming of a Robot in a Grid](./solutions/2087-minimum-cost-homecoming-of-a-robot-in-a-grid.js)|Medium| 2088|[Count Fertile Pyramids in a Land](./solutions/2088-count-fertile-pyramids-in-a-land.js)|Hard| +2089|[Find Target Indices After Sorting Array](./solutions/2089-find-target-indices-after-sorting-array.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| diff --git a/solutions/2089-find-target-indices-after-sorting-array.js b/solutions/2089-find-target-indices-after-sorting-array.js new file mode 100644 index 00000000..c7235faa --- /dev/null +++ b/solutions/2089-find-target-indices-after-sorting-array.js @@ -0,0 +1,32 @@ +/** + * 2089. Find Target Indices After Sorting Array + * https://leetcode.com/problems/find-target-indices-after-sorting-array/ + * Difficulty: Easy + * + * You are given a 0-indexed integer array nums and a target element target. + * + * A target index is an index i such that nums[i] == target. + * + * Return a list of the target indices of nums after sorting nums in non-decreasing order. + * If there are no target indices, return an empty list. The returned list must be sorted + * in increasing order. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var targetIndices = function(nums, target) { + const result = []; + + nums.sort((a, b) => a - b); + + for (let i = 0; i < nums.length; i++) { + if (nums[i] === target) { + result.push(i); + } + } + + return result; +}; From 4eb48220736eb2e263d57daaa98f765987945b99 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 12:09:32 -0500 Subject: [PATCH 234/495] Add solution #2090 --- README.md | 3 +- solutions/2090-k-radius-subarray-averages.js | 46 ++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 solutions/2090-k-radius-subarray-averages.js diff --git a/README.md b/README.md index 1c66a2c3..e9c64729 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,738 LeetCode solutions in JavaScript +# 1,739 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1600,6 +1600,7 @@ 2087|[Minimum Cost Homecoming of a Robot in a Grid](./solutions/2087-minimum-cost-homecoming-of-a-robot-in-a-grid.js)|Medium| 2088|[Count Fertile Pyramids in a Land](./solutions/2088-count-fertile-pyramids-in-a-land.js)|Hard| 2089|[Find Target Indices After Sorting Array](./solutions/2089-find-target-indices-after-sorting-array.js)|Easy| +2090|[K Radius Subarray Averages](./solutions/2090-k-radius-subarray-averages.js)|Medium| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| diff --git a/solutions/2090-k-radius-subarray-averages.js b/solutions/2090-k-radius-subarray-averages.js new file mode 100644 index 00000000..3808077d --- /dev/null +++ b/solutions/2090-k-radius-subarray-averages.js @@ -0,0 +1,46 @@ +/** + * 2090. K Radius Subarray Averages + * https://leetcode.com/problems/k-radius-subarray-averages/ + * Difficulty: Medium + * + * You are given a 0-indexed array nums of n integers, and an integer k. + * + * The k-radius average for a subarray of nums centered at some index i with the radius k is + * the average of all elements in nums between the indices i - k and i + k (inclusive). If + * there are less than k elements before or after the index i, then the k-radius average is -1. + * + * Build and return an array avgs of length n where avgs[i] is the k-radius average for the + * subarray centered at index i. + * + * The average of x elements is the sum of the x elements divided by x, using integer division. + * The integer division truncates toward zero, which means losing its fractional part. + * - For example, the average of four elements 2, 3, 1, and + * 5 is (2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75, which truncates to 2. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var getAverages = function(nums, k) { + const n = nums.length; + const windowSize = 2 * k + 1; + const result = new Array(n).fill(-1); + + if (windowSize > n) return result; + + let sum = 0; + for (let i = 0; i < windowSize; i++) { + sum += nums[i]; + } + + result[k] = Math.floor(sum / windowSize); + + for (let i = k + 1; i < n - k; i++) { + sum = sum - nums[i - k - 1] + nums[i + k]; + result[i] = Math.floor(sum / windowSize); + } + + return result; +}; From 3d7d4e31dee60250bcf677ed696477af32dec9a5 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 12:10:36 -0500 Subject: [PATCH 235/495] Add solution #2091 --- README.md | 3 +- ...removing-minimum-and-maximum-from-array.js | 41 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 solutions/2091-removing-minimum-and-maximum-from-array.js diff --git a/README.md b/README.md index e9c64729..e3ca3f9a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,739 LeetCode solutions in JavaScript +# 1,740 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1601,6 +1601,7 @@ 2088|[Count Fertile Pyramids in a Land](./solutions/2088-count-fertile-pyramids-in-a-land.js)|Hard| 2089|[Find Target Indices After Sorting Array](./solutions/2089-find-target-indices-after-sorting-array.js)|Easy| 2090|[K Radius Subarray Averages](./solutions/2090-k-radius-subarray-averages.js)|Medium| +2091|[Removing Minimum and Maximum From Array](./solutions/2091-removing-minimum-and-maximum-from-array.js)|Medium| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| diff --git a/solutions/2091-removing-minimum-and-maximum-from-array.js b/solutions/2091-removing-minimum-and-maximum-from-array.js new file mode 100644 index 00000000..b62e781e --- /dev/null +++ b/solutions/2091-removing-minimum-and-maximum-from-array.js @@ -0,0 +1,41 @@ +/** + * 2091. Removing Minimum and Maximum From Array + * https://leetcode.com/problems/removing-minimum-and-maximum-from-array/ + * Difficulty: Medium + * + * You are given a 0-indexed array of distinct integers nums. + * + * There is an element in nums that has the lowest value and an element that has the highest + * value. We call them the minimum and maximum respectively. Your goal is to remove both these + * elements from the array. + * + * A deletion is defined as either removing an element from the front of the array or removing + * an element from the back of the array. + * + * Return the minimum number of deletions it would take to remove both the minimum and maximum + * element from the array. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var minimumDeletions = function(nums) { + const n = nums.length; + let minIndex = 0; + let maxIndex = 0; + + for (let i = 1; i < n; i++) { + if (nums[i] < nums[minIndex]) minIndex = i; + if (nums[i] > nums[maxIndex]) maxIndex = i; + } + + const left = Math.min(minIndex, maxIndex); + const right = Math.max(minIndex, maxIndex); + + return Math.min( + right + 1, + n - left, + left + 1 + n - right + ); +}; From dfb90fbab23bc756b0f34f2880f823ad542840c8 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 22:07:59 -0500 Subject: [PATCH 236/495] Add solution #2092 --- README.md | 3 +- solutions/2092-find-all-people-with-secret.js | 73 +++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 solutions/2092-find-all-people-with-secret.js diff --git a/README.md b/README.md index e3ca3f9a..b0bd05db 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,740 LeetCode solutions in JavaScript +# 1,741 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1602,6 +1602,7 @@ 2089|[Find Target Indices After Sorting Array](./solutions/2089-find-target-indices-after-sorting-array.js)|Easy| 2090|[K Radius Subarray Averages](./solutions/2090-k-radius-subarray-averages.js)|Medium| 2091|[Removing Minimum and Maximum From Array](./solutions/2091-removing-minimum-and-maximum-from-array.js)|Medium| +2092|[Find All People With Secret](./solutions/2092-find-all-people-with-secret.js)|Hard| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| diff --git a/solutions/2092-find-all-people-with-secret.js b/solutions/2092-find-all-people-with-secret.js new file mode 100644 index 00000000..f5fecbdc --- /dev/null +++ b/solutions/2092-find-all-people-with-secret.js @@ -0,0 +1,73 @@ +/** + * 2092. Find All People With Secret + * https://leetcode.com/problems/find-all-people-with-secret/ + * Difficulty: Hard + * + * You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also + * given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that + * person xi and person yi have a meeting at timei. A person may attend multiple meetings at the + * same time. Finally, you are given an integer firstPerson. + * + * Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This + * secret is then shared every time a meeting takes place with a person that has the secret. More + * formally, for every meeting, if a person xi has the secret at timei, then they will share the + * secret with person yi, and vice versa. + * + * The secrets are shared instantaneously. That is, a person may receive the secret and share it + * with people in other meetings within the same time frame. + * + * Return a list of all the people that have the secret after all the meetings have taken place. + * You may return the answer in any order. + */ + +/** + * @param {number} n + * @param {number[][]} meetings + * @param {number} firstPerson + * @return {number[]} + */ +var findAllPeople = function(n, meetings, firstPerson) { + const parent = Array.from({ length: n }, (_, i) => i); + + union(0, firstPerson); + meetings.sort((a, b) => a[2] - b[2]); + + let i = 0; + while (i < meetings.length) { + const currentTime = meetings[i][2]; + const group = []; + + while (i < meetings.length && meetings[i][2] === currentTime) { + const [x, y] = meetings[i]; + group.push(x, y); + union(x, y); + i++; + } + + for (const person of group) { + if (find(person) !== find(0)) { + parent[person] = person; + } + } + } + + const result = []; + for (let j = 0; j < n; j++) { + if (find(j) === find(0)) { + result.push(j); + } + } + + return result; + + function find(x) { + if (parent[x] !== x) { + parent[x] = find(parent[x]); + } + return parent[x]; + } + + function union(x, y) { + parent[find(x)] = find(y); + } +}; From be2fea9b7d363b98e65cbe09526691d71edf6bd5 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 22:08:58 -0500 Subject: [PATCH 237/495] Add solution #2094 --- README.md | 3 +- .../2094-finding-3-digit-even-numbers.js | 51 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 solutions/2094-finding-3-digit-even-numbers.js diff --git a/README.md b/README.md index b0bd05db..4156b28f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,741 LeetCode solutions in JavaScript +# 1,742 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1603,6 +1603,7 @@ 2090|[K Radius Subarray Averages](./solutions/2090-k-radius-subarray-averages.js)|Medium| 2091|[Removing Minimum and Maximum From Array](./solutions/2091-removing-minimum-and-maximum-from-array.js)|Medium| 2092|[Find All People With Secret](./solutions/2092-find-all-people-with-secret.js)|Hard| +2094|[Finding 3-Digit Even Numbers](./solutions/2094-finding-3-digit-even-numbers.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| diff --git a/solutions/2094-finding-3-digit-even-numbers.js b/solutions/2094-finding-3-digit-even-numbers.js new file mode 100644 index 00000000..f021bdff --- /dev/null +++ b/solutions/2094-finding-3-digit-even-numbers.js @@ -0,0 +1,51 @@ +/** + * 2094. Finding 3-Digit Even Numbers + * https://leetcode.com/problems/finding-3-digit-even-numbers/ + * Difficulty: Easy + * + * You are given an integer array digits, where each element is a digit. The array may contain + * duplicates. + * + * You need to find all the unique integers that follow the given requirements: + * - The integer consists of the concatenation of three elements from digits in any arbitrary order. + * - The integer does not have leading zeros. + * - The integer is even. + * + * For example, if the given digits were [1, 2, 3], integers 132 and 312 follow the requirements. + * + * Return a sorted array of the unique integers. + */ + +/** + * @param {number[]} digits + * @return {number[]} + */ +var findEvenNumbers = function(digits) { + const frequency = new Array(10).fill(0); + const uniqueNumbers = new Set(); + + for (const digit of digits) { + frequency[digit]++; + } + + for (let hundreds = 1; hundreds <= 9; hundreds++) { + if (frequency[hundreds] === 0) continue; + frequency[hundreds]--; + + for (let tens = 0; tens <= 9; tens++) { + if (frequency[tens] === 0) continue; + frequency[tens]--; + + for (let ones = 0; ones <= 8; ones += 2) { + if (frequency[ones] === 0) continue; + uniqueNumbers.add(hundreds * 100 + tens * 10 + ones); + } + + frequency[tens]++; + } + + frequency[hundreds]++; + } + + return Array.from(uniqueNumbers).sort((a, b) => a - b); +}; From f222dd292e9f8f6e9eeddfe14668d606b7eddc07 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 22:10:46 -0500 Subject: [PATCH 238/495] Add solution #2096 --- README.md | 3 +- ...ions-from-a-binary-tree-node-to-another.js | 65 +++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 solutions/2096-step-by-step-directions-from-a-binary-tree-node-to-another.js diff --git a/README.md b/README.md index 4156b28f..e0d000fe 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,742 LeetCode solutions in JavaScript +# 1,743 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1605,6 +1605,7 @@ 2092|[Find All People With Secret](./solutions/2092-find-all-people-with-secret.js)|Hard| 2094|[Finding 3-Digit Even Numbers](./solutions/2094-finding-3-digit-even-numbers.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| +2096|[Step-By-Step Directions From a Binary Tree Node to Another](./solutions/2096-step-by-step-directions-from-a-binary-tree-node-to-another.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2115|[Find All Possible Recipes from Given Supplies](./solutions/2115-find-all-possible-recipes-from-given-supplies.js)|Medium| diff --git a/solutions/2096-step-by-step-directions-from-a-binary-tree-node-to-another.js b/solutions/2096-step-by-step-directions-from-a-binary-tree-node-to-another.js new file mode 100644 index 00000000..4eb7d4e9 --- /dev/null +++ b/solutions/2096-step-by-step-directions-from-a-binary-tree-node-to-another.js @@ -0,0 +1,65 @@ +/** + * 2096. Step-By-Step Directions From a Binary Tree Node to Another + * https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/ + * Difficulty: Medium + * + * You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value + * from 1 to n. You are also given an integer startValue representing the value of the start node + * s, and a different integer destValue representing the value of the destination node t. + * + * Find the shortest path starting from node s and ending at node t. Generate step-by-step + * directions of such path as a string consisting of only the uppercase letters 'L', 'R', and + * 'U'. Each letter indicates a specific direction: + * - 'L' means to go from a node to its left child node. + * - 'R' means to go from a node to its right child node. + * - 'U' means to go from a node to its parent node. + * + * Return the step-by-step directions of the shortest path from node s to node t. + */ + +/** + * 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} startValue + * @param {number} destValue + * @return {string} + */ +var getDirections = function(root, startValue, destValue) { + const startPath = []; + const destPath = []; + + findPath(root, startValue, startPath); + findPath(root, destValue, destPath); + + let i = 0; + while (i < startPath.length && i < destPath.length && startPath[i] === destPath[i]) { + i++; + } + + const upMoves = 'U'.repeat(startPath.length - i); + const downMoves = destPath.slice(i).join(''); + + return upMoves + downMoves; + + function findPath(node, value, path) { + if (!node) return false; + if (node.val === value) return true; + + path.push('L'); + if (findPath(node.left, value, path)) return true; + path.pop(); + + path.push('R'); + if (findPath(node.right, value, path)) return true; + path.pop(); + + return false; + } +}; From bbd19a6e18ec4151bdc37c63ac5211688f2b06b0 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 22:12:11 -0500 Subject: [PATCH 239/495] Add solution #2097 --- README.md | 3 +- solutions/2097-valid-arrangement-of-pairs.js | 50 ++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 solutions/2097-valid-arrangement-of-pairs.js diff --git a/README.md b/README.md index e0d000fe..46598faa 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,743 LeetCode solutions in JavaScript +# 1,744 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1606,6 +1606,7 @@ 2094|[Finding 3-Digit Even Numbers](./solutions/2094-finding-3-digit-even-numbers.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./solutions/2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2096|[Step-By-Step Directions From a Binary Tree Node to Another](./solutions/2096-step-by-step-directions-from-a-binary-tree-node-to-another.js)|Medium| +2097|[Valid Arrangement of Pairs](./solutions/2097-valid-arrangement-of-pairs.js)|Hard| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2115|[Find All Possible Recipes from Given Supplies](./solutions/2115-find-all-possible-recipes-from-given-supplies.js)|Medium| diff --git a/solutions/2097-valid-arrangement-of-pairs.js b/solutions/2097-valid-arrangement-of-pairs.js new file mode 100644 index 00000000..d3c5ee1c --- /dev/null +++ b/solutions/2097-valid-arrangement-of-pairs.js @@ -0,0 +1,50 @@ +/** + * 2097. Valid Arrangement of Pairs + * https://leetcode.com/problems/valid-arrangement-of-pairs/ + * Difficulty: Hard + * + * You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement + * of pairs is valid if for every index i where 1 <= i < pairs.length, we have endi-1 == starti. + * + * Return any valid arrangement of pairs. + * + * Note: The inputs will be generated such that there exists a valid arrangement of pairs. + */ + +/** + * @param {number[][]} pairs + * @return {number[][]} + */ +var validArrangement = function(pairs) { + const graph = new Map(); + const degree = new Map(); + + for (const [start, end] of pairs) { + if (!graph.has(start)) graph.set(start, []); + graph.get(start).push(end); + + degree.set(start, (degree.get(start) || 0) + 1); + degree.set(end, (degree.get(end) || 0) - 1); + } + + let startNode = pairs[0][0]; + for (const [node, deg] of degree) { + if (deg > 0) { + startNode = node; + break; + } + } + + const result = []; + helper(startNode); + + return result.reverse(); + + function helper(node) { + while (graph.get(node)?.length) { + const next = graph.get(node).pop(); + helper(next); + result.push([node, next]); + } + } +}; From 952b4b802ff03908f9874faea2654ce15e5b824e Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Sun, 11 May 2025 22:14:02 -0500 Subject: [PATCH 240/495] Add solution #2100 --- README.md | 3 +- .../2100-find-good-days-to-rob-the-bank.js | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 solutions/2100-find-good-days-to-rob-the-bank.js diff --git a/README.md b/README.md index 46598faa..01efa306 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,744 LeetCode solutions in JavaScript +# 1,745 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1608,6 +1608,7 @@ 2096|[Step-By-Step Directions From a Binary Tree Node to Another](./solutions/2096-step-by-step-directions-from-a-binary-tree-node-to-another.js)|Medium| 2097|[Valid Arrangement of Pairs](./solutions/2097-valid-arrangement-of-pairs.js)|Hard| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| +2100|[Find Good Days to Rob the Bank](./solutions/2100-find-good-days-to-rob-the-bank.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2115|[Find All Possible Recipes from Given Supplies](./solutions/2115-find-all-possible-recipes-from-given-supplies.js)|Medium| 2116|[Check if a Parentheses String Can Be Valid](./solutions/2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| diff --git a/solutions/2100-find-good-days-to-rob-the-bank.js b/solutions/2100-find-good-days-to-rob-the-bank.js new file mode 100644 index 00000000..1dc59611 --- /dev/null +++ b/solutions/2100-find-good-days-to-rob-the-bank.js @@ -0,0 +1,50 @@ +/** + * 2100. Find Good Days to Rob the Bank + * https://leetcode.com/problems/find-good-days-to-rob-the-bank/ + * Difficulty: Medium + * + * You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer + * array security, where security[i] is the number of guards on duty on the ith day. The days + * are numbered starting from 0. You are also given an integer time. + * + * The ith day is a good day to rob the bank if: + * - There are at least time days before and after the ith day, + * - The number of guards at the bank for the time days before i are non-increasing, and + * - The number of guards at the bank for the time days after i are non-decreasing. + * + * More formally, this means day i is a good day to rob the bank if and only if + * security[i - time] >= security[i - time + 1] >= ... >= security[i] + * <= ... <= security[i + time - 1] <= security[i + time]. + * + * Return a list of all days (0-indexed) that are good days to rob the bank. The order that the + * days are returned in does not matter. + */ + +/** + * @param {number[]} security + * @param {number} time + * @return {number[]} + */ +var goodDaysToRobBank = function(security, time) { + const n = security.length; + const nonIncreasing = new Array(n).fill(0); + const nonDecreasing = new Array(n).fill(0); + const result = []; + + for (let i = 1; i < n; i++) { + if (security[i] <= security[i - 1]) { + nonIncreasing[i] = nonIncreasing[i - 1] + 1; + } + if (security[n - i - 1] <= security[n - i]) { + nonDecreasing[n - i - 1] = nonDecreasing[n - i] + 1; + } + } + + for (let i = time; i < n - time; i++) { + if (nonIncreasing[i] >= time && nonDecreasing[i] >= time) { + result.push(i); + } + } + + return result; +}; From d31482340034a2680a256db71dafae06b05ca252 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 12 May 2025 08:12:00 -0500 Subject: [PATCH 241/495] Add solution #2101 --- README.md | 3 +- solutions/2101-detonate-the-maximum-bombs.js | 57 ++++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 solutions/2101-detonate-the-maximum-bombs.js diff --git a/README.md b/README.md index 01efa306..46d7bd18 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,745 LeetCode solutions in JavaScript +# 1,746 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1609,6 +1609,7 @@ 2097|[Valid Arrangement of Pairs](./solutions/2097-valid-arrangement-of-pairs.js)|Hard| 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2100|[Find Good Days to Rob the Bank](./solutions/2100-find-good-days-to-rob-the-bank.js)|Medium| +2101|[Detonate the Maximum Bombs](./solutions/2101-detonate-the-maximum-bombs.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2115|[Find All Possible Recipes from Given Supplies](./solutions/2115-find-all-possible-recipes-from-given-supplies.js)|Medium| 2116|[Check if a Parentheses String Can Be Valid](./solutions/2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| diff --git a/solutions/2101-detonate-the-maximum-bombs.js b/solutions/2101-detonate-the-maximum-bombs.js new file mode 100644 index 00000000..11069857 --- /dev/null +++ b/solutions/2101-detonate-the-maximum-bombs.js @@ -0,0 +1,57 @@ +/** + * 2101. Detonate the Maximum Bombs + * https://leetcode.com/problems/detonate-the-maximum-bombs/ + * Difficulty: Medium + * + * You are given a list of bombs. The range of a bomb is defined as the area where its effect + * can be felt. This area is in the shape of a circle with the center as the location of the bomb. + * + * The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. + * xi and yi denote the X-coordinate and Y-coordinate of the location of the ith bomb, whereas ri + * denotes the radius of its range. + * + * You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs + * that lie in its range. These bombs will further detonate the bombs that lie in their ranges. + * + * Given the list of bombs, return the maximum number of bombs that can be detonated if you are + * allowed to detonate only one bomb. + */ + +/** + * @param {number[][]} bombs + * @return {number} + */ +var maximumDetonation = function(bombs) { + const n = bombs.length; + const graph = Array.from({ length: n }, () => []); + + for (let i = 0; i < n; i++) { + const [x1, y1, r1] = bombs[i]; + for (let j = 0; j < n; j++) { + if (i === j) continue; + const [x2, y2] = bombs[j]; + const distance = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2); + if (distance <= r1) { + graph[i].push(j); + } + } + } + + let result = 0; + for (let i = 0; i < n; i++) { + result = Math.max(result, dfs(i, new Set())); + } + + return result; + + function dfs(node, visited) { + visited.add(node); + let count = 1; + for (const neighbor of graph[node]) { + if (!visited.has(neighbor)) { + count += dfs(neighbor, visited); + } + } + return count; + } +}; From 05f52643b7ee3b73901dd92af71c920bde1453f0 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 12 May 2025 08:13:44 -0500 Subject: [PATCH 242/495] Add solution #2103 --- README.md | 3 ++- solutions/2103-rings-and-rods.js | 42 ++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 solutions/2103-rings-and-rods.js diff --git a/README.md b/README.md index 46d7bd18..797e1157 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,746 LeetCode solutions in JavaScript +# 1,747 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1610,6 +1610,7 @@ 2099|[Find Subsequence of Length K With the Largest Sum](./solutions/2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2100|[Find Good Days to Rob the Bank](./solutions/2100-find-good-days-to-rob-the-bank.js)|Medium| 2101|[Detonate the Maximum Bombs](./solutions/2101-detonate-the-maximum-bombs.js)|Medium| +2103|[Rings and Rods](./solutions/2103-rings-and-rods.js)|Easy| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2115|[Find All Possible Recipes from Given Supplies](./solutions/2115-find-all-possible-recipes-from-given-supplies.js)|Medium| 2116|[Check if a Parentheses String Can Be Valid](./solutions/2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| diff --git a/solutions/2103-rings-and-rods.js b/solutions/2103-rings-and-rods.js new file mode 100644 index 00000000..b7cc219e --- /dev/null +++ b/solutions/2103-rings-and-rods.js @@ -0,0 +1,42 @@ +/** + * 2103. Rings and Rods + * https://leetcode.com/problems/rings-and-rods/ + * Difficulty: Easy + * + * There are n rings and each ring is either red, green, or blue. The rings are distributed across + * ten rods labeled from 0 to 9. + * + * You are given a string rings of length 2n that describes the n rings that are placed onto the + * rods. Every two characters in rings forms a color-position pair that is used to describe each + * ring where: + * - The first character of the ith pair denotes the ith ring's color ('R', 'G', 'B'). + * - The second character of the ith pair denotes the rod that the ith ring is placed on + * ('0' to '9'). + * + * For example, "R3G2B1" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green + * ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1. + * + * Return the number of rods that have all three colors of rings on them. + */ + +/** + * @param {string} rings + * @return {number} + */ +var countPoints = function(rings) { + const map = new Map(); + + for (let i = 0; i < rings.length; i += 2) { + const color = rings[i]; + const rod = rings[i + 1]; + if (!map.has(rod)) map.set(rod, new Set()); + map.get(rod).add(color); + } + + let result = 0; + for (const colors of map.values()) { + if (colors.size === 3) result++; + } + + return result; +}; From dc08ccadafae200205d3e8e2ef2065abc92f5c5d Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 12 May 2025 08:16:56 -0500 Subject: [PATCH 243/495] Add solution #2104 --- README.md | 3 ++- solutions/2104-sum-of-subarray-ranges.js | 33 ++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 solutions/2104-sum-of-subarray-ranges.js diff --git a/README.md b/README.md index 797e1157..00486aa9 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,747 LeetCode solutions in JavaScript +# 1,748 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1611,6 +1611,7 @@ 2100|[Find Good Days to Rob the Bank](./solutions/2100-find-good-days-to-rob-the-bank.js)|Medium| 2101|[Detonate the Maximum Bombs](./solutions/2101-detonate-the-maximum-bombs.js)|Medium| 2103|[Rings and Rods](./solutions/2103-rings-and-rods.js)|Easy| +2104|[Sum of Subarray Ranges](./solutions/2104-sum-of-subarray-ranges.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2115|[Find All Possible Recipes from Given Supplies](./solutions/2115-find-all-possible-recipes-from-given-supplies.js)|Medium| 2116|[Check if a Parentheses String Can Be Valid](./solutions/2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| diff --git a/solutions/2104-sum-of-subarray-ranges.js b/solutions/2104-sum-of-subarray-ranges.js new file mode 100644 index 00000000..0efaf1d7 --- /dev/null +++ b/solutions/2104-sum-of-subarray-ranges.js @@ -0,0 +1,33 @@ +/** + * 2104. Sum of Subarray Ranges + * https://leetcode.com/problems/sum-of-subarray-ranges/ + * Difficulty: Medium + * + * You are given an integer array nums. The range of a subarray of nums is the difference between + * the largest and smallest element in the subarray. + * + * Return the sum of all subarray ranges of nums. + * + * A subarray is a contiguous non-empty sequence of elements within an array. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var subArrayRanges = function(nums) { + let result = 0; + + for (let i = 0; i < nums.length; i++) { + let min = nums[i]; + let max = nums[i]; + + for (let j = i; j < nums.length; j++) { + min = Math.min(min, nums[j]); + max = Math.max(max, nums[j]); + result += max - min; + } + } + + return result; +}; From 19e669ae90eb553a4c9548c877f146848fc35ab8 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 12 May 2025 08:19:10 -0500 Subject: [PATCH 244/495] Add solution #2105 --- README.md | 3 +- solutions/2105-watering-plants-ii.js | 61 ++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 solutions/2105-watering-plants-ii.js diff --git a/README.md b/README.md index 00486aa9..88f126ac 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,748 LeetCode solutions in JavaScript +# 1,749 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1612,6 +1612,7 @@ 2101|[Detonate the Maximum Bombs](./solutions/2101-detonate-the-maximum-bombs.js)|Medium| 2103|[Rings and Rods](./solutions/2103-rings-and-rods.js)|Easy| 2104|[Sum of Subarray Ranges](./solutions/2104-sum-of-subarray-ranges.js)|Medium| +2105|[Watering Plants II](./solutions/2105-watering-plants-ii.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2115|[Find All Possible Recipes from Given Supplies](./solutions/2115-find-all-possible-recipes-from-given-supplies.js)|Medium| 2116|[Check if a Parentheses String Can Be Valid](./solutions/2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| diff --git a/solutions/2105-watering-plants-ii.js b/solutions/2105-watering-plants-ii.js new file mode 100644 index 00000000..dcdaf994 --- /dev/null +++ b/solutions/2105-watering-plants-ii.js @@ -0,0 +1,61 @@ +/** + * 2105. Watering Plants II + * https://leetcode.com/problems/watering-plants-ii/ + * Difficulty: Medium + * + * Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are + * labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. + * + * Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially + * full. They water the plants in the following way: + * - Alice waters the plants in order from left to right, starting from the 0th plant. Bob waters + * the plants in order from right to left, starting from the (n - 1)th plant. They begin watering + * the plants simultaneously. + * - It takes the same amount of time to water each plant regardless of how much water it needs. + * - Alice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, + * they first refill their can (instantaneously) then water the plant. + * - In case both Alice and Bob reach the same plant, the one with more water currently in his/her + * watering can should water this plant. If they have the same amount of water, then Alice should + * water this plant. + * + * Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the + * ith plant needs, and two integers capacityA and capacityB representing the capacities of Alice's + * and Bob's watering cans respectively, return the number of times they have to refill to water all + * the plants. + */ + +/** + * @param {number[]} plants + * @param {number} capacityA + * @param {number} capacityB + * @return {number} + */ +var minimumRefill = function(plants, capacityA, capacityB) { + let result = 0; + let left = 0; + let right = plants.length - 1; + let waterA = capacityA; + let waterB = capacityB; + + while (left <= right) { + if (left === right) { + if (waterA >= waterB && waterA < plants[left]) result++; + if (waterB > waterA && waterB < plants[right]) result++; + break; + } + + if (waterA < plants[left]) { + waterA = capacityA; + result++; + } + waterA -= plants[left++]; + + if (waterB < plants[right]) { + waterB = capacityB; + result++; + } + waterB -= plants[right--]; + } + + return result; +}; From 44a71e2bec2b93b1a975a6400fa7577fd91b7698 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 12 May 2025 08:20:35 -0500 Subject: [PATCH 245/495] Add solution #2106 --- README.md | 3 +- ...-fruits-harvested-after-at-most-k-steps.js | 52 +++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 solutions/2106-maximum-fruits-harvested-after-at-most-k-steps.js diff --git a/README.md b/README.md index 88f126ac..229c57ee 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,749 LeetCode solutions in JavaScript +# 1,750 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1613,6 +1613,7 @@ 2103|[Rings and Rods](./solutions/2103-rings-and-rods.js)|Easy| 2104|[Sum of Subarray Ranges](./solutions/2104-sum-of-subarray-ranges.js)|Medium| 2105|[Watering Plants II](./solutions/2105-watering-plants-ii.js)|Medium| +2106|[Maximum Fruits Harvested After at Most K Steps](./solutions/2106-maximum-fruits-harvested-after-at-most-k-steps.js)|Hard| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2115|[Find All Possible Recipes from Given Supplies](./solutions/2115-find-all-possible-recipes-from-given-supplies.js)|Medium| 2116|[Check if a Parentheses String Can Be Valid](./solutions/2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| diff --git a/solutions/2106-maximum-fruits-harvested-after-at-most-k-steps.js b/solutions/2106-maximum-fruits-harvested-after-at-most-k-steps.js new file mode 100644 index 00000000..bd81e17e --- /dev/null +++ b/solutions/2106-maximum-fruits-harvested-after-at-most-k-steps.js @@ -0,0 +1,52 @@ +/** + * 2106. Maximum Fruits Harvested After at Most K Steps + * https://leetcode.com/problems/maximum-fruits-harvested-after-at-most-k-steps/ + * Difficulty: Hard + * + * Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array + * fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. + * fruits is already sorted by positioni in ascending order, and each positioni is unique. + * + * You are also given an integer startPos and an integer k. Initially, you are at the position + * startPos. From any position, you can either walk to the left or right. It takes one step to + * move one unit on the x-axis, and you can walk at most k steps in total. For every position + * you reach, you harvest all the fruits at that position, and the fruits will disappear from + * that position. + * + * Return the maximum total number of fruits you can harvest. + */ + +/** + * @param {number[][]} fruits + * @param {number} startPos + * @param {number} k + * @return {number} + */ +var maxTotalFruits = function(fruits, startPos, k) { + let result = 0; + let left = 0; + let currentSum = 0; + + for (let right = 0; right < fruits.length; right++) { + currentSum += fruits[right][1]; + + while (left <= right) { + const minPos = fruits[left][0]; + const maxPos = fruits[right][0]; + const steps = Math.min( + Math.abs(startPos - minPos) + (maxPos - minPos), + Math.abs(startPos - maxPos) + (maxPos - minPos) + ); + + if (steps <= k) break; + currentSum -= fruits[left][1]; + left++; + } + + if (left <= right) { + result = Math.max(result, currentSum); + } + } + + return result; +}; From 81be90b55e61f11c3c932e2becb322ff0767a035 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 12 May 2025 19:11:01 -0500 Subject: [PATCH 246/495] Add solution #3335 --- README.md | 3 +- ...cters-in-string-after-transformations-i.js | 47 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 solutions/3335-total-characters-in-string-after-transformations-i.js diff --git a/README.md b/README.md index 229c57ee..019ad017 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,750 LeetCode solutions in JavaScript +# 1,751 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1741,6 +1741,7 @@ 3223|[Minimum Length of String After Operations](./solutions/3223-minimum-length-of-string-after-operations.js)|Medium| 3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard| 3306|[Count of Substrings Containing Every Vowel and K Consonants II](./solutions/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js)|Medium| +3335|[Total Characters in String After Transformations I](./solutions/3335-total-characters-in-string-after-transformations-i.js)|Medium| 3341|[Find Minimum Time to Reach Last Room I](./solutions/3341-find-minimum-time-to-reach-last-room-i.js)|Medium| 3342|[Find Minimum Time to Reach Last Room II](./solutions/3342-find-minimum-time-to-reach-last-room-ii.js)|Medium| 3343|[Count Number of Balanced Permutations](./solutions/3343-count-number-of-balanced-permutations.js)|Hard| diff --git a/solutions/3335-total-characters-in-string-after-transformations-i.js b/solutions/3335-total-characters-in-string-after-transformations-i.js new file mode 100644 index 00000000..e62e76ea --- /dev/null +++ b/solutions/3335-total-characters-in-string-after-transformations-i.js @@ -0,0 +1,47 @@ +/** + * 3335. Total Characters in String After Transformations I + * https://leetcode.com/problems/total-characters-in-string-after-transformations-i/ + * Difficulty: Medium + * + * You are given a string s and an integer t, representing the number of transformations to + * perform. In one transformation, every character in s is replaced according to the following + * rules: + * - If the character is 'z', replace it with the string "ab". + * - Otherwise, replace it with the next character in the alphabet. For example, 'a' is replaced + * with 'b', 'b' is replaced with 'c', and so on. + * + * Return the length of the resulting string after exactly t transformations. + * + * Since the answer may be very large, return it modulo 109 + 7. + */ + +/** + * @param {string} s + * @param {number} t + * @return {number} + */ +var lengthAfterTransformations = function(s, t) { + const MOD = 1e9 + 7; + const freq = new Array(26).fill(0); + + for (const char of s) { + freq[char.charCodeAt(0) - 97]++; + } + + for (let i = 0; i < t; i++) { + const newFreq = new Array(26).fill(0); + for (let j = 0; j < 25; j++) { + newFreq[j + 1] = freq[j]; + } + newFreq[0] = (newFreq[0] + freq[25]) % MOD; + newFreq[1] = (newFreq[1] + freq[25]) % MOD; + freq.splice(0, 26, ...newFreq); + } + + let result = 0; + for (const count of freq) { + result = (result + count) % MOD; + } + + return result; +}; From 5b2bf975ab2b91679942fc129a50cd00bf28f8fb Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 12 May 2025 19:14:50 -0500 Subject: [PATCH 247/495] Add solution #2108 --- README.md | 3 ++- ...d-first-palindromic-string-in-the-array.js | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 solutions/2108-find-first-palindromic-string-in-the-array.js diff --git a/README.md b/README.md index 019ad017..edb79c5e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,751 LeetCode solutions in JavaScript +# 1,752 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1614,6 +1614,7 @@ 2104|[Sum of Subarray Ranges](./solutions/2104-sum-of-subarray-ranges.js)|Medium| 2105|[Watering Plants II](./solutions/2105-watering-plants-ii.js)|Medium| 2106|[Maximum Fruits Harvested After at Most K Steps](./solutions/2106-maximum-fruits-harvested-after-at-most-k-steps.js)|Hard| +2108|[Find First Palindromic String in the Array](./solutions/2108-find-first-palindromic-string-in-the-array.js)|Easy| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2115|[Find All Possible Recipes from Given Supplies](./solutions/2115-find-all-possible-recipes-from-given-supplies.js)|Medium| 2116|[Check if a Parentheses String Can Be Valid](./solutions/2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| diff --git a/solutions/2108-find-first-palindromic-string-in-the-array.js b/solutions/2108-find-first-palindromic-string-in-the-array.js new file mode 100644 index 00000000..a72a02b0 --- /dev/null +++ b/solutions/2108-find-first-palindromic-string-in-the-array.js @@ -0,0 +1,23 @@ +/** + * 2108. Find First Palindromic String in the Array + * https://leetcode.com/problems/find-first-palindromic-string-in-the-array/ + * Difficulty: Easy + * + * Given an array of strings words, return the first palindromic string in the array. If there is + * no such string, return an empty string "". + * + * A string is palindromic if it reads the same forward and backward. + */ + +/** + * @param {string[]} words + * @return {string} + */ +var firstPalindrome = function(words) { + for (const word of words) { + if (word === word.split('').reverse().join('')) { + return word; + } + } + return ''; +}; From d167a4b7cd2d9bc11fec36478ff40c388a7a2107 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 12 May 2025 19:15:46 -0500 Subject: [PATCH 248/495] Add solution #2109 --- README.md | 3 +- solutions/2109-adding-spaces-to-a-string.js | 33 +++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 solutions/2109-adding-spaces-to-a-string.js diff --git a/README.md b/README.md index edb79c5e..87fe45d8 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,752 LeetCode solutions in JavaScript +# 1,753 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1615,6 +1615,7 @@ 2105|[Watering Plants II](./solutions/2105-watering-plants-ii.js)|Medium| 2106|[Maximum Fruits Harvested After at Most K Steps](./solutions/2106-maximum-fruits-harvested-after-at-most-k-steps.js)|Hard| 2108|[Find First Palindromic String in the Array](./solutions/2108-find-first-palindromic-string-in-the-array.js)|Easy| +2109|[Adding Spaces to a String](./solutions/2109-adding-spaces-to-a-string.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2115|[Find All Possible Recipes from Given Supplies](./solutions/2115-find-all-possible-recipes-from-given-supplies.js)|Medium| 2116|[Check if a Parentheses String Can Be Valid](./solutions/2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| diff --git a/solutions/2109-adding-spaces-to-a-string.js b/solutions/2109-adding-spaces-to-a-string.js new file mode 100644 index 00000000..7f4a85ba --- /dev/null +++ b/solutions/2109-adding-spaces-to-a-string.js @@ -0,0 +1,33 @@ +/** + * 2109. Adding Spaces to a String + * https://leetcode.com/problems/adding-spaces-to-a-string/ + * Difficulty: Medium + * + * You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the + * indices in the original string where spaces will be added. Each space should be inserted + * before the character at the given index. + * - For example, given s = "EnjoyYourCoffee" and spaces = [5, 9], we place spaces before 'Y' + * and 'C', which are at indices 5 and 9 respectively. Thus, we obtain "Enjoy Your Coffee". + * + * Return the modified string after the spaces have been added. + */ + +/** + * @param {string} s + * @param {number[]} spaces + * @return {string} + */ +var addSpaces = function(s, spaces) { + let result = ''; + let spaceIndex = 0; + + for (let i = 0; i < s.length; i++) { + if (spaceIndex < spaces.length && i === spaces[spaceIndex]) { + result += ' '; + spaceIndex++; + } + result += s[i]; + } + + return result; +}; From bede0a05617f8d14bf55d812a7fe9f975db32406 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 12 May 2025 19:16:59 -0500 Subject: [PATCH 249/495] Add solution #2110 --- README.md | 3 +- ...er-of-smooth-descent-periods-of-a-stock.js | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 solutions/2110-number-of-smooth-descent-periods-of-a-stock.js diff --git a/README.md b/README.md index 87fe45d8..17d6608c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,753 LeetCode solutions in JavaScript +# 1,754 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1616,6 +1616,7 @@ 2106|[Maximum Fruits Harvested After at Most K Steps](./solutions/2106-maximum-fruits-harvested-after-at-most-k-steps.js)|Hard| 2108|[Find First Palindromic String in the Array](./solutions/2108-find-first-palindromic-string-in-the-array.js)|Easy| 2109|[Adding Spaces to a String](./solutions/2109-adding-spaces-to-a-string.js)|Medium| +2110|[Number of Smooth Descent Periods of a Stock](./solutions/2110-number-of-smooth-descent-periods-of-a-stock.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2115|[Find All Possible Recipes from Given Supplies](./solutions/2115-find-all-possible-recipes-from-given-supplies.js)|Medium| 2116|[Check if a Parentheses String Can Be Valid](./solutions/2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| diff --git a/solutions/2110-number-of-smooth-descent-periods-of-a-stock.js b/solutions/2110-number-of-smooth-descent-periods-of-a-stock.js new file mode 100644 index 00000000..09a08e95 --- /dev/null +++ b/solutions/2110-number-of-smooth-descent-periods-of-a-stock.js @@ -0,0 +1,34 @@ +/** + * 2110. Number of Smooth Descent Periods of a Stock + * https://leetcode.com/problems/number-of-smooth-descent-periods-of-a-stock/ + * Difficulty: Medium + * + * You are given an integer array prices representing the daily price history of a stock, + * where prices[i] is the stock price on the ith day. + * + * A smooth descent period of a stock consists of one or more contiguous days such that the + * price on each day is lower than the price on the preceding day by exactly 1. The first + * day of the period is exempted from this rule. + * + * Return the number of smooth descent periods. + */ + +/** + * @param {number[]} prices + * @return {number} + */ +var getDescentPeriods = function(prices) { + let result = 1; + let currentLength = 1; + + for (let i = 1; i < prices.length; i++) { + if (prices[i] === prices[i - 1] - 1) { + currentLength++; + } else { + currentLength = 1; + } + result += currentLength; + } + + return result; +}; From 458edebd762b05b34d5e3c8f521a2009e6d61d54 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 12 May 2025 19:18:47 -0500 Subject: [PATCH 250/495] Add solution #2111 --- README.md | 3 +- ...erations-to-make-the-array-k-increasing.js | 58 +++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 solutions/2111-minimum-operations-to-make-the-array-k-increasing.js diff --git a/README.md b/README.md index 17d6608c..f480feef 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,754 LeetCode solutions in JavaScript +# 1,755 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1617,6 +1617,7 @@ 2108|[Find First Palindromic String in the Array](./solutions/2108-find-first-palindromic-string-in-the-array.js)|Easy| 2109|[Adding Spaces to a String](./solutions/2109-adding-spaces-to-a-string.js)|Medium| 2110|[Number of Smooth Descent Periods of a Stock](./solutions/2110-number-of-smooth-descent-periods-of-a-stock.js)|Medium| +2111|[Minimum Operations to Make the Array K-Increasing](./solutions/2111-minimum-operations-to-make-the-array-k-increasing.js)|Hard| 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2115|[Find All Possible Recipes from Given Supplies](./solutions/2115-find-all-possible-recipes-from-given-supplies.js)|Medium| 2116|[Check if a Parentheses String Can Be Valid](./solutions/2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| diff --git a/solutions/2111-minimum-operations-to-make-the-array-k-increasing.js b/solutions/2111-minimum-operations-to-make-the-array-k-increasing.js new file mode 100644 index 00000000..8f861b84 --- /dev/null +++ b/solutions/2111-minimum-operations-to-make-the-array-k-increasing.js @@ -0,0 +1,58 @@ +/** + * 2111. Minimum Operations to Make the Array K-Increasing + * https://leetcode.com/problems/minimum-operations-to-make-the-array-k-increasing/ + * Difficulty: Hard + * + * You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k. + * + * The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where + * k <= i <= n-1. + * + * - For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because: + * - arr[0] <= arr[2] (4 <= 5) + * - arr[1] <= arr[3] (1 <= 2) + * - arr[2] <= arr[4] (5 <= 6) + * - arr[3] <= arr[5] (2 <= 2) + * - However, the same arr is not K-increasing for k = 1 (because arr[0] > arr[1]) or k = 3 (because + * arr[0] > arr[3]). + * + * In one operation, you can choose an index i and change arr[i] into any positive integer. + * + * Return the minimum number of operations required to make the array K-increasing for the given k. + */ + +/** + * @param {number[]} arr + * @param {number} k + * @return {number} + */ +var kIncreasing = function(arr, k) { + let result = 0; + for (let i = 0; i < k; i++) { + const subsequence = []; + for (let j = i; j < arr.length; j += k) { + subsequence.push(arr[j]); + } + result += longestNonDecreasingSubsequence(subsequence); + } + + return result; + + function longestNonDecreasingSubsequence(nums) { + const tails = []; + for (const num of nums) { + let left = 0; + let right = tails.length; + while (left < right) { + const mid = Math.floor((left + right) / 2); + if (tails[mid] <= num) { + left = mid + 1; + } else { + right = mid; + } + } + tails[left] = num; + } + return nums.length - tails.length; + } +}; From 25d7607fb2b8f2cb93d6aaab7d340a8c5d8a6bb6 Mon Sep 17 00:00:00 2001 From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com> Date: Mon, 12 May 2025 19:56:06 -0500 Subject: [PATCH 251/495] Add solution #2117 --- README.md | 3 +- ...117-abbreviating-the-product-of-a-range.js | 91 +++++++++++++++++++ 2 files changed, 93 insertions(+), 1 deletion(-) create mode 100644 solutions/2117-abbreviating-the-product-of-a-range.js diff --git a/README.md b/README.md index f480feef..8789cfd9 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 1,755 LeetCode solutions in JavaScript +# 1,756 LeetCode solutions in JavaScript [https://leetcodejavascript.com](https://leetcodejavascript.com) @@ -1621,6 +1621,7 @@ 2114|[Maximum Number of Words Found in Sentences](./solutions/2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2115|[Find All Possible Recipes from Given Supplies](./solutions/2115-find-all-possible-recipes-from-given-supplies.js)|Medium| 2116|[Check if a Parentheses String Can Be Valid](./solutions/2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| +2117|[Abbreviating the Product of a Range](./solutions/2117-abbreviating-the-product-of-a-range.js)|Hard| 2127|[Maximum Employees to Be Invited to a Meeting](./solutions/2127-maximum-employees-to-be-invited-to-a-meeting.js)|Hard| 2129|[Capitalize the Title](./solutions/2129-capitalize-the-title.js)|Easy| 2130|[Maximum Twin Sum of a Linked List](./solutions/2130-maximum-twin-sum-of-a-linked-list.js)|Medium| diff --git a/solutions/2117-abbreviating-the-product-of-a-range.js b/solutions/2117-abbreviating-the-product-of-a-range.js new file mode 100644 index 00000000..4334b25b --- /dev/null +++ b/solutions/2117-abbreviating-the-product-of-a-range.js @@ -0,0 +1,91 @@ +/** + * 2117. Abbreviating the Product of a Range + * https://leetcode.com/problems/abbreviating-the-product-of-a-range/ + * Difficulty: Hard + * + * You are given two positive integers left and right with left <= right. Calculate the product of + * all integers in the inclusive range [left, right]. + * + * Since the product may be very large, you will abbreviate it following these steps: + * 1. Count all trailing zeros in the product and remove them. Let us denote this count as C. + * - For example, there are 3 trailing zeros in 1000, and there are 0 trailing zeros in 546. + * 2. Denote the remaining number of digits in the product as d. If d > 10, then express the product + * as
... where 
 denotes the first 5 digits of the product, and  denotes the
+ *    last 5 digits of the product after removing all trailing zeros. If d <= 10, we keep it
+ *    unchanged.
+ *    - For example, we express 1234567654321 as 12345...54321, but 1234567 is represented as
+ *      1234567.
+ * 3. Finally, represent the product as a string "
...eC".
+ *    - For example, 12345678987600000 will be represented as "12345...89876e5".
+ *
+ * Return a string denoting the abbreviated product of all integers in the inclusive range [left,
+ * right].
+ */
+
+/**
+ * @param {number} left
+ * @param {number} right
+ * @return {string}
+ */
+var abbreviateProduct = function(left, right) {
+  let zeros = 0;
+  let count2 = 0;
+  let count5 = 0;
+
+  for (let i = left; i <= right; i++) {
+    let n = i;
+    while (n % 2 === 0) {
+      count2++;
+      n = Math.floor(n / 2);
+    }
+    n = i;
+    while (n % 5 === 0) {
+      count5++;
+      n = Math.floor(n / 5);
+    }
+  }
+  zeros = Math.min(count2, count5);
+
+  let digits = 0;
+  for (let i = left; i <= right; i++) {
+    digits += Math.log10(i);
+  }
+  digits = Math.floor(digits) + 1;
+
+  if (digits - zeros <= 10) {
+    let product = 1n;
+    for (let i = left; i <= right; i++) {
+      product *= BigInt(i);
+    }
+    for (let i = 0; i < zeros; i++) {
+      product /= 10n;
+    }
+    return product.toString() + 'e' + zeros;
+  }
+
+  let prefix = 1;
+  for (let i = left; i <= right; i++) {
+    prefix *= i;
+    while (prefix >= 1e10) {
+      prefix /= 10;
+    }
+  }
+  prefix = prefix.toString().slice(0, 5);
+
+  let suffix = 1n;
+  for (let i = right; i >= left; i--) {
+    suffix = (suffix * BigInt(i));
+    while (suffix % 10n === 0n) {
+      suffix /= 10n;
+    }
+    suffix = suffix % (10n ** 15n);
+  }
+
+  suffix = suffix.toString();
+  while (suffix.length < 5) {
+    suffix = '0' + suffix;
+  }
+  suffix = suffix.slice(-5);
+
+  return prefix + '...' + suffix + 'e' + zeros;
+};

From 151962b1a8e1cbaf04792ae24c2871e01d53fd3e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 12 May 2025 19:57:17 -0500
Subject: [PATCH 252/495] Add solution #2119

---
 README.md                                     |  3 ++-
 .../2119-a-number-after-a-double-reversal.js  | 20 +++++++++++++++++++
 2 files changed, 22 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2119-a-number-after-a-double-reversal.js

diff --git a/README.md b/README.md
index 8789cfd9..99ce13cb 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,756 LeetCode solutions in JavaScript
+# 1,757 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1622,6 +1622,7 @@
 2115|[Find All Possible Recipes from Given Supplies](./solutions/2115-find-all-possible-recipes-from-given-supplies.js)|Medium|
 2116|[Check if a Parentheses String Can Be Valid](./solutions/2116-check-if-a-parentheses-string-can-be-valid.js)|Medium|
 2117|[Abbreviating the Product of a Range](./solutions/2117-abbreviating-the-product-of-a-range.js)|Hard|
+2119|[A Number After a Double Reversal](./solutions/2119-a-number-after-a-double-reversal.js)|Easy|
 2127|[Maximum Employees to Be Invited to a Meeting](./solutions/2127-maximum-employees-to-be-invited-to-a-meeting.js)|Hard|
 2129|[Capitalize the Title](./solutions/2129-capitalize-the-title.js)|Easy|
 2130|[Maximum Twin Sum of a Linked List](./solutions/2130-maximum-twin-sum-of-a-linked-list.js)|Medium|
diff --git a/solutions/2119-a-number-after-a-double-reversal.js b/solutions/2119-a-number-after-a-double-reversal.js
new file mode 100644
index 00000000..efc1d321
--- /dev/null
+++ b/solutions/2119-a-number-after-a-double-reversal.js
@@ -0,0 +1,20 @@
+/**
+ * 2119. A Number After a Double Reversal
+ * https://leetcode.com/problems/a-number-after-a-double-reversal/
+ * Difficulty: Easy
+ *
+ * Reversing an integer means to reverse all its digits.
+ * - For example, reversing 2021 gives 1202. Reversing 12300 gives 321 as the leading zeros
+ *   are not retained.
+ *
+ * Given an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2.
+ * Return true if reversed2 equals num. Otherwise return false.
+ */
+
+/**
+ * @param {number} num
+ * @return {boolean}
+ */
+var isSameAfterReversals = function(num) {
+  return num === 0 || num % 10 !== 0;
+};

From 8b2704be3d061138c4e543ae1eac0b1b97cd83ee Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 12 May 2025 19:58:36 -0500
Subject: [PATCH 253/495] Add solution #2120

---
 README.md                                     |  3 +-
 ...l-suffix-instructions-staying-in-a-grid.js | 51 +++++++++++++++++++
 2 files changed, 53 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2120-execution-of-all-suffix-instructions-staying-in-a-grid.js

diff --git a/README.md b/README.md
index 99ce13cb..179b55d7 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,757 LeetCode solutions in JavaScript
+# 1,758 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1623,6 +1623,7 @@
 2116|[Check if a Parentheses String Can Be Valid](./solutions/2116-check-if-a-parentheses-string-can-be-valid.js)|Medium|
 2117|[Abbreviating the Product of a Range](./solutions/2117-abbreviating-the-product-of-a-range.js)|Hard|
 2119|[A Number After a Double Reversal](./solutions/2119-a-number-after-a-double-reversal.js)|Easy|
+2120|[Execution of All Suffix Instructions Staying in a Grid](./solutions/2120-execution-of-all-suffix-instructions-staying-in-a-grid.js)|Medium|
 2127|[Maximum Employees to Be Invited to a Meeting](./solutions/2127-maximum-employees-to-be-invited-to-a-meeting.js)|Hard|
 2129|[Capitalize the Title](./solutions/2129-capitalize-the-title.js)|Easy|
 2130|[Maximum Twin Sum of a Linked List](./solutions/2130-maximum-twin-sum-of-a-linked-list.js)|Medium|
diff --git a/solutions/2120-execution-of-all-suffix-instructions-staying-in-a-grid.js b/solutions/2120-execution-of-all-suffix-instructions-staying-in-a-grid.js
new file mode 100644
index 00000000..940ddc72
--- /dev/null
+++ b/solutions/2120-execution-of-all-suffix-instructions-staying-in-a-grid.js
@@ -0,0 +1,51 @@
+/**
+ * 2120. Execution of All Suffix Instructions Staying in a Grid
+ * https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/
+ * Difficulty: Medium
+ *
+ * There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at
+ * (n - 1, n - 1). You are given the integer n and an integer array startPos where
+ * startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol).
+ *
+ * You are also given a 0-indexed string s of length m where s[i] is the ith instruction for the
+ * robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down).
+ *
+ * The robot can begin executing from any ith instruction in s. It executes the instructions one
+ * by one towards the end of s but it stops if either of these conditions is met:
+ * - The next instruction will move the robot off the grid.
+ * - There are no more instructions left to execute.
+ *
+ * Return an array answer of length m where answer[i] is the number of instructions the robot can
+ * execute if the robot begins executing from the ith instruction in s.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[]} startPos
+ * @param {string} s
+ * @return {number[]}
+ */
+var executeInstructions = function(n, startPos, s) {
+  const m = s.length;
+  const result = new Array(m).fill(0);
+
+  for (let i = 0; i < m; i++) {
+    let row = startPos[0];
+    let col = startPos[1];
+    let steps = 0;
+
+    for (let j = i; j < m; j++) {
+      if (s[j] === 'L') col--;
+      else if (s[j] === 'R') col++;
+      else if (s[j] === 'U') row--;
+      else row++;
+
+      if (row < 0 || row >= n || col < 0 || col >= n) break;
+      steps++;
+    }
+
+    result[i] = steps;
+  }
+
+  return result;
+};

From 2570aaee4c1f2777519d70fa05a9f42c2d36ebf2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 12 May 2025 19:59:49 -0500
Subject: [PATCH 254/495] Add solution #2121

---
 README.md                                     |  3 +-
 ...21-intervals-between-identical-elements.js | 48 +++++++++++++++++++
 2 files changed, 50 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2121-intervals-between-identical-elements.js

diff --git a/README.md b/README.md
index 179b55d7..8b14d40f 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,758 LeetCode solutions in JavaScript
+# 1,759 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1624,6 +1624,7 @@
 2117|[Abbreviating the Product of a Range](./solutions/2117-abbreviating-the-product-of-a-range.js)|Hard|
 2119|[A Number After a Double Reversal](./solutions/2119-a-number-after-a-double-reversal.js)|Easy|
 2120|[Execution of All Suffix Instructions Staying in a Grid](./solutions/2120-execution-of-all-suffix-instructions-staying-in-a-grid.js)|Medium|
+2121|[Intervals Between Identical Elements](./solutions/2121-intervals-between-identical-elements.js)|Medium|
 2127|[Maximum Employees to Be Invited to a Meeting](./solutions/2127-maximum-employees-to-be-invited-to-a-meeting.js)|Hard|
 2129|[Capitalize the Title](./solutions/2129-capitalize-the-title.js)|Easy|
 2130|[Maximum Twin Sum of a Linked List](./solutions/2130-maximum-twin-sum-of-a-linked-list.js)|Medium|
diff --git a/solutions/2121-intervals-between-identical-elements.js b/solutions/2121-intervals-between-identical-elements.js
new file mode 100644
index 00000000..3686726b
--- /dev/null
+++ b/solutions/2121-intervals-between-identical-elements.js
@@ -0,0 +1,48 @@
+/**
+ * 2121. Intervals Between Identical Elements
+ * https://leetcode.com/problems/intervals-between-identical-elements/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array of n integers arr.
+ *
+ * The interval between two elements in arr is defined as the absolute difference between their
+ * indices. More formally, the interval between arr[i] and arr[j] is |i - j|.
+ *
+ * Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i]
+ * and each element in arr with the same value as arr[i].
+ *
+ * Note: |x| is the absolute value of x.
+ */
+
+/**
+ * @param {number[]} arr
+ * @return {number[]}
+ */
+var getDistances = function(arr) {
+  const valueIndices = new Map();
+  const result = new Array(arr.length).fill(0);
+
+  for (let i = 0; i < arr.length; i++) {
+    if (!valueIndices.has(arr[i])) {
+      valueIndices.set(arr[i], []);
+    }
+    valueIndices.get(arr[i]).push(i);
+  }
+
+  for (const indices of valueIndices.values()) {
+    let prefixSum = 0;
+    for (let i = 1; i < indices.length; i++) {
+      prefixSum += indices[i] - indices[0];
+    }
+
+    result[indices[0]] = prefixSum;
+
+    for (let i = 1; i < indices.length; i++) {
+      const diff = indices[i] - indices[i - 1];
+      prefixSum += diff * (i - (indices.length - i));
+      result[indices[i]] = prefixSum;
+    }
+  }
+
+  return result;
+};

From 1bf168e0c08e3fee91e54730bfa2d26287d30445 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 12 May 2025 20:00:54 -0500
Subject: [PATCH 255/495] Add solution #2615

---
 README.md                          |  3 +-
 solutions/2615-sum-of-distances.js | 44 ++++++++++++++++++++++++++++++
 2 files changed, 46 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2615-sum-of-distances.js

diff --git a/README.md b/README.md
index 8b14d40f..81579f95 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,759 LeetCode solutions in JavaScript
+# 1,760 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1680,6 +1680,7 @@
 2570|[Merge Two 2D Arrays by Summing Values](./solutions/2570-merge-two-2d-arrays-by-summing-values.js)|Easy|
 2579|[Count Total Number of Colored Cells](./solutions/2579-count-total-number-of-colored-cells.js)|Medium|
 2594|[Minimum Time to Repair Cars](./solutions/2594-minimum-time-to-repair-cars.js)|Medium|
+2615|[Sum of Distances](./solutions/2615-sum-of-distances.js)|Medium|
 2618|[Check if Object Instance of Class](./solutions/2618-check-if-object-instance-of-class.js)|Medium|
 2619|[Array Prototype Last](./solutions/2619-array-prototype-last.js)|Easy|
 2620|[Counter](./solutions/2620-counter.js)|Easy|
diff --git a/solutions/2615-sum-of-distances.js b/solutions/2615-sum-of-distances.js
new file mode 100644
index 00000000..470c10cf
--- /dev/null
+++ b/solutions/2615-sum-of-distances.js
@@ -0,0 +1,44 @@
+/**
+ * 2615. Sum of Distances
+ * https://leetcode.com/problems/sum-of-distances/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums. There exists an array arr of length nums.length,
+ * where arr[i] is the sum of |i - j| over all j such that nums[j] == nums[i] and j != i. If there
+ * is no such j, set arr[i] to be 0.
+ *
+ * Return the array arr.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var distance = function(nums) {
+  const valueIndices = new Map();
+  const result = new Array(nums.length).fill(0);
+
+  for (let i = 0; i < nums.length; i++) {
+    if (!valueIndices.has(nums[i])) {
+      valueIndices.set(nums[i], []);
+    }
+    valueIndices.get(nums[i]).push(i);
+  }
+
+  for (const indices of valueIndices.values()) {
+    let prefixSum = 0;
+    for (let i = 1; i < indices.length; i++) {
+      prefixSum += indices[i] - indices[0];
+    }
+
+    result[indices[0]] = prefixSum;
+
+    for (let i = 1; i < indices.length; i++) {
+      const diff = indices[i] - indices[i - 1];
+      prefixSum += diff * (i - (indices.length - i));
+      result[indices[i]] = prefixSum;
+    }
+  }
+
+  return result;
+};

From 3580cdc2808dd129f3972ecedc95fed51bb4a066 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 13 May 2025 00:17:36 -0500
Subject: [PATCH 256/495] Add solution #2122

---
 README.md                                    |  3 +-
 solutions/2122-recover-the-original-array.js | 55 ++++++++++++++++++++
 2 files changed, 57 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2122-recover-the-original-array.js

diff --git a/README.md b/README.md
index 81579f95..1978614e 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,760 LeetCode solutions in JavaScript
+# 1,761 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1625,6 +1625,7 @@
 2119|[A Number After a Double Reversal](./solutions/2119-a-number-after-a-double-reversal.js)|Easy|
 2120|[Execution of All Suffix Instructions Staying in a Grid](./solutions/2120-execution-of-all-suffix-instructions-staying-in-a-grid.js)|Medium|
 2121|[Intervals Between Identical Elements](./solutions/2121-intervals-between-identical-elements.js)|Medium|
+2122|[Recover the Original Array](./solutions/2122-recover-the-original-array.js)|Hard|
 2127|[Maximum Employees to Be Invited to a Meeting](./solutions/2127-maximum-employees-to-be-invited-to-a-meeting.js)|Hard|
 2129|[Capitalize the Title](./solutions/2129-capitalize-the-title.js)|Easy|
 2130|[Maximum Twin Sum of a Linked List](./solutions/2130-maximum-twin-sum-of-a-linked-list.js)|Medium|
diff --git a/solutions/2122-recover-the-original-array.js b/solutions/2122-recover-the-original-array.js
new file mode 100644
index 00000000..7b6030fb
--- /dev/null
+++ b/solutions/2122-recover-the-original-array.js
@@ -0,0 +1,55 @@
+/**
+ * 2122. Recover the Original Array
+ * https://leetcode.com/problems/recover-the-original-array/
+ * Difficulty: Hard
+ *
+ * Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary
+ * positive integer k and created two new 0-indexed integer arrays lower and higher in the
+ * following manner:
+ * 1. lower[i] = arr[i] - k, for every index i where 0 <= i < n
+ * 2. higher[i] = arr[i] + k, for every index i where 0 <= i < n
+ *
+ * Unfortunately, Alice lost all three arrays. However, she remembers the integers that were
+ * present in the arrays lower and higher, but not the array each integer belonged to. Help
+ * Alice and recover the original array.
+ *
+ * Given an array nums consisting of 2n integers, where exactly n of the integers were present
+ * in lower and the remaining in higher, return the original array arr. In case the answer is
+ * not unique, return any valid array.
+ *
+ * Note: The test cases are generated such that there exists at least one valid array arr.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var recoverArray = function(nums) {
+  const n = nums.length / 2;
+  nums.sort((a, b) => a - b);
+
+  for (let i = 1; i < 2 * n; i++) {
+    const k = nums[i] - nums[0];
+    if (k <= 0 || k % 2 !== 0) continue;
+
+    const original = [];
+    const used = new Array(2 * n).fill(false);
+    let count = 0;
+
+    for (let left = 0, right = i; right < 2 * n && count < n; right++) {
+      while (left < right && used[left]) left++;
+      if (left >= right) continue;
+
+      if (nums[right] - nums[left] === k) {
+        original.push(nums[left] + k / 2);
+        used[left] = used[right] = true;
+        count++;
+        left++;
+      }
+    }
+
+    if (count === n) return original;
+  }
+
+  return [];
+};

From b43b927771047729bd9e241628de85b69cdfed48 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 13 May 2025 00:19:10 -0500
Subject: [PATCH 257/495] Add solution #2124

---
 README.md                                     |  3 ++-
 ...4-check-if-all-as-appears-before-all-bs.js | 23 +++++++++++++++++++
 2 files changed, 25 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2124-check-if-all-as-appears-before-all-bs.js

diff --git a/README.md b/README.md
index 1978614e..71ae28ae 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,761 LeetCode solutions in JavaScript
+# 1,762 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1626,6 +1626,7 @@
 2120|[Execution of All Suffix Instructions Staying in a Grid](./solutions/2120-execution-of-all-suffix-instructions-staying-in-a-grid.js)|Medium|
 2121|[Intervals Between Identical Elements](./solutions/2121-intervals-between-identical-elements.js)|Medium|
 2122|[Recover the Original Array](./solutions/2122-recover-the-original-array.js)|Hard|
+2124|[Check if All A's Appears Before All B's](./solutions/2124-check-if-all-as-appears-before-all-bs.js)|Easy|
 2127|[Maximum Employees to Be Invited to a Meeting](./solutions/2127-maximum-employees-to-be-invited-to-a-meeting.js)|Hard|
 2129|[Capitalize the Title](./solutions/2129-capitalize-the-title.js)|Easy|
 2130|[Maximum Twin Sum of a Linked List](./solutions/2130-maximum-twin-sum-of-a-linked-list.js)|Medium|
diff --git a/solutions/2124-check-if-all-as-appears-before-all-bs.js b/solutions/2124-check-if-all-as-appears-before-all-bs.js
new file mode 100644
index 00000000..57f06772
--- /dev/null
+++ b/solutions/2124-check-if-all-as-appears-before-all-bs.js
@@ -0,0 +1,23 @@
+/**
+ * 2124. Check if All A's Appears Before All B's
+ * https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/
+ * Difficulty: Easy
+ *
+ * Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears
+ * before every 'b' in the string. Otherwise, return false.
+ */
+
+/**
+ * @param {string} s
+ * @return {boolean}
+ */
+var checkString = function(s) {
+  let seen = false;
+
+  for (const char of s) {
+    if (char === 'b') seen = true;
+    else if (seen) return false;
+  }
+
+  return true;
+};

From 0b9fd3855c66959d5f57865c4c4faeb450f5939c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 13 May 2025 00:20:19 -0500
Subject: [PATCH 258/495] Add solution #2125

---
 README.md                                     |  3 +-
 .../2125-number-of-laser-beams-in-a-bank.js   | 40 +++++++++++++++++++
 2 files changed, 42 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2125-number-of-laser-beams-in-a-bank.js

diff --git a/README.md b/README.md
index 71ae28ae..fb686698 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,762 LeetCode solutions in JavaScript
+# 1,763 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1627,6 +1627,7 @@
 2121|[Intervals Between Identical Elements](./solutions/2121-intervals-between-identical-elements.js)|Medium|
 2122|[Recover the Original Array](./solutions/2122-recover-the-original-array.js)|Hard|
 2124|[Check if All A's Appears Before All B's](./solutions/2124-check-if-all-as-appears-before-all-bs.js)|Easy|
+2125|[Number of Laser Beams in a Bank](./solutions/2125-number-of-laser-beams-in-a-bank.js)|Medium|
 2127|[Maximum Employees to Be Invited to a Meeting](./solutions/2127-maximum-employees-to-be-invited-to-a-meeting.js)|Hard|
 2129|[Capitalize the Title](./solutions/2129-capitalize-the-title.js)|Easy|
 2130|[Maximum Twin Sum of a Linked List](./solutions/2130-maximum-twin-sum-of-a-linked-list.js)|Medium|
diff --git a/solutions/2125-number-of-laser-beams-in-a-bank.js b/solutions/2125-number-of-laser-beams-in-a-bank.js
new file mode 100644
index 00000000..58a8afb7
--- /dev/null
+++ b/solutions/2125-number-of-laser-beams-in-a-bank.js
@@ -0,0 +1,40 @@
+/**
+ * 2125. Number of Laser Beams in a Bank
+ * https://leetcode.com/problems/number-of-laser-beams-in-a-bank/
+ * Difficulty: Medium
+ *
+ * Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string
+ * array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i]
+ * represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1'
+ * means the cell has a security device.
+ *
+ * There is one laser beam between any two security devices if both conditions are met:
+ * - The two devices are located on two different rows: r1 and r2, where r1 < r2.
+ * - For each row i where r1 < i < r2, there are no security devices in the ith row.
+ *
+ * Laser beams are independent, i.e., one beam does not interfere nor join with another.
+ *
+ * Return the total number of laser beams in the bank.
+ */
+
+/**
+ * @param {string[]} bank
+ * @return {number}
+ */
+var numberOfBeams = function(bank) {
+  let result = 0;
+  let prevDevices = 0;
+
+  for (const row of bank) {
+    let currentDevices = 0;
+    for (const cell of row) {
+      if (cell === '1') currentDevices++;
+    }
+    if (currentDevices > 0) {
+      result += prevDevices * currentDevices;
+      prevDevices = currentDevices;
+    }
+  }
+
+  return result;
+};

From d9cda3358c2f90b34e9bfdaf9049855336bcf699 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 13 May 2025 00:21:28 -0500
Subject: [PATCH 259/495] Add solution #2126

---
 README.md                              |  3 ++-
 solutions/2126-destroying-asteroids.js | 31 ++++++++++++++++++++++++++
 2 files changed, 33 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2126-destroying-asteroids.js

diff --git a/README.md b/README.md
index fb686698..1b4606e9 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,763 LeetCode solutions in JavaScript
+# 1,764 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1628,6 +1628,7 @@
 2122|[Recover the Original Array](./solutions/2122-recover-the-original-array.js)|Hard|
 2124|[Check if All A's Appears Before All B's](./solutions/2124-check-if-all-as-appears-before-all-bs.js)|Easy|
 2125|[Number of Laser Beams in a Bank](./solutions/2125-number-of-laser-beams-in-a-bank.js)|Medium|
+2126|[Destroying Asteroids](./solutions/2126-destroying-asteroids.js)|Medium|
 2127|[Maximum Employees to Be Invited to a Meeting](./solutions/2127-maximum-employees-to-be-invited-to-a-meeting.js)|Hard|
 2129|[Capitalize the Title](./solutions/2129-capitalize-the-title.js)|Easy|
 2130|[Maximum Twin Sum of a Linked List](./solutions/2130-maximum-twin-sum-of-a-linked-list.js)|Medium|
diff --git a/solutions/2126-destroying-asteroids.js b/solutions/2126-destroying-asteroids.js
new file mode 100644
index 00000000..8c0ff17e
--- /dev/null
+++ b/solutions/2126-destroying-asteroids.js
@@ -0,0 +1,31 @@
+/**
+ * 2126. Destroying Asteroids
+ * https://leetcode.com/problems/destroying-asteroids/
+ * Difficulty: Medium
+ *
+ * You are given an integer mass, which represents the original mass of a planet. You are further
+ * given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid.
+ *
+ * You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass
+ * of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed
+ * and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed.
+ *
+ * Return true if all asteroids can be destroyed. Otherwise, return false.
+ */
+
+/**
+ * @param {number} mass
+ * @param {number[]} asteroids
+ * @return {boolean}
+ */
+var asteroidsDestroyed = function(mass, asteroids) {
+  asteroids.sort((a, b) => a - b);
+
+  let planetMass = BigInt(mass);
+  for (const asteroid of asteroids) {
+    if (planetMass < BigInt(asteroid)) return false;
+    planetMass += BigInt(asteroid);
+  }
+
+  return true;
+};

From ef07b06672bad4ca9d8c0eddd38b941dd07ea412 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 13 May 2025 00:22:41 -0500
Subject: [PATCH 260/495] Add solution #2131

---
 README.md                                     |  3 +-
 ...drome-by-concatenating-two-letter-words.js | 47 +++++++++++++++++++
 2 files changed, 49 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2131-longest-palindrome-by-concatenating-two-letter-words.js

diff --git a/README.md b/README.md
index 1b4606e9..6c22f9d0 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,764 LeetCode solutions in JavaScript
+# 1,765 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1632,6 +1632,7 @@
 2127|[Maximum Employees to Be Invited to a Meeting](./solutions/2127-maximum-employees-to-be-invited-to-a-meeting.js)|Hard|
 2129|[Capitalize the Title](./solutions/2129-capitalize-the-title.js)|Easy|
 2130|[Maximum Twin Sum of a Linked List](./solutions/2130-maximum-twin-sum-of-a-linked-list.js)|Medium|
+2131|[Longest Palindrome by Concatenating Two Letter Words](./solutions/2131-longest-palindrome-by-concatenating-two-letter-words.js)|Medium|
 2140|[Solving Questions With Brainpower](./solutions/2140-solving-questions-with-brainpower.js)|Medium|
 2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
diff --git a/solutions/2131-longest-palindrome-by-concatenating-two-letter-words.js b/solutions/2131-longest-palindrome-by-concatenating-two-letter-words.js
new file mode 100644
index 00000000..296b3bd0
--- /dev/null
+++ b/solutions/2131-longest-palindrome-by-concatenating-two-letter-words.js
@@ -0,0 +1,47 @@
+/**
+ * 2131. Longest Palindrome by Concatenating Two Letter Words
+ * https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/
+ * Difficulty: Medium
+ *
+ * You are given an array of strings words. Each element of words consists of two lowercase
+ * English letters.
+ *
+ * Create the longest possible palindrome by selecting some elements from words and concatenating
+ * them in any order. Each element can be selected at most once.
+ *
+ * Return the length of the longest palindrome that you can create. If it is impossible to create
+ * any palindrome, return 0.
+ *
+ * A palindrome is a string that reads the same forward and backward.
+ */
+
+/**
+ * @param {string[]} words
+ * @return {number}
+ */
+var longestPalindrome = function(words) {
+  const map = new Map();
+  let length = 0;
+  let hasCenter = false;
+
+  for (const word of words) {
+    map.set(word, (map.get(word) || 0) + 1);
+  }
+
+  for (const word of map.keys()) {
+    const reverse = word[1] + word[0];
+
+    if (word === reverse) {
+      const count = map.get(word);
+      length += Math.floor(count / 2) * 4;
+      if (count % 2 === 1) hasCenter = true;
+    } else if (map.has(reverse)) {
+      const pairs = Math.min(map.get(word), map.get(reverse));
+      length += pairs * 4;
+      map.set(word, 0);
+      map.set(reverse, 0);
+    }
+  }
+
+  return hasCenter ? length + 2 : length;
+};

From 10a4ad8b25582161e2613f59b582260f4c14d3e7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 13 May 2025 22:38:30 -0500
Subject: [PATCH 261/495] Add solution #3337

---
 README.md                                     |  3 +-
 ...ters-in-string-after-transformations-ii.js | 78 +++++++++++++++++++
 2 files changed, 80 insertions(+), 1 deletion(-)
 create mode 100644 solutions/3337-total-characters-in-string-after-transformations-ii.js

diff --git a/README.md b/README.md
index 6c22f9d0..834cbe4f 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,765 LeetCode solutions in JavaScript
+# 1,766 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1756,6 +1756,7 @@
 3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard|
 3306|[Count of Substrings Containing Every Vowel and K Consonants II](./solutions/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js)|Medium|
 3335|[Total Characters in String After Transformations I](./solutions/3335-total-characters-in-string-after-transformations-i.js)|Medium|
+3337|[Total Characters in String After Transformations II](./solutions/3337-total-characters-in-string-after-transformations-ii.js)|Hard|
 3341|[Find Minimum Time to Reach Last Room I](./solutions/3341-find-minimum-time-to-reach-last-room-i.js)|Medium|
 3342|[Find Minimum Time to Reach Last Room II](./solutions/3342-find-minimum-time-to-reach-last-room-ii.js)|Medium|
 3343|[Count Number of Balanced Permutations](./solutions/3343-count-number-of-balanced-permutations.js)|Hard|
diff --git a/solutions/3337-total-characters-in-string-after-transformations-ii.js b/solutions/3337-total-characters-in-string-after-transformations-ii.js
new file mode 100644
index 00000000..91d4d6aa
--- /dev/null
+++ b/solutions/3337-total-characters-in-string-after-transformations-ii.js
@@ -0,0 +1,78 @@
+/**
+ * 3337. Total Characters in String After Transformations II
+ * https://leetcode.com/problems/total-characters-in-string-after-transformations-ii/
+ * Difficulty: Hard
+ *
+ * You are given a string s consisting of lowercase English letters, an integer t representing
+ * the number of transformations to perform, and an array nums of size 26. In one transformation,
+ * every character in s is replaced according to the following rules:
+ * - Replace s[i] with the next nums[s[i] - 'a'] consecutive characters in the alphabet. For
+ *   example, if s[i] = 'a' and nums[0] = 3, the character 'a' transforms into the next 3
+ *   consecutive characters ahead of it, which results in "bcd".
+ * - The transformation wraps around the alphabet if it exceeds 'z'. For example, if s[i] = 'y'
+ *   and nums[24] = 3, the character 'y' transforms into the next 3 consecutive characters ahead
+ *   of it, which results in "zab".
+ *
+ * Return the length of the resulting string after exactly t transformations.
+ *
+ * Since the answer may be very large, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} t
+ * @param {number[]} nums
+ * @return {number}
+ */
+var lengthAfterTransformations = function(s, t, nums) {
+  const MOD = 1000000007n;
+  const freq = new Array(26).fill(0n);
+
+  for (const char of s) {
+    freq[char.charCodeAt(0) - 97]++;
+  }
+
+  const matrix = new Array(26).fill().map(() => new Array(26).fill(0n));
+  for (let i = 0; i < 26; i++) {
+    for (let j = 0; j < nums[i]; j++) {
+      matrix[(i + j + 1) % 26][i] = 1n;
+    }
+  }
+
+  const finalMatrix = matrixPower(matrix, t);
+  let total = 0n;
+
+  for (let i = 0; i < 26; i++) {
+    let sum = 0n;
+    for (let j = 0; j < 26; j++) {
+      sum = (sum + finalMatrix[i][j] * freq[j]) % MOD;
+    }
+    total = (total + sum) % MOD;
+  }
+
+  return Number(total);
+
+  function matrixMultiply(a, b) {
+    const result = new Array(26).fill().map(() => new Array(26).fill(0n));
+    for (let i = 0; i < 26; i++) {
+      for (let j = 0; j < 26; j++) {
+        for (let k = 0; k < 26; k++) {
+          result[i][j] = (result[i][j] + a[i][k] * b[k][j]) % MOD;
+        }
+      }
+    }
+    return result;
+  }
+
+  function matrixPower(mat, power) {
+    let result = new Array(26).fill().map(() => new Array(26).fill(0n));
+    for (let i = 0; i < 26; i++) result[i][i] = 1n;
+
+    while (power > 0) {
+      if (power & 1) result = matrixMultiply(result, mat);
+      mat = matrixMultiply(mat, mat);
+      power >>= 1;
+    }
+    return result;
+  }
+};

From fbd680b9a64d10897dc776fe728417c84b72a0c1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 13 May 2025 22:41:44 -0500
Subject: [PATCH 262/495] Add solution #2132

---
 README.md                           |  3 +-
 solutions/2132-stamping-the-grid.js | 64 +++++++++++++++++++++++++++++
 2 files changed, 66 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2132-stamping-the-grid.js

diff --git a/README.md b/README.md
index 834cbe4f..84a5ed76 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,766 LeetCode solutions in JavaScript
+# 1,767 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1633,6 +1633,7 @@
 2129|[Capitalize the Title](./solutions/2129-capitalize-the-title.js)|Easy|
 2130|[Maximum Twin Sum of a Linked List](./solutions/2130-maximum-twin-sum-of-a-linked-list.js)|Medium|
 2131|[Longest Palindrome by Concatenating Two Letter Words](./solutions/2131-longest-palindrome-by-concatenating-two-letter-words.js)|Medium|
+2132|[Stamping the Grid](./solutions/2132-stamping-the-grid.js)|Hard|
 2140|[Solving Questions With Brainpower](./solutions/2140-solving-questions-with-brainpower.js)|Medium|
 2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
diff --git a/solutions/2132-stamping-the-grid.js b/solutions/2132-stamping-the-grid.js
new file mode 100644
index 00000000..3143e1e3
--- /dev/null
+++ b/solutions/2132-stamping-the-grid.js
@@ -0,0 +1,64 @@
+/**
+ * 2132. Stamping the Grid
+ * https://leetcode.com/problems/stamping-the-grid/
+ * Difficulty: Hard
+ *
+ * You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied).
+ *
+ * You are then given stamps of size stampHeight x stampWidth. We want to fit the stamps such that
+ * they follow the given restrictions and requirements:
+ * 1. Cover all the empty cells.
+ * 2. Do not cover any of the occupied cells.
+ * 3. We can put as many stamps as we want.
+ * 4. Stamps can overlap with each other.
+ * 5. Stamps are not allowed to be rotated.
+ * 6. Stamps must stay completely inside the grid.
+ *
+ * Return true if it is possible to fit the stamps while following the given restrictions and
+ * requirements. Otherwise, return false.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @param {number} stampHeight
+ * @param {number} stampWidth
+ * @return {boolean}
+ */
+var possibleToStamp = function(grid, stampHeight, stampWidth) {
+  const rows = grid.length;
+  const cols = grid[0].length;
+  const prefixSum = new Array(rows + 1).fill().map(() => new Array(cols + 1).fill(0));
+  const diff = new Array(rows + 1).fill().map(() => new Array(cols + 1).fill(0));
+
+  for (let i = 0; i < rows; i++) {
+    for (let j = 0; j < cols; j++) {
+      prefixSum[i + 1][j + 1] = prefixSum[i + 1][j] + prefixSum[i][j + 1]
+        - prefixSum[i][j] + grid[i][j];
+    }
+  }
+
+  for (let i = 0; i <= rows - stampHeight; i++) {
+    for (let j = 0; j <= cols - stampWidth; j++) {
+      const x = i + stampHeight;
+      const y = j + stampWidth;
+      if (prefixSum[x][y] - prefixSum[x][j] - prefixSum[i][y] + prefixSum[i][j] === 0) {
+        diff[i][j]++;
+        diff[i][y]--;
+        diff[x][j]--;
+        diff[x][y]++;
+      }
+    }
+  }
+
+  const covered = new Array(rows).fill().map(() => new Array(cols).fill(0));
+  for (let i = 0; i < rows; i++) {
+    for (let j = 0; j < cols; j++) {
+      covered[i][j] = (i > 0 ? covered[i - 1][j] : 0)
+        + (j > 0 ? covered[i][j - 1] : 0)
+        - (i > 0 && j > 0 ? covered[i - 1][j - 1] : 0) + diff[i][j];
+      if (grid[i][j] === 0 && covered[i][j] === 0) return false;
+    }
+  }
+
+  return true;
+};

From 55482a763f6892f39be071c39b45fb642114b9b5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 13 May 2025 22:43:06 -0500
Subject: [PATCH 263/495] Add solution #2133

---
 README.md                                     |  3 +-
 ...ery-row-and-column-contains-all-numbers.js | 33 +++++++++++++++++++
 2 files changed, 35 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2133-check-if-every-row-and-column-contains-all-numbers.js

diff --git a/README.md b/README.md
index 84a5ed76..6f3021e2 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,767 LeetCode solutions in JavaScript
+# 1,768 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1634,6 +1634,7 @@
 2130|[Maximum Twin Sum of a Linked List](./solutions/2130-maximum-twin-sum-of-a-linked-list.js)|Medium|
 2131|[Longest Palindrome by Concatenating Two Letter Words](./solutions/2131-longest-palindrome-by-concatenating-two-letter-words.js)|Medium|
 2132|[Stamping the Grid](./solutions/2132-stamping-the-grid.js)|Hard|
+2133|[Check if Every Row and Column Contains All Numbers](./solutions/2133-check-if-every-row-and-column-contains-all-numbers.js)|Easy|
 2140|[Solving Questions With Brainpower](./solutions/2140-solving-questions-with-brainpower.js)|Medium|
 2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
diff --git a/solutions/2133-check-if-every-row-and-column-contains-all-numbers.js b/solutions/2133-check-if-every-row-and-column-contains-all-numbers.js
new file mode 100644
index 00000000..e8d6990a
--- /dev/null
+++ b/solutions/2133-check-if-every-row-and-column-contains-all-numbers.js
@@ -0,0 +1,33 @@
+/**
+ * 2133. Check if Every Row and Column Contains All Numbers
+ * https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/
+ * Difficulty: Easy
+ *
+ * An n x n matrix is valid if every row and every column contains all the integers from 1
+ * to n (inclusive).
+ *
+ * Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise,
+ * return false.
+ */
+
+/**
+ * @param {number[][]} matrix
+ * @return {boolean}
+ */
+var checkValid = function(matrix) {
+  const n = matrix.length;
+
+  for (let i = 0; i < n; i++) {
+    const rowSet = new Set();
+    const colSet = new Set();
+
+    for (let j = 0; j < n; j++) {
+      rowSet.add(matrix[i][j]);
+      colSet.add(matrix[j][i]);
+    }
+
+    if (rowSet.size !== n || colSet.size !== n) return false;
+  }
+
+  return true;
+};

From 36c933fb43d8e06de8cb64550320f7ce9f8736a3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 13 May 2025 22:44:46 -0500
Subject: [PATCH 264/495] Add solution #2134

---
 README.md                                     |  3 +-
 ...nimum-swaps-to-group-all-1s-together-ii.js | 38 +++++++++++++++++++
 2 files changed, 40 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2134-minimum-swaps-to-group-all-1s-together-ii.js

diff --git a/README.md b/README.md
index 6f3021e2..06798418 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,768 LeetCode solutions in JavaScript
+# 1,769 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1635,6 +1635,7 @@
 2131|[Longest Palindrome by Concatenating Two Letter Words](./solutions/2131-longest-palindrome-by-concatenating-two-letter-words.js)|Medium|
 2132|[Stamping the Grid](./solutions/2132-stamping-the-grid.js)|Hard|
 2133|[Check if Every Row and Column Contains All Numbers](./solutions/2133-check-if-every-row-and-column-contains-all-numbers.js)|Easy|
+2134|[Minimum Swaps to Group All 1's Together II](./solutions/2134-minimum-swaps-to-group-all-1s-together-ii.js)|Medium|
 2140|[Solving Questions With Brainpower](./solutions/2140-solving-questions-with-brainpower.js)|Medium|
 2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
diff --git a/solutions/2134-minimum-swaps-to-group-all-1s-together-ii.js b/solutions/2134-minimum-swaps-to-group-all-1s-together-ii.js
new file mode 100644
index 00000000..1105dced
--- /dev/null
+++ b/solutions/2134-minimum-swaps-to-group-all-1s-together-ii.js
@@ -0,0 +1,38 @@
+/**
+ * 2134. Minimum Swaps to Group All 1's Together II
+ * https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/
+ * Difficulty: Medium
+ *
+ * A swap is defined as taking two distinct positions in an array and swapping the values in them.
+ *
+ * A circular array is defined as an array where we consider the first element and the last element
+ * to be adjacent.
+ *
+ * Given a binary circular array nums, return the minimum number of swaps required to group all
+ * 1's present in the array together at any location.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minSwaps = function(nums) {
+  const onesCount = nums.reduce((sum, num) => sum + num, 0);
+  const n = nums.length;
+  let result = Infinity;
+  let currentZeros = 0;
+
+  for (let i = 0; i < onesCount; i++) {
+    if (nums[i] === 0) currentZeros++;
+  }
+
+  result = currentZeros;
+
+  for (let i = 1; i < n; i++) {
+    if (nums[(i - 1) % n] === 0) currentZeros--;
+    if (nums[(i + onesCount - 1) % n] === 0) currentZeros++;
+    result = Math.min(result, currentZeros);
+  }
+
+  return result;
+};

From 817fc0fe6c42b04bdf2d431763c5914705446153 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 13 May 2025 22:46:30 -0500
Subject: [PATCH 265/495] Add solution #2135

---
 README.md                                     |  3 +-
 ...nt-words-obtained-after-adding-a-letter.js | 49 +++++++++++++++++++
 2 files changed, 51 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2135-count-words-obtained-after-adding-a-letter.js

diff --git a/README.md b/README.md
index 06798418..db1aedd3 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,769 LeetCode solutions in JavaScript
+# 1,770 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1636,6 +1636,7 @@
 2132|[Stamping the Grid](./solutions/2132-stamping-the-grid.js)|Hard|
 2133|[Check if Every Row and Column Contains All Numbers](./solutions/2133-check-if-every-row-and-column-contains-all-numbers.js)|Easy|
 2134|[Minimum Swaps to Group All 1's Together II](./solutions/2134-minimum-swaps-to-group-all-1s-together-ii.js)|Medium|
+2135|[Count Words Obtained After Adding a Letter](./solutions/2135-count-words-obtained-after-adding-a-letter.js)|Medium|
 2140|[Solving Questions With Brainpower](./solutions/2140-solving-questions-with-brainpower.js)|Medium|
 2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
diff --git a/solutions/2135-count-words-obtained-after-adding-a-letter.js b/solutions/2135-count-words-obtained-after-adding-a-letter.js
new file mode 100644
index 00000000..c7b08943
--- /dev/null
+++ b/solutions/2135-count-words-obtained-after-adding-a-letter.js
@@ -0,0 +1,49 @@
+/**
+ * 2135. Count Words Obtained After Adding a Letter
+ * https://leetcode.com/problems/count-words-obtained-after-adding-a-letter/
+ * Difficulty: Medium
+ *
+ * You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists
+ * of lowercase English letters only.
+ *
+ * For each string in targetWords, check if it is possible to choose a string from startWords and
+ * perform a conversion operation on it to be equal to that from targetWords.
+ *
+ * The conversion operation is described in the following two steps:
+ * 1. Append any lowercase letter that is not present in the string to its end.
+ *    - For example, if the string is "abc", the letters 'd', 'e', or 'y' can be added to it, but
+ *      not 'a'. If 'd' is added, the resulting string will be "abcd".
+ * 2. Rearrange the letters of the new string in any arbitrary order.
+ *    - For example, "abcd" can be rearranged to "acbd", "bacd", "cbda", and so on. Note that it
+ *      can also be rearranged to "abcd" itself.
+ *
+ * Return the number of strings in targetWords that can be obtained by performing the operations
+ * on any string of startWords.
+ *
+ * Note that you will only be verifying if the string in targetWords can be obtained from a string
+ * in startWords by performing the operations. The strings in startWords do not actually change
+ * during this process.
+ */
+
+/**
+ * @param {string[]} startWords
+ * @param {string[]} targetWords
+ * @return {number}
+ */
+var wordCount = function(startWords, targetWords) {
+  const sortedStartWords = new Set(startWords.map(word => [...word].sort().join('')));
+  let result = 0;
+
+  for (const target of targetWords) {
+    const sortedTarget = [...target].sort().join('');
+    for (let i = 0; i < target.length; i++) {
+      const candidate = sortedTarget.slice(0, i) + sortedTarget.slice(i + 1);
+      if (sortedStartWords.has(candidate)) {
+        result++;
+        break;
+      }
+    }
+  }
+
+  return result;
+};

From c77d264e7f0dc2056d86a17c5e67da84897aa529 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 13 May 2025 22:55:56 -0500
Subject: [PATCH 266/495] Add solution #2136

---
 README.md                                     |  3 +-
 ...136-earliest-possible-day-of-full-bloom.js | 39 +++++++++++++++++++
 2 files changed, 41 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2136-earliest-possible-day-of-full-bloom.js

diff --git a/README.md b/README.md
index db1aedd3..60db9fc9 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,770 LeetCode solutions in JavaScript
+# 1,771 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1637,6 +1637,7 @@
 2133|[Check if Every Row and Column Contains All Numbers](./solutions/2133-check-if-every-row-and-column-contains-all-numbers.js)|Easy|
 2134|[Minimum Swaps to Group All 1's Together II](./solutions/2134-minimum-swaps-to-group-all-1s-together-ii.js)|Medium|
 2135|[Count Words Obtained After Adding a Letter](./solutions/2135-count-words-obtained-after-adding-a-letter.js)|Medium|
+2136|[Earliest Possible Day of Full Bloom](./solutions/2136-earliest-possible-day-of-full-bloom.js)|Hard|
 2140|[Solving Questions With Brainpower](./solutions/2140-solving-questions-with-brainpower.js)|Medium|
 2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
diff --git a/solutions/2136-earliest-possible-day-of-full-bloom.js b/solutions/2136-earliest-possible-day-of-full-bloom.js
new file mode 100644
index 00000000..e4a07b6c
--- /dev/null
+++ b/solutions/2136-earliest-possible-day-of-full-bloom.js
@@ -0,0 +1,39 @@
+/**
+ * 2136. Earliest Possible Day of Full Bloom
+ * https://leetcode.com/problems/earliest-possible-day-of-full-bloom/
+ * Difficulty: Hard
+ *
+ * You have n flower seeds. Every seed must be planted first before it can begin to grow, then
+ * bloom. Planting a seed takes time and so does the growth of a seed. You are given two 0-indexed
+ * integer arrays plantTime and growTime, of length n each:
+ * - plantTime[i] is the number of full days it takes you to plant the ith seed. Every day, you can
+ *   work on planting exactly one seed. You do not have to work on planting the same seed on
+ *   consecutive days, but the planting of a seed is not complete until you have worked plantTime[i]
+ *   days on planting it in total.
+ * - growTime[i] is the number of full days it takes the ith seed to grow after being completely
+ *   planted. After the last day of its growth, the flower blooms and stays bloomed forever.
+ *
+ * From the beginning of day 0, you can plant the seeds in any order.
+ *
+ * Return the earliest possible day where all seeds are blooming.
+ */
+
+/**
+ * @param {number[]} plantTime
+ * @param {number[]} growTime
+ * @return {number}
+ */
+var earliestFullBloom = function(plantTime, growTime) {
+  const seeds = plantTime.map((plant, index) => ({ plant, grow: growTime[index] }));
+  seeds.sort((a, b) => b.grow - a.grow);
+
+  let plantingDays = 0;
+  let result = 0;
+
+  for (const { plant, grow } of seeds) {
+    plantingDays += plant;
+    result = Math.max(result, plantingDays + grow);
+  }
+
+  return result;
+};

From ec1b489e0c85cc53ac0844bd79fe15fd606d3a85 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 13 May 2025 22:58:55 -0500
Subject: [PATCH 267/495] Add solution #2138

---
 README.md                                     |  3 +-
 ...8-divide-a-string-into-groups-of-size-k.js | 35 +++++++++++++++++++
 2 files changed, 37 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2138-divide-a-string-into-groups-of-size-k.js

diff --git a/README.md b/README.md
index 60db9fc9..52a2f60d 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,771 LeetCode solutions in JavaScript
+# 1,772 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1638,6 +1638,7 @@
 2134|[Minimum Swaps to Group All 1's Together II](./solutions/2134-minimum-swaps-to-group-all-1s-together-ii.js)|Medium|
 2135|[Count Words Obtained After Adding a Letter](./solutions/2135-count-words-obtained-after-adding-a-letter.js)|Medium|
 2136|[Earliest Possible Day of Full Bloom](./solutions/2136-earliest-possible-day-of-full-bloom.js)|Hard|
+2138|[Divide a String Into Groups of Size k](./solutions/2138-divide-a-string-into-groups-of-size-k.js)|Easy|
 2140|[Solving Questions With Brainpower](./solutions/2140-solving-questions-with-brainpower.js)|Medium|
 2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
diff --git a/solutions/2138-divide-a-string-into-groups-of-size-k.js b/solutions/2138-divide-a-string-into-groups-of-size-k.js
new file mode 100644
index 00000000..24d0197f
--- /dev/null
+++ b/solutions/2138-divide-a-string-into-groups-of-size-k.js
@@ -0,0 +1,35 @@
+/**
+ * 2138. Divide a String Into Groups of Size k
+ * https://leetcode.com/problems/divide-a-string-into-groups-of-size-k/
+ * Difficulty: Easy
+ *
+ * A string s can be partitioned into groups of size k using the following procedure:
+ * - The first group consists of the first k characters of the string, the second group consists
+ *   of the next k characters of the string, and so on. Each element can be a part of exactly one
+ *   group.
+ * - For the last group, if the string does not have k characters remaining, a character fill is
+ *   used to complete the group.
+ *
+ * Note that the partition is done so that after removing the fill character from the last group
+ * (if it exists) and concatenating all the groups in order, the resultant string should be s.
+ *
+ * Given the string s, the size of each group k and the character fill, return a string array
+ * denoting the composition of every group s has been divided into, using the above procedure.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} k
+ * @param {character} fill
+ * @return {string[]}
+ */
+var divideString = function(s, k, fill) {
+  const paddedString = s + fill.repeat((k - s.length % k) % k);
+  const result = [];
+
+  for (let i = 0; i < paddedString.length; i += k) {
+    result.push(paddedString.slice(i, i + k));
+  }
+
+  return result;
+};

From b048eebe95d542450b54c124e5d054d18bdcb6a4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 13 May 2025 23:01:50 -0500
Subject: [PATCH 268/495] Add solution #2139

---
 README.md                                     |  3 +-
 ...139-minimum-moves-to-reach-target-score.js | 40 +++++++++++++++++++
 2 files changed, 42 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2139-minimum-moves-to-reach-target-score.js

diff --git a/README.md b/README.md
index 52a2f60d..656bb447 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,772 LeetCode solutions in JavaScript
+# 1,773 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1639,6 +1639,7 @@
 2135|[Count Words Obtained After Adding a Letter](./solutions/2135-count-words-obtained-after-adding-a-letter.js)|Medium|
 2136|[Earliest Possible Day of Full Bloom](./solutions/2136-earliest-possible-day-of-full-bloom.js)|Hard|
 2138|[Divide a String Into Groups of Size k](./solutions/2138-divide-a-string-into-groups-of-size-k.js)|Easy|
+2139|[Minimum Moves to Reach Target Score](./solutions/2139-minimum-moves-to-reach-target-score.js)|Medium|
 2140|[Solving Questions With Brainpower](./solutions/2140-solving-questions-with-brainpower.js)|Medium|
 2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
diff --git a/solutions/2139-minimum-moves-to-reach-target-score.js b/solutions/2139-minimum-moves-to-reach-target-score.js
new file mode 100644
index 00000000..a074595f
--- /dev/null
+++ b/solutions/2139-minimum-moves-to-reach-target-score.js
@@ -0,0 +1,40 @@
+/**
+ * 2139. Minimum Moves to Reach Target Score
+ * https://leetcode.com/problems/minimum-moves-to-reach-target-score/
+ * Difficulty: Medium
+ *
+ * You are playing a game with integers. You start with the integer 1 and you want to reach
+ * the integer target.
+ *
+ * In one move, you can either:
+ * - Increment the current integer by one (i.e., x = x + 1).
+ * - Double the current integer (i.e., x = 2 * x).
+ *
+ * You can use the increment operation any number of times, however, you can only use the double
+ * operation at most maxDoubles times.
+ *
+ * Given the two integers target and maxDoubles, return the minimum number of moves needed to
+ * reach target starting with 1.
+ */
+
+/**
+ * @param {number} target
+ * @param {number} maxDoubles
+ * @return {number}
+ */
+var minMoves = function(target, maxDoubles) {
+  let moves = 0;
+  let current = target;
+
+  while (current > 1 && maxDoubles > 0) {
+    if (current % 2 === 0) {
+      current /= 2;
+      maxDoubles--;
+    } else {
+      current--;
+    }
+    moves++;
+  }
+
+  return moves + (current - 1);
+};

From bc30ef9836e85609cb68daca41d535b4db23f2b5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 13 May 2025 23:04:46 -0500
Subject: [PATCH 269/495] Add solution #2141

---
 README.md                                     |  3 +-
 ...141-maximum-running-time-of-n-computers.js | 41 +++++++++++++++++++
 2 files changed, 43 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2141-maximum-running-time-of-n-computers.js

diff --git a/README.md b/README.md
index 656bb447..7d99e579 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,773 LeetCode solutions in JavaScript
+# 1,774 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1641,6 +1641,7 @@
 2138|[Divide a String Into Groups of Size k](./solutions/2138-divide-a-string-into-groups-of-size-k.js)|Easy|
 2139|[Minimum Moves to Reach Target Score](./solutions/2139-minimum-moves-to-reach-target-score.js)|Medium|
 2140|[Solving Questions With Brainpower](./solutions/2140-solving-questions-with-brainpower.js)|Medium|
+2141|[Maximum Running Time of N Computers](./solutions/2141-maximum-running-time-of-n-computers.js)|Hard|
 2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
 2161|[Partition Array According to Given Pivot](./solutions/2161-partition-array-according-to-given-pivot.js)|Medium|
diff --git a/solutions/2141-maximum-running-time-of-n-computers.js b/solutions/2141-maximum-running-time-of-n-computers.js
new file mode 100644
index 00000000..b5f7b090
--- /dev/null
+++ b/solutions/2141-maximum-running-time-of-n-computers.js
@@ -0,0 +1,41 @@
+/**
+ * 2141. Maximum Running Time of N Computers
+ * https://leetcode.com/problems/maximum-running-time-of-n-computers/
+ * Difficulty: Hard
+ *
+ * You have n computers. You are given the integer n and a 0-indexed integer array batteries
+ * where the ith battery can run a computer for batteries[i] minutes. You are interested in
+ * running all n computers simultaneously using the given batteries.
+ *
+ * Initially, you can insert at most one battery into each computer. After that and at any
+ * integer time moment, you can remove a battery from a computer and insert another battery
+ * any number of times. The inserted battery can be a totally new battery or a battery from
+ * another computer. You may assume that the removing and inserting processes take no time.
+ *
+ * Note that the batteries cannot be recharged.
+ *
+ * Return the maximum number of minutes you can run all the n computers simultaneously.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[]} batteries
+ * @return {number}
+ */
+var maxRunTime = function(n, batteries) {
+  let left = 1;
+  let right = Math.floor(batteries.reduce((sum, battery) => sum + battery, 0) / n);
+
+  while (left < right) {
+    const mid = Math.floor((left + right + 1) / 2);
+    const total = batteries.reduce((sum, battery) => sum + Math.min(battery, mid), 0);
+
+    if (total >= n * mid) {
+      left = mid;
+    } else {
+      right = mid - 1;
+    }
+  }
+
+  return left;
+};

From d6aa3c91cd89784af0acb5f3dfa9b99ffedcc2a9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 13 May 2025 23:06:23 -0500
Subject: [PATCH 270/495] Add solution #2144

---
 README.md                                     |  3 +-
 ...um-cost-of-buying-candies-with-discount.js | 33 +++++++++++++++++++
 2 files changed, 35 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2144-minimum-cost-of-buying-candies-with-discount.js

diff --git a/README.md b/README.md
index 7d99e579..03f965e4 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,774 LeetCode solutions in JavaScript
+# 1,775 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1642,6 +1642,7 @@
 2139|[Minimum Moves to Reach Target Score](./solutions/2139-minimum-moves-to-reach-target-score.js)|Medium|
 2140|[Solving Questions With Brainpower](./solutions/2140-solving-questions-with-brainpower.js)|Medium|
 2141|[Maximum Running Time of N Computers](./solutions/2141-maximum-running-time-of-n-computers.js)|Hard|
+2144|[Minimum Cost of Buying Candies With Discount](./solutions/2144-minimum-cost-of-buying-candies-with-discount.js)|Easy|
 2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
 2161|[Partition Array According to Given Pivot](./solutions/2161-partition-array-according-to-given-pivot.js)|Medium|
diff --git a/solutions/2144-minimum-cost-of-buying-candies-with-discount.js b/solutions/2144-minimum-cost-of-buying-candies-with-discount.js
new file mode 100644
index 00000000..86eca1e2
--- /dev/null
+++ b/solutions/2144-minimum-cost-of-buying-candies-with-discount.js
@@ -0,0 +1,33 @@
+/**
+ * 2144. Minimum Cost of Buying Candies With Discount
+ * https://leetcode.com/problems/minimum-cost-of-buying-candies-with-discount/
+ * Difficulty: Easy
+ *
+ * A shop is selling candies at a discount. For every two candies sold, the shop gives a
+ * third candy for free.
+ *
+ * The customer can choose any candy to take away for free as long as the cost of the
+ * chosen candy is less than or equal to the minimum cost of the two candies bought.
+ *
+ * - For example, if there are 4 candies with costs 1, 2, 3, and 4, and the customer buys
+ *   candies with costs 2 and 3, they can take the candy with cost 1 for free, but not the
+ *   candy with cost 4.
+ *
+ * Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy,
+ * return the minimum cost of buying all the candies.
+ */
+
+/**
+ * @param {number[]} cost
+ * @return {number}
+ */
+var minimumCost = function(cost) {
+  cost.sort((a, b) => b - a);
+  let result = 0;
+
+  for (let i = 0; i < cost.length; i += 3) {
+    result += cost[i] + (cost[i + 1] || 0);
+  }
+
+  return result;
+};

From f435a3cbe826339f660883e12ffd04a991cd439c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 00:05:52 -0500
Subject: [PATCH 271/495] Add solution #2147

---
 README.md                                     |  3 +-
 ...umber-of-ways-to-divide-a-long-corridor.js | 58 +++++++++++++++++++
 2 files changed, 60 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2147-number-of-ways-to-divide-a-long-corridor.js

diff --git a/README.md b/README.md
index 03f965e4..9fa70bf5 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,775 LeetCode solutions in JavaScript
+# 1,776 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1644,6 +1644,7 @@
 2141|[Maximum Running Time of N Computers](./solutions/2141-maximum-running-time-of-n-computers.js)|Hard|
 2144|[Minimum Cost of Buying Candies With Discount](./solutions/2144-minimum-cost-of-buying-candies-with-discount.js)|Easy|
 2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium|
+2147|[Number of Ways to Divide a Long Corridor](./solutions/2147-number-of-ways-to-divide-a-long-corridor.js)|Hard|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
 2161|[Partition Array According to Given Pivot](./solutions/2161-partition-array-according-to-given-pivot.js)|Medium|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
diff --git a/solutions/2147-number-of-ways-to-divide-a-long-corridor.js b/solutions/2147-number-of-ways-to-divide-a-long-corridor.js
new file mode 100644
index 00000000..e504b765
--- /dev/null
+++ b/solutions/2147-number-of-ways-to-divide-a-long-corridor.js
@@ -0,0 +1,58 @@
+/**
+ * 2147. Number of Ways to Divide a Long Corridor
+ * https://leetcode.com/problems/number-of-ways-to-divide-a-long-corridor/
+ * Difficulty: Hard
+ *
+ * Along a long library corridor, there is a line of seats and decorative plants. You are given
+ * a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S'
+ * represents a seat and each 'P' represents a plant.
+ *
+ * One room divider has already been installed to the left of index 0, and another to the right
+ * of index n - 1. Additional room dividers can be installed. For each position between indices
+ * i - 1 and i (1 <= i <= n - 1), at most one divider can be installed.
+ *
+ * Divide the corridor into non-overlapping sections, where each section has exactly two seats
+ * with any number of plants. There may be multiple ways to perform the division. Two ways are
+ * different if there is a position with a room divider installed in the first way but not in
+ * the second way.
+ *
+ * Return the number of ways to divide the corridor. Since the answer may be very large, return
+ * it modulo 109 + 7. If there is no way, return 0.
+ */
+
+/**
+ * @param {string} corridor
+ * @return {number}
+ */
+var numberOfWays = function(corridor) {
+  const MOD = 1e9 + 7;
+  let seatCount = 0;
+  let result = 1;
+  let lastPairEnd = -1;
+
+  for (let i = 0; i < corridor.length; i++) {
+    if (corridor[i] === 'S') {
+      seatCount++;
+    }
+  }
+  if (seatCount === 0 || seatCount % 2 !== 0) {
+    return 0;
+  }
+
+  seatCount = 0;
+
+  for (let i = 0; i < corridor.length; i++) {
+    if (corridor[i] === 'S') {
+      seatCount++;
+
+      if (seatCount % 2 === 0) {
+        lastPairEnd = i;
+      } else if (seatCount > 1) {
+        const plantsCount = i - lastPairEnd - 1;
+        result = (result * (plantsCount + 1)) % MOD;
+      }
+    }
+  }
+
+  return result;
+};

From 59d562e261ff4a3eb800fbf60d99fa3883e1ebbf Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 00:07:15 -0500
Subject: [PATCH 272/495] Add solution #2148

---
 README.md                                     |  3 ++-
 ...h-strictly-smaller-and-greater-elements.js | 25 +++++++++++++++++++
 2 files changed, 27 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2148-count-elements-with-strictly-smaller-and-greater-elements.js

diff --git a/README.md b/README.md
index 9fa70bf5..6742d0f5 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,776 LeetCode solutions in JavaScript
+# 1,777 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1645,6 +1645,7 @@
 2144|[Minimum Cost of Buying Candies With Discount](./solutions/2144-minimum-cost-of-buying-candies-with-discount.js)|Easy|
 2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium|
 2147|[Number of Ways to Divide a Long Corridor](./solutions/2147-number-of-ways-to-divide-a-long-corridor.js)|Hard|
+2148|[Count Elements With Strictly Smaller and Greater Elements](./solutions/2148-count-elements-with-strictly-smaller-and-greater-elements.js)|Easy|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
 2161|[Partition Array According to Given Pivot](./solutions/2161-partition-array-according-to-given-pivot.js)|Medium|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
diff --git a/solutions/2148-count-elements-with-strictly-smaller-and-greater-elements.js b/solutions/2148-count-elements-with-strictly-smaller-and-greater-elements.js
new file mode 100644
index 00000000..194880af
--- /dev/null
+++ b/solutions/2148-count-elements-with-strictly-smaller-and-greater-elements.js
@@ -0,0 +1,25 @@
+/**
+ * 2148. Count Elements With Strictly Smaller and Greater Elements
+ * https://leetcode.com/problems/count-elements-with-strictly-smaller-and-greater-elements/
+ * Difficulty: Easy
+ *
+ * Given an integer array nums, return the number of elements that have both a strictly
+ * smaller and a strictly greater element appear in nums.
+ */
+
+/**
+* @param {number[]} nums
+* @return {number}
+*/
+var countElements = function(nums) {
+  let result = 0;
+
+  if (nums.length <= 2) return 0;
+  for (const num of nums) {
+    if (num > Math.min(...nums) && num < Math.max(...nums)) {
+      result++;
+    }
+  }
+
+  return result;
+};

From bbef6109c02ab5b1e00ce0d671a461940c6f7de8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 00:08:30 -0500
Subject: [PATCH 273/495] Add solution #2149

---
 README.md                                     |  3 +-
 .../2149-rearrange-array-elements-by-sign.js  | 33 +++++++++++++++++++
 2 files changed, 35 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2149-rearrange-array-elements-by-sign.js

diff --git a/README.md b/README.md
index 6742d0f5..25992b29 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,777 LeetCode solutions in JavaScript
+# 1,778 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1646,6 +1646,7 @@
 2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium|
 2147|[Number of Ways to Divide a Long Corridor](./solutions/2147-number-of-ways-to-divide-a-long-corridor.js)|Hard|
 2148|[Count Elements With Strictly Smaller and Greater Elements](./solutions/2148-count-elements-with-strictly-smaller-and-greater-elements.js)|Easy|
+2149|[Rearrange Array Elements by Sign](./solutions/2149-rearrange-array-elements-by-sign.js)|Medium|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
 2161|[Partition Array According to Given Pivot](./solutions/2161-partition-array-according-to-given-pivot.js)|Medium|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
diff --git a/solutions/2149-rearrange-array-elements-by-sign.js b/solutions/2149-rearrange-array-elements-by-sign.js
new file mode 100644
index 00000000..7979e5ef
--- /dev/null
+++ b/solutions/2149-rearrange-array-elements-by-sign.js
@@ -0,0 +1,33 @@
+/**
+ * 2149. Rearrange Array Elements by Sign
+ * https://leetcode.com/problems/rearrange-array-elements-by-sign/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums of even length consisting of an equal number
+ * of positive and negative integers.
+ *
+ * You should return the array of nums such that the the array follows the given conditions:
+ * 1. Every consecutive pair of integers have opposite signs.
+ * 2. For all integers with the same sign, the order in which they were present in nums is
+ *    preserved.
+ * 3. The rearranged array begins with a positive integer.
+ *
+ * Return the modified array after rearranging the elements to satisfy the aforementioned
+ * conditions.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var rearrangeArray = function(nums) {
+  const positives = nums.filter(num => num > 0);
+  const negatives = nums.filter(num => num < 0);
+  const result = [];
+
+  for (let i = 0; i < positives.length; i++) {
+    result.push(positives[i], negatives[i]);
+  }
+
+  return result;
+};

From 5b9bfa32c1b3c1800453621bbab6a2db7fe807d6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 00:09:41 -0500
Subject: [PATCH 274/495] Add solution #2150

---
 README.md                                     |  3 +-
 ...50-find-all-lonely-numbers-in-the-array.js | 31 +++++++++++++++++++
 2 files changed, 33 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2150-find-all-lonely-numbers-in-the-array.js

diff --git a/README.md b/README.md
index 25992b29..65ff2cb8 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,778 LeetCode solutions in JavaScript
+# 1,779 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1647,6 +1647,7 @@
 2147|[Number of Ways to Divide a Long Corridor](./solutions/2147-number-of-ways-to-divide-a-long-corridor.js)|Hard|
 2148|[Count Elements With Strictly Smaller and Greater Elements](./solutions/2148-count-elements-with-strictly-smaller-and-greater-elements.js)|Easy|
 2149|[Rearrange Array Elements by Sign](./solutions/2149-rearrange-array-elements-by-sign.js)|Medium|
+2150|[Find All Lonely Numbers in the Array](./solutions/2150-find-all-lonely-numbers-in-the-array.js)|Medium|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
 2161|[Partition Array According to Given Pivot](./solutions/2161-partition-array-according-to-given-pivot.js)|Medium|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
diff --git a/solutions/2150-find-all-lonely-numbers-in-the-array.js b/solutions/2150-find-all-lonely-numbers-in-the-array.js
new file mode 100644
index 00000000..676badc6
--- /dev/null
+++ b/solutions/2150-find-all-lonely-numbers-in-the-array.js
@@ -0,0 +1,31 @@
+/**
+ * 2150. Find All Lonely Numbers in the Array
+ * https://leetcode.com/problems/find-all-lonely-numbers-in-the-array/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums. A number x is lonely when it appears only once, and
+ * no adjacent numbers (i.e. x + 1 and x - 1) appear in the array.
+ *
+ * Return all lonely numbers in nums. You may return the answer in any order.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var findLonely = function(nums) {
+  const map = new Map();
+
+  for (const num of nums) {
+    map.set(num, (map.get(num) || 0) + 1);
+  }
+
+  const result = [];
+  for (const [num, count] of map) {
+    if (count === 1 && !map.has(num - 1) && !map.has(num + 1)) {
+      result.push(num);
+    }
+  }
+
+  return result;
+};

From 6845bfe190d87233ca12a9dee627be91a83566e2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 00:14:07 -0500
Subject: [PATCH 275/495] Add solution #2151

---
 README.md                                     |  3 +-
 ...maximum-good-people-based-on-statements.js | 59 +++++++++++++++++++
 2 files changed, 61 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2151-maximum-good-people-based-on-statements.js

diff --git a/README.md b/README.md
index 65ff2cb8..2d622581 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,779 LeetCode solutions in JavaScript
+# 1,780 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1648,6 +1648,7 @@
 2148|[Count Elements With Strictly Smaller and Greater Elements](./solutions/2148-count-elements-with-strictly-smaller-and-greater-elements.js)|Easy|
 2149|[Rearrange Array Elements by Sign](./solutions/2149-rearrange-array-elements-by-sign.js)|Medium|
 2150|[Find All Lonely Numbers in the Array](./solutions/2150-find-all-lonely-numbers-in-the-array.js)|Medium|
+2151|[Maximum Good People Based on Statements](./solutions/2151-maximum-good-people-based-on-statements.js)|Hard|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
 2161|[Partition Array According to Given Pivot](./solutions/2161-partition-array-according-to-given-pivot.js)|Medium|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
diff --git a/solutions/2151-maximum-good-people-based-on-statements.js b/solutions/2151-maximum-good-people-based-on-statements.js
new file mode 100644
index 00000000..9a5d71cd
--- /dev/null
+++ b/solutions/2151-maximum-good-people-based-on-statements.js
@@ -0,0 +1,59 @@
+/**
+ * 2151. Maximum Good People Based on Statements
+ * https://leetcode.com/problems/maximum-good-people-based-on-statements/
+ * Difficulty: Hard
+ *
+ * There are two types of persons:
+ * - The good person: The person who always tells the truth.
+ * - The bad person: The person who might tell the truth and might lie.
+ *
+ * You are given a 0-indexed 2D integer array statements of size n x n that represents the
+ * statements made by n people about each other. More specifically, statements[i][j] could
+ * be one of the following:
+ * - 0 which represents a statement made by person i that person j is a bad person.
+ * - 1 which represents a statement made by person i that person j is a good person.
+ * - 2 represents that no statement is made by person i about person j.
+ *
+ * Additionally, no person ever makes a statement about themselves. Formally, we have that
+ * statements[i][i] = 2 for all 0 <= i < n.
+ *
+ * Return the maximum number of people who can be good based on the statements made by the
+ * n people.
+ */
+
+/**
+ * @param {number[][]} statements
+ * @return {number}
+ */
+var maximumGood = function(statements) {
+  const n = statements.length;
+  let result = 0;
+
+  backtrack(0, new Array(n).fill(false), 0);
+  return result;
+
+  function isValid(goodPeople) {
+    for (let i = 0; i < n; i++) {
+      if (!goodPeople[i]) continue;
+      for (let j = 0; j < n; j++) {
+        if (statements[i][j] === 0 && goodPeople[j]) return false;
+        if (statements[i][j] === 1 && !goodPeople[j]) return false;
+      }
+    }
+    return true;
+  }
+
+  function backtrack(index, goodPeople, goodCount) {
+    if (index === n) {
+      if (isValid(goodPeople)) {
+        result = Math.max(result, goodCount);
+      }
+      return;
+    }
+
+    goodPeople[index] = true;
+    backtrack(index + 1, goodPeople, goodCount + 1);
+    goodPeople[index] = false;
+    backtrack(index + 1, goodPeople, goodCount);
+  }
+};

From 8ab9d01e01124a314dcc1ea3344067a911597b30 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 00:17:01 -0500
Subject: [PATCH 276/495] Add solution #2155

---
 README.md                                     |  3 +-
 ...ith-the-highest-score-of-a-binary-array.js | 45 +++++++++++++++++++
 2 files changed, 47 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2155-all-divisions-with-the-highest-score-of-a-binary-array.js

diff --git a/README.md b/README.md
index 2d622581..64bc7152 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,780 LeetCode solutions in JavaScript
+# 1,781 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1650,6 +1650,7 @@
 2150|[Find All Lonely Numbers in the Array](./solutions/2150-find-all-lonely-numbers-in-the-array.js)|Medium|
 2151|[Maximum Good People Based on Statements](./solutions/2151-maximum-good-people-based-on-statements.js)|Hard|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
+2155|[All Divisions With the Highest Score of a Binary Array](./solutions/2155-all-divisions-with-the-highest-score-of-a-binary-array.js)|Medium|
 2161|[Partition Array According to Given Pivot](./solutions/2161-partition-array-according-to-given-pivot.js)|Medium|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
diff --git a/solutions/2155-all-divisions-with-the-highest-score-of-a-binary-array.js b/solutions/2155-all-divisions-with-the-highest-score-of-a-binary-array.js
new file mode 100644
index 00000000..66db5b2f
--- /dev/null
+++ b/solutions/2155-all-divisions-with-the-highest-score-of-a-binary-array.js
@@ -0,0 +1,45 @@
+/**
+ * 2155. All Divisions With the Highest Score of a Binary Array
+ * https://leetcode.com/problems/all-divisions-with-the-highest-score-of-a-binary-array/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed binary array nums of length n. nums can be divided at index i
+ * (where 0 <= i <= n) into two arrays (possibly empty) numsleft and numsright:
+ * - numsleft has all the elements of nums between index 0 and i - 1 (inclusive), while numsright
+ *   has all the elements of nums between index i and n - 1 (inclusive).
+ * - If i == 0, numsleft is empty, while numsright has all the elements of nums.
+ * - If i == n, numsleft has all the elements of nums, while numsright is empty.
+ *
+ * The division score of an index i is the sum of the number of 0's in numsleft and the number
+ * of 1's in numsright.
+ *
+ * Return all distinct indices that have the highest possible division score. You may return
+ * the answer in any order.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var maxScoreIndices = function(nums) {
+  const result = [0];
+  let leftZeros = 0;
+  let rightOnes = nums.reduce((sum, num) => sum + num, 0);
+  let maxScore = rightOnes;
+
+  for (let i = 0; i < nums.length; i++) {
+    leftZeros += nums[i] === 0 ? 1 : 0;
+    rightOnes -= nums[i];
+    const score = leftZeros + rightOnes;
+
+    if (score > maxScore) {
+      maxScore = score;
+      result.length = 0;
+      result.push(i + 1);
+    } else if (score === maxScore) {
+      result.push(i + 1);
+    }
+  }
+
+  return result;
+};

From 1fbf170622b4318bf680887b4171bd6eae60c53a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 00:35:10 -0500
Subject: [PATCH 277/495] Add solution #2156

---
 README.md                                     |  3 +-
 ...56-find-substring-with-given-hash-value.js | 51 +++++++++++++++++++
 2 files changed, 53 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2156-find-substring-with-given-hash-value.js

diff --git a/README.md b/README.md
index 64bc7152..b985d65d 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,781 LeetCode solutions in JavaScript
+# 1,782 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1651,6 +1651,7 @@
 2151|[Maximum Good People Based on Statements](./solutions/2151-maximum-good-people-based-on-statements.js)|Hard|
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
 2155|[All Divisions With the Highest Score of a Binary Array](./solutions/2155-all-divisions-with-the-highest-score-of-a-binary-array.js)|Medium|
+2156|[Find Substring With Given Hash Value](./solutions/2156-find-substring-with-given-hash-value.js)|Hard|
 2161|[Partition Array According to Given Pivot](./solutions/2161-partition-array-according-to-given-pivot.js)|Medium|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
diff --git a/solutions/2156-find-substring-with-given-hash-value.js b/solutions/2156-find-substring-with-given-hash-value.js
new file mode 100644
index 00000000..a43f4a10
--- /dev/null
+++ b/solutions/2156-find-substring-with-given-hash-value.js
@@ -0,0 +1,51 @@
+/**
+ * 2156. Find Substring With Given Hash Value
+ * https://leetcode.com/problems/find-substring-with-given-hash-value/
+ * Difficulty: Hard
+ *
+ * The hash of a 0-indexed string s of length k, given integers p and m, is computed using
+ * the following function:
+ * - hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m.
+ *
+ * Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26.
+ *
+ * You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the
+ * first substring of s of length k such that hash(sub, power, modulo) == hashValue.
+ *
+ * The test cases will be generated such that an answer always exists.
+ *
+ * A substring is a contiguous non-empty sequence of characters within a string.
+ */
+
+/**
+* @param {string} s
+* @param {number} power
+* @param {number} modulo
+* @param {number} k
+* @param {number} hashValue
+* @return {string}
+*/
+var subStrHash = function(s, power, modulo, k, hashValue) {
+  power = BigInt(power);
+  modulo = BigInt(modulo);
+  hashValue = BigInt(hashValue);
+
+  const powers = new Array(k);
+  powers[0] = 1n;
+  for (let i = 1; i < k; i++) {
+    powers[i] = (powers[i - 1] * power) % modulo;
+  }
+
+  for (let start = 0; start <= s.length - k; start++) {
+    let hash = 0n;
+    for (let i = 0; i < k; i++) {
+      const charVal = BigInt(s.charCodeAt(start + i) - 'a'.charCodeAt(0) + 1);
+      hash = (hash + charVal * powers[i]) % modulo;
+    }
+    if (hash === hashValue) {
+      return s.substring(start, start + k);
+    }
+  }
+
+  return '';
+};

From d2ea5b5535964dcd1cba214b0eb390742a68edf9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 00:45:27 -0500
Subject: [PATCH 278/495] Add solution #2157

---
 README.md                           |   3 +-
 solutions/2157-groups-of-strings.js | 140 ++++++++++++++++++++++++++++
 2 files changed, 142 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2157-groups-of-strings.js

diff --git a/README.md b/README.md
index b985d65d..453530ee 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,782 LeetCode solutions in JavaScript
+# 1,783 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1652,6 +1652,7 @@
 2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
 2155|[All Divisions With the Highest Score of a Binary Array](./solutions/2155-all-divisions-with-the-highest-score-of-a-binary-array.js)|Medium|
 2156|[Find Substring With Given Hash Value](./solutions/2156-find-substring-with-given-hash-value.js)|Hard|
+2157|[Groups of Strings](./solutions/2157-groups-of-strings.js)|Hard|
 2161|[Partition Array According to Given Pivot](./solutions/2161-partition-array-according-to-given-pivot.js)|Medium|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
diff --git a/solutions/2157-groups-of-strings.js b/solutions/2157-groups-of-strings.js
new file mode 100644
index 00000000..8af51c12
--- /dev/null
+++ b/solutions/2157-groups-of-strings.js
@@ -0,0 +1,140 @@
+/**
+ * 2157. Groups of Strings
+ * https://leetcode.com/problems/groups-of-strings/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed array of strings words. Each string consists of lowercase English
+ * letters only. No letter occurs more than once in any string of words.
+ *
+ * Two strings s1 and s2 are said to be connected if the set of letters of s2 can be obtained
+ * from the set of letters of s1 by any one of the following operations:
+ * - Adding exactly one letter to the set of the letters of s1.
+ * - Deleting exactly one letter from the set of the letters of s1.
+ * - Replacing exactly one letter from the set of the letters of s1 with any letter, including
+ *   itself.
+ *
+ * The array words can be divided into one or more non-intersecting groups. A string belongs
+ * to a group if any one of the following is true:
+ * - It is connected to at least one other string of the group.
+ * - It is the only string present in the group.
+ *
+ * Note that the strings in words should be grouped in such a manner that a string belonging
+ * to a group cannot be connected to a string present in any other group. It can be proved
+ * that such an arrangement is always unique.
+ *
+ * Return an array ans of size 2 where:
+ * - ans[0] is the maximum number of groups words can be divided into, and
+ * - ans[1] is the size of the largest group.
+ */
+
+/**
+ * @param {string[]} words
+ * @return {number[]}
+ */
+var groupStrings = function(words) {
+  const n = words.length;
+  const masks = words.map(word => {
+    let mask = 0;
+    for (let i = 0; i < word.length; i++) {
+      mask |= (1 << (word.charCodeAt(i) - 'a'.charCodeAt(0)));
+    }
+    return mask;
+  });
+  const uf = new UnionFind(n);
+  const maskToIndex = new Map();
+  for (let i = 0; i < n; i++) {
+    if (maskToIndex.has(masks[i])) {
+      uf.union(maskToIndex.get(masks[i]), i);
+    } else {
+      maskToIndex.set(masks[i], i);
+    }
+  }
+  const processed = new Set();
+
+  for (let i = 0; i < n; i++) {
+    const mask = masks[i];
+    if (processed.has(mask)) continue;
+    processed.add(mask);
+
+    for (let bit = 0; bit < 26; bit++) {
+      if ((mask & (1 << bit)) === 0) {
+        const newMask = mask | (1 << bit);
+        if (maskToIndex.has(newMask)) {
+          uf.union(i, maskToIndex.get(newMask));
+        }
+      }
+    }
+
+    for (let bit = 0; bit < 26; bit++) {
+      if ((mask & (1 << bit)) !== 0) {
+        const newMask = mask & ~(1 << bit);
+        if (maskToIndex.has(newMask)) {
+          uf.union(i, maskToIndex.get(newMask));
+        }
+      }
+    }
+
+    for (let remove = 0; remove < 26; remove++) {
+      if ((mask & (1 << remove)) !== 0) {
+        for (let add = 0; add < 26; add++) {
+          if ((mask & (1 << add)) === 0) {
+            const newMask = (mask & ~(1 << remove)) | (1 << add);
+            if (maskToIndex.has(newMask)) {
+              uf.union(i, maskToIndex.get(newMask));
+            }
+          }
+        }
+      }
+    }
+  }
+
+  return [uf.count, uf.getMaxSize()];
+};
+
+class UnionFind {
+  constructor(n) {
+    this.parent = Array(n).fill().map((_, i) => i);
+    this.rank = Array(n).fill(0);
+    this.count = n;
+    this.sizes = Array(n).fill(1);
+  }
+
+  find(x) {
+    if (this.parent[x] !== x) {
+      this.parent[x] = this.find(this.parent[x]);
+    }
+    return this.parent[x];
+  }
+
+  union(x, y) {
+    const rootX = this.find(x);
+    const rootY = this.find(y);
+
+    if (rootX === rootY) return false;
+
+    if (this.rank[rootX] < this.rank[rootY]) {
+      this.parent[rootX] = rootY;
+      this.sizes[rootY] += this.sizes[rootX];
+    } else if (this.rank[rootX] > this.rank[rootY]) {
+      this.parent[rootY] = rootX;
+      this.sizes[rootX] += this.sizes[rootY];
+    } else {
+      this.parent[rootY] = rootX;
+      this.rank[rootX]++;
+      this.sizes[rootX] += this.sizes[rootY];
+    }
+
+    this.count--;
+    return true;
+  }
+
+  getMaxSize() {
+    let maxSize = 0;
+    for (let i = 0; i < this.parent.length; i++) {
+      if (this.parent[i] === i) {
+        maxSize = Math.max(maxSize, this.sizes[i]);
+      }
+    }
+    return maxSize;
+  }
+}

From 4ac50a7a701573b37bfeeecead1d0a42a7e2e07b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 00:46:44 -0500
Subject: [PATCH 279/495] Add solution #2160

---
 README.md                                     |  3 ++-
 ...our-digit-number-after-splitting-digits.js | 22 +++++++++++++++++++
 2 files changed, 24 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2160-minimum-sum-of-four-digit-number-after-splitting-digits.js

diff --git a/README.md b/README.md
index 453530ee..75413a3f 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,783 LeetCode solutions in JavaScript
+# 1,784 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1653,6 +1653,7 @@
 2155|[All Divisions With the Highest Score of a Binary Array](./solutions/2155-all-divisions-with-the-highest-score-of-a-binary-array.js)|Medium|
 2156|[Find Substring With Given Hash Value](./solutions/2156-find-substring-with-given-hash-value.js)|Hard|
 2157|[Groups of Strings](./solutions/2157-groups-of-strings.js)|Hard|
+2160|[Minimum Sum of Four Digit Number After Splitting Digits](./solutions/2160-minimum-sum-of-four-digit-number-after-splitting-digits.js)|Easy|
 2161|[Partition Array According to Given Pivot](./solutions/2161-partition-array-according-to-given-pivot.js)|Medium|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
diff --git a/solutions/2160-minimum-sum-of-four-digit-number-after-splitting-digits.js b/solutions/2160-minimum-sum-of-four-digit-number-after-splitting-digits.js
new file mode 100644
index 00000000..fa3b9b86
--- /dev/null
+++ b/solutions/2160-minimum-sum-of-four-digit-number-after-splitting-digits.js
@@ -0,0 +1,22 @@
+/**
+ * 2160. Minimum Sum of Four Digit Number After Splitting Digits
+ * https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits/
+ * Difficulty: Easy
+ *
+ * You are given a positive integer num consisting of exactly four digits. Split num into two
+ * new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in
+ * new1 and new2, and all the digits found in num must be used.
+ * - For example, given num = 2932, you have the following digits: two 2's, one 9 and one 3.
+ *   Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329].
+ *
+ * Return the minimum possible sum of new1 and new2.
+ */
+
+/**
+ * @param {number} num
+ * @return {number}
+ */
+var minimumSum = function(num) {
+  const digits = String(num).split('').map(Number).sort((a, b) => a - b);
+  return (digits[0] * 10 + digits[2]) + (digits[1] * 10 + digits[3]);
+};

From 4b614dffcd7fa9fcd186dea800c5437178b03327 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 00:51:18 -0500
Subject: [PATCH 280/495] Add solution #2162

---
 README.md                                     |  3 +-
 .../2162-minimum-cost-to-set-cooking-time.js  | 90 +++++++++++++++++++
 2 files changed, 92 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2162-minimum-cost-to-set-cooking-time.js

diff --git a/README.md b/README.md
index 75413a3f..13c33f3c 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,784 LeetCode solutions in JavaScript
+# 1,785 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1655,6 +1655,7 @@
 2157|[Groups of Strings](./solutions/2157-groups-of-strings.js)|Hard|
 2160|[Minimum Sum of Four Digit Number After Splitting Digits](./solutions/2160-minimum-sum-of-four-digit-number-after-splitting-digits.js)|Easy|
 2161|[Partition Array According to Given Pivot](./solutions/2161-partition-array-according-to-given-pivot.js)|Medium|
+2162|[Minimum Cost to Set Cooking Time](./solutions/2162-minimum-cost-to-set-cooking-time.js)|Medium|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
diff --git a/solutions/2162-minimum-cost-to-set-cooking-time.js b/solutions/2162-minimum-cost-to-set-cooking-time.js
new file mode 100644
index 00000000..e1c51c1b
--- /dev/null
+++ b/solutions/2162-minimum-cost-to-set-cooking-time.js
@@ -0,0 +1,90 @@
+/**
+ * 2162. Minimum Cost to Set Cooking Time
+ * https://leetcode.com/problems/minimum-cost-to-set-cooking-time/
+ * Difficulty: Medium
+ *
+ * A generic microwave supports cooking times for:
+ * - at least 1 second.
+ * - at most 99 minutes and 99 seconds.
+ *
+ * To set the cooking time, you push at most four digits. The microwave normalizes what you push
+ * as four digits by prepending zeroes. It interprets the first two digits as the minutes and
+ * the last two digits as the seconds. It then adds them up as the cooking time. For example,
+ * - You push 9 5 4 (three digits). It is normalized as 0954 and interpreted as 9 minutes and
+ *   54 seconds.
+ * - You push 0 0 0 8 (four digits). It is interpreted as 0 minutes and 8 seconds.
+ * - You push 8 0 9 0. It is interpreted as 80 minutes and 90 seconds.
+ * - You push 8 1 3 0. It is interpreted as 81 minutes and 30 seconds.
+ *
+ * You are given integers startAt, moveCost, pushCost, and targetSeconds. Initially, your finger
+ * is on the digit startAt. Moving the finger above any specific digit costs moveCost units of
+ * fatigue. Pushing the digit below the finger once costs pushCost units of fatigue.
+ *
+ * There can be multiple ways to set the microwave to cook for targetSeconds seconds but you are
+ * interested in the way with the minimum cost.
+ *
+ * Return the minimum cost to set targetSeconds seconds of cooking time.
+ *
+ * Remember that one minute consists of 60 seconds.
+ */
+
+/**
+ * @param {number} startAt
+ * @param {number} moveCost
+ * @param {number} pushCost
+ * @param {number} targetSeconds
+ * @return {number}
+ */
+var minCostSetTime = function(startAt, moveCost, pushCost, targetSeconds) {
+  const minutes1 = Math.floor(targetSeconds / 60);
+  const seconds1 = targetSeconds % 60;
+  let result = Infinity;
+
+  if (minutes1 <= 99) {
+    const digits1 = getDigits(minutes1, seconds1);
+    result = Math.min(result, calculateCost(digits1));
+  }
+
+  const minutes2 = Math.floor(targetSeconds / 60) - 1;
+  const seconds2 = targetSeconds % 60 + 60;
+  if (minutes2 >= 0 && minutes2 <= 99 && seconds2 <= 99) {
+    const digits2 = getDigits(minutes2, seconds2);
+    result = Math.min(result, calculateCost(digits2));
+  }
+
+  return result;
+
+  function calculateCost(digits) {
+    let totalCost = 0;
+    let currentDigit = startAt;
+
+    for (const digit of digits) {
+      if (digit !== currentDigit) {
+        totalCost += moveCost;
+        currentDigit = digit;
+      }
+      totalCost += pushCost;
+    }
+
+    return totalCost;
+  }
+
+  function getDigits(minutes, seconds) {
+    const result = [];
+
+    if (minutes > 0) {
+      if (minutes >= 10) {
+        result.push(Math.floor(minutes / 10));
+      }
+      result.push(minutes % 10);
+    }
+
+    if (minutes > 0 || seconds >= 10) {
+      result.push(Math.floor(seconds / 10));
+    }
+
+    result.push(seconds % 10);
+
+    return result;
+  }
+};

From dfcd6a2e3bed6be3e90f52c5287b993a2864ed66 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 19:04:45 -0500
Subject: [PATCH 281/495] Add solution #2900

---
 README.md                                     |  3 +-
 ...t-unequal-adjacent-groups-subsequence-i.js | 40 +++++++++++++++++++
 2 files changed, 42 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2900-longest-unequal-adjacent-groups-subsequence-i.js

diff --git a/README.md b/README.md
index 13c33f3c..ef853b16 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,785 LeetCode solutions in JavaScript
+# 1,786 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1755,6 +1755,7 @@
 2845|[Count of Interesting Subarrays](./solutions/2845-count-of-interesting-subarrays.js)|Medium|
 2873|[Maximum Value of an Ordered Triplet I](./solutions/2873-maximum-value-of-an-ordered-triplet-i.js)|Easy|
 2874|[Maximum Value of an Ordered Triplet II](./solutions/2874-maximum-value-of-an-ordered-triplet-ii.js)|Medium|
+2900|[Longest Unequal Adjacent Groups Subsequence I](./solutions/2900-longest-unequal-adjacent-groups-subsequence-i.js)|Easy|
 2918|[Minimum Equal Sum of Two Arrays After Replacing Zeros](./solutions/2918-minimum-equal-sum-of-two-arrays-after-replacing-zeros.js)|Medium|
 2948|[Make Lexicographically Smallest Array by Swapping Elements](./solutions/2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium|
 2962|[Count Subarrays Where Max Element Appears at Least K Times](./solutions/2962-count-subarrays-where-max-element-appears-at-least-k-times.js)|Medium|
diff --git a/solutions/2900-longest-unequal-adjacent-groups-subsequence-i.js b/solutions/2900-longest-unequal-adjacent-groups-subsequence-i.js
new file mode 100644
index 00000000..b4df7c52
--- /dev/null
+++ b/solutions/2900-longest-unequal-adjacent-groups-subsequence-i.js
@@ -0,0 +1,40 @@
+/**
+ * 2900. Longest Unequal Adjacent Groups Subsequence I
+ * https://leetcode.com/problems/longest-unequal-adjacent-groups-subsequence-i/
+ * Difficulty: Easy
+ *
+ * You are given a string array words and a binary array groups both of length n, where words[i]
+ * is associated with groups[i].
+ *
+ * Your task is to select the longest alternating subsequence from words. A subsequence of words
+ * is alternating if for any two consecutive strings in the sequence, their corresponding elements
+ * in the binary array groups differ. Essentially, you are to choose strings such that adjacent
+ * elements have non-matching corresponding bits in the groups array.
+ *
+ * Formally, you need to find the longest subsequence of an array of indices [0, 1, ..., n - 1]
+ * denoted as [i0, i1, ..., ik-1], such that groups[ij] != groups[ij+1] for each 0 <= j < k - 1
+ * and then find the words corresponding to these indices.
+ *
+ * Return the selected subsequence. If there are multiple answers, return any of them.
+ *
+ * Note: The elements in words are distinct.
+ */
+
+/**
+ * @param {string[]} words
+ * @param {number[]} groups
+ * @return {string[]}
+ */
+var getLongestSubsequence = function(words, groups) {
+  const result = [words[0]];
+  let lastGroup = groups[0];
+
+  for (let i = 1; i < words.length; i++) {
+    if (groups[i] !== lastGroup) {
+      result.push(words[i]);
+      lastGroup = groups[i];
+    }
+  }
+
+  return result;
+};

From e4dfc44a21f320f6fd9ed4eac9969ffc5f9ff92d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 19:06:27 -0500
Subject: [PATCH 282/495] Add solution #2164

---
 README.md                                     |  3 +-
 ...sort-even-and-odd-indices-independently.js | 50 +++++++++++++++++++
 2 files changed, 52 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2164-sort-even-and-odd-indices-independently.js

diff --git a/README.md b/README.md
index ef853b16..4dfacef7 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,786 LeetCode solutions in JavaScript
+# 1,787 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1656,6 +1656,7 @@
 2160|[Minimum Sum of Four Digit Number After Splitting Digits](./solutions/2160-minimum-sum-of-four-digit-number-after-splitting-digits.js)|Easy|
 2161|[Partition Array According to Given Pivot](./solutions/2161-partition-array-according-to-given-pivot.js)|Medium|
 2162|[Minimum Cost to Set Cooking Time](./solutions/2162-minimum-cost-to-set-cooking-time.js)|Medium|
+2164|[Sort Even and Odd Indices Independently](./solutions/2164-sort-even-and-odd-indices-independently.js)|Easy|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
diff --git a/solutions/2164-sort-even-and-odd-indices-independently.js b/solutions/2164-sort-even-and-odd-indices-independently.js
new file mode 100644
index 00000000..ed9322c6
--- /dev/null
+++ b/solutions/2164-sort-even-and-odd-indices-independently.js
@@ -0,0 +1,50 @@
+/**
+ * 2164. Sort Even and Odd Indices Independently
+ * https://leetcode.com/problems/sort-even-and-odd-indices-independently/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums. Rearrange the values of nums according to the
+ * following rules:
+ * 1. Sort the values at odd indices of nums in non-increasing order.
+ *    - For example, if nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after. The values
+ *      at odd indices 1 and 3 are sorted in non-increasing order.
+ * 2. Sort the values at even indices of nums in non-decreasing order.
+ *    - For example, if nums = [4,1,2,3] before this step, it becomes [2,1,4,3] after. The values
+ *      at even indices 0 and 2 are sorted in non-decreasing order.
+ *
+ * Return the array formed after rearranging the values of nums.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var sortEvenOdd = function(nums) {
+  const evens = [];
+  const odds = [];
+
+  for (let i = 0; i < nums.length; i++) {
+    if (i % 2 === 0) {
+      evens.push(nums[i]);
+    } else {
+      odds.push(nums[i]);
+    }
+  }
+
+  evens.sort((a, b) => a - b);
+  odds.sort((a, b) => b - a);
+
+  const result = [];
+  let evenIndex = 0;
+  let oddIndex = 0;
+
+  for (let i = 0; i < nums.length; i++) {
+    if (i % 2 === 0) {
+      result.push(evens[evenIndex++]);
+    } else {
+      result.push(odds[oddIndex++]);
+    }
+  }
+
+  return result;
+};

From 70a639e7d5e88132cce3cabcb9b2737538725903 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 19:07:34 -0500
Subject: [PATCH 283/495] Add solution #2165

---
 README.md                                     |  3 +-
 ...smallest-value-of-the-rearranged-number.js | 34 +++++++++++++++++++
 2 files changed, 36 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2165-smallest-value-of-the-rearranged-number.js

diff --git a/README.md b/README.md
index 4dfacef7..31a480ea 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,787 LeetCode solutions in JavaScript
+# 1,788 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1657,6 +1657,7 @@
 2161|[Partition Array According to Given Pivot](./solutions/2161-partition-array-according-to-given-pivot.js)|Medium|
 2162|[Minimum Cost to Set Cooking Time](./solutions/2162-minimum-cost-to-set-cooking-time.js)|Medium|
 2164|[Sort Even and Odd Indices Independently](./solutions/2164-sort-even-and-odd-indices-independently.js)|Easy|
+2165|[Smallest Value of the Rearranged Number](./solutions/2165-smallest-value-of-the-rearranged-number.js)|Medium|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
diff --git a/solutions/2165-smallest-value-of-the-rearranged-number.js b/solutions/2165-smallest-value-of-the-rearranged-number.js
new file mode 100644
index 00000000..c3226062
--- /dev/null
+++ b/solutions/2165-smallest-value-of-the-rearranged-number.js
@@ -0,0 +1,34 @@
+/**
+ * 2165. Smallest Value of the Rearranged Number
+ * https://leetcode.com/problems/smallest-value-of-the-rearranged-number/
+ * Difficulty: Medium
+ *
+ * You are given an integer num. Rearrange the digits of num such that its value is minimized
+ * and it does not contain any leading zeros.
+ *
+ * Return the rearranged number with minimal value.
+ *
+ * Note that the sign of the number does not change after rearranging the digits.
+ */
+
+/**
+ * @param {number} num
+ * @return {number}
+ */
+var smallestNumber = function(num) {
+  const isNegative = num < 0;
+  const digits = Math.abs(num).toString().split('').map(Number);
+
+  if (isNegative) {
+    digits.sort((a, b) => b - a);
+    return -parseInt(digits.join(''), 10);
+  }
+
+  digits.sort((a, b) => a - b);
+  const firstNonZero = digits.findIndex(d => d !== 0);
+
+  if (firstNonZero === -1) return 0;
+
+  [digits[0], digits[firstNonZero]] = [digits[firstNonZero], digits[0]];
+  return parseInt(digits.join(''), 10);
+};

From 700eabcdb667ea7b54ce6d69c702786e33a21317 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 19:09:15 -0500
Subject: [PATCH 284/495] Add solution #2166

---
 README.md                       |   3 +-
 solutions/2166-design-bitset.js | 109 ++++++++++++++++++++++++++++++++
 2 files changed, 111 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2166-design-bitset.js

diff --git a/README.md b/README.md
index 31a480ea..f5523ebf 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,788 LeetCode solutions in JavaScript
+# 1,789 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1658,6 +1658,7 @@
 2162|[Minimum Cost to Set Cooking Time](./solutions/2162-minimum-cost-to-set-cooking-time.js)|Medium|
 2164|[Sort Even and Odd Indices Independently](./solutions/2164-sort-even-and-odd-indices-independently.js)|Easy|
 2165|[Smallest Value of the Rearranged Number](./solutions/2165-smallest-value-of-the-rearranged-number.js)|Medium|
+2166|[Design Bitset](./solutions/2166-design-bitset.js)|Medium|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
diff --git a/solutions/2166-design-bitset.js b/solutions/2166-design-bitset.js
new file mode 100644
index 00000000..155fe39b
--- /dev/null
+++ b/solutions/2166-design-bitset.js
@@ -0,0 +1,109 @@
+/**
+ * 2166. Design Bitset
+ * https://leetcode.com/problems/design-bitset/
+ * Difficulty: Medium
+ *
+ * A Bitset is a data structure that compactly stores bits.
+ *
+ * Implement the Bitset class:
+ * - Bitset(int size) Initializes the Bitset with size bits, all of which are 0.
+ * - void fix(int idx) Updates the value of the bit at the index idx to 1. If the value was
+ *   already 1, no change occurs.
+ * - void unfix(int idx) Updates the value of the bit at the index idx to 0. If the value
+ *   was already 0, no change occurs.
+ * - void flip() Flips the values of each bit in the Bitset. In other words, all bits with
+ *   value 0 will now have value 1 and vice versa.
+ * - boolean all() Checks if the value of each bit in the Bitset is 1. Returns true if it
+ *   satisfies the condition, false otherwise.
+ * - boolean one() Checks if there is at least one bit in the Bitset with value 1. Returns
+ *   true if it satisfies the condition, false otherwise.
+ * - int count() Returns the total number of bits in the Bitset which have value 1.
+ * - String toString() Returns the current composition of the Bitset. Note that in the
+ *   resultant string, the character at the ith index should coincide with the value at
+ *   the ith bit of the Bitset.
+ */
+
+/**
+ * @param {number} size
+ */
+var Bitset = function(size) {
+  this.bits = new Uint8Array(size);
+  this.ones = 0;
+  this.flipped = false;
+};
+
+/**
+ * @param {number} idx
+ * @return {void}
+ */
+Bitset.prototype.fix = function(idx) {
+  if (this.flipped) {
+    if (this.bits[idx] === 1) {
+      this.bits[idx] = 0;
+      this.ones++;
+    }
+  } else {
+    if (this.bits[idx] === 0) {
+      this.bits[idx] = 1;
+      this.ones++;
+    }
+  }
+};
+
+/**
+ * @param {number} idx
+ * @return {void}
+ */
+Bitset.prototype.unfix = function(idx) {
+  if (this.flipped) {
+    if (this.bits[idx] === 0) {
+      this.bits[idx] = 1;
+      this.ones--;
+    }
+  } else {
+    if (this.bits[idx] === 1) {
+      this.bits[idx] = 0;
+      this.ones--;
+    }
+  }
+};
+
+/**
+ * @return {void}
+ */
+Bitset.prototype.flip = function() {
+  this.flipped = !this.flipped;
+  this.ones = this.bits.length - this.ones;
+};
+
+/**
+ * @return {boolean}
+ */
+Bitset.prototype.all = function() {
+  return this.ones === this.bits.length;
+};
+
+/**
+ * @return {boolean}
+ */
+Bitset.prototype.one = function() {
+  return this.ones > 0;
+};
+
+/**
+ * @return {number}
+ */
+Bitset.prototype.count = function() {
+  return this.ones;
+};
+
+/**
+ * @return {string}
+ */
+Bitset.prototype.toString = function() {
+  let result = '';
+  for (let i = 0; i < this.bits.length; i++) {
+    result += this.flipped ? 1 - this.bits[i] : this.bits[i];
+  }
+  return result;
+};

From 0f6c0fcdc3c122ce6f85145a517bd4e2739e5c0b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 19:10:46 -0500
Subject: [PATCH 285/495] Add solution #2167

---
 README.md                                     |  3 +-
 ...emove-all-cars-containing-illegal-goods.js | 37 +++++++++++++++++++
 2 files changed, 39 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2167-minimum-time-to-remove-all-cars-containing-illegal-goods.js

diff --git a/README.md b/README.md
index f5523ebf..8b522d77 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,789 LeetCode solutions in JavaScript
+# 1,790 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1659,6 +1659,7 @@
 2164|[Sort Even and Odd Indices Independently](./solutions/2164-sort-even-and-odd-indices-independently.js)|Easy|
 2165|[Smallest Value of the Rearranged Number](./solutions/2165-smallest-value-of-the-rearranged-number.js)|Medium|
 2166|[Design Bitset](./solutions/2166-design-bitset.js)|Medium|
+2167|[Minimum Time to Remove All Cars Containing Illegal Goods](./solutions/2167-minimum-time-to-remove-all-cars-containing-illegal-goods.js)|Hard|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
diff --git a/solutions/2167-minimum-time-to-remove-all-cars-containing-illegal-goods.js b/solutions/2167-minimum-time-to-remove-all-cars-containing-illegal-goods.js
new file mode 100644
index 00000000..4877a0de
--- /dev/null
+++ b/solutions/2167-minimum-time-to-remove-all-cars-containing-illegal-goods.js
@@ -0,0 +1,37 @@
+/**
+ * 2167. Minimum Time to Remove All Cars Containing Illegal Goods
+ * https://leetcode.com/problems/minimum-time-to-remove-all-cars-containing-illegal-goods/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0'
+ * denotes that the ith car does not contain illegal goods and s[i] = '1' denotes that the ith car
+ * does contain illegal goods.
+ *
+ * As the train conductor, you would like to get rid of all the cars containing illegal goods.
+ * You can do any of the following three operations any number of times:
+ * 1. Remove a train car from the left end (i.e., remove s[0]) which takes 1 unit of time.
+ * 2. Remove a train car from the right end (i.e., remove s[s.length - 1]) which takes 1 unit
+ *    of time.
+ * 3. Remove a train car from anywhere in the sequence which takes 2 units of time.
+ *
+ * Return the minimum time to remove all the cars containing illegal goods.
+ *
+ * Note that an empty sequence of cars is considered to have no cars containing illegal goods.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var minimumTime = function(s) {
+  let leftCost = 0;
+  let result = s.length;
+
+  for (let i = 0; i < s.length; i++) {
+    leftCost = Math.min(leftCost + (s[i] === '1' ? 2 : 0), i + 1);
+    const rightCost = s.length - i - 1;
+    result = Math.min(result, leftCost + rightCost);
+  }
+
+  return result;
+};

From 034afefc63b99b475e164648d74afc69848148b3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 19:20:27 -0500
Subject: [PATCH 286/495] Add solution #2169

---
 README.md                                     |  3 +-
 .../2169-count-operations-to-obtain-zero.js   | 34 +++++++++++++++++++
 2 files changed, 36 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2169-count-operations-to-obtain-zero.js

diff --git a/README.md b/README.md
index 8b522d77..aa6f989f 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,790 LeetCode solutions in JavaScript
+# 1,791 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1660,6 +1660,7 @@
 2165|[Smallest Value of the Rearranged Number](./solutions/2165-smallest-value-of-the-rearranged-number.js)|Medium|
 2166|[Design Bitset](./solutions/2166-design-bitset.js)|Medium|
 2167|[Minimum Time to Remove All Cars Containing Illegal Goods](./solutions/2167-minimum-time-to-remove-all-cars-containing-illegal-goods.js)|Hard|
+2169|[Count Operations to Obtain Zero](./solutions/2169-count-operations-to-obtain-zero.js)|Easy|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
diff --git a/solutions/2169-count-operations-to-obtain-zero.js b/solutions/2169-count-operations-to-obtain-zero.js
new file mode 100644
index 00000000..428bd42a
--- /dev/null
+++ b/solutions/2169-count-operations-to-obtain-zero.js
@@ -0,0 +1,34 @@
+/**
+ * 2169. Count Operations to Obtain Zero
+ * https://leetcode.com/problems/count-operations-to-obtain-zero/
+ * Difficulty: Easy
+ *
+ * You are given two non-negative integers num1 and num2.
+ *
+ * In one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1
+ * from num2.
+ * - For example, if num1 = 5 and num2 = 4, subtract num2 from num1, thus obtaining num1 = 1 and
+ *   num2 = 4. However, if num1 = 4 and num2 = 5, after one operation, num1 = 4 and num2 = 1.
+ *
+ * Return the number of operations required to make either num1 = 0 or num2 = 0.
+ */
+
+/**
+ * @param {number} num1
+ * @param {number} num2
+ * @return {number}
+ */
+var countOperations = function(num1, num2) {
+  let operations = 0;
+
+  while (num1 !== 0 && num2 !== 0) {
+    if (num1 >= num2) {
+      num1 -= num2;
+    } else {
+      num2 -= num1;
+    }
+    operations++;
+  }
+
+  return operations;
+};

From 939b77385efb954d3384f7e27038f2a67a3eaea8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 19:24:48 -0500
Subject: [PATCH 287/495] Add solution #2170

---
 README.md                                     |  3 +-
 ...perations-to-make-the-array-alternating.js | 49 +++++++++++++++++++
 2 files changed, 51 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2170-minimum-operations-to-make-the-array-alternating.js

diff --git a/README.md b/README.md
index aa6f989f..822b4e21 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,791 LeetCode solutions in JavaScript
+# 1,792 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1661,6 +1661,7 @@
 2166|[Design Bitset](./solutions/2166-design-bitset.js)|Medium|
 2167|[Minimum Time to Remove All Cars Containing Illegal Goods](./solutions/2167-minimum-time-to-remove-all-cars-containing-illegal-goods.js)|Hard|
 2169|[Count Operations to Obtain Zero](./solutions/2169-count-operations-to-obtain-zero.js)|Easy|
+2170|[Minimum Operations to Make the Array Alternating](./solutions/2170-minimum-operations-to-make-the-array-alternating.js)|Medium|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
diff --git a/solutions/2170-minimum-operations-to-make-the-array-alternating.js b/solutions/2170-minimum-operations-to-make-the-array-alternating.js
new file mode 100644
index 00000000..770b6d62
--- /dev/null
+++ b/solutions/2170-minimum-operations-to-make-the-array-alternating.js
@@ -0,0 +1,49 @@
+/**
+ * 2170. Minimum Operations to Make the Array Alternating
+ * https://leetcode.com/problems/minimum-operations-to-make-the-array-alternating/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array nums consisting of n positive integers.
+ *
+ * The array nums is called alternating if:
+ * - nums[i - 2] == nums[i], where 2 <= i <= n - 1.
+ * - nums[i - 1] != nums[i], where 1 <= i <= n - 1.
+ *
+ * In one operation, you can choose an index i and change nums[i] into any positive integer.
+ *
+ * Return the minimum number of operations required to make the array alternating.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimumOperations = function(nums) {
+  const evenFreq = new Map();
+  const oddFreq = new Map();
+
+  if (nums.length <= 1) return 0;
+  for (let i = 0; i < nums.length; i++) {
+    if (i % 2 === 0) {
+      evenFreq.set(nums[i], (evenFreq.get(nums[i]) || 0) + 1);
+    } else {
+      oddFreq.set(nums[i], (oddFreq.get(nums[i]) || 0) + 1);
+    }
+  }
+
+  const evenTop = [...evenFreq.entries()].sort((a, b) => b[1] - a[1]).slice(0, 2);
+  const oddTop = [...oddFreq.entries()].sort((a, b) => b[1] - a[1]).slice(0, 2);
+  const evenTotal = Math.ceil(nums.length / 2);
+  const oddTotal = Math.floor(nums.length / 2);
+  let minOps = nums.length;
+
+  for (const [evenNum, evenCount] of evenTop.length ? evenTop : [[0, 0]]) {
+    for (const [oddNum, oddCount] of oddTop.length ? oddTop : [[0, 0]]) {
+      if (evenNum !== oddNum || evenNum === 0) {
+        minOps = Math.min(minOps, (evenTotal - evenCount) + (oddTotal - oddCount));
+      }
+    }
+  }
+
+  return minOps === nums.length ? Math.min(evenTotal, oddTotal) : minOps;
+};

From bbe10f7b2a71880e8783fb60cc5a00a23d010992 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 19:25:56 -0500
Subject: [PATCH 288/495] Add solution #2171

---
 README.md                                     |  3 +-
 ...-removing-minimum-number-of-magic-beans.js | 33 +++++++++++++++++++
 2 files changed, 35 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2171-removing-minimum-number-of-magic-beans.js

diff --git a/README.md b/README.md
index 822b4e21..fe0b988c 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,792 LeetCode solutions in JavaScript
+# 1,793 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1662,6 +1662,7 @@
 2167|[Minimum Time to Remove All Cars Containing Illegal Goods](./solutions/2167-minimum-time-to-remove-all-cars-containing-illegal-goods.js)|Hard|
 2169|[Count Operations to Obtain Zero](./solutions/2169-count-operations-to-obtain-zero.js)|Easy|
 2170|[Minimum Operations to Make the Array Alternating](./solutions/2170-minimum-operations-to-make-the-array-alternating.js)|Medium|
+2171|[Removing Minimum Number of Magic Beans](./solutions/2171-removing-minimum-number-of-magic-beans.js)|Medium|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
diff --git a/solutions/2171-removing-minimum-number-of-magic-beans.js b/solutions/2171-removing-minimum-number-of-magic-beans.js
new file mode 100644
index 00000000..23fd2236
--- /dev/null
+++ b/solutions/2171-removing-minimum-number-of-magic-beans.js
@@ -0,0 +1,33 @@
+/**
+ * 2171. Removing Minimum Number of Magic Beans
+ * https://leetcode.com/problems/removing-minimum-number-of-magic-beans/
+ * Difficulty: Medium
+ *
+ * You are given an array of positive integers beans, where each integer represents the number
+ * of magic beans found in a particular magic bag.
+ *
+ * Remove any number of beans (possibly none) from each bag such that the number of beans in
+ * each remaining non-empty bag (still containing at least one bean) is equal. Once a bean
+ * has been removed from a bag, you are not allowed to return it to any of the bags.
+ *
+ * Return the minimum number of magic beans that you have to remove.
+ */
+
+/**
+ * @param {number[]} beans
+ * @return {number}
+ */
+var minimumRemoval = function(beans) {
+  const sortedBeans = beans.sort((a, b) => a - b);
+  const totalBeans = sortedBeans.reduce((sum, bean) => sum + bean, 0);
+  let result = totalBeans;
+  let remaining = totalBeans;
+
+  for (let i = 0; i < sortedBeans.length; i++) {
+    remaining -= sortedBeans[i];
+    const equalBags = sortedBeans.length - i;
+    result = Math.min(result, totalBeans - sortedBeans[i] * equalBags);
+  }
+
+  return result;
+};

From 0b09cc8e2097b96bfbd7c5421a0a564cc694c235 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 19:27:25 -0500
Subject: [PATCH 289/495] Add solution #2172

---
 README.md                                  |  3 +-
 solutions/2172-maximum-and-sum-of-array.js | 46 ++++++++++++++++++++++
 2 files changed, 48 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2172-maximum-and-sum-of-array.js

diff --git a/README.md b/README.md
index fe0b988c..821db657 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,793 LeetCode solutions in JavaScript
+# 1,794 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1663,6 +1663,7 @@
 2169|[Count Operations to Obtain Zero](./solutions/2169-count-operations-to-obtain-zero.js)|Easy|
 2170|[Minimum Operations to Make the Array Alternating](./solutions/2170-minimum-operations-to-make-the-array-alternating.js)|Medium|
 2171|[Removing Minimum Number of Magic Beans](./solutions/2171-removing-minimum-number-of-magic-beans.js)|Medium|
+2172|[Maximum AND Sum of Array](./solutions/2172-maximum-and-sum-of-array.js)|Hard|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
diff --git a/solutions/2172-maximum-and-sum-of-array.js b/solutions/2172-maximum-and-sum-of-array.js
new file mode 100644
index 00000000..6c9020d6
--- /dev/null
+++ b/solutions/2172-maximum-and-sum-of-array.js
@@ -0,0 +1,46 @@
+/**
+ * 2172. Maximum AND Sum of Array
+ * https://leetcode.com/problems/maximum-and-sum-of-array/
+ * Difficulty: Hard
+ *
+ * You are given an integer array nums of length n and an integer numSlots such that
+ * 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots.
+ *
+ * You have to place all n integers into the slots such that each slot contains at most
+ * two numbers. The AND sum of a given placement is the sum of the bitwise AND of every
+ * number with its respective slot number.
+ * - For example, the AND sum of placing the numbers [1, 3] into slot 1 and [4, 6] into
+ *   slot 2 is equal to (1 AND 1) + (3 AND 1) + (4 AND 2) + (6 AND 2) = 1 + 1 + 0 + 2 = 4.
+ *
+ * Return the maximum possible AND sum of nums given numSlots slots.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} numSlots
+ * @return {number}
+ */
+var maximumANDSum = function(nums, numSlots) {
+  const map = new Map();
+
+  return dp(0, new Array(numSlots).fill(0));
+
+  function dp(index, slots) {
+    if (index >= nums.length) return 0;
+
+    const key = `${index},${slots.join(',')}`;
+    if (map.has(key)) return map.get(key);
+
+    let result = 0;
+    for (let i = 0; i < numSlots; i++) {
+      if (slots[i] < 2) {
+        slots[i]++;
+        result = Math.max(result, (nums[index] & (i + 1)) + dp(index + 1, slots));
+        slots[i]--;
+      }
+    }
+
+    map.set(key, result);
+    return result;
+  }
+};

From 82261b0781a2e5eaa32fdeb7882da47d9a39bfc2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 19:28:25 -0500
Subject: [PATCH 290/495] Add solution #2177

---
 README.md                                     |  3 ++-
 ...ive-integers-that-sum-to-a-given-number.js | 19 +++++++++++++++++++
 2 files changed, 21 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2177-find-three-consecutive-integers-that-sum-to-a-given-number.js

diff --git a/README.md b/README.md
index 821db657..9ce8f877 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,794 LeetCode solutions in JavaScript
+# 1,795 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1665,6 +1665,7 @@
 2171|[Removing Minimum Number of Magic Beans](./solutions/2171-removing-minimum-number-of-magic-beans.js)|Medium|
 2172|[Maximum AND Sum of Array](./solutions/2172-maximum-and-sum-of-array.js)|Hard|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
+2177|[Find Three Consecutive Integers That Sum to a Given Number](./solutions/2177-find-three-consecutive-integers-that-sum-to-a-given-number.js)|Medium|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
diff --git a/solutions/2177-find-three-consecutive-integers-that-sum-to-a-given-number.js b/solutions/2177-find-three-consecutive-integers-that-sum-to-a-given-number.js
new file mode 100644
index 00000000..f77b1221
--- /dev/null
+++ b/solutions/2177-find-three-consecutive-integers-that-sum-to-a-given-number.js
@@ -0,0 +1,19 @@
+/**
+ * 2177. Find Three Consecutive Integers That Sum to a Given Number
+ * https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/
+ * Difficulty: Medium
+ *
+ * Given an integer num, return three consecutive integers (as a sorted array) that sum to num.
+ * If num cannot be expressed as the sum of three consecutive integers, return an empty array.
+ */
+
+/**
+ * @param {number} num
+ * @return {number[]}
+ */
+var sumOfThree = function(num) {
+  if (num % 3 !== 0) return [];
+
+  const middle = num / 3;
+  return [middle - 1, middle, middle + 1];
+};

From c4ece59b84dd86e47655d0cd53b7bc0e44cf74bf Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 19:30:28 -0500
Subject: [PATCH 291/495] Add solution #2178

---
 README.md                                     |  3 +-
 ...maximum-split-of-positive-even-integers.js | 40 +++++++++++++++++++
 2 files changed, 42 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2178-maximum-split-of-positive-even-integers.js

diff --git a/README.md b/README.md
index 9ce8f877..f7a25ce5 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,795 LeetCode solutions in JavaScript
+# 1,796 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1666,6 +1666,7 @@
 2172|[Maximum AND Sum of Array](./solutions/2172-maximum-and-sum-of-array.js)|Hard|
 2176|[Count Equal and Divisible Pairs in an Array](./solutions/2176-count-equal-and-divisible-pairs-in-an-array.js)|Easy|
 2177|[Find Three Consecutive Integers That Sum to a Given Number](./solutions/2177-find-three-consecutive-integers-that-sum-to-a-given-number.js)|Medium|
+2178|[Maximum Split of Positive Even Integers](./solutions/2178-maximum-split-of-positive-even-integers.js)|Medium|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
diff --git a/solutions/2178-maximum-split-of-positive-even-integers.js b/solutions/2178-maximum-split-of-positive-even-integers.js
new file mode 100644
index 00000000..602b2ab7
--- /dev/null
+++ b/solutions/2178-maximum-split-of-positive-even-integers.js
@@ -0,0 +1,40 @@
+/**
+ * 2178. Maximum Split of Positive Even Integers
+ * https://leetcode.com/problems/maximum-split-of-positive-even-integers/
+ * Difficulty: Medium
+ *
+ * You are given an integer finalSum. Split it into a sum of a maximum number of unique
+ * positive even integers.
+ * - For example, given finalSum = 12, the following splits are valid (unique positive even
+ *   integers summing up to finalSum): (12), (2 + 10), (2 + 4 + 6), and (4 + 8). Among them,
+ *   (2 + 4 + 6) contains the maximum number of integers. Note that finalSum cannot be split
+ *   into (2 + 2 + 4 + 4) as all the numbers should be unique.
+ *
+ * Return a list of integers that represent a valid split containing a maximum number of
+ * integers. If no valid split exists for finalSum, return an empty list. You may return
+ * the integers in any order.
+ */
+
+/**
+ * @param {number} finalSum
+ * @return {number[]}
+ */
+var maximumEvenSplit = function(finalSum) {
+  if (finalSum % 2 !== 0) return [];
+
+  const result = [];
+  let current = 2;
+  let remaining = finalSum;
+
+  while (remaining >= current) {
+    if (remaining - current <= current) {
+      result.push(remaining);
+      return result;
+    }
+    result.push(current);
+    remaining -= current;
+    current += 2;
+  }
+
+  return result;
+};

From 56ee4f0e5cb571732447316ff5467df0d85b956c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 19:31:37 -0500
Subject: [PATCH 292/495] Add solution #2180

---
 README.md                                     |  3 +-
 ...2180-count-integers-with-even-digit-sum.js | 32 +++++++++++++++++++
 2 files changed, 34 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2180-count-integers-with-even-digit-sum.js

diff --git a/README.md b/README.md
index f7a25ce5..b8019b07 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,796 LeetCode solutions in JavaScript
+# 1,797 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1668,6 +1668,7 @@
 2177|[Find Three Consecutive Integers That Sum to a Given Number](./solutions/2177-find-three-consecutive-integers-that-sum-to-a-given-number.js)|Medium|
 2178|[Maximum Split of Positive Even Integers](./solutions/2178-maximum-split-of-positive-even-integers.js)|Medium|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
+2180|[Count Integers With Even Digit Sum](./solutions/2180-count-integers-with-even-digit-sum.js)|Easy|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
diff --git a/solutions/2180-count-integers-with-even-digit-sum.js b/solutions/2180-count-integers-with-even-digit-sum.js
new file mode 100644
index 00000000..c1a077e6
--- /dev/null
+++ b/solutions/2180-count-integers-with-even-digit-sum.js
@@ -0,0 +1,32 @@
+/**
+ * 2180. Count Integers With Even Digit Sum
+ * https://leetcode.com/problems/count-integers-with-even-digit-sum/
+ * Difficulty: Easy
+ *
+ * Given a positive integer num, return the number of positive integers less than or equal to num
+ * whose digit sums are even.
+ *
+ * The digit sum of a positive integer is the sum of all its digits.
+ */
+
+/**
+ * @param {number} num
+ * @return {number}
+ */
+var countEven = function(num) {
+  let result = 0;
+
+  for (let i = 1; i <= num; i++) {
+    let sum = 0;
+    let current = i;
+    while (current > 0) {
+      sum += current % 10;
+      current = Math.floor(current / 10);
+    }
+    if (sum % 2 === 0) {
+      result++;
+    }
+  }
+
+  return result;
+};

From f30729031b120d769ef1700e6dc9fcfbf7439fec Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 19:32:44 -0500
Subject: [PATCH 293/495] Add solution #2181

---
 README.md                                     |  3 +-
 .../2181-merge-nodes-in-between-zeros.js      | 46 +++++++++++++++++++
 2 files changed, 48 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2181-merge-nodes-in-between-zeros.js

diff --git a/README.md b/README.md
index b8019b07..a6e929d4 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,797 LeetCode solutions in JavaScript
+# 1,798 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1669,6 +1669,7 @@
 2178|[Maximum Split of Positive Even Integers](./solutions/2178-maximum-split-of-positive-even-integers.js)|Medium|
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
 2180|[Count Integers With Even Digit Sum](./solutions/2180-count-integers-with-even-digit-sum.js)|Easy|
+2181|[Merge Nodes in Between Zeros](./solutions/2181-merge-nodes-in-between-zeros.js)|Medium|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
diff --git a/solutions/2181-merge-nodes-in-between-zeros.js b/solutions/2181-merge-nodes-in-between-zeros.js
new file mode 100644
index 00000000..f5993c27
--- /dev/null
+++ b/solutions/2181-merge-nodes-in-between-zeros.js
@@ -0,0 +1,46 @@
+/**
+ * 2181. Merge Nodes in Between Zeros
+ * https://leetcode.com/problems/merge-nodes-in-between-zeros/
+ * Difficulty: Medium
+ *
+ * You are given the head of a linked list, which contains a series of integers separated
+ * by 0's. The beginning and end of the linked list will have Node.val == 0.
+ *
+ * For every two consecutive 0's, merge all the nodes lying in between them into a single
+ * node whose value is the sum of all the merged nodes. The modified list should not contain
+ * any 0's.
+ *
+ * Return the head of the modified linked list.
+ */
+
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val, next) {
+ *     this.val = (val===undefined ? 0 : val)
+ *     this.next = (next===undefined ? null : next)
+ * }
+ */
+/**
+ * @param {ListNode} head
+ * @return {ListNode}
+ */
+var mergeNodes = function(head) {
+  const result = new ListNode(0);
+  let current = result;
+  let sum = 0;
+
+  head = head.next;
+
+  while (head) {
+    if (head.val === 0) {
+      current.next = new ListNode(sum);
+      current = current.next;
+      sum = 0;
+    } else {
+      sum += head.val;
+    }
+    head = head.next;
+  }
+
+  return result.next;
+};

From bafa902146d4e2564d76fb6ebdbbfaa275acac39 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 19:33:57 -0500
Subject: [PATCH 294/495] Add solution #2183

---
 README.md                                     |  3 +-
 .../2183-count-array-pairs-divisible-by-k.js  | 39 +++++++++++++++++++
 2 files changed, 41 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2183-count-array-pairs-divisible-by-k.js

diff --git a/README.md b/README.md
index a6e929d4..a3e0141d 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,798 LeetCode solutions in JavaScript
+# 1,799 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1670,6 +1670,7 @@
 2179|[Count Good Triplets in an Array](./solutions/2179-count-good-triplets-in-an-array.js)|Hard|
 2180|[Count Integers With Even Digit Sum](./solutions/2180-count-integers-with-even-digit-sum.js)|Easy|
 2181|[Merge Nodes in Between Zeros](./solutions/2181-merge-nodes-in-between-zeros.js)|Medium|
+2183|[Count Array Pairs Divisible by K](./solutions/2183-count-array-pairs-divisible-by-k.js)|Hard|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
diff --git a/solutions/2183-count-array-pairs-divisible-by-k.js b/solutions/2183-count-array-pairs-divisible-by-k.js
new file mode 100644
index 00000000..96f923c4
--- /dev/null
+++ b/solutions/2183-count-array-pairs-divisible-by-k.js
@@ -0,0 +1,39 @@
+/**
+ * 2183. Count Array Pairs Divisible by K
+ * https://leetcode.com/problems/count-array-pairs-divisible-by-k/
+ * Difficulty: Hard
+ *
+ * Given a 0-indexed integer array nums of length n and an integer k, return the number
+ * of pairs (i, j) such that:
+ * - 0 <= i < j <= n - 1 and
+ * - nums[i] * nums[j] is divisible by k.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var countPairs = function(nums, k) {
+  const map = new Map();
+  let pairs = 0;
+
+  for (const num of nums) {
+    const gcd1 = gcd(num, k);
+    for (const [gcd2, count] of map) {
+      if ((gcd1 * gcd2) % k === 0) {
+        pairs += count;
+      }
+    }
+    map.set(gcd1, (map.get(gcd1) || 0) + 1);
+  }
+
+  return pairs;
+};
+
+function gcd(a, b) {
+  while (b) {
+    [a, b] = [b, a % b];
+  }
+  return a;
+}

From 17517e48ff39964c566b44b3ff155521f57028f7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 19:35:05 -0500
Subject: [PATCH 295/495] Add solution #2186

---
 README.md                                     |  3 +-
 ...of-steps-to-make-two-strings-anagram-ii.js | 36 +++++++++++++++++++
 2 files changed, 38 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2186-minimum-number-of-steps-to-make-two-strings-anagram-ii.js

diff --git a/README.md b/README.md
index a3e0141d..a85496e7 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,799 LeetCode solutions in JavaScript
+# 1,800 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1672,6 +1672,7 @@
 2181|[Merge Nodes in Between Zeros](./solutions/2181-merge-nodes-in-between-zeros.js)|Medium|
 2183|[Count Array Pairs Divisible by K](./solutions/2183-count-array-pairs-divisible-by-k.js)|Hard|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
+2186|[Minimum Number of Steps to Make Two Strings Anagram II](./solutions/2186-minimum-number-of-steps-to-make-two-strings-anagram-ii.js)|Medium|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
diff --git a/solutions/2186-minimum-number-of-steps-to-make-two-strings-anagram-ii.js b/solutions/2186-minimum-number-of-steps-to-make-two-strings-anagram-ii.js
new file mode 100644
index 00000000..2501cbd5
--- /dev/null
+++ b/solutions/2186-minimum-number-of-steps-to-make-two-strings-anagram-ii.js
@@ -0,0 +1,36 @@
+/**
+ * 2186. Minimum Number of Steps to Make Two Strings Anagram II
+ * https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram-ii/
+ * Difficulty: Medium
+ *
+ * You are given two strings s and t. In one step, you can append any character to either s or t.
+ *
+ * Return the minimum number of steps to make s and t anagrams of each other.
+ *
+ * An anagram of a string is a string that contains the same characters with a different (or the
+ * same) ordering.
+ */
+
+/**
+ * @param {string} s
+ * @param {string} t
+ * @return {number}
+ */
+var minSteps = function(s, t) {
+  const charCount = new Array(26).fill(0);
+
+  for (const char of s) {
+    charCount[char.charCodeAt(0) - 97]++;
+  }
+
+  for (const char of t) {
+    charCount[char.charCodeAt(0) - 97]--;
+  }
+
+  let result = 0;
+  for (const count of charCount) {
+    result += Math.abs(count);
+  }
+
+  return result;
+};

From 37c1725537c3bec63a2a578e967ded6b18815dbd Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 23:21:39 -0500
Subject: [PATCH 296/495] Add solution #2187

---
 README.md                                     |  3 +-
 .../2187-minimum-time-to-complete-trips.js    | 39 +++++++++++++++++++
 2 files changed, 41 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2187-minimum-time-to-complete-trips.js

diff --git a/README.md b/README.md
index a85496e7..350b9d19 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,800 LeetCode solutions in JavaScript
+# 1,801 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1673,6 +1673,7 @@
 2183|[Count Array Pairs Divisible by K](./solutions/2183-count-array-pairs-divisible-by-k.js)|Hard|
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
 2186|[Minimum Number of Steps to Make Two Strings Anagram II](./solutions/2186-minimum-number-of-steps-to-make-two-strings-anagram-ii.js)|Medium|
+2187|[Minimum Time to Complete Trips](./solutions/2187-minimum-time-to-complete-trips.js)|Medium|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
diff --git a/solutions/2187-minimum-time-to-complete-trips.js b/solutions/2187-minimum-time-to-complete-trips.js
new file mode 100644
index 00000000..305712f8
--- /dev/null
+++ b/solutions/2187-minimum-time-to-complete-trips.js
@@ -0,0 +1,39 @@
+/**
+ * 2187. Minimum Time to Complete Trips
+ * https://leetcode.com/problems/minimum-time-to-complete-trips/
+ * Difficulty: Medium
+ *
+ * You are given an array time where time[i] denotes the time taken by the ith bus to complete
+ * one trip.
+ *
+ * Each bus can make multiple trips successively; that is, the next trip can start immediately
+ * after completing the current trip. Also, each bus operates independently; that is, the trips
+ * of one bus do not influence the trips of any other bus.
+ *
+ * You are also given an integer totalTrips, which denotes the number of trips all buses should
+ * make in total. Return the minimum time required for all buses to complete at least totalTrips
+ * trips.
+ */
+
+/**
+ * @param {number[]} time
+ * @param {number} totalTrips
+ * @return {number}
+ */
+var minimumTime = function(time, totalTrips) {
+  let left = 1;
+  let right = Math.min(...time) * totalTrips;
+
+  while (left < right) {
+    const mid = Math.floor((left + right) / 2);
+    const trips = time.reduce((sum, t) => sum + Math.floor(mid / t), 0);
+
+    if (trips >= totalTrips) {
+      right = mid;
+    } else {
+      left = mid + 1;
+    }
+  }
+
+  return left;
+};

From 5c3e0d28cd672dacd4bacdd83209e9cf34b901d1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 23:23:20 -0500
Subject: [PATCH 297/495] Add solution #2188

---
 README.md                                     |  3 +-
 .../2188-minimum-time-to-finish-the-race.js   | 56 +++++++++++++++++++
 2 files changed, 58 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2188-minimum-time-to-finish-the-race.js

diff --git a/README.md b/README.md
index 350b9d19..bb8210f1 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,801 LeetCode solutions in JavaScript
+# 1,802 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1674,6 +1674,7 @@
 2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
 2186|[Minimum Number of Steps to Make Two Strings Anagram II](./solutions/2186-minimum-number-of-steps-to-make-two-strings-anagram-ii.js)|Medium|
 2187|[Minimum Time to Complete Trips](./solutions/2187-minimum-time-to-complete-trips.js)|Medium|
+2188|[Minimum Time to Finish the Race](./solutions/2188-minimum-time-to-finish-the-race.js)|Hard|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
diff --git a/solutions/2188-minimum-time-to-finish-the-race.js b/solutions/2188-minimum-time-to-finish-the-race.js
new file mode 100644
index 00000000..fbce3d25
--- /dev/null
+++ b/solutions/2188-minimum-time-to-finish-the-race.js
@@ -0,0 +1,56 @@
+/**
+ * 2188. Minimum Time to Finish the Race
+ * https://leetcode.com/problems/minimum-time-to-finish-the-race/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed 2D integer array tires where tires[i] = [fi, ri] indicates that
+ * the ith tire can finish its xth successive lap in fi * ri(x-1) seconds.
+ * - For example, if fi = 3 and ri = 2, then the tire would finish its 1st lap in 3 seconds,
+ *   its 2nd lap in 3 * 2 = 6 seconds, its 3rd lap in 3 * 22 = 12 seconds, etc.
+ *
+ * You are also given an integer changeTime and an integer numLaps.
+ *
+ * The race consists of numLaps laps and you may start the race with any tire. You have an
+ * unlimited supply of each tire and after every lap, you may change to any given tire (including
+ * the current tire type) if you wait changeTime seconds.
+ *
+ * Return the minimum time to finish the race.
+ */
+
+/**
+ * @param {number[][]} tires
+ * @param {number} changeTime
+ * @param {number} numLaps
+ * @return {number}
+ */
+var minimumFinishTime = function(tires, changeTime, numLaps) {
+  const minTimes = new Array(18).fill(Infinity);
+  const bestTime = new Array(numLaps + 1).fill(Infinity);
+
+  for (const [baseTime, multiplier] of tires) {
+    let currentTime = baseTime;
+    let totalTime = baseTime;
+
+    for (let lap = 1; lap <= Math.min(numLaps, 17); lap++) {
+      if (currentTime > changeTime + baseTime) break;
+      minTimes[lap] = Math.min(minTimes[lap], totalTime);
+      currentTime *= multiplier;
+      totalTime += currentTime;
+    }
+  }
+
+  bestTime[0] = 0;
+
+  for (let lap = 1; lap <= numLaps; lap++) {
+    for (let prev = 1; prev <= Math.min(lap, 17); prev++) {
+      if (minTimes[prev] !== Infinity) {
+        bestTime[lap] = Math.min(
+          bestTime[lap],
+          bestTime[lap - prev] + minTimes[prev] + (lap === prev ? 0 : changeTime)
+        );
+      }
+    }
+  }
+
+  return bestTime[numLaps];
+};

From 3772d65f3efc1c9be2f91a9a16cfeaf1279310e3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 23:25:29 -0500
Subject: [PATCH 298/495] Add solution #2190

---
 README.md                                     |  3 +-
 ...equent-number-following-key-in-an-array.js | 43 +++++++++++++++++++
 2 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2190-most-frequent-number-following-key-in-an-array.js

diff --git a/README.md b/README.md
index bb8210f1..dc946658 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,802 LeetCode solutions in JavaScript
+# 1,803 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1675,6 +1675,7 @@
 2186|[Minimum Number of Steps to Make Two Strings Anagram II](./solutions/2186-minimum-number-of-steps-to-make-two-strings-anagram-ii.js)|Medium|
 2187|[Minimum Time to Complete Trips](./solutions/2187-minimum-time-to-complete-trips.js)|Medium|
 2188|[Minimum Time to Finish the Race](./solutions/2188-minimum-time-to-finish-the-race.js)|Hard|
+2190|[Most Frequent Number Following Key In an Array](./solutions/2190-most-frequent-number-following-key-in-an-array.js)|Easy|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
diff --git a/solutions/2190-most-frequent-number-following-key-in-an-array.js b/solutions/2190-most-frequent-number-following-key-in-an-array.js
new file mode 100644
index 00000000..b5485503
--- /dev/null
+++ b/solutions/2190-most-frequent-number-following-key-in-an-array.js
@@ -0,0 +1,43 @@
+/**
+ * 2190. Most Frequent Number Following Key In an Array
+ * https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums. You are also given an integer key, which is
+ * present in nums.
+ *
+ * For every unique integer target in nums, count the number of times target immediately follows
+ * an occurrence of key in nums. In other words, count the number of indices i such that:
+ * - 0 <= i <= nums.length - 2,
+ * - nums[i] == key and,
+ * - nums[i + 1] == target.
+ *
+ * Return the target with the maximum count. The test cases will be generated such that the target
+ * with maximum count is unique.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} key
+ * @return {number}
+ */
+var mostFrequent = function(nums, key) {
+  const frequency = new Map();
+  let maxCount = 0;
+  let result = 0;
+
+  for (let i = 0; i < nums.length - 1; i++) {
+    if (nums[i] === key) {
+      const target = nums[i + 1];
+      const count = (frequency.get(target) || 0) + 1;
+      frequency.set(target, count);
+
+      if (count > maxCount) {
+        maxCount = count;
+        result = target;
+      }
+    }
+  }
+
+  return result;
+};

From 384eb223846c285fc9f95bd77027f0db9a891413 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 23:29:57 -0500
Subject: [PATCH 299/495] Add solution #2191

---
 README.md                                  |  3 +-
 solutions/2191-sort-the-jumbled-numbers.js | 53 ++++++++++++++++++++++
 2 files changed, 55 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2191-sort-the-jumbled-numbers.js

diff --git a/README.md b/README.md
index dc946658..c16f399b 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,803 LeetCode solutions in JavaScript
+# 1,804 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1676,6 +1676,7 @@
 2187|[Minimum Time to Complete Trips](./solutions/2187-minimum-time-to-complete-trips.js)|Medium|
 2188|[Minimum Time to Finish the Race](./solutions/2188-minimum-time-to-finish-the-race.js)|Hard|
 2190|[Most Frequent Number Following Key In an Array](./solutions/2190-most-frequent-number-following-key-in-an-array.js)|Easy|
+2191|[Sort the Jumbled Numbers](./solutions/2191-sort-the-jumbled-numbers.js)|Medium|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
diff --git a/solutions/2191-sort-the-jumbled-numbers.js b/solutions/2191-sort-the-jumbled-numbers.js
new file mode 100644
index 00000000..490e1d17
--- /dev/null
+++ b/solutions/2191-sort-the-jumbled-numbers.js
@@ -0,0 +1,53 @@
+/**
+ * 2191. Sort the Jumbled Numbers
+ * https://leetcode.com/problems/sort-the-jumbled-numbers/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array mapping which represents the mapping rule of a shuffled
+ * decimal system. mapping[i] = j means digit i should be mapped to digit j in this system.
+ *
+ * The mapped value of an integer is the new integer obtained by replacing each occurrence of digit
+ * i in the integer with mapping[i] for all 0 <= i <= 9.
+ *
+ * You are also given another integer array nums. Return the array nums sorted in non-decreasing
+ * order based on the mapped values of its elements.
+ *
+ * Notes:
+ * - Elements with the same mapped values should appear in the same relative order as in the input.
+ * - The elements of nums should only be sorted based on their mapped values and not be replaced by
+ *   them.
+ */
+
+/**
+ * @param {number[]} mapping
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var sortJumbled = function(mapping, nums) {
+  const mapped = nums.map((num, index) => {
+    let mappedNum = 0;
+    let temp = num;
+
+    if (temp === 0) {
+      mappedNum = mapping[0];
+    } else {
+      const digits = [];
+      while (temp > 0) {
+        digits.push(mapping[temp % 10]);
+        temp = Math.floor(temp / 10);
+      }
+      while (digits.length > 0) {
+        mappedNum = mappedNum * 10 + digits.pop();
+      }
+    }
+
+    return { original: num, mapped: mappedNum, index };
+  });
+
+  mapped.sort((a, b) => {
+    if (a.mapped === b.mapped) return a.index - b.index;
+    return a.mapped - b.mapped;
+  });
+
+  return mapped.map(item => item.original);
+};

From ca673593ad0c12fa50bc8df093f32b79279d1dd8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 14 May 2025 23:33:08 -0500
Subject: [PATCH 300/495] Add solution #2192

---
 README.md                                     |  3 +-
 ...s-of-a-node-in-a-directed-acyclic-graph.js | 48 +++++++++++++++++++
 2 files changed, 50 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.js

diff --git a/README.md b/README.md
index c16f399b..1679c28a 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,804 LeetCode solutions in JavaScript
+# 1,805 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1677,6 +1677,7 @@
 2188|[Minimum Time to Finish the Race](./solutions/2188-minimum-time-to-finish-the-race.js)|Hard|
 2190|[Most Frequent Number Following Key In an Array](./solutions/2190-most-frequent-number-following-key-in-an-array.js)|Easy|
 2191|[Sort the Jumbled Numbers](./solutions/2191-sort-the-jumbled-numbers.js)|Medium|
+2192|[All Ancestors of a Node in a Directed Acyclic Graph](./solutions/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.js)|Medium|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
diff --git a/solutions/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.js b/solutions/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.js
new file mode 100644
index 00000000..9eeb8509
--- /dev/null
+++ b/solutions/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.js
@@ -0,0 +1,48 @@
+/**
+ * 2192. All Ancestors of a Node in a Directed Acyclic Graph
+ * https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/
+ * Difficulty: Medium
+ *
+ * You are given a positive integer n representing the number of nodes of a Directed Acyclic
+ * Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive).
+ *
+ * You are also given a 2D integer array edges, where edges[i] = [fromi, toi] denotes that there
+ * is a unidirectional edge from fromi to toi in the graph.
+ *
+ * Return a list answer, where answer[i] is the list of ancestors of the ith node, sorted in
+ * ascending order.
+ *
+ * A node u is an ancestor of another node v if u can reach v via a set of edges.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @return {number[][]}
+ */
+var getAncestors = function(n, edges) {
+  const graph = Array.from({ length: n }, () => []);
+  const ancestors = Array.from({ length: n }, () => new Set());
+
+  for (const [from, to] of edges) {
+    graph[to].push(from);
+  }
+
+  for (let i = 0; i < n; i++) {
+    findAncestors(i);
+  }
+
+  return ancestors.map(set => [...set].sort((a, b) => a - b));
+
+  function findAncestors(node) {
+    if (ancestors[node].size > 0) return;
+
+    for (const parent of graph[node]) {
+      ancestors[node].add(parent);
+      findAncestors(parent);
+      for (const ancestor of ancestors[parent]) {
+        ancestors[node].add(ancestor);
+      }
+    }
+  }
+};

From 9a6af5df8e74e09e508cc20362c59aa93974d73b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 15 May 2025 00:19:40 -0500
Subject: [PATCH 301/495] Add solution #2193

---
 README.md                                     |  3 +-
 ...imum-number-of-moves-to-make-palindrome.js | 42 +++++++++++++++++++
 2 files changed, 44 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2193-minimum-number-of-moves-to-make-palindrome.js

diff --git a/README.md b/README.md
index 1679c28a..1e7f1fdf 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,805 LeetCode solutions in JavaScript
+# 1,806 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1678,6 +1678,7 @@
 2190|[Most Frequent Number Following Key In an Array](./solutions/2190-most-frequent-number-following-key-in-an-array.js)|Easy|
 2191|[Sort the Jumbled Numbers](./solutions/2191-sort-the-jumbled-numbers.js)|Medium|
 2192|[All Ancestors of a Node in a Directed Acyclic Graph](./solutions/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.js)|Medium|
+2193|[Minimum Number of Moves to Make Palindrome](./solutions/2193-minimum-number-of-moves-to-make-palindrome.js)|Hard|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
diff --git a/solutions/2193-minimum-number-of-moves-to-make-palindrome.js b/solutions/2193-minimum-number-of-moves-to-make-palindrome.js
new file mode 100644
index 00000000..c25800e2
--- /dev/null
+++ b/solutions/2193-minimum-number-of-moves-to-make-palindrome.js
@@ -0,0 +1,42 @@
+/**
+ * 2193. Minimum Number of Moves to Make Palindrome
+ * https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/
+ * Difficulty: Hard
+ *
+ * You are given a string s consisting only of lowercase English letters.
+ *
+ * In one move, you can select any two adjacent characters of s and swap them.
+ *
+ * Return the minimum number of moves needed to make s a palindrome.
+ *
+ * Note that the input will be generated such that s can always be converted to a palindrome.
+ */
+
+/**
+* @param {string} s
+* @return {number}
+*/
+var minMovesToMakePalindrome = function(s) {
+  const chars = s.split('');
+  let moves = 0;
+
+  while (chars.length > 1) {
+    const matchIndex = chars.lastIndexOf(chars[0]);
+
+    if (matchIndex === 0) {
+      const middlePos = Math.floor(chars.length / 2);
+      moves += middlePos;
+      chars.splice(0, 1);
+    } else {
+      for (let i = matchIndex; i < chars.length - 1; i++) {
+        [chars[i], chars[i + 1]] = [chars[i + 1], chars[i]];
+        moves++;
+      }
+
+      chars.pop();
+      chars.shift();
+    }
+  }
+
+  return moves;
+};

From d3f113195721db502d6e8ce3a469445e7770e4ed Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 15 May 2025 00:21:35 -0500
Subject: [PATCH 302/495] Add solution #2194

---
 README.md                                     |  3 +-
 ...2194-cells-in-a-range-on-an-excel-sheet.js | 37 +++++++++++++++++++
 2 files changed, 39 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2194-cells-in-a-range-on-an-excel-sheet.js

diff --git a/README.md b/README.md
index 1e7f1fdf..d572b7c9 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,806 LeetCode solutions in JavaScript
+# 1,807 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1679,6 +1679,7 @@
 2191|[Sort the Jumbled Numbers](./solutions/2191-sort-the-jumbled-numbers.js)|Medium|
 2192|[All Ancestors of a Node in a Directed Acyclic Graph](./solutions/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.js)|Medium|
 2193|[Minimum Number of Moves to Make Palindrome](./solutions/2193-minimum-number-of-moves-to-make-palindrome.js)|Hard|
+2194|[Cells in a Range on an Excel Sheet](./solutions/2194-cells-in-a-range-on-an-excel-sheet.js)|Easy|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
diff --git a/solutions/2194-cells-in-a-range-on-an-excel-sheet.js b/solutions/2194-cells-in-a-range-on-an-excel-sheet.js
new file mode 100644
index 00000000..194c60cc
--- /dev/null
+++ b/solutions/2194-cells-in-a-range-on-an-excel-sheet.js
@@ -0,0 +1,37 @@
+/**
+ * 2194. Cells in a Range on an Excel Sheet
+ * https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/
+ * Difficulty: Easy
+ *
+ * A cell (r, c) of an excel sheet is represented as a string "" where:
+ * -  denotes the column number c of the cell. It is represented by alphabetical letters.
+ *   - For example, the 1st column is denoted by 'A', the 2nd by 'B', the 3rd by 'C', and so on.
+ * -  is the row number r of the cell. The rth row is represented by the integer r.
+ *   - You are given a string s in the format ":", where  represents
+ *     the column c1,  represents the row r1,  represents the column c2, and 
+ *     represents the row r2, such that r1 <= r2 and c1 <= c2.
+ *
+ * Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should
+ * be represented as strings in the format mentioned above and be sorted in non-decreasing order
+ * first by columns and then by rows.
+ */
+
+/**
+ * @param {string} s
+ * @return {string[]}
+ */
+var cellsInRange = function(s) {
+  const result = [];
+  const startCol = s.charCodeAt(0);
+  const endCol = s.charCodeAt(3);
+  const startRow = parseInt(s[1], 10);
+  const endRow = parseInt(s[4], 10);
+
+  for (let col = startCol; col <= endCol; col++) {
+    for (let row = startRow; row <= endRow; row++) {
+      result.push(String.fromCharCode(col) + row);
+    }
+  }
+
+  return result;
+};

From 8b58825a27fcee635778192e6e2b6bcaf8c12ca6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 15 May 2025 00:23:06 -0500
Subject: [PATCH 303/495] Add solution #2195

---
 README.md                                     |  3 +-
 ...2195-append-k-integers-with-minimal-sum.js | 40 +++++++++++++++++++
 2 files changed, 42 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2195-append-k-integers-with-minimal-sum.js

diff --git a/README.md b/README.md
index d572b7c9..62a0e019 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,807 LeetCode solutions in JavaScript
+# 1,808 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1680,6 +1680,7 @@
 2192|[All Ancestors of a Node in a Directed Acyclic Graph](./solutions/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.js)|Medium|
 2193|[Minimum Number of Moves to Make Palindrome](./solutions/2193-minimum-number-of-moves-to-make-palindrome.js)|Hard|
 2194|[Cells in a Range on an Excel Sheet](./solutions/2194-cells-in-a-range-on-an-excel-sheet.js)|Easy|
+2195|[Append K Integers With Minimal Sum](./solutions/2195-append-k-integers-with-minimal-sum.js)|Medium|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
diff --git a/solutions/2195-append-k-integers-with-minimal-sum.js b/solutions/2195-append-k-integers-with-minimal-sum.js
new file mode 100644
index 00000000..bc873455
--- /dev/null
+++ b/solutions/2195-append-k-integers-with-minimal-sum.js
@@ -0,0 +1,40 @@
+/**
+ * 2195. Append K Integers With Minimal Sum
+ * https://leetcode.com/problems/append-k-integers-with-minimal-sum/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums and an integer k. Append k unique positive integers that do
+ * not appear in nums to nums such that the resulting total sum is minimum.
+ *
+ * Return the sum of the k integers appended to nums.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var minimalKSum = function(nums, k) {
+  const sortedUnique = [...new Set(nums)].sort((a, b) => a - b);
+  let sum = BigInt(0);
+  let current = 1;
+  let i = 0;
+
+  while (k > 0 && i < sortedUnique.length) {
+    if (current < sortedUnique[i]) {
+      const count = Math.min(k, sortedUnique[i] - current);
+      sum += (BigInt(current) + BigInt(current + count - 1)) * BigInt(count) / BigInt(2);
+      k -= count;
+      current += count;
+    } else {
+      current = sortedUnique[i] + 1;
+      i++;
+    }
+  }
+
+  if (k > 0) {
+    sum += (BigInt(current) + BigInt(current + k - 1)) * BigInt(k) / BigInt(2);
+  }
+
+  return Number(sum);
+};

From 3571aea58fc1fc5332a35e1ce1370184fb366686 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 15 May 2025 00:24:26 -0500
Subject: [PATCH 304/495] Add solution #2196

---
 README.md                                     |  3 +-
 ...96-create-binary-tree-from-descriptions.js | 54 +++++++++++++++++++
 2 files changed, 56 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2196-create-binary-tree-from-descriptions.js

diff --git a/README.md b/README.md
index 62a0e019..da9c9883 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,808 LeetCode solutions in JavaScript
+# 1,809 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1681,6 +1681,7 @@
 2193|[Minimum Number of Moves to Make Palindrome](./solutions/2193-minimum-number-of-moves-to-make-palindrome.js)|Hard|
 2194|[Cells in a Range on an Excel Sheet](./solutions/2194-cells-in-a-range-on-an-excel-sheet.js)|Easy|
 2195|[Append K Integers With Minimal Sum](./solutions/2195-append-k-integers-with-minimal-sum.js)|Medium|
+2196|[Create Binary Tree From Descriptions](./solutions/2196-create-binary-tree-from-descriptions.js)|Medium|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
diff --git a/solutions/2196-create-binary-tree-from-descriptions.js b/solutions/2196-create-binary-tree-from-descriptions.js
new file mode 100644
index 00000000..67af6416
--- /dev/null
+++ b/solutions/2196-create-binary-tree-from-descriptions.js
@@ -0,0 +1,54 @@
+/**
+ * 2196. Create Binary Tree From Descriptions
+ * https://leetcode.com/problems/create-binary-tree-from-descriptions/
+ * Difficulty: Medium
+ *
+ * You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti]
+ * indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore,
+ * - If isLefti == 1, then childi is the left child of parenti.
+ * - If isLefti == 0, then childi is the right child of parenti.
+ *
+ * Construct the binary tree described by descriptions and return its root.
+ *
+ * The test cases will be generated such that the binary tree is valid.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ *     this.val = (val===undefined ? 0 : val)
+ *     this.left = (left===undefined ? null : left)
+ *     this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {number[][]} descriptions
+ * @return {TreeNode}
+ */
+var createBinaryTree = function(descriptions) {
+  const nodes = new Map();
+  const children = new Set();
+
+  for (const [parent, child, isLeft] of descriptions) {
+    if (!nodes.has(parent)) {
+      nodes.set(parent, new TreeNode(parent));
+    }
+    if (!nodes.has(child)) {
+      nodes.set(child, new TreeNode(child));
+    }
+    children.add(child);
+    if (isLeft) {
+      nodes.get(parent).left = nodes.get(child);
+    } else {
+      nodes.get(parent).right = nodes.get(child);
+    }
+  }
+
+  for (const [val, node] of nodes) {
+    if (!children.has(val)) {
+      return node;
+    }
+  }
+
+  return null;
+};

From 0e251fcf8b91c606ab6d9e4d0eb7f1971e22d599 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 15 May 2025 00:26:40 -0500
Subject: [PATCH 305/495] Add solution #2197

---
 README.md                                     |  3 +-
 ...97-replace-non-coprime-numbers-in-array.js | 48 +++++++++++++++++++
 2 files changed, 50 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2197-replace-non-coprime-numbers-in-array.js

diff --git a/README.md b/README.md
index da9c9883..7fc7982d 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,809 LeetCode solutions in JavaScript
+# 1,810 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1682,6 +1682,7 @@
 2194|[Cells in a Range on an Excel Sheet](./solutions/2194-cells-in-a-range-on-an-excel-sheet.js)|Easy|
 2195|[Append K Integers With Minimal Sum](./solutions/2195-append-k-integers-with-minimal-sum.js)|Medium|
 2196|[Create Binary Tree From Descriptions](./solutions/2196-create-binary-tree-from-descriptions.js)|Medium|
+2197|[Replace Non-Coprime Numbers in Array](./solutions/2197-replace-non-coprime-numbers-in-array.js)|Hard|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
diff --git a/solutions/2197-replace-non-coprime-numbers-in-array.js b/solutions/2197-replace-non-coprime-numbers-in-array.js
new file mode 100644
index 00000000..2bc8e2d5
--- /dev/null
+++ b/solutions/2197-replace-non-coprime-numbers-in-array.js
@@ -0,0 +1,48 @@
+/**
+ * 2197. Replace Non-Coprime Numbers in Array
+ * https://leetcode.com/problems/replace-non-coprime-numbers-in-array/
+ * Difficulty: Hard
+ *
+ * You are given an array of integers nums. Perform the following steps:
+ * 1. Find any two adjacent numbers in nums that are non-coprime.
+ * 2. If no such numbers are found, stop the process.
+ * 3. Otherwise, delete the two numbers and replace them with their LCM (Least Common Multiple).
+ * 4. Repeat this process as long as you keep finding two adjacent non-coprime numbers.
+ *
+ * Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in
+ * any arbitrary order will lead to the same result.
+ *
+ * The test cases are generated such that the values in the final array are less than or equal to
+ * 108.
+ *
+ * Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common
+ * Divisor of x and y.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var replaceNonCoprimes = function(nums) {
+  const result = [];
+
+  for (let num of nums) {
+    while (result.length > 0) {
+      const last = result[result.length - 1];
+      const gcdValue = gcd(last, num);
+      if (gcdValue === 1) break;
+      result.pop();
+      num = (last / gcdValue) * num;
+    }
+    result.push(num);
+  }
+
+  return result;
+};
+
+function gcd(a, b) {
+  while (b) {
+    [a, b] = [b, a % b];
+  }
+  return a;
+}

From 6a18abb9c2ca2bbeece317b236bfb31dde81c070 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 15 May 2025 22:44:07 -0500
Subject: [PATCH 306/495] Add solution #2901

---
 README.md                                     |  3 +-
 ...-unequal-adjacent-groups-subsequence-ii.js | 68 +++++++++++++++++++
 2 files changed, 70 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2901-longest-unequal-adjacent-groups-subsequence-ii.js

diff --git a/README.md b/README.md
index 7fc7982d..172d9d03 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,810 LeetCode solutions in JavaScript
+# 1,811 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1780,6 +1780,7 @@
 2873|[Maximum Value of an Ordered Triplet I](./solutions/2873-maximum-value-of-an-ordered-triplet-i.js)|Easy|
 2874|[Maximum Value of an Ordered Triplet II](./solutions/2874-maximum-value-of-an-ordered-triplet-ii.js)|Medium|
 2900|[Longest Unequal Adjacent Groups Subsequence I](./solutions/2900-longest-unequal-adjacent-groups-subsequence-i.js)|Easy|
+2901|[Longest Unequal Adjacent Groups Subsequence II](./solutions/2901-longest-unequal-adjacent-groups-subsequence-ii.js)|Medium|
 2918|[Minimum Equal Sum of Two Arrays After Replacing Zeros](./solutions/2918-minimum-equal-sum-of-two-arrays-after-replacing-zeros.js)|Medium|
 2948|[Make Lexicographically Smallest Array by Swapping Elements](./solutions/2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium|
 2962|[Count Subarrays Where Max Element Appears at Least K Times](./solutions/2962-count-subarrays-where-max-element-appears-at-least-k-times.js)|Medium|
diff --git a/solutions/2901-longest-unequal-adjacent-groups-subsequence-ii.js b/solutions/2901-longest-unequal-adjacent-groups-subsequence-ii.js
new file mode 100644
index 00000000..1a290423
--- /dev/null
+++ b/solutions/2901-longest-unequal-adjacent-groups-subsequence-ii.js
@@ -0,0 +1,68 @@
+/**
+ * 2901. Longest Unequal Adjacent Groups Subsequence II
+ * https://leetcode.com/problems/longest-unequal-adjacent-groups-subsequence-ii/
+ * Difficulty: Medium
+ *
+ * You are given a string array words, and an array groups, both arrays having length n.
+ *
+ * The hamming distance between two strings of equal length is the number of positions at which the
+ * corresponding characters are different.
+ *
+ * You need to select the longest subsequence from an array of indices [0, 1, ..., n - 1], such
+ * that for the subsequence denoted as [i0, i1, ..., ik-1] having length k, the following holds:
+ * - For adjacent indices in the subsequence, their corresponding groups are unequal, i.e.,
+ *   groups[ij] != groups[ij+1], for each j where 0 < j + 1 < k.
+ * - words[ij] and words[ij+1] are equal in length, and the hamming distance between them is 1,
+ *   where 0 < j + 1 < k, for all indices in the subsequence.
+ *
+ * Return a string array containing the words corresponding to the indices (in order) in the
+ * selected subsequence. If there are multiple answers, return any of them.
+ *
+ * Note: strings in words may be unequal in length.
+ */
+
+/**
+ * @param {string[]} words
+ * @param {number[]} groups
+ * @return {string[]}
+ */
+var getWordsInLongestSubsequence = function(words, groups) {
+  const n = words.length;
+  const dp = new Array(n).fill(1);
+  const prev = new Array(n).fill(-1);
+  let maxLen = 1;
+  let lastIndex = 0;
+
+  for (let i = 1; i < n; i++) {
+    for (let j = 0; j < i; j++) {
+      if (groups[i] !== groups[j] && helper(words[i], words[j])) {
+        if (dp[j] + 1 > dp[i]) {
+          dp[i] = dp[j] + 1;
+          prev[i] = j;
+        }
+      }
+    }
+    if (dp[i] > maxLen) {
+      maxLen = dp[i];
+      lastIndex = i;
+    }
+  }
+
+  const result = [];
+  while (lastIndex !== -1) {
+    result.push(words[lastIndex]);
+    lastIndex = prev[lastIndex];
+  }
+
+  return result.reverse();
+
+  function helper(s1, s2) {
+    if (s1.length !== s2.length) return false;
+    let diff = 0;
+    for (let i = 0; i < s1.length; i++) {
+      if (s1[i] !== s2[i]) diff++;
+      if (diff > 1) return false;
+    }
+    return diff === 1;
+  }
+};

From 8051d84cb66af3881db81ce9063d430f73c411f0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 15 May 2025 22:45:52 -0500
Subject: [PATCH 307/495] Add solution #2200

---
 README.md                                     |  3 +-
 ...-find-all-k-distant-indices-in-an-array.js | 31 +++++++++++++++++++
 2 files changed, 33 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2200-find-all-k-distant-indices-in-an-array.js

diff --git a/README.md b/README.md
index 172d9d03..1d7cea7f 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,811 LeetCode solutions in JavaScript
+# 1,812 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1683,6 +1683,7 @@
 2195|[Append K Integers With Minimal Sum](./solutions/2195-append-k-integers-with-minimal-sum.js)|Medium|
 2196|[Create Binary Tree From Descriptions](./solutions/2196-create-binary-tree-from-descriptions.js)|Medium|
 2197|[Replace Non-Coprime Numbers in Array](./solutions/2197-replace-non-coprime-numbers-in-array.js)|Hard|
+2200|[Find All K-Distant Indices in an Array](./solutions/2200-find-all-k-distant-indices-in-an-array.js)|Easy|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
diff --git a/solutions/2200-find-all-k-distant-indices-in-an-array.js b/solutions/2200-find-all-k-distant-indices-in-an-array.js
new file mode 100644
index 00000000..5a2cd1bd
--- /dev/null
+++ b/solutions/2200-find-all-k-distant-indices-in-an-array.js
@@ -0,0 +1,31 @@
+/**
+ * 2200. Find All K-Distant Indices in an Array
+ * https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums and two integers key and k. A k-distant index
+ * is an index i of nums for which there exists at least one index j such that |i - j| <= k
+ * and nums[j] == key.
+ *
+ * Return a list of all k-distant indices sorted in increasing order.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} key
+ * @param {number} k
+ * @return {number[]}
+ */
+var findKDistantIndices = function(nums, key, k) {
+  const result = new Set();
+
+  for (let j = 0; j < nums.length; j++) {
+    if (nums[j] === key) {
+      for (let i = Math.max(0, j - k); i <= Math.min(nums.length - 1, j + k); i++) {
+        result.add(i);
+      }
+    }
+  }
+
+  return [...result].sort((a, b) => a - b);
+};

From 5ddaacacc191852f6c6811a17e0758cd368f3a66 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 15 May 2025 22:47:34 -0500
Subject: [PATCH 308/495] Add solution #2201

---
 README.md                                     |  3 +-
 ...1-count-artifacts-that-can-be-extracted.js | 57 +++++++++++++++++++
 2 files changed, 59 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2201-count-artifacts-that-can-be-extracted.js

diff --git a/README.md b/README.md
index 1d7cea7f..718141c2 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,812 LeetCode solutions in JavaScript
+# 1,813 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1684,6 +1684,7 @@
 2196|[Create Binary Tree From Descriptions](./solutions/2196-create-binary-tree-from-descriptions.js)|Medium|
 2197|[Replace Non-Coprime Numbers in Array](./solutions/2197-replace-non-coprime-numbers-in-array.js)|Hard|
 2200|[Find All K-Distant Indices in an Array](./solutions/2200-find-all-k-distant-indices-in-an-array.js)|Easy|
+2201|[Count Artifacts That Can Be Extracted](./solutions/2201-count-artifacts-that-can-be-extracted.js)|Medium|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
diff --git a/solutions/2201-count-artifacts-that-can-be-extracted.js b/solutions/2201-count-artifacts-that-can-be-extracted.js
new file mode 100644
index 00000000..cd5f5627
--- /dev/null
+++ b/solutions/2201-count-artifacts-that-can-be-extracted.js
@@ -0,0 +1,57 @@
+/**
+ * 2201. Count Artifacts That Can Be Extracted
+ * https://leetcode.com/problems/count-artifacts-that-can-be-extracted/
+ * Difficulty: Medium
+ *
+ * There is an n x n 0-indexed grid with some artifacts buried in it. You are given the integer
+ * n and a 0-indexed 2D integer array artifacts describing the positions of the rectangular
+ * artifacts where artifacts[i] = [r1i, c1i, r2i, c2i] denotes that the ith artifact is buried
+ * in the subgrid where:
+ * - (r1i, c1i) is the coordinate of the top-left cell of the ith artifact and
+ * - (r2i, c2i) is the coordinate of the bottom-right cell of the ith artifact.
+ *
+ * You will excavate some cells of the grid and remove all the mud from them. If the cell has a
+ * part of an artifact buried underneath, it will be uncovered. If all the parts of an artifact
+ * are uncovered, you can extract it.
+ *
+ * Given a 0-indexed 2D integer array dig where dig[i] = [ri, ci] indicates that you will excavate
+ * the cell (ri, ci), return the number of artifacts that you can extract.
+ *
+ * The test cases are generated such that:
+ * - No two artifacts overlap.
+ * - Each artifact only covers at most 4 cells.
+ * - The entries of dig are unique.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} artifacts
+ * @param {number[][]} dig
+ * @return {number}
+ */
+var digArtifacts = function(n, artifacts, dig) {
+  const excavated = new Set();
+  let result = 0;
+
+  for (const [row, col] of dig) {
+    excavated.add(`${row},${col}`);
+  }
+
+  for (const [r1, c1, r2, c2] of artifacts) {
+    let allUncovered = true;
+
+    for (let r = r1; r <= r2; r++) {
+      for (let c = c1; c <= c2; c++) {
+        if (!excavated.has(`${r},${c}`)) {
+          allUncovered = false;
+          break;
+        }
+      }
+      if (!allUncovered) break;
+    }
+
+    if (allUncovered) result++;
+  }
+
+  return result;
+};

From cb2094f235cd26e6163d2f3f4d1664ba53feee5f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 15 May 2025 22:48:47 -0500
Subject: [PATCH 309/495] Add solution #2202

---
 README.md                                     |  3 +-
 ...imize-the-topmost-element-after-k-moves.js | 42 +++++++++++++++++++
 2 files changed, 44 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2202-maximize-the-topmost-element-after-k-moves.js

diff --git a/README.md b/README.md
index 718141c2..b51468a5 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,813 LeetCode solutions in JavaScript
+# 1,814 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1685,6 +1685,7 @@
 2197|[Replace Non-Coprime Numbers in Array](./solutions/2197-replace-non-coprime-numbers-in-array.js)|Hard|
 2200|[Find All K-Distant Indices in an Array](./solutions/2200-find-all-k-distant-indices-in-an-array.js)|Easy|
 2201|[Count Artifacts That Can Be Extracted](./solutions/2201-count-artifacts-that-can-be-extracted.js)|Medium|
+2202|[Maximize the Topmost Element After K Moves](./solutions/2202-maximize-the-topmost-element-after-k-moves.js)|Medium|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
diff --git a/solutions/2202-maximize-the-topmost-element-after-k-moves.js b/solutions/2202-maximize-the-topmost-element-after-k-moves.js
new file mode 100644
index 00000000..8b1554b2
--- /dev/null
+++ b/solutions/2202-maximize-the-topmost-element-after-k-moves.js
@@ -0,0 +1,42 @@
+/**
+ * 2202. Maximize the Topmost Element After K Moves
+ * https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums representing the contents of a pile, where nums[0]
+ * is the topmost element of the pile.
+ *
+ * In one move, you can perform either of the following:
+ * - If the pile is not empty, remove the topmost element of the pile.
+ * - If there are one or more removed elements, add any one of them back onto the pile. This element
+ *   becomes the new topmost element.
+ *
+ * You are also given an integer k, which denotes the total number of moves to be made.
+ *
+ * Return the maximum value of the topmost element of the pile possible after exactly k moves. In
+ * case it is not possible to obtain a non-empty pile after k moves, return -1.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var maximumTop = function(nums, k) {
+  const n = nums.length;
+
+  if (n === 1 && k % 2 === 1) return -1;
+  if (k === 0) return nums[0];
+  if (k === 1) return n > 1 ? nums[1] : -1;
+
+  let result = 0;
+  for (let i = 0; i < Math.min(k - 1, n); i++) {
+    result = Math.max(result, nums[i]);
+  }
+
+  if (k < n) {
+    result = Math.max(result, nums[k]);
+  }
+
+  return result;
+};

From ac0b66f847fb44835b0f10b03d12b46c4850c5d1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 15 May 2025 22:53:20 -0500
Subject: [PATCH 310/495] Add solution #2203

---
 README.md                                     |  3 +-
 ...ighted-subgraph-with-the-required-paths.js | 73 +++++++++++++++++++
 2 files changed, 75 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2203-minimum-weighted-subgraph-with-the-required-paths.js

diff --git a/README.md b/README.md
index b51468a5..6561d0f7 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,814 LeetCode solutions in JavaScript
+# 1,815 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1686,6 +1686,7 @@
 2200|[Find All K-Distant Indices in an Array](./solutions/2200-find-all-k-distant-indices-in-an-array.js)|Easy|
 2201|[Count Artifacts That Can Be Extracted](./solutions/2201-count-artifacts-that-can-be-extracted.js)|Medium|
 2202|[Maximize the Topmost Element After K Moves](./solutions/2202-maximize-the-topmost-element-after-k-moves.js)|Medium|
+2203|[Minimum Weighted Subgraph With the Required Paths](./solutions/2203-minimum-weighted-subgraph-with-the-required-paths.js)|Hard|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
diff --git a/solutions/2203-minimum-weighted-subgraph-with-the-required-paths.js b/solutions/2203-minimum-weighted-subgraph-with-the-required-paths.js
new file mode 100644
index 00000000..4ace48ff
--- /dev/null
+++ b/solutions/2203-minimum-weighted-subgraph-with-the-required-paths.js
@@ -0,0 +1,73 @@
+/**
+ * 2203. Minimum Weighted Subgraph With the Required Paths
+ * https://leetcode.com/problems/minimum-weighted-subgraph-with-the-required-paths/
+ * Difficulty: Hard
+ *
+ * You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes
+ * are numbered from 0 to n - 1.
+ *
+ * You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that
+ * there exists a directed edge from fromi to toi with weight weighti.
+ *
+ * Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes
+ * of the graph.
+ *
+ * Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from
+ * both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist,
+ * return -1.
+ *
+ * A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of
+ * a subgraph is the sum of weights of its constituent edges.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @param {number} src1
+ * @param {number} src2
+ * @param {number} dest
+ * @return {number}
+ */
+var minimumWeight = function(n, edges, src1, src2, dest) {
+  const forwardGraph = Array.from({ length: n }, () => []);
+  const reverseGraph = Array.from({ length: n }, () => []);
+
+  for (const [from, to, weight] of edges) {
+    forwardGraph[from].push([to, weight]);
+    reverseGraph[to].push([from, weight]);
+  }
+
+  const distFromSrc1 = dijkstra(forwardGraph, src1);
+  const distFromSrc2 = dijkstra(forwardGraph, src2);
+  const distToDest = dijkstra(reverseGraph, dest);
+  let minWeight = Infinity;
+  for (let i = 0; i < n; i++) {
+    if (distFromSrc1[i] !== Infinity && distFromSrc2[i] !== Infinity
+        && distToDest[i] !== Infinity) {
+      minWeight = Math.min(minWeight, distFromSrc1[i] + distFromSrc2[i] + distToDest[i]);
+    }
+  }
+
+  return minWeight === Infinity ? -1 : minWeight;
+
+  function dijkstra(graph, start) {
+    const distances = new Array(n).fill(Infinity);
+    distances[start] = 0;
+    const pq = new PriorityQueue((a, b) => a[0] - b[0]);
+    pq.enqueue([0, start]);
+
+    while (!pq.isEmpty()) {
+      const [dist, node] = pq.dequeue();
+      if (dist > distances[node]) continue;
+
+      for (const [next, weight] of graph[node]) {
+        if (distances[next] > dist + weight) {
+          distances[next] = dist + weight;
+          pq.enqueue([distances[next], next]);
+        }
+      }
+    }
+
+    return distances;
+  }
+};

From be6e4c234d890321eb13a75cef0317f91e57cf8d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 16 May 2025 00:10:44 -0500
Subject: [PATCH 311/495] Add solution #2207

---
 README.md                                     |  3 +-
 ...mize-number-of-subsequences-in-a-string.js | 41 +++++++++++++++++++
 2 files changed, 43 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2207-maximize-number-of-subsequences-in-a-string.js

diff --git a/README.md b/README.md
index 6561d0f7..7241c137 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,815 LeetCode solutions in JavaScript
+# 1,816 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1688,6 +1688,7 @@
 2202|[Maximize the Topmost Element After K Moves](./solutions/2202-maximize-the-topmost-element-after-k-moves.js)|Medium|
 2203|[Minimum Weighted Subgraph With the Required Paths](./solutions/2203-minimum-weighted-subgraph-with-the-required-paths.js)|Hard|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
+2207|[Maximize Number of Subsequences in a String](./solutions/2207-maximize-number-of-subsequences-in-a-string.js)|Medium|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
diff --git a/solutions/2207-maximize-number-of-subsequences-in-a-string.js b/solutions/2207-maximize-number-of-subsequences-in-a-string.js
new file mode 100644
index 00000000..d7ad35a6
--- /dev/null
+++ b/solutions/2207-maximize-number-of-subsequences-in-a-string.js
@@ -0,0 +1,41 @@
+/**
+ * 2207. Maximize Number of Subsequences in a String
+ * https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both
+ * of which consist of only lowercase English letters.
+ *
+ * You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the
+ * character can be added even at the beginning or at the end of text.
+ *
+ * Return the maximum number of times pattern can occur as a subsequence of the modified text.
+ *
+ * A subsequence is a string that can be derived from another string by deleting some or no
+ * characters without changing the order of the remaining characters.
+ */
+
+/**
+ * @param {string} text
+ * @param {string} pattern
+ * @return {number}
+ */
+var maximumSubsequenceCount = function(text, pattern) {
+  const firstChar = pattern[0];
+  const secondChar = pattern[1];
+  let firstCount = 0;
+  let secondCount = 0;
+  let subsequences = 0;
+
+  for (const char of text) {
+    if (char === secondChar) {
+      subsequences += firstCount;
+      secondCount++;
+    }
+    if (char === firstChar) {
+      firstCount++;
+    }
+  }
+
+  return subsequences + Math.max(firstCount, secondCount);
+};

From 384c94ef807a14f971c8f75818e7d74b1b106ac3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 16 May 2025 00:12:24 -0500
Subject: [PATCH 312/495] Add solution #2209

---
 README.md                                     |  3 +-
 ...white-tiles-after-covering-with-carpets.js | 36 +++++++++++++++++++
 2 files changed, 38 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2209-minimum-white-tiles-after-covering-with-carpets.js

diff --git a/README.md b/README.md
index 7241c137..6977c275 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,816 LeetCode solutions in JavaScript
+# 1,817 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1689,6 +1689,7 @@
 2203|[Minimum Weighted Subgraph With the Required Paths](./solutions/2203-minimum-weighted-subgraph-with-the-required-paths.js)|Hard|
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2207|[Maximize Number of Subsequences in a String](./solutions/2207-maximize-number-of-subsequences-in-a-string.js)|Medium|
+2209|[Minimum White Tiles After Covering With Carpets](./solutions/2209-minimum-white-tiles-after-covering-with-carpets.js)|Hard|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
diff --git a/solutions/2209-minimum-white-tiles-after-covering-with-carpets.js b/solutions/2209-minimum-white-tiles-after-covering-with-carpets.js
new file mode 100644
index 00000000..08fb5fd3
--- /dev/null
+++ b/solutions/2209-minimum-white-tiles-after-covering-with-carpets.js
@@ -0,0 +1,36 @@
+/**
+ * 2209. Minimum White Tiles After Covering With Carpets
+ * https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor:
+ * - floor[i] = '0' denotes that the ith tile of the floor is colored black.
+ * - On the other hand, floor[i] = '1' denotes that the ith tile of the floor is colored white.
+ *
+ * You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length
+ * carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles
+ * still visible is minimum. Carpets may overlap one another.
+ *
+ * Return the minimum number of white tiles still visible.
+ */
+
+/**
+ * @param {string} floor
+ * @param {number} numCarpets
+ * @param {number} carpetLen
+ * @return {number}
+ */
+var minimumWhiteTiles = function(floor, numCarpets, carpetLen) {
+  const n = floor.length;
+  const dp = Array.from({ length: n + 1 }, () => Array(numCarpets + 1).fill(0));
+
+  for (let i = 1; i <= n; i++) {
+    for (let j = 0; j <= numCarpets; j++) {
+      const skip = dp[i - 1][j] + (floor[i - 1] === '1' ? 1 : 0);
+      const cover = j > 0 ? dp[Math.max(0, i - carpetLen)][j - 1] : Infinity;
+      dp[i][j] = Math.min(skip, cover);
+    }
+  }
+
+  return dp[n][numCarpets];
+};

From 7e0d1888d7f17af82e7e3edfd6de73127b7bc3ac Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 16 May 2025 00:15:38 -0500
Subject: [PATCH 313/495] Add solution #2210

---
 README.md                                     |  3 +-
 ...210-count-hills-and-valleys-in-an-array.js | 38 +++++++++++++++++++
 2 files changed, 40 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2210-count-hills-and-valleys-in-an-array.js

diff --git a/README.md b/README.md
index 6977c275..d41df174 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,817 LeetCode solutions in JavaScript
+# 1,818 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1690,6 +1690,7 @@
 2206|[Divide Array Into Equal Pairs](./solutions/2206-divide-array-into-equal-pairs.js)|Easy|
 2207|[Maximize Number of Subsequences in a String](./solutions/2207-maximize-number-of-subsequences-in-a-string.js)|Medium|
 2209|[Minimum White Tiles After Covering With Carpets](./solutions/2209-minimum-white-tiles-after-covering-with-carpets.js)|Hard|
+2210|[Count Hills and Valleys in an Array](./solutions/2210-count-hills-and-valleys-in-an-array.js)|Easy|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
diff --git a/solutions/2210-count-hills-and-valleys-in-an-array.js b/solutions/2210-count-hills-and-valleys-in-an-array.js
new file mode 100644
index 00000000..388d78f5
--- /dev/null
+++ b/solutions/2210-count-hills-and-valleys-in-an-array.js
@@ -0,0 +1,38 @@
+/**
+ * 2210. Count Hills and Valleys in an Array
+ * https://leetcode.com/problems/count-hills-and-valleys-in-an-array/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the
+ * closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part
+ * of a valley in nums if the closest non-equal neighbors of i are larger than nums[i].
+ * Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j].
+ *
+ * Note that for an index to be part of a hill or valley, it must have a non-equal neighbor
+ * on both the left and right of the index.
+ *
+ * Return the number of hills and valleys in nums.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var countHillValley = function(nums) {
+  let count = 0;
+  let prev = nums[0];
+
+  for (let i = 1; i < nums.length - 1; i++) {
+    if (nums[i] === nums[i + 1]) continue;
+    const left = prev;
+    const right = nums[i + 1];
+
+    if ((nums[i] > left && nums[i] > right) || (nums[i] < left && nums[i] < right)) {
+      count++;
+    }
+
+    prev = nums[i];
+  }
+
+  return count;
+};

From eb0931e3aa0a9d2384299afcc2094a2dc5589810 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 16 May 2025 00:18:02 -0500
Subject: [PATCH 314/495] Add solution #2211

---
 README.md                                    |  3 +-
 solutions/2211-count-collisions-on-a-road.js | 41 ++++++++++++++++++++
 2 files changed, 43 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2211-count-collisions-on-a-road.js

diff --git a/README.md b/README.md
index d41df174..0f9c5eec 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,818 LeetCode solutions in JavaScript
+# 1,819 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1691,6 +1691,7 @@
 2207|[Maximize Number of Subsequences in a String](./solutions/2207-maximize-number-of-subsequences-in-a-string.js)|Medium|
 2209|[Minimum White Tiles After Covering With Carpets](./solutions/2209-minimum-white-tiles-after-covering-with-carpets.js)|Hard|
 2210|[Count Hills and Valleys in an Array](./solutions/2210-count-hills-and-valleys-in-an-array.js)|Easy|
+2211|[Count Collisions on a Road](./solutions/2211-count-collisions-on-a-road.js)|Medium|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
diff --git a/solutions/2211-count-collisions-on-a-road.js b/solutions/2211-count-collisions-on-a-road.js
new file mode 100644
index 00000000..acbd8920
--- /dev/null
+++ b/solutions/2211-count-collisions-on-a-road.js
@@ -0,0 +1,41 @@
+/**
+ * 2211. Count Collisions on a Road
+ * https://leetcode.com/problems/count-collisions-on-a-road/
+ * Difficulty: Medium
+ *
+ * There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left
+ * to right and each car is present at a unique point.
+ *
+ * You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R',
+ * or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying
+ * at its current point respectively. Each moving car has the same speed.
+ *
+ * The number of collisions can be calculated as follows:
+ * - When two cars moving in opposite directions collide with each other, the number of collisions
+ *   increases by 2.
+ * - When a moving car collides with a stationary car, the number of collisions increases by 1.
+ *
+ * After a collision, the cars involved can no longer move and will stay at the point where they
+ * collided. Other than that, cars cannot change their state or direction of motion.
+ *
+ * Return the total number of collisions that will happen on the road.
+ */
+
+/**
+ * @param {string} directions
+ * @return {number}
+ */
+var countCollisions = function(directions) {
+  let result = 0;
+  let left = 0;
+  let right = directions.length - 1;
+
+  while (left < directions.length && directions[left] === 'L') left++;
+  while (right >= 0 && directions[right] === 'R') right--;
+
+  for (let i = left; i <= right; i++) {
+    if (directions[i] !== 'S') result++;
+  }
+
+  return result;
+};

From f13299b081096c17e7528b6842a0d563924f6092 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 16 May 2025 00:24:28 -0500
Subject: [PATCH 315/495] Add solution #2212

---
 README.md                                     |  3 +-
 ...aximum-points-in-an-archery-competition.js | 60 +++++++++++++++++++
 2 files changed, 62 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2212-maximum-points-in-an-archery-competition.js

diff --git a/README.md b/README.md
index 0f9c5eec..bd19451b 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,819 LeetCode solutions in JavaScript
+# 1,820 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1692,6 +1692,7 @@
 2209|[Minimum White Tiles After Covering With Carpets](./solutions/2209-minimum-white-tiles-after-covering-with-carpets.js)|Hard|
 2210|[Count Hills and Valleys in an Array](./solutions/2210-count-hills-and-valleys-in-an-array.js)|Easy|
 2211|[Count Collisions on a Road](./solutions/2211-count-collisions-on-a-road.js)|Medium|
+2212|[Maximum Points in an Archery Competition](./solutions/2212-maximum-points-in-an-archery-competition.js)|Medium|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
diff --git a/solutions/2212-maximum-points-in-an-archery-competition.js b/solutions/2212-maximum-points-in-an-archery-competition.js
new file mode 100644
index 00000000..2c09fc29
--- /dev/null
+++ b/solutions/2212-maximum-points-in-an-archery-competition.js
@@ -0,0 +1,60 @@
+/**
+ * 2212. Maximum Points in an Archery Competition
+ * https://leetcode.com/problems/maximum-points-in-an-archery-competition/
+ * Difficulty: Medium
+ *
+ * Alice and Bob are opponents in an archery competition. The competition has set the
+ * following rules:
+ * 1. Alice first shoots numArrows arrows and then Bob shoots numArrows arrows.
+ * 2. The points are then calculated as follows:
+ *    1. The target has integer scoring sections ranging from 0 to 11 inclusive.
+ *    2. For each section of the target with score k (in between 0 to 11), say Alice and Bob have
+ *       shot ak and bk arrows on that section respectively. If ak >= bk, then Alice takes k points.
+ *       If ak < bk, then Bob takes k points.
+ *    3. However, if ak == bk == 0, then nobody takes k points.
+ * - For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes
+ *   11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot
+ *   2 arrows on that same section, then Bob takes 11 points.
+ *
+ * You are given the integer numArrows and an integer array aliceArrows of size 12, which represents
+ * the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize
+ * the total number of points he can obtain.
+ *
+ * Return the array bobArrows which represents the number of arrows Bob shot on each scoring section
+ * from 0 to 11. The sum of the values in bobArrows should equal numArrows.
+ *
+ * If there are multiple ways for Bob to earn the maximum total points, return any one of them.
+ */
+
+/**
+ * @param {number} numArrows
+ * @param {number[]} aliceArrows
+ * @return {number[]}
+ */
+var maximumBobPoints = function(numArrows, aliceArrows) {
+  let maxScore = 0;
+  let bestConfig = new Array(12).fill(0);
+
+  backtrack(1, numArrows, 0, new Array(12).fill(0));
+  return bestConfig;
+
+  function backtrack(index, arrowsLeft, score, config) {
+    if (index === 12 || arrowsLeft === 0) {
+      if (score > maxScore) {
+        maxScore = score;
+        bestConfig = [...config];
+        bestConfig[0] += arrowsLeft;
+      }
+      return;
+    }
+
+    const needed = aliceArrows[index] + 1;
+    if (arrowsLeft >= needed) {
+      config[index] = needed;
+      backtrack(index + 1, arrowsLeft - needed, score + index, config);
+      config[index] = 0;
+    }
+
+    backtrack(index + 1, arrowsLeft, score, config);
+  }
+};

From d040bfca27f7a0911b4d64e549ec36677f3e20ea Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 16 May 2025 23:09:39 -0500
Subject: [PATCH 316/495] Add solution #2216

---
 README.md                                     |  3 +-
 ...nimum-deletions-to-make-array-beautiful.js | 41 +++++++++++++++++++
 2 files changed, 43 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2216-minimum-deletions-to-make-array-beautiful.js

diff --git a/README.md b/README.md
index bd19451b..f041f740 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,820 LeetCode solutions in JavaScript
+# 1,821 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1694,6 +1694,7 @@
 2211|[Count Collisions on a Road](./solutions/2211-count-collisions-on-a-road.js)|Medium|
 2212|[Maximum Points in an Archery Competition](./solutions/2212-maximum-points-in-an-archery-competition.js)|Medium|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
+2216|[Minimum Deletions to Make Array Beautiful](./solutions/2216-minimum-deletions-to-make-array-beautiful.js)|Medium|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
diff --git a/solutions/2216-minimum-deletions-to-make-array-beautiful.js b/solutions/2216-minimum-deletions-to-make-array-beautiful.js
new file mode 100644
index 00000000..7cb1012e
--- /dev/null
+++ b/solutions/2216-minimum-deletions-to-make-array-beautiful.js
@@ -0,0 +1,41 @@
+/**
+ * 2216. Minimum Deletions to Make Array Beautiful
+ * https://leetcode.com/problems/minimum-deletions-to-make-array-beautiful/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums. The array nums is beautiful if:
+ * - nums.length is even.
+ * - nums[i] != nums[i + 1] for all i % 2 == 0.
+ *
+ * Note that an empty array is considered beautiful.
+ *
+ * You can delete any number of elements from nums. When you delete an element, all the elements
+ * to the right of the deleted element will be shifted one unit to the left to fill the gap
+ * created and all the elements to the left of the deleted element will remain unchanged.
+ *
+ * Return the minimum number of elements to delete from nums to make it beautiful.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minDeletion = function(nums) {
+  let result = 0;
+  let i = 0;
+
+  while (i < nums.length - 1) {
+    if (nums[i] === nums[i + 1]) {
+      result++;
+      i++;
+    } else {
+      i += 2;
+    }
+  }
+
+  if ((nums.length - result) % 2 !== 0) {
+    result++;
+  }
+
+  return result;
+};

From 5837760a2dab5ce812b674fc68bcdd242eacfebb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 16 May 2025 23:10:54 -0500
Subject: [PATCH 317/495] Add solution #2217

---
 README.md                                     |  3 +-
 .../2217-find-palindrome-with-fixed-length.js | 40 +++++++++++++++++++
 2 files changed, 42 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2217-find-palindrome-with-fixed-length.js

diff --git a/README.md b/README.md
index f041f740..6ed8de14 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,821 LeetCode solutions in JavaScript
+# 1,822 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1695,6 +1695,7 @@
 2212|[Maximum Points in an Archery Competition](./solutions/2212-maximum-points-in-an-archery-competition.js)|Medium|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2216|[Minimum Deletions to Make Array Beautiful](./solutions/2216-minimum-deletions-to-make-array-beautiful.js)|Medium|
+2217|[Find Palindrome With Fixed Length](./solutions/2217-find-palindrome-with-fixed-length.js)|Medium|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
diff --git a/solutions/2217-find-palindrome-with-fixed-length.js b/solutions/2217-find-palindrome-with-fixed-length.js
new file mode 100644
index 00000000..4e6a83aa
--- /dev/null
+++ b/solutions/2217-find-palindrome-with-fixed-length.js
@@ -0,0 +1,40 @@
+/**
+ * 2217. Find Palindrome With Fixed Length
+ * https://leetcode.com/problems/find-palindrome-with-fixed-length/
+ * Difficulty: Medium
+ *
+ * Given an integer array queries and a positive integer intLength, return an array answer where
+ * answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1
+ * if no such palindrome exists.
+ *
+ * A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have
+ * leading zeros.
+ */
+
+/**
+ * @param {number[]} queries
+ * @param {number} intLength
+ * @return {number[]}
+ */
+var kthPalindrome = function(queries, intLength) {
+  const halfLength = Math.ceil(intLength / 2);
+  const maxPalindromes = Math.pow(10, halfLength - 1) * 9;
+
+  return queries.map(generatePalindrome);
+
+  function generatePalindrome(query) {
+    if (query > maxPalindromes) return -1;
+
+    let firstHalf = Math.pow(10, halfLength - 1) + query - 1;
+    let result = firstHalf;
+
+    if (intLength % 2 === 1) firstHalf = Math.floor(firstHalf / 10);
+
+    while (firstHalf > 0) {
+      result = result * 10 + (firstHalf % 10);
+      firstHalf = Math.floor(firstHalf / 10);
+    }
+
+    return result;
+  }
+};

From 45b4d9b9e9722145ec1c969e29f678e16ba67fa0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 16 May 2025 23:12:25 -0500
Subject: [PATCH 318/495] Add solution #2220

---
 README.md                                     |  3 ++-
 ...220-minimum-bit-flips-to-convert-number.js | 24 +++++++++++++++++++
 2 files changed, 26 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2220-minimum-bit-flips-to-convert-number.js

diff --git a/README.md b/README.md
index 6ed8de14..e2bb94a2 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,822 LeetCode solutions in JavaScript
+# 1,823 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1696,6 +1696,7 @@
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2216|[Minimum Deletions to Make Array Beautiful](./solutions/2216-minimum-deletions-to-make-array-beautiful.js)|Medium|
 2217|[Find Palindrome With Fixed Length](./solutions/2217-find-palindrome-with-fixed-length.js)|Medium|
+2220|[Minimum Bit Flips to Convert Number](./solutions/2220-minimum-bit-flips-to-convert-number.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
diff --git a/solutions/2220-minimum-bit-flips-to-convert-number.js b/solutions/2220-minimum-bit-flips-to-convert-number.js
new file mode 100644
index 00000000..28e0a9da
--- /dev/null
+++ b/solutions/2220-minimum-bit-flips-to-convert-number.js
@@ -0,0 +1,24 @@
+/**
+ * 2220. Minimum Bit Flips to Convert Number
+ * https://leetcode.com/problems/minimum-bit-flips-to-convert-number/
+ * Difficulty: Easy
+ *
+ * A bit flip of a number x is choosing a bit in the binary representation of x and flipping it
+ * from either 0 to 1 or 1 to 0.
+ * - For example, for x = 7, the binary representation is 111 and we may choose any bit (including
+ *   any leading zeros not shown) and flip it. We can flip the first bit from the right to get 110,
+ *   flip the second bit from the right to get 101, flip the fifth bit from the right (a leading
+ *   zero) to get 10111, etc.
+ *
+ * Given two integers start and goal, return the minimum number of bit flips to convert start to
+ * goal.
+ */
+
+/**
+ * @param {number} start
+ * @param {number} goal
+ * @return {number}
+ */
+var minBitFlips = function(start, goal) {
+  return (start ^ goal).toString(2).replace(/0+/g, '').length;
+};

From 5c800196a28732ea501e682b21b45f6f04e6b1cb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 16 May 2025 23:14:58 -0500
Subject: [PATCH 319/495] Add solution #2221

---
 README.md                                     |  3 +-
 .../2221-find-triangular-sum-of-an-array.js   | 34 +++++++++++++++++++
 2 files changed, 36 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2221-find-triangular-sum-of-an-array.js

diff --git a/README.md b/README.md
index e2bb94a2..d0689dd0 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,823 LeetCode solutions in JavaScript
+# 1,824 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1697,6 +1697,7 @@
 2216|[Minimum Deletions to Make Array Beautiful](./solutions/2216-minimum-deletions-to-make-array-beautiful.js)|Medium|
 2217|[Find Palindrome With Fixed Length](./solutions/2217-find-palindrome-with-fixed-length.js)|Medium|
 2220|[Minimum Bit Flips to Convert Number](./solutions/2220-minimum-bit-flips-to-convert-number.js)|Easy|
+2221|[Find Triangular Sum of an Array](./solutions/2221-find-triangular-sum-of-an-array.js)|Medium|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
diff --git a/solutions/2221-find-triangular-sum-of-an-array.js b/solutions/2221-find-triangular-sum-of-an-array.js
new file mode 100644
index 00000000..3ef02fcd
--- /dev/null
+++ b/solutions/2221-find-triangular-sum-of-an-array.js
@@ -0,0 +1,34 @@
+/**
+ * 2221. Find Triangular Sum of an Array
+ * https://leetcode.com/problems/find-triangular-sum-of-an-array/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and
+ * 9 (inclusive).
+ *
+ * The triangular sum of nums is the value of the only element present in nums after the
+ * following process terminates:
+ * 1. Let nums comprise of n elements. If n == 1, end the process. Otherwise, create a new
+ *    0-indexed integer array newNums of length n - 1.
+ * 2. For each index i, where 0 <= i < n - 1, assign the value of newNums[i] as
+ *    (nums[i] + nums[i+1]) % 10, where % denotes modulo operator.
+ * 3. Replace the array nums with newNums.
+ * 4. Repeat the entire process starting from step 1.
+ *
+ * Return the triangular sum of nums.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var triangularSum = function(nums) {
+  while (nums.length > 1) {
+    const updated = [];
+    for (let i = 0; i < nums.length - 1; i++) {
+      updated.push((nums[i] + nums[i + 1]) % 10);
+    }
+    nums = updated;
+  }
+  return nums[0];
+};

From 70f51e562d9a2142a840d385b650692f9ef56fc8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 16 May 2025 23:24:27 -0500
Subject: [PATCH 320/495] Add solution #2222

---
 README.md                                     |  3 +-
 ...2222-number-of-ways-to-select-buildings.js | 49 +++++++++++++++++++
 2 files changed, 51 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2222-number-of-ways-to-select-buildings.js

diff --git a/README.md b/README.md
index d0689dd0..eae091b2 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,824 LeetCode solutions in JavaScript
+# 1,825 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1698,6 +1698,7 @@
 2217|[Find Palindrome With Fixed Length](./solutions/2217-find-palindrome-with-fixed-length.js)|Medium|
 2220|[Minimum Bit Flips to Convert Number](./solutions/2220-minimum-bit-flips-to-convert-number.js)|Easy|
 2221|[Find Triangular Sum of an Array](./solutions/2221-find-triangular-sum-of-an-array.js)|Medium|
+2222|[Number of Ways to Select Buildings](./solutions/2222-number-of-ways-to-select-buildings.js)|Medium|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
diff --git a/solutions/2222-number-of-ways-to-select-buildings.js b/solutions/2222-number-of-ways-to-select-buildings.js
new file mode 100644
index 00000000..012573fc
--- /dev/null
+++ b/solutions/2222-number-of-ways-to-select-buildings.js
@@ -0,0 +1,49 @@
+/**
+ * 2222. Number of Ways to Select Buildings
+ * https://leetcode.com/problems/number-of-ways-to-select-buildings/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed binary string s which represents the types of buildings along
+ * a street where:
+ * - s[i] = '0' denotes that the ith building is an office and
+ * - s[i] = '1' denotes that the ith building is a restaurant.
+ *
+ * As a city official, you would like to select 3 buildings for random inspection. However, to
+ * ensure variety, no two consecutive buildings out of the selected buildings can be of the same
+ * type.
+ * - For example, given s = "001101", we cannot select the 1st, 3rd, and 5th buildings as that
+ *   would form "011" which is not allowed due to having two consecutive buildings of the same type.
+ *
+ * Return the number of valid ways to select 3 buildings.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var numberOfWays = function(s) {
+  const prefixCounts = [[0, 0]];
+  let zeros = 0;
+  let ones = 0;
+
+  for (const char of s) {
+    if (char === '0') zeros++;
+    else ones++;
+    prefixCounts.push([zeros, ones]);
+  }
+
+  let result = 0;
+  for (let i = 1; i < s.length - 1; i++) {
+    if (s[i] === '0') {
+      const leftOnes = prefixCounts[i][1];
+      const rightOnes = prefixCounts[s.length][1] - prefixCounts[i + 1][1];
+      result += leftOnes * rightOnes;
+    } else {
+      const leftZeros = prefixCounts[i][0];
+      const rightZeros = prefixCounts[s.length][0] - prefixCounts[i + 1][0];
+      result += leftZeros * rightZeros;
+    }
+  }
+
+  return result;
+};

From 48158321fcf6ea6dd282ea677eaa1f0e6b42b963 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 00:00:53 -0500
Subject: [PATCH 321/495] Add solution #2213

---
 README.md                                     |   3 +-
 ...st-substring-of-one-repeating-character.js | 117 ++++++++++++++++++
 2 files changed, 119 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2213-longest-substring-of-one-repeating-character.js

diff --git a/README.md b/README.md
index eae091b2..16f055ae 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,825 LeetCode solutions in JavaScript
+# 1,826 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1693,6 +1693,7 @@
 2210|[Count Hills and Valleys in an Array](./solutions/2210-count-hills-and-valleys-in-an-array.js)|Easy|
 2211|[Count Collisions on a Road](./solutions/2211-count-collisions-on-a-road.js)|Medium|
 2212|[Maximum Points in an Archery Competition](./solutions/2212-maximum-points-in-an-archery-competition.js)|Medium|
+2213|[Longest Substring of One Repeating Character](./solutions/2213-longest-substring-of-one-repeating-character.js)|Hard|
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2216|[Minimum Deletions to Make Array Beautiful](./solutions/2216-minimum-deletions-to-make-array-beautiful.js)|Medium|
 2217|[Find Palindrome With Fixed Length](./solutions/2217-find-palindrome-with-fixed-length.js)|Medium|
diff --git a/solutions/2213-longest-substring-of-one-repeating-character.js b/solutions/2213-longest-substring-of-one-repeating-character.js
new file mode 100644
index 00000000..ca5e006d
--- /dev/null
+++ b/solutions/2213-longest-substring-of-one-repeating-character.js
@@ -0,0 +1,117 @@
+/**
+ * 2213. Longest Substring of One Repeating Character
+ * https://leetcode.com/problems/longest-substring-of-one-repeating-character/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of
+ * length k and a 0-indexed array of integer indices queryIndices of length k, both of which are
+ * used to describe k queries.
+ *
+ * The ith query updates the character in s at index queryIndices[i] to the character
+ * queryCharacters[i].
+ *
+ * Return an array lengths of length k where lengths[i] is the length of the longest substring of
+ * s consisting of only one repeating character after the ith query is performed.
+ */
+
+/**
+* @param {string} s
+* @param {string} queryCharacters
+* @param {number[]} queryIndices
+* @return {number[]}
+*/
+var longestRepeating = function(s, queryCharacters, queryIndices) {
+  const chars = s.split('');
+  const n = chars.length;
+  const k = queryIndices.length;
+  const result = [];
+
+  class Node {
+    constructor() {
+      this.left = 0;
+      this.right = 0;
+      this.max = 0;
+      this.total = 0;
+    }
+  }
+
+  const tree = new Array(4 * n);
+  for (let i = 0; i < 4 * n; i++) {
+    tree[i] = new Node();
+  }
+
+  function buildTree(node, start, end) {
+    if (start === end) {
+      tree[node].left = 1;
+      tree[node].right = 1;
+      tree[node].max = 1;
+      tree[node].total = 1;
+      return;
+    }
+
+    const mid = Math.floor((start + end) / 2);
+    buildTree(2 * node, start, mid);
+    buildTree(2 * node + 1, mid + 1, end);
+
+    updateNode(node, start, end);
+  }
+
+  function updateNode(node, start, end) {
+    const leftChild = 2 * node;
+    const rightChild = 2 * node + 1;
+    const mid = Math.floor((start + end) / 2);
+
+    tree[node].total = tree[leftChild].total + tree[rightChild].total;
+
+    if (tree[leftChild].total === tree[leftChild].left
+        && mid + 1 <= end && chars[mid] === chars[mid + 1]) {
+      tree[node].left = tree[leftChild].total + tree[rightChild].left;
+    } else {
+      tree[node].left = tree[leftChild].left;
+    }
+
+    if (tree[rightChild].total === tree[rightChild].right
+        && mid >= start && chars[mid] === chars[mid + 1]) {
+      tree[node].right = tree[rightChild].total + tree[leftChild].right;
+    } else {
+      tree[node].right = tree[rightChild].right;
+    }
+
+    tree[node].max = Math.max(tree[leftChild].max, tree[rightChild].max);
+
+    if (mid >= start && mid + 1 <= end && chars[mid] === chars[mid + 1]) {
+      tree[node].max = Math.max(tree[node].max,
+        tree[leftChild].right + tree[rightChild].left);
+    }
+  }
+
+  function update(node, start, end, index) {
+    if (index < start || index > end) {
+      return;
+    }
+
+    if (start === end) {
+      return;
+    }
+
+    const mid = Math.floor((start + end) / 2);
+    update(2 * node, start, mid, index);
+    update(2 * node + 1, mid + 1, end, index);
+
+    updateNode(node, start, end);
+  }
+
+  buildTree(1, 0, n - 1);
+
+  for (let q = 0; q < k; q++) {
+    const index = queryIndices[q];
+    const newChar = queryCharacters[q];
+
+    chars[index] = newChar;
+    update(1, 0, n - 1, index);
+
+    result.push(tree[1].max);
+  }
+
+  return result;
+};

From 4da99ca4bdfeba473c8fb40c5db07a12fd0bc858 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 00:02:35 -0500
Subject: [PATCH 322/495] Add solution #2218

---
 README.md                                     |  3 +-
 ...218-maximum-value-of-k-coins-from-piles.js | 44 +++++++++++++++++++
 2 files changed, 46 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2218-maximum-value-of-k-coins-from-piles.js

diff --git a/README.md b/README.md
index 16f055ae..2ba4402d 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,826 LeetCode solutions in JavaScript
+# 1,827 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1697,6 +1697,7 @@
 2215|[Find the Difference of Two Arrays](./solutions/2215-find-the-difference-of-two-arrays.js)|Easy|
 2216|[Minimum Deletions to Make Array Beautiful](./solutions/2216-minimum-deletions-to-make-array-beautiful.js)|Medium|
 2217|[Find Palindrome With Fixed Length](./solutions/2217-find-palindrome-with-fixed-length.js)|Medium|
+2218|[Maximum Value of K Coins From Piles](./solutions/2218-maximum-value-of-k-coins-from-piles.js)|Hard|
 2220|[Minimum Bit Flips to Convert Number](./solutions/2220-minimum-bit-flips-to-convert-number.js)|Easy|
 2221|[Find Triangular Sum of an Array](./solutions/2221-find-triangular-sum-of-an-array.js)|Medium|
 2222|[Number of Ways to Select Buildings](./solutions/2222-number-of-ways-to-select-buildings.js)|Medium|
diff --git a/solutions/2218-maximum-value-of-k-coins-from-piles.js b/solutions/2218-maximum-value-of-k-coins-from-piles.js
new file mode 100644
index 00000000..743b4b17
--- /dev/null
+++ b/solutions/2218-maximum-value-of-k-coins-from-piles.js
@@ -0,0 +1,44 @@
+/**
+ * 2218. Maximum Value of K Coins From Piles
+ * https://leetcode.com/problems/maximum-value-of-k-coins-from-piles/
+ * Difficulty: Hard
+ *
+ * There are n piles of coins on a table. Each pile consists of a positive number of coins of
+ * assorted denominations.
+ *
+ * In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet.
+ *
+ * Given a list piles, where piles[i] is a list of integers denoting the composition of the ith
+ * pile from top to bottom, and a positive integer k, return the maximum total value of coins
+ * you can have in your wallet if you choose exactly k coins optimally.
+ */
+
+/**
+ * @param {number[][]} piles
+ * @param {number} k
+ * @return {number}
+ */
+var maxValueOfCoins = function(piles, k) {
+  const n = piles.length;
+  const dp = Array.from({ length: n + 1 }, () => new Array(k + 1).fill(-1));
+
+  return maximize(0, k);
+
+  function maximize(pileIndex, remainingCoins) {
+    if (pileIndex === n || remainingCoins === 0) return 0;
+    if (dp[pileIndex][remainingCoins] !== -1) return dp[pileIndex][remainingCoins];
+
+    let maxValue = maximize(pileIndex + 1, remainingCoins);
+    let currentSum = 0;
+
+    for (let i = 0; i < Math.min(piles[pileIndex].length, remainingCoins); i++) {
+      currentSum += piles[pileIndex][i];
+      maxValue = Math.max(
+        maxValue,
+        currentSum + maximize(pileIndex + 1, remainingCoins - (i + 1))
+      );
+    }
+
+    return dp[pileIndex][remainingCoins] = maxValue;
+  }
+};

From ffe662bacd579d1a625241a1e5af57960289f7f8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 00:03:32 -0500
Subject: [PATCH 323/495] Add solution #2223

---
 README.md                                     |  3 +-
 .../2223-sum-of-scores-of-built-strings.js    | 40 +++++++++++++++++++
 2 files changed, 42 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2223-sum-of-scores-of-built-strings.js

diff --git a/README.md b/README.md
index 2ba4402d..8c5449be 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,827 LeetCode solutions in JavaScript
+# 1,828 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1701,6 +1701,7 @@
 2220|[Minimum Bit Flips to Convert Number](./solutions/2220-minimum-bit-flips-to-convert-number.js)|Easy|
 2221|[Find Triangular Sum of an Array](./solutions/2221-find-triangular-sum-of-an-array.js)|Medium|
 2222|[Number of Ways to Select Buildings](./solutions/2222-number-of-ways-to-select-buildings.js)|Medium|
+2223|[Sum of Scores of Built Strings](./solutions/2223-sum-of-scores-of-built-strings.js)|Hard|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
diff --git a/solutions/2223-sum-of-scores-of-built-strings.js b/solutions/2223-sum-of-scores-of-built-strings.js
new file mode 100644
index 00000000..4b5110cc
--- /dev/null
+++ b/solutions/2223-sum-of-scores-of-built-strings.js
@@ -0,0 +1,40 @@
+/**
+ * 2223. Sum of Scores of Built Strings
+ * https://leetcode.com/problems/sum-of-scores-of-built-strings/
+ * Difficulty: Hard
+ *
+ * You are building a string s of length n one character at a time, prepending each new character
+ * to the front of the string. The strings are labeled from 1 to n, where the string with length
+ * i is labeled si.
+ * - For example, for s = "abaca", s1 == "a", s2 == "ca", s3 == "aca", etc.
+ *
+ * The score of si is the length of the longest common prefix between si and sn (Note that s == sn).
+ *
+ * Given the final string s, return the sum of the score of every si.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var sumScores = function(s) {
+  const n = s.length;
+  const z = new Array(n).fill(0);
+  let left = 0;
+  let right = 0;
+
+  for (let i = 1; i < n; i++) {
+    if (i <= right) {
+      z[i] = Math.min(right - i + 1, z[i - left]);
+    }
+    while (i + z[i] < n && s[z[i]] === s[i + z[i]]) {
+      z[i]++;
+    }
+    if (i + z[i] - 1 > right) {
+      left = i;
+      right = i + z[i] - 1;
+    }
+  }
+
+  return z.reduce((sum, val) => sum + val, n);
+};

From 9f6dfdb0685caf754c2a6842b7595b4011e7f96c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 00:04:36 -0500
Subject: [PATCH 324/495] Add solution #2224

---
 README.md                                     |  3 +-
 ...um-number-of-operations-to-convert-time.js | 38 +++++++++++++++++++
 2 files changed, 40 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2224-minimum-number-of-operations-to-convert-time.js

diff --git a/README.md b/README.md
index 8c5449be..346a23a7 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,828 LeetCode solutions in JavaScript
+# 1,829 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1702,6 +1702,7 @@
 2221|[Find Triangular Sum of an Array](./solutions/2221-find-triangular-sum-of-an-array.js)|Medium|
 2222|[Number of Ways to Select Buildings](./solutions/2222-number-of-ways-to-select-buildings.js)|Medium|
 2223|[Sum of Scores of Built Strings](./solutions/2223-sum-of-scores-of-built-strings.js)|Hard|
+2224|[Minimum Number of Operations to Convert Time](./solutions/2224-minimum-number-of-operations-to-convert-time.js)|Easy|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
diff --git a/solutions/2224-minimum-number-of-operations-to-convert-time.js b/solutions/2224-minimum-number-of-operations-to-convert-time.js
new file mode 100644
index 00000000..95b7a154
--- /dev/null
+++ b/solutions/2224-minimum-number-of-operations-to-convert-time.js
@@ -0,0 +1,38 @@
+/**
+ * 2224. Minimum Number of Operations to Convert Time
+ * https://leetcode.com/problems/minimum-number-of-operations-to-convert-time/
+ * Difficulty: Easy
+ *
+ * You are given two strings current and correct representing two 24-hour times.
+ *
+ * 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00
+ * and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.
+ *
+ * In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform
+ * this operation any number of times.
+ *
+ * Return the minimum number of operations needed to convert current to correct.
+ */
+
+/**
+ * @param {string} current
+ * @param {string} correct
+ * @return {number}
+ */
+var convertTime = function(current, correct) {
+  const toMinutes = time => {
+    const [hours, minutes] = time.split(':').map(Number);
+    return hours * 60 + minutes;
+  };
+
+  let diff = toMinutes(correct) - toMinutes(current);
+  const increments = [60, 15, 5, 1];
+  let result = 0;
+
+  for (const increment of increments) {
+    result += Math.floor(diff / increment);
+    diff %= increment;
+  }
+
+  return result;
+};

From 827f641554ceb42ba47968f715559d964b7eeedc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 00:05:40 -0500
Subject: [PATCH 325/495] Add solution #2225

---
 README.md                                     |  3 +-
 ...25-find-players-with-zero-or-one-losses.js | 44 +++++++++++++++++++
 2 files changed, 46 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2225-find-players-with-zero-or-one-losses.js

diff --git a/README.md b/README.md
index 346a23a7..7fa4a5fb 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,829 LeetCode solutions in JavaScript
+# 1,830 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1703,6 +1703,7 @@
 2222|[Number of Ways to Select Buildings](./solutions/2222-number-of-ways-to-select-buildings.js)|Medium|
 2223|[Sum of Scores of Built Strings](./solutions/2223-sum-of-scores-of-built-strings.js)|Hard|
 2224|[Minimum Number of Operations to Convert Time](./solutions/2224-minimum-number-of-operations-to-convert-time.js)|Easy|
+2225|[Find Players With Zero or One Losses](./solutions/2225-find-players-with-zero-or-one-losses.js)|Medium|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
diff --git a/solutions/2225-find-players-with-zero-or-one-losses.js b/solutions/2225-find-players-with-zero-or-one-losses.js
new file mode 100644
index 00000000..3182523e
--- /dev/null
+++ b/solutions/2225-find-players-with-zero-or-one-losses.js
@@ -0,0 +1,44 @@
+/**
+ * 2225. Find Players With Zero or One Losses
+ * https://leetcode.com/problems/find-players-with-zero-or-one-losses/
+ * Difficulty: Medium
+ *
+ * You are given an integer array matches where matches[i] = [winneri, loseri] indicates that
+ * the player winneri defeated player loseri in a match.
+ *
+ * Return a list answer of size 2 where:
+ * - answer[0] is a list of all players that have not lost any matches.
+ * - answer[1] is a list of all players that have lost exactly one match.
+ *
+ * The values in the two lists should be returned in increasing order.
+ *
+ * Note:
+ * - You should only consider the players that have played at least one match.
+ * - The testcases will be generated such that no two matches will have the same outcome.
+ */
+
+/**
+ * @param {number[][]} matches
+ * @return {number[][]}
+ */
+var findWinners = function(matches) {
+  const lossCount = new Map();
+
+  for (const [winner, loser] of matches) {
+    lossCount.set(winner, lossCount.get(winner) || 0);
+    lossCount.set(loser, (lossCount.get(loser) || 0) + 1);
+  }
+
+  const noLosses = [];
+  const oneLoss = [];
+
+  for (const [player, losses] of lossCount) {
+    if (losses === 0) noLosses.push(player);
+    else if (losses === 1) oneLoss.push(player);
+  }
+
+  return [
+    noLosses.sort((a, b) => a - b),
+    oneLoss.sort((a, b) => a - b)
+  ];
+};

From 9288c10e0b81a1bc3413d3545cc4c8d09d9b80e9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 00:15:37 -0500
Subject: [PATCH 326/495] Add solution #2232

---
 README.md                                     |  3 +-
 ...ult-by-adding-parentheses-to-expression.js | 50 +++++++++++++++++++
 2 files changed, 52 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2232-minimize-result-by-adding-parentheses-to-expression.js

diff --git a/README.md b/README.md
index 7fa4a5fb..c81a32a0 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,830 LeetCode solutions in JavaScript
+# 1,831 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1705,6 +1705,7 @@
 2224|[Minimum Number of Operations to Convert Time](./solutions/2224-minimum-number-of-operations-to-convert-time.js)|Easy|
 2225|[Find Players With Zero or One Losses](./solutions/2225-find-players-with-zero-or-one-losses.js)|Medium|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
+2232|[Minimize Result by Adding Parentheses to Expression](./solutions/2232-minimize-result-by-adding-parentheses-to-expression.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
diff --git a/solutions/2232-minimize-result-by-adding-parentheses-to-expression.js b/solutions/2232-minimize-result-by-adding-parentheses-to-expression.js
new file mode 100644
index 00000000..f32f3fd9
--- /dev/null
+++ b/solutions/2232-minimize-result-by-adding-parentheses-to-expression.js
@@ -0,0 +1,50 @@
+/**
+ * 2232. Minimize Result by Adding Parentheses to Expression
+ * https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed string expression of the form "+" where 
+ * and  represent positive integers.
+ *
+ * Add a pair of parentheses to expression such that after the addition of parentheses,
+ * expression is a valid mathematical expression and evaluates to the smallest possible
+ * value. The left parenthesis must be added to the left of '+' and the right parenthesis
+ * must be added to the right of '+'.
+ *
+ * Return expression after adding a pair of parentheses such that expression evaluates to the
+ * smallest possible value. If there are multiple answers that yield the same result, return
+ * any of them.
+ *
+ * The input has been generated such that the original value of expression, and the value of
+ * expression after adding any pair of parentheses that meets the requirements fits within
+ * a signed 32-bit integer.
+ */
+
+/**
+ * @param {string} expression
+ * @return {string}
+ */
+var minimizeResult = function(expression) {
+  const plusIndex = expression.indexOf('+');
+  const left = expression.slice(0, plusIndex);
+  const right = expression.slice(plusIndex + 1);
+  let minValue = Infinity;
+  let result = '';
+
+  for (let i = 0; i < left.length; i++) {
+    for (let j = 1; j <= right.length; j++) {
+      const leftPrefix = i === 0 ? 1 : parseInt(left.slice(0, i));
+      const leftNum = parseInt(left.slice(i), 10);
+      const rightNum = parseInt(right.slice(0, j), 10);
+      const rightSuffix = j === right.length ? 1 : parseInt(right.slice(j), 10);
+      const value = leftPrefix * (leftNum + rightNum) * rightSuffix;
+
+      if (value < minValue) {
+        minValue = value;
+        result = `${left.slice(0, i)}(${left.slice(i)}+${right.slice(0, j)})${right.slice(j)}`;
+      }
+    }
+  }
+
+  return result;
+};

From 6d1e53ec22343f0d52d73a2c2196e6b986a23ccb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 00:18:26 -0500
Subject: [PATCH 327/495] Add solution #2236

---
 README.md                                     |  3 ++-
 solutions/2236-root-equals-sum-of-children.js | 27 +++++++++++++++++++
 2 files changed, 29 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2236-root-equals-sum-of-children.js

diff --git a/README.md b/README.md
index c81a32a0..f11f6ee7 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,831 LeetCode solutions in JavaScript
+# 1,832 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1707,6 +1707,7 @@
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
 2232|[Minimize Result by Adding Parentheses to Expression](./solutions/2232-minimize-result-by-adding-parentheses-to-expression.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
+2236|[Root Equals Sum of Children](./solutions/2236-root-equals-sum-of-children.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
diff --git a/solutions/2236-root-equals-sum-of-children.js b/solutions/2236-root-equals-sum-of-children.js
new file mode 100644
index 00000000..fa9a3cd9
--- /dev/null
+++ b/solutions/2236-root-equals-sum-of-children.js
@@ -0,0 +1,27 @@
+/**
+ * 2236. Root Equals Sum of Children
+ * https://leetcode.com/problems/root-equals-sum-of-children/
+ * Difficulty: Easy
+ *
+ * You are given the root of a binary tree that consists of exactly 3 nodes: the root, its
+ * left child, and its right child.
+ *
+ * Return true if the value of the root is equal to the sum of the values of its two children,
+ * or false otherwise.
+ */
+
+/**
+ * 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 checkTree = function(root) {
+  return root.val === root.left.val + root.right.val;
+};

From 5098fea2f87dc2ef7ed9ab85ba45d453ddeea26e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 00:19:17 -0500
Subject: [PATCH 328/495] Add solution #2239

---
 README.md                                     |  3 ++-
 solutions/2239-find-closest-number-to-zero.js | 27 +++++++++++++++++++
 2 files changed, 29 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2239-find-closest-number-to-zero.js

diff --git a/README.md b/README.md
index f11f6ee7..508a5784 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,832 LeetCode solutions in JavaScript
+# 1,833 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1708,6 +1708,7 @@
 2232|[Minimize Result by Adding Parentheses to Expression](./solutions/2232-minimize-result-by-adding-parentheses-to-expression.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
 2236|[Root Equals Sum of Children](./solutions/2236-root-equals-sum-of-children.js)|Easy|
+2239|[Find Closest Number to Zero](./solutions/2239-find-closest-number-to-zero.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
diff --git a/solutions/2239-find-closest-number-to-zero.js b/solutions/2239-find-closest-number-to-zero.js
new file mode 100644
index 00000000..56d07d8e
--- /dev/null
+++ b/solutions/2239-find-closest-number-to-zero.js
@@ -0,0 +1,27 @@
+/**
+ * 2239. Find Closest Number to Zero
+ * https://leetcode.com/problems/find-closest-number-to-zero/
+ * Difficulty: Easy
+ *
+ * Given an integer array nums of size n, return the number with the value closest to 0 in nums.
+ * If there are multiple answers, return the number with the largest value.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var findClosestNumber = function(nums) {
+  let result = nums[0];
+  let minDistance = Math.abs(nums[0]);
+
+  for (const num of nums) {
+    const distance = Math.abs(num);
+    if (distance < minDistance || (distance === minDistance && num > result)) {
+      minDistance = distance;
+      result = num;
+    }
+  }
+
+  return result;
+};

From 377c7dabebb3d3f1973740821bac63cc8a507d37 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 00:20:35 -0500
Subject: [PATCH 329/495] Add solution #2240

---
 README.md                                     |  3 +-
 ...-number-of-ways-to-buy-pens-and-pencils.js | 31 +++++++++++++++++++
 2 files changed, 33 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2240-number-of-ways-to-buy-pens-and-pencils.js

diff --git a/README.md b/README.md
index 508a5784..7c76fac2 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,833 LeetCode solutions in JavaScript
+# 1,834 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1709,6 +1709,7 @@
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
 2236|[Root Equals Sum of Children](./solutions/2236-root-equals-sum-of-children.js)|Easy|
 2239|[Find Closest Number to Zero](./solutions/2239-find-closest-number-to-zero.js)|Easy|
+2240|[Number of Ways to Buy Pens and Pencils](./solutions/2240-number-of-ways-to-buy-pens-and-pencils.js)|Medium|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
diff --git a/solutions/2240-number-of-ways-to-buy-pens-and-pencils.js b/solutions/2240-number-of-ways-to-buy-pens-and-pencils.js
new file mode 100644
index 00000000..b55f1cff
--- /dev/null
+++ b/solutions/2240-number-of-ways-to-buy-pens-and-pencils.js
@@ -0,0 +1,31 @@
+/**
+ * 2240. Number of Ways to Buy Pens and Pencils
+ * https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/
+ * Difficulty: Medium
+ *
+ * You are given an integer total indicating the amount of money you have. You are also given
+ * two integers cost1 and cost2 indicating the price of a pen and pencil respectively. You can
+ * spend part or all of your money to buy multiple quantities (or none) of each kind of writing
+ * utensil.
+ *
+ * Return the number of distinct ways you can buy some number of pens and pencils.
+ */
+
+/**
+ * @param {number} total
+ * @param {number} cost1
+ * @param {number} cost2
+ * @return {number}
+ */
+var waysToBuyPensPencils = function(total, cost1, cost2) {
+  let result = 0;
+  const maxPens = Math.floor(total / cost1);
+
+  for (let pens = 0; pens <= maxPens; pens++) {
+    const remaining = total - pens * cost1;
+    const pencils = Math.floor(remaining / cost2);
+    result += pencils + 1;
+  }
+
+  return result;
+};

From e7e195355fb59d660dae3405f8a0e09a850aaf18 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 00:22:33 -0500
Subject: [PATCH 330/495] Add solution #2241

---
 README.md                               |  3 +-
 solutions/2241-design-an-atm-machine.js | 64 +++++++++++++++++++++++++
 2 files changed, 66 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2241-design-an-atm-machine.js

diff --git a/README.md b/README.md
index 7c76fac2..3b8d4111 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,834 LeetCode solutions in JavaScript
+# 1,835 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1710,6 +1710,7 @@
 2236|[Root Equals Sum of Children](./solutions/2236-root-equals-sum-of-children.js)|Easy|
 2239|[Find Closest Number to Zero](./solutions/2239-find-closest-number-to-zero.js)|Easy|
 2240|[Number of Ways to Buy Pens and Pencils](./solutions/2240-number-of-ways-to-buy-pens-and-pencils.js)|Medium|
+2241|[Design an ATM Machine](./solutions/2241-design-an-atm-machine.js)|Medium|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
diff --git a/solutions/2241-design-an-atm-machine.js b/solutions/2241-design-an-atm-machine.js
new file mode 100644
index 00000000..4a5afa87
--- /dev/null
+++ b/solutions/2241-design-an-atm-machine.js
@@ -0,0 +1,64 @@
+/**
+ * 2241. Design an ATM Machine
+ * https://leetcode.com/problems/design-an-atm-machine/
+ * Difficulty: Medium
+ *
+ * There is an ATM machine that stores banknotes of 5 denominations: 20, 50, 100, 200, and
+ * 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or
+ * withdraw any amount of money.
+ *
+ * When withdrawing, the machine prioritizes using banknotes of larger values.
+ * - For example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote,
+ *   and 1 $200 banknote, then the machine will use the $100 and $200 banknotes.
+ * - However, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote,
+ *   then the withdraw request will be rejected because the machine will first try to use the
+ *   $500 banknote and then be unable to use banknotes to complete the remaining $100. Note
+ *   that the machine is not allowed to use the $200 banknotes instead of the $500 banknote.
+ *
+ * Implement the ATM class:
+ * - ATM() Initializes the ATM object.
+ * - void deposit(int[] banknotesCount) Deposits new banknotes in the order $20, $50, $100,
+ *   $200, and $500.
+ * - int[] withdraw(int amount) Returns an array of length 5 of the number of banknotes that
+ *   will be handed to the user in the order $20, $50, $100, $200, and $500, and update the
+ *   number of banknotes in the ATM after withdrawing. Returns [-1] if it is not possible (do
+ *   not withdraw any banknotes in this case).
+ */
+
+var ATM = function() {
+  this.denominations = [20, 50, 100, 200, 500];
+  this.notes = [0, 0, 0, 0, 0];
+};
+
+/**
+ * @param {number[]} banknotesCount
+ * @return {void}
+ */
+ATM.prototype.deposit = function(banknotesCount) {
+  for (let i = 0; i < 5; i++) {
+    this.notes[i] += banknotesCount[i];
+  }
+};
+
+/**
+ * @param {number} amount
+ * @return {number[]}
+ */
+ATM.prototype.withdraw = function(amount) {
+  const result = [0, 0, 0, 0, 0];
+  let remaining = amount;
+
+  for (let i = 4; i >= 0; i--) {
+    const count = Math.min(Math.floor(remaining / this.denominations[i]), this.notes[i]);
+    result[i] = count;
+    remaining -= count * this.denominations[i];
+  }
+
+  if (remaining !== 0) return [-1];
+
+  for (let i = 0; i < 5; i++) {
+    this.notes[i] -= result[i];
+  }
+
+  return result;
+};

From f789b7b5de9fb2a82db6753b5444d67417719c27 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 00:24:53 -0500
Subject: [PATCH 331/495] Add solution #2243

---
 README.md                                     |  3 +-
 .../2243-calculate-digit-sum-of-a-string.js   | 36 +++++++++++++++++++
 2 files changed, 38 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2243-calculate-digit-sum-of-a-string.js

diff --git a/README.md b/README.md
index 3b8d4111..9144d89c 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,835 LeetCode solutions in JavaScript
+# 1,836 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1711,6 +1711,7 @@
 2239|[Find Closest Number to Zero](./solutions/2239-find-closest-number-to-zero.js)|Easy|
 2240|[Number of Ways to Buy Pens and Pencils](./solutions/2240-number-of-ways-to-buy-pens-and-pencils.js)|Medium|
 2241|[Design an ATM Machine](./solutions/2241-design-an-atm-machine.js)|Medium|
+2243|[Calculate Digit Sum of a String](./solutions/2243-calculate-digit-sum-of-a-string.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
diff --git a/solutions/2243-calculate-digit-sum-of-a-string.js b/solutions/2243-calculate-digit-sum-of-a-string.js
new file mode 100644
index 00000000..293438ed
--- /dev/null
+++ b/solutions/2243-calculate-digit-sum-of-a-string.js
@@ -0,0 +1,36 @@
+/**
+ * 2243. Calculate Digit Sum of a String
+ * https://leetcode.com/problems/calculate-digit-sum-of-a-string/
+ * Difficulty: Easy
+ *
+ * You are given a string s consisting of digits and an integer k.
+ *
+ * A round can be completed if the length of s is greater than k. In one round, do the following:
+ * 1. Divide s into consecutive groups of size k such that the first k characters are in the first
+ *    group, the next k characters are in the second group, and so on. Note that the size of the
+ *    last group can be smaller than k.
+ * 2. Replace each group of s with a string representing the sum of all its digits. For example,
+ *    "346" is replaced with "13" because 3 + 4 + 6 = 13.
+ * 3. Merge consecutive groups together to form a new string. If the length of the string is greater
+ *    than k, repeat from step 1.
+ *
+ * Return s after all rounds have been completed.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} k
+ * @return {string}
+ */
+var digitSum = function(s, k) {
+  while (s.length > k) {
+    let next = '';
+    for (let i = 0; i < s.length; i += k) {
+      const group = s.slice(i, i + k);
+      const sum = group.split('').reduce((acc, digit) => acc + Number(digit), 0);
+      next += sum;
+    }
+    s = next;
+  }
+  return s;
+};

From aff4bb352c40ae8b8924d05f39ba78a9ec4fe0b0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 00:26:24 -0500
Subject: [PATCH 332/495] Add solution #2246

---
 README.md                                     |  3 +-
 ...path-with-different-adjacent-characters.js | 54 +++++++++++++++++++
 2 files changed, 56 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2246-longest-path-with-different-adjacent-characters.js

diff --git a/README.md b/README.md
index 9144d89c..59fe8b72 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,836 LeetCode solutions in JavaScript
+# 1,837 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1713,6 +1713,7 @@
 2241|[Design an ATM Machine](./solutions/2241-design-an-atm-machine.js)|Medium|
 2243|[Calculate Digit Sum of a String](./solutions/2243-calculate-digit-sum-of-a-string.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
+2246|[Longest Path With Different Adjacent Characters](./solutions/2246-longest-path-with-different-adjacent-characters.js)|Hard|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
diff --git a/solutions/2246-longest-path-with-different-adjacent-characters.js b/solutions/2246-longest-path-with-different-adjacent-characters.js
new file mode 100644
index 00000000..4eb8cb53
--- /dev/null
+++ b/solutions/2246-longest-path-with-different-adjacent-characters.js
@@ -0,0 +1,54 @@
+/**
+ * 2246. Longest Path With Different Adjacent Characters
+ * https://leetcode.com/problems/longest-path-with-different-adjacent-characters/
+ * Difficulty: Hard
+ *
+ * You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node
+ * 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array
+ * parent of size n, where parent[i] is the parent of node i. Since node 0 is the root,
+ * parent[0] == -1.
+ *
+ * You are also given a string s of length n, where s[i] is the character assigned to node i.
+ *
+ * Return the length of the longest path in the tree such that no pair of adjacent nodes on the path
+ * have the same character assigned to them.
+ */
+
+/**
+ * @param {number[]} parent
+ * @param {string} s
+ * @return {number}
+ */
+var longestPath = function(parent, s) {
+  const n = parent.length;
+  const children = Array.from({ length: n }, () => []);
+  let result = 1;
+
+  for (let i = 1; i < n; i++) {
+    children[parent[i]].push(i);
+  }
+
+  findLongest(0);
+
+  return result;
+
+  function findLongest(node) {
+    let longest = 0;
+    let secondLongest = 0;
+
+    for (const child of children[node]) {
+      const length = findLongest(child);
+      if (s[child] !== s[node]) {
+        if (length > longest) {
+          secondLongest = longest;
+          longest = length;
+        } else if (length > secondLongest) {
+          secondLongest = length;
+        }
+      }
+    }
+
+    result = Math.max(result, longest + secondLongest + 1);
+    return longest + 1;
+  }
+};

From c41e4175c8889f82e5d590b9ec904d9bd8f8215b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 00:27:18 -0500
Subject: [PATCH 333/495] Add solution #2248

---
 README.md                                     |  3 +-
 .../2248-intersection-of-multiple-arrays.js   | 31 +++++++++++++++++++
 2 files changed, 33 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2248-intersection-of-multiple-arrays.js

diff --git a/README.md b/README.md
index 59fe8b72..8067b3bc 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,837 LeetCode solutions in JavaScript
+# 1,838 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1714,6 +1714,7 @@
 2243|[Calculate Digit Sum of a String](./solutions/2243-calculate-digit-sum-of-a-string.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
 2246|[Longest Path With Different Adjacent Characters](./solutions/2246-longest-path-with-different-adjacent-characters.js)|Hard|
+2248|[Intersection of Multiple Arrays](./solutions/2248-intersection-of-multiple-arrays.js)|Easy|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
diff --git a/solutions/2248-intersection-of-multiple-arrays.js b/solutions/2248-intersection-of-multiple-arrays.js
new file mode 100644
index 00000000..fa162656
--- /dev/null
+++ b/solutions/2248-intersection-of-multiple-arrays.js
@@ -0,0 +1,31 @@
+/**
+ * 2248. Intersection of Multiple Arrays
+ * https://leetcode.com/problems/intersection-of-multiple-arrays/
+ * Difficulty: Easy
+ *
+ * Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers,
+ * return the list of integers that are present in each array of nums sorted in ascending order.
+ */
+
+/**
+ * @param {number[][]} nums
+ * @return {number[]}
+ */
+var intersection = function(nums) {
+  const count = new Map();
+
+  for (const array of nums) {
+    for (const num of array) {
+      count.set(num, (count.get(num) || 0) + 1);
+    }
+  }
+
+  const result = [];
+  for (const [num, freq] of count) {
+    if (freq === nums.length) {
+      result.push(num);
+    }
+  }
+
+  return result.sort((a, b) => a - b);
+};

From 7520d382168470f8bba7dff3660264161540c355 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 00:28:26 -0500
Subject: [PATCH 334/495] Add solution #2249

---
 README.md                                     |  3 +-
 ...49-count-lattice-points-inside-a-circle.js | 33 +++++++++++++++++++
 2 files changed, 35 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2249-count-lattice-points-inside-a-circle.js

diff --git a/README.md b/README.md
index 8067b3bc..6ade4a7e 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,838 LeetCode solutions in JavaScript
+# 1,839 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1715,6 +1715,7 @@
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
 2246|[Longest Path With Different Adjacent Characters](./solutions/2246-longest-path-with-different-adjacent-characters.js)|Hard|
 2248|[Intersection of Multiple Arrays](./solutions/2248-intersection-of-multiple-arrays.js)|Easy|
+2249|[Count Lattice Points Inside a Circle](./solutions/2249-count-lattice-points-inside-a-circle.js)|Medium|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
diff --git a/solutions/2249-count-lattice-points-inside-a-circle.js b/solutions/2249-count-lattice-points-inside-a-circle.js
new file mode 100644
index 00000000..2c762806
--- /dev/null
+++ b/solutions/2249-count-lattice-points-inside-a-circle.js
@@ -0,0 +1,33 @@
+/**
+ * 2249. Count Lattice Points Inside a Circle
+ * https://leetcode.com/problems/count-lattice-points-inside-a-circle/
+ * Difficulty: Medium
+ *
+ * Given a 2D integer array circles where circles[i] = [xi, yi, ri] represents the center (xi, yi)
+ * and radius ri of the ith circle drawn on a grid, return the number of lattice points that are
+ * present inside at least one circle.
+ *
+ * Note:
+ * - A lattice point is a point with integer coordinates.
+ * - Points that lie on the circumference of a circle are also considered to be inside it.
+ */
+
+/**
+ * @param {number[][]} circles
+ * @return {number}
+ */
+var countLatticePoints = function(circles) {
+  const set = new Set();
+
+  for (const [x, y, r] of circles) {
+    for (let i = x - r; i <= x + r; i++) {
+      for (let j = y - r; j <= y + r; j++) {
+        if ((x - i) ** 2 + (y - j) ** 2 <= r ** 2) {
+          set.add(`${i},${j}`);
+        }
+      }
+    }
+  }
+
+  return set.size;
+};

From dc06fe78ffede65fc3b4bcac33cd744b51d530f1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 00:29:24 -0500
Subject: [PATCH 335/495] Add solution #2251

---
 README.md                                     |  3 +-
 .../2251-number-of-flowers-in-full-bloom.js   | 43 +++++++++++++++++++
 2 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2251-number-of-flowers-in-full-bloom.js

diff --git a/README.md b/README.md
index 6ade4a7e..fd14d66d 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,839 LeetCode solutions in JavaScript
+# 1,840 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1716,6 +1716,7 @@
 2246|[Longest Path With Different Adjacent Characters](./solutions/2246-longest-path-with-different-adjacent-characters.js)|Hard|
 2248|[Intersection of Multiple Arrays](./solutions/2248-intersection-of-multiple-arrays.js)|Easy|
 2249|[Count Lattice Points Inside a Circle](./solutions/2249-count-lattice-points-inside-a-circle.js)|Medium|
+2251|[Number of Flowers in Full Bloom](./solutions/2251-number-of-flowers-in-full-bloom.js)|Hard|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
diff --git a/solutions/2251-number-of-flowers-in-full-bloom.js b/solutions/2251-number-of-flowers-in-full-bloom.js
new file mode 100644
index 00000000..c9ae393f
--- /dev/null
+++ b/solutions/2251-number-of-flowers-in-full-bloom.js
@@ -0,0 +1,43 @@
+/**
+ * 2251. Number of Flowers in Full Bloom
+ * https://leetcode.com/problems/number-of-flowers-in-full-bloom/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means
+ * the ith flower will be in full bloom from starti to endi (inclusive). You are also given a
+ * 0-indexed integer array people of size n, where people[i] is the time that the ith person
+ * will arrive to see the flowers.
+ *
+ * Return an integer array answer of size n, where answer[i] is the number of flowers that are
+ * in full bloom when the ith person arrives.
+ */
+
+/**
+ * @param {number[][]} flowers
+ * @param {number[]} people
+ * @return {number[]}
+ */
+var fullBloomFlowers = function(flowers, people) {
+  const events = [];
+  for (const [start, end] of flowers) {
+    events.push([start, 1]);
+    events.push([end + 1, -1]);
+  }
+  events.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
+
+  const result = new Array(people.length).fill(0);
+  const peopleWithIndex = people.map((time, index) => [time, index]);
+  peopleWithIndex.sort((a, b) => a[0] - b[0]);
+
+  let bloomCount = 0;
+  let eventIndex = 0;
+  for (const [time, personIndex] of peopleWithIndex) {
+    while (eventIndex < events.length && events[eventIndex][0] <= time) {
+      bloomCount += events[eventIndex][1];
+      eventIndex++;
+    }
+    result[personIndex] = bloomCount;
+  }
+
+  return result;
+};

From 646079d6568ab6647bc848e19c0e29af79d9e6d3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 11:09:04 -0500
Subject: [PATCH 336/495] Add solution #2227

---
 README.md                                     |  3 +-
 solutions/2227-encrypt-and-decrypt-strings.js | 77 +++++++++++++++++++
 2 files changed, 79 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2227-encrypt-and-decrypt-strings.js

diff --git a/README.md b/README.md
index fd14d66d..5b326ee9 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,840 LeetCode solutions in JavaScript
+# 1,841 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1705,6 +1705,7 @@
 2224|[Minimum Number of Operations to Convert Time](./solutions/2224-minimum-number-of-operations-to-convert-time.js)|Easy|
 2225|[Find Players With Zero or One Losses](./solutions/2225-find-players-with-zero-or-one-losses.js)|Medium|
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
+2227|[Encrypt and Decrypt Strings](./solutions/2227-encrypt-and-decrypt-strings.js)|Hard|
 2232|[Minimize Result by Adding Parentheses to Expression](./solutions/2232-minimize-result-by-adding-parentheses-to-expression.js)|Medium|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
 2236|[Root Equals Sum of Children](./solutions/2236-root-equals-sum-of-children.js)|Easy|
diff --git a/solutions/2227-encrypt-and-decrypt-strings.js b/solutions/2227-encrypt-and-decrypt-strings.js
new file mode 100644
index 00000000..fd773ffb
--- /dev/null
+++ b/solutions/2227-encrypt-and-decrypt-strings.js
@@ -0,0 +1,77 @@
+/**
+ * 2227. Encrypt and Decrypt Strings
+ * https://leetcode.com/problems/encrypt-and-decrypt-strings/
+ * Difficulty: Hard
+ *
+ * You are given a character array keys containing unique characters and a string array values
+ * containing strings of length 2. You are also given another string array dictionary that
+ * contains all permitted original strings after decryption. You should implement a data structure
+ * that can encrypt or decrypt a 0-indexed string.
+ *
+ * A string is encrypted with the following process:
+ * 1. For each character c in the string, we find the index i satisfying keys[i] == c in keys.
+ * 2. Replace c with values[i] in the string.
+ *
+ * Note that in case a character of the string is not present in keys, the encryption process cannot
+ * be carried out, and an empty string "" is returned.
+ *
+ * A string is decrypted with the following process:
+ * 1. For each substring s of length 2 occurring at an even index in the string, we find an i such
+ *    that values[i] == s. If there are multiple valid i, we choose any one of them. This means a
+ *    string could have multiple possible strings it can decrypt to.
+ * 2. Replace s with keys[i] in the string.
+ *
+ * Implement the Encrypter class:
+ * - Encrypter(char[] keys, String[] values, String[] dictionary) Initializes the Encrypter class
+ *   with keys, values, and dictionary.
+ * - String encrypt(String word1) Encrypts word1 with the encryption process described above and
+ *   returns the encrypted string.
+ * - int decrypt(String word2) Returns the number of possible strings word2 could decrypt to that
+ *   also appear in dictionary.
+ */
+
+/**
+ * @param {character[]} keys
+ * @param {string[]} values
+ * @param {string[]} dictionary
+ */
+var Encrypter = function(keys, values, dictionary) {
+  this.encryptMap = new Map();
+  this.validEncryptions = new Map();
+
+  for (let i = 0; i < keys.length; i++) {
+    this.encryptMap.set(keys[i], values[i]);
+  }
+
+  for (const word of dictionary) {
+    const encrypted = this.encrypt(word);
+    if (encrypted !== '') {
+      this.validEncryptions.set(encrypted, (this.validEncryptions.get(encrypted) || 0) + 1);
+    }
+  }
+};
+
+/**
+ * @param {string} word1
+ * @return {string}
+ */
+Encrypter.prototype.encrypt = function(word1) {
+  let result = '';
+
+  for (const char of word1) {
+    if (!this.encryptMap.has(char)) {
+      return '';
+    }
+    result += this.encryptMap.get(char);
+  }
+
+  return result;
+};
+
+/**
+ * @param {string} word2
+ * @return {number}
+ */
+Encrypter.prototype.decrypt = function(word2) {
+  return this.validEncryptions.get(word2) || 0;
+};

From 07d917800befa7267dac07134d281f7a04c1b60b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 11:29:41 -0500
Subject: [PATCH 337/495] Add solution #2234

---
 README.md                                     |  3 +-
 ...234-maximum-total-beauty-of-the-gardens.js | 99 +++++++++++++++++++
 2 files changed, 101 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2234-maximum-total-beauty-of-the-gardens.js

diff --git a/README.md b/README.md
index 5b326ee9..85bdb7cc 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,841 LeetCode solutions in JavaScript
+# 1,842 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1707,6 +1707,7 @@
 2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
 2227|[Encrypt and Decrypt Strings](./solutions/2227-encrypt-and-decrypt-strings.js)|Hard|
 2232|[Minimize Result by Adding Parentheses to Expression](./solutions/2232-minimize-result-by-adding-parentheses-to-expression.js)|Medium|
+2234|[Maximum Total Beauty of the Gardens](./solutions/2234-maximum-total-beauty-of-the-gardens.js)|Hard|
 2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
 2236|[Root Equals Sum of Children](./solutions/2236-root-equals-sum-of-children.js)|Easy|
 2239|[Find Closest Number to Zero](./solutions/2239-find-closest-number-to-zero.js)|Easy|
diff --git a/solutions/2234-maximum-total-beauty-of-the-gardens.js b/solutions/2234-maximum-total-beauty-of-the-gardens.js
new file mode 100644
index 00000000..54985527
--- /dev/null
+++ b/solutions/2234-maximum-total-beauty-of-the-gardens.js
@@ -0,0 +1,99 @@
+/**
+ * 2234. Maximum Total Beauty of the Gardens
+ * https://leetcode.com/problems/maximum-total-beauty-of-the-gardens/
+ * Difficulty: Hard
+ *
+ * Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total
+ * beauty of all her gardens.
+ *
+ * You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number
+ * of flowers already planted in the ith garden. Flowers that are already planted cannot be
+ * removed. You are then given another integer newFlowers, which is the maximum number of
+ * flowers that Alice can additionally plant. You are also given the integers target, full,
+ * and partial.
+ *
+ * A garden is considered complete if it has at least target flowers. The total beauty of the
+ * gardens is then determined as the sum of the following:
+ * - The number of complete gardens multiplied by full.
+ * - The minimum number of flowers in any of the incomplete gardens multiplied by partial.
+ *   If there are no incomplete gardens, then this value will be 0.
+ *
+ * Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.
+ */
+
+/**
+ * @param {number[]} flowers
+ * @param {number} newFlowers
+ * @param {number} target
+ * @param {number} full
+ * @param {number} partial
+ * @return {number}
+ */
+var maximumBeauty = function(flowers, newFlowers, target, full, partial) {
+  const n = flowers.length;
+  flowers.sort((a, b) => b - a);
+
+  const suffixCost = Array(n + 1).fill(0);
+  let lastUniqueIndex = n - 1;
+  let minIndex = n - 2;
+
+  for (; minIndex >= 0; --minIndex) {
+    if (flowers[minIndex] >= target) break;
+
+    const flowerDiff = flowers[minIndex] - flowers[minIndex + 1];
+    const gardenCount = n - lastUniqueIndex;
+    suffixCost[minIndex] = suffixCost[minIndex + 1] + flowerDiff * gardenCount;
+
+    if (suffixCost[minIndex] > newFlowers) break;
+
+    if (flowers[minIndex] !== flowers[minIndex - 1]) {
+      lastUniqueIndex = minIndex;
+    }
+  }
+
+  ++minIndex;
+
+  const remainingFlowersForMin = newFlowers - suffixCost[minIndex];
+  const gardenCountForMin = n - minIndex;
+  let minFlowerValue = Math.min(
+    target - 1,
+    flowers[minIndex] + Math.floor(remainingFlowersForMin / gardenCountForMin)
+  );
+
+  let result = 0;
+
+  for (let i = 0; i < n; ++i) {
+    if (flowers[i] >= target) {
+      continue;
+    }
+
+    const currentBeauty = i * full + minFlowerValue * partial;
+    result = Math.max(result, currentBeauty);
+
+    const flowersNeeded = target - flowers[i];
+    if (flowersNeeded > newFlowers) break;
+
+    newFlowers -= flowersNeeded;
+    flowers[i] = target;
+
+    while (
+      minIndex <= i || newFlowers < suffixCost[minIndex]
+      || (minIndex > 0 && flowers[minIndex] === flowers[minIndex - 1])
+    ) {
+      ++minIndex;
+    }
+
+    const updatedRemaining = newFlowers - suffixCost[minIndex];
+    const updatedGardenCount = n - minIndex;
+    minFlowerValue = Math.min(
+      target - 1,
+      flowers[minIndex] + Math.floor(updatedRemaining / updatedGardenCount)
+    );
+  }
+
+  if (flowers[n - 1] >= target) {
+    result = Math.max(result, n * full);
+  }
+
+  return result;
+};

From 107e00a20c4e27b022da5149b7818a51b05148ce Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 11:32:27 -0500
Subject: [PATCH 338/495] Add solution #2242

---
 README.md                                     |  3 +-
 .../2242-maximum-score-of-a-node-sequence.js  | 55 +++++++++++++++++++
 2 files changed, 57 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2242-maximum-score-of-a-node-sequence.js

diff --git a/README.md b/README.md
index 85bdb7cc..d2d2f692 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,842 LeetCode solutions in JavaScript
+# 1,843 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1713,6 +1713,7 @@
 2239|[Find Closest Number to Zero](./solutions/2239-find-closest-number-to-zero.js)|Easy|
 2240|[Number of Ways to Buy Pens and Pencils](./solutions/2240-number-of-ways-to-buy-pens-and-pencils.js)|Medium|
 2241|[Design an ATM Machine](./solutions/2241-design-an-atm-machine.js)|Medium|
+2242|[Maximum Score of a Node Sequence](./solutions/2242-maximum-score-of-a-node-sequence.js)|Hard|
 2243|[Calculate Digit Sum of a String](./solutions/2243-calculate-digit-sum-of-a-string.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
 2246|[Longest Path With Different Adjacent Characters](./solutions/2246-longest-path-with-different-adjacent-characters.js)|Hard|
diff --git a/solutions/2242-maximum-score-of-a-node-sequence.js b/solutions/2242-maximum-score-of-a-node-sequence.js
new file mode 100644
index 00000000..b64c16ce
--- /dev/null
+++ b/solutions/2242-maximum-score-of-a-node-sequence.js
@@ -0,0 +1,55 @@
+/**
+ * 2242. Maximum Score of a Node Sequence
+ * https://leetcode.com/problems/maximum-score-of-a-node-sequence/
+ * Difficulty: Hard
+ *
+ * There is an undirected graph with n nodes, numbered from 0 to n - 1.
+ *
+ * You are given a 0-indexed integer array scores of length n where scores[i] denotes the score
+ * of node i. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that
+ * there exists an undirected edge connecting nodes ai and bi.
+ *
+ * A node sequence is valid if it meets the following conditions:
+ * - There is an edge connecting every pair of adjacent nodes in the sequence.
+ * - No node appears more than once in the sequence.
+ *
+ * The score of a node sequence is defined as the sum of the scores of the nodes in the sequence.
+ *
+ * Return the maximum score of a valid node sequence with a length of 4. If no such sequence exists,
+ * return -1.
+ */
+
+/**
+ * @param {number[]} scores
+ * @param {number[][]} edges
+ * @return {number}
+ */
+var maximumScore = function(scores, edges) {
+  const n = scores.length;
+  const graph = new Array(n).fill().map(() => []);
+
+  for (const [a, b] of edges) {
+    graph[a].push(b);
+    graph[b].push(a);
+  }
+
+  for (let i = 0; i < n; i++) {
+    graph[i].sort((a, b) => scores[b] - scores[a]);
+    if (graph[i].length > 3) {
+      graph[i] = graph[i].slice(0, 3);
+    }
+  }
+
+  let result = -1;
+  for (const [a, b] of edges) {
+    for (const c of graph[a]) {
+      if (c === b) continue;
+      for (const d of graph[b]) {
+        if (d === a || d === c) continue;
+        result = Math.max(result, scores[a] + scores[b] + scores[c] + scores[d]);
+      }
+    }
+  }
+
+  return result;
+};

From dada64e68c9caa477e9b2ee80ead88e3dd0abd64 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 11:35:25 -0500
Subject: [PATCH 339/495] Add solution #2245

---
 README.md                                     |   3 +-
 ...ximum-trailing-zeros-in-a-cornered-path.js | 112 ++++++++++++++++++
 2 files changed, 114 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2245-maximum-trailing-zeros-in-a-cornered-path.js

diff --git a/README.md b/README.md
index d2d2f692..84f847c1 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,843 LeetCode solutions in JavaScript
+# 1,844 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1716,6 +1716,7 @@
 2242|[Maximum Score of a Node Sequence](./solutions/2242-maximum-score-of-a-node-sequence.js)|Hard|
 2243|[Calculate Digit Sum of a String](./solutions/2243-calculate-digit-sum-of-a-string.js)|Easy|
 2244|[Minimum Rounds to Complete All Tasks](./solutions/2244-minimum-rounds-to-complete-all-tasks.js)|Medium|
+2245|[Maximum Trailing Zeros in a Cornered Path](./solutions/2245-maximum-trailing-zeros-in-a-cornered-path.js)|Medium|
 2246|[Longest Path With Different Adjacent Characters](./solutions/2246-longest-path-with-different-adjacent-characters.js)|Hard|
 2248|[Intersection of Multiple Arrays](./solutions/2248-intersection-of-multiple-arrays.js)|Easy|
 2249|[Count Lattice Points Inside a Circle](./solutions/2249-count-lattice-points-inside-a-circle.js)|Medium|
diff --git a/solutions/2245-maximum-trailing-zeros-in-a-cornered-path.js b/solutions/2245-maximum-trailing-zeros-in-a-cornered-path.js
new file mode 100644
index 00000000..7f18ed32
--- /dev/null
+++ b/solutions/2245-maximum-trailing-zeros-in-a-cornered-path.js
@@ -0,0 +1,112 @@
+/**
+ * 2245. Maximum Trailing Zeros in a Cornered Path
+ * https://leetcode.com/problems/maximum-trailing-zeros-in-a-cornered-path/
+ * Difficulty: Medium
+ *
+ * You are given a 2D integer array grid of size m x n, where each cell contains a positive integer.
+ *
+ * A cornered path is defined as a set of adjacent cells with at most one turn. More specifically,
+ * the path should exclusively move either horizontally or vertically up to the turn (if there is
+ * one), without returning to a previously visited cell. After the turn, the path will then move
+ * exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa,
+ * also without returning to a previously visited cell.
+ *
+ * The product of a path is defined as the product of all the values in the path.
+ *
+ * Return the maximum number of trailing zeros in the product of a cornered path found in grid.
+ *
+ * Note:
+ * - Horizontal movement means moving in either the left or right direction.
+ * - Vertical movement means moving in either the up or down direction.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var maxTrailingZeros = function(grid) {
+  const m = grid.length;
+  const n = grid[0].length;
+
+  function countFactors(num) {
+    let count2 = 0;
+    let count5 = 0;
+
+    while (num % 2 === 0) {
+      count2++;
+      num = Math.floor(num / 2);
+    }
+
+    while (num % 5 === 0) {
+      count5++;
+      num = Math.floor(num / 5);
+    }
+
+    return [count2, count5];
+  }
+
+  const factors = new Array(m).fill().map(() => new Array(n).fill().map(() => [0, 0]));
+  for (let i = 0; i < m; i++) {
+    for (let j = 0; j < n; j++) {
+      factors[i][j] = countFactors(grid[i][j]);
+    }
+  }
+
+  const rowPrefix = new Array(m).fill().map(() => new Array(n + 1).fill().map(() => [0, 0]));
+  for (let i = 0; i < m; i++) {
+    for (let j = 0; j < n; j++) {
+      rowPrefix[i][j + 1][0] = rowPrefix[i][j][0] + factors[i][j][0];
+      rowPrefix[i][j + 1][1] = rowPrefix[i][j][1] + factors[i][j][1];
+    }
+  }
+
+  const colPrefix = new Array(m + 1).fill().map(() => new Array(n).fill().map(() => [0, 0]));
+  for (let j = 0; j < n; j++) {
+    for (let i = 0; i < m; i++) {
+      colPrefix[i + 1][j][0] = colPrefix[i][j][0] + factors[i][j][0];
+      colPrefix[i + 1][j][1] = colPrefix[i][j][1] + factors[i][j][1];
+    }
+  }
+
+  let maxZeros = 0;
+  for (let i = 0; i < m; i++) {
+    for (let j = 0; j < n; j++) {
+      const [count2, count5] = factors[i][j];
+
+      const leftUp = [
+        rowPrefix[i][j][0] + colPrefix[i][j][0],
+        rowPrefix[i][j][1] + colPrefix[i][j][1]
+      ];
+
+      const leftDown = [
+        rowPrefix[i][j][0] + (colPrefix[m][j][0] - colPrefix[i + 1][j][0]),
+        rowPrefix[i][j][1] + (colPrefix[m][j][1] - colPrefix[i + 1][j][1])
+      ];
+
+      const rightUp = [
+        (rowPrefix[i][n][0] - rowPrefix[i][j + 1][0]) + colPrefix[i][j][0],
+        (rowPrefix[i][n][1] - rowPrefix[i][j + 1][1]) + colPrefix[i][j][1]
+      ];
+
+      const rightDown = [
+        (rowPrefix[i][n][0] - rowPrefix[i][j + 1][0])
+          + (colPrefix[m][j][0] - colPrefix[i + 1][j][0]),
+        (rowPrefix[i][n][1] - rowPrefix[i][j + 1][1])
+          + (colPrefix[m][j][1] - colPrefix[i + 1][j][1])
+      ];
+
+      const paths = [
+        [leftUp[0] + count2, leftUp[1] + count5],
+        [leftDown[0] + count2, leftDown[1] + count5],
+        [rightUp[0] + count2, rightUp[1] + count5],
+        [rightDown[0] + count2, rightDown[1] + count5]
+      ];
+
+      for (const [path2, path5] of paths) {
+        maxZeros = Math.max(maxZeros, Math.min(path2, path5));
+      }
+    }
+  }
+
+  return maxZeros;
+};

From 79704df0607bdd8a68f96e4fba00549c8f3f49f0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 11:36:50 -0500
Subject: [PATCH 340/495] Add solution #2250

---
 README.md                                     |  3 +-
 ...ber-of-rectangles-containing-each-point.js | 62 +++++++++++++++++++
 2 files changed, 64 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2250-count-number-of-rectangles-containing-each-point.js

diff --git a/README.md b/README.md
index 84f847c1..8aee3f41 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,844 LeetCode solutions in JavaScript
+# 1,845 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1720,6 +1720,7 @@
 2246|[Longest Path With Different Adjacent Characters](./solutions/2246-longest-path-with-different-adjacent-characters.js)|Hard|
 2248|[Intersection of Multiple Arrays](./solutions/2248-intersection-of-multiple-arrays.js)|Easy|
 2249|[Count Lattice Points Inside a Circle](./solutions/2249-count-lattice-points-inside-a-circle.js)|Medium|
+2250|[Count Number of Rectangles Containing Each Point](./solutions/2250-count-number-of-rectangles-containing-each-point.js)|Medium|
 2251|[Number of Flowers in Full Bloom](./solutions/2251-number-of-flowers-in-full-bloom.js)|Hard|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
diff --git a/solutions/2250-count-number-of-rectangles-containing-each-point.js b/solutions/2250-count-number-of-rectangles-containing-each-point.js
new file mode 100644
index 00000000..79ed186c
--- /dev/null
+++ b/solutions/2250-count-number-of-rectangles-containing-each-point.js
@@ -0,0 +1,62 @@
+/**
+ * 2250. Count Number of Rectangles Containing Each Point
+ * https://leetcode.com/problems/count-number-of-rectangles-containing-each-point/
+ * Difficulty: Medium
+ *
+ * You are given a 2D integer array rectangles where rectangles[i] = [li, hi] indicates that ith
+ * rectangle has a length of li and a height of hi. You are also given a 2D integer array points
+ * where points[j] = [xj, yj] is a point with coordinates (xj, yj).
+ *
+ * The ith rectangle has its bottom-left corner point at the coordinates (0, 0) and its top-right
+ * corner point at (li, hi).
+ *
+ * Return an integer array count of length points.length where count[j] is the number of rectangles
+ * that contain the jth point.
+ *
+ * The ith rectangle contains the jth point if 0 <= xj <= li and 0 <= yj <= hi. Note that points
+ * that lie on the edges of a rectangle are also considered to be contained by that rectangle.
+ */
+
+/**
+ * @param {number[][]} rectangles
+ * @param {number[][]} points
+ * @return {number[]}
+ */
+var countRectangles = function(rectangles, points) {
+  const rectByHeight = new Array(101).fill().map(() => []);
+
+  for (const [length, height] of rectangles) {
+    rectByHeight[height].push(length);
+  }
+
+  for (let h = 0; h <= 100; h++) {
+    rectByHeight[h].sort((a, b) => a - b);
+  }
+
+  const result = new Array(points.length).fill(0);
+  for (let i = 0; i < points.length; i++) {
+    const [x, y] = points[i];
+
+    for (let h = y; h <= 100; h++) {
+      const lengths = rectByHeight[h];
+
+      let left = 0;
+      let right = lengths.length - 1;
+      let insertPos = lengths.length;
+
+      while (left <= right) {
+        const mid = Math.floor((left + right) / 2);
+        if (lengths[mid] >= x) {
+          insertPos = mid;
+          right = mid - 1;
+        } else {
+          left = mid + 1;
+        }
+      }
+
+      result[i] += lengths.length - insertPos;
+    }
+  }
+
+  return result;
+};

From 0d435cd15e0ac2b322c2d7830e272b23f051d03f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 13:07:27 -0500
Subject: [PATCH 341/495] Add solution #2255

---
 README.md                                     |  3 +-
 .../2255-count-prefixes-of-a-given-string.js  | 30 +++++++++++++++++++
 2 files changed, 32 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2255-count-prefixes-of-a-given-string.js

diff --git a/README.md b/README.md
index 8aee3f41..4b0b8335 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,845 LeetCode solutions in JavaScript
+# 1,846 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1722,6 +1722,7 @@
 2249|[Count Lattice Points Inside a Circle](./solutions/2249-count-lattice-points-inside-a-circle.js)|Medium|
 2250|[Count Number of Rectangles Containing Each Point](./solutions/2250-count-number-of-rectangles-containing-each-point.js)|Medium|
 2251|[Number of Flowers in Full Bloom](./solutions/2251-number-of-flowers-in-full-bloom.js)|Hard|
+2255|[Count Prefixes of a Given String](./solutions/2255-count-prefixes-of-a-given-string.js)|Easy|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
diff --git a/solutions/2255-count-prefixes-of-a-given-string.js b/solutions/2255-count-prefixes-of-a-given-string.js
new file mode 100644
index 00000000..25f3ecbf
--- /dev/null
+++ b/solutions/2255-count-prefixes-of-a-given-string.js
@@ -0,0 +1,30 @@
+/**
+ * 2255. Count Prefixes of a Given String
+ * https://leetcode.com/problems/count-prefixes-of-a-given-string/
+ * Difficulty: Easy
+ *
+ * You are given a string array words and a string s, where words[i] and s comprise only of
+ * lowercase English letters.
+ *
+ * Return the number of strings in words that are a prefix of s.
+ *
+ * A prefix of a string is a substring that occurs at the beginning of the string. A substring
+ * is a contiguous sequence of characters within a string.
+ */
+
+/**
+ * @param {string[]} words
+ * @param {string} s
+ * @return {number}
+ */
+var countPrefixes = function(words, s) {
+  let result = 0;
+
+  for (const word of words) {
+    if (word.length <= s.length && s.startsWith(word)) {
+      result++;
+    }
+  }
+
+  return result;
+};

From ab86882bf8662752b5d794ca6387ec0ea5f73dcc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 13:08:34 -0500
Subject: [PATCH 342/495] Add solution #2256

---
 README.md                                    |  3 +-
 solutions/2256-minimum-average-difference.js | 46 ++++++++++++++++++++
 2 files changed, 48 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2256-minimum-average-difference.js

diff --git a/README.md b/README.md
index 4b0b8335..f9d85692 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,846 LeetCode solutions in JavaScript
+# 1,847 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1723,6 +1723,7 @@
 2250|[Count Number of Rectangles Containing Each Point](./solutions/2250-count-number-of-rectangles-containing-each-point.js)|Medium|
 2251|[Number of Flowers in Full Bloom](./solutions/2251-number-of-flowers-in-full-bloom.js)|Hard|
 2255|[Count Prefixes of a Given String](./solutions/2255-count-prefixes-of-a-given-string.js)|Easy|
+2256|[Minimum Average Difference](./solutions/2256-minimum-average-difference.js)|Medium|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
diff --git a/solutions/2256-minimum-average-difference.js b/solutions/2256-minimum-average-difference.js
new file mode 100644
index 00000000..8c7ebdde
--- /dev/null
+++ b/solutions/2256-minimum-average-difference.js
@@ -0,0 +1,46 @@
+/**
+ * 2256. Minimum Average Difference
+ * https://leetcode.com/problems/minimum-average-difference/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums of length n.
+ *
+ * The average difference of the index i is the absolute difference between the average of the
+ * first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages
+ * should be rounded down to the nearest integer.
+ *
+ * Return the index with the minimum average difference. If there are multiple such indices,
+ * return the smallest one.
+ *
+ * Note:
+ * - The absolute difference of two numbers is the absolute value of their difference.
+ * - The average of n elements is the sum of the n elements divided (integer division) by n.
+ * - The average of 0 elements is considered to be 0.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimumAverageDifference = function(nums) {
+  const n = nums.length;
+  let leftSum = 0;
+  let rightSum = nums.reduce((sum, num) => sum + num, 0);
+  let minDiff = Infinity;
+  let result = 0;
+
+  for (let i = 0; i < n; i++) {
+    leftSum += nums[i];
+    rightSum -= nums[i];
+    const leftAvg = Math.floor(leftSum / (i + 1));
+    const rightAvg = i === n - 1 ? 0 : Math.floor(rightSum / (n - i - 1));
+    const diff = Math.abs(leftAvg - rightAvg);
+
+    if (diff < minDiff) {
+      minDiff = diff;
+      result = i;
+    }
+  }
+
+  return result;
+};

From 4146eaf9bf96096cfe4599591c1686cc45178b38 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 13:09:47 -0500
Subject: [PATCH 343/495] Add solution #2257

---
 README.md                                     |  3 +-
 .../2257-count-unguarded-cells-in-the-grid.js | 59 +++++++++++++++++++
 2 files changed, 61 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2257-count-unguarded-cells-in-the-grid.js

diff --git a/README.md b/README.md
index f9d85692..e672a31c 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,847 LeetCode solutions in JavaScript
+# 1,848 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1724,6 +1724,7 @@
 2251|[Number of Flowers in Full Bloom](./solutions/2251-number-of-flowers-in-full-bloom.js)|Hard|
 2255|[Count Prefixes of a Given String](./solutions/2255-count-prefixes-of-a-given-string.js)|Easy|
 2256|[Minimum Average Difference](./solutions/2256-minimum-average-difference.js)|Medium|
+2257|[Count Unguarded Cells in the Grid](./solutions/2257-count-unguarded-cells-in-the-grid.js)|Medium|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
diff --git a/solutions/2257-count-unguarded-cells-in-the-grid.js b/solutions/2257-count-unguarded-cells-in-the-grid.js
new file mode 100644
index 00000000..87cbde16
--- /dev/null
+++ b/solutions/2257-count-unguarded-cells-in-the-grid.js
@@ -0,0 +1,59 @@
+/**
+ * 2257. Count Unguarded Cells in the Grid
+ * https://leetcode.com/problems/count-unguarded-cells-in-the-grid/
+ * Difficulty: Medium
+ *
+ * You are given two integers m and n representing a 0-indexed m x n grid. You are also given two
+ * 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj]
+ * represent the positions of the ith guard and jth wall respectively.
+ *
+ * A guard can see every cell in the four cardinal directions (north, east, south, or west) starting
+ * from their position unless obstructed by a wall or another guard. A cell is guarded if there is
+ * at least one guard that can see it.
+ *
+ * Return the number of unoccupied cells that are not guarded.
+ */
+
+/**
+ * @param {number} m
+ * @param {number} n
+ * @param {number[][]} guards
+ * @param {number[][]} walls
+ * @return {number}
+ */
+var countUnguarded = function(m, n, guards, walls) {
+  const grid = Array.from({ length: m }, () => Array(n).fill(0));
+
+  for (const [row, col] of walls) {
+    grid[row][col] = 1;
+  }
+  for (const [row, col] of guards) {
+    grid[row][col] = 2;
+  }
+
+  for (const [row, col] of guards) {
+    for (let i = row - 1; i >= 0 && grid[i][col] !== 1 && grid[i][col] !== 2; i--) {
+      grid[i][col] = 3;
+    }
+    for (let i = row + 1; i < m && grid[i][col] !== 1 && grid[i][col] !== 2; i++) {
+      grid[i][col] = 3;
+    }
+    for (let j = col - 1; j >= 0 && grid[row][j] !== 1 && grid[row][j] !== 2; j--) {
+      grid[row][j] = 3;
+    }
+    for (let j = col + 1; j < n && grid[row][j] !== 1 && grid[row][j] !== 2; j++) {
+      grid[row][j] = 3;
+    }
+  }
+
+  let result = 0;
+  for (let i = 0; i < m; i++) {
+    for (let j = 0; j < n; j++) {
+      if (grid[i][j] === 0) {
+        result++;
+      }
+    }
+  }
+
+  return result;
+};

From 8ba1878f05b37ce5aeab2f56e6c4177bd26eba65 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 13:10:36 -0500
Subject: [PATCH 344/495] Add solution #2259

---
 README.md                                     |  3 +-
 ...ve-digit-from-number-to-maximize-result.js | 31 +++++++++++++++++++
 2 files changed, 33 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2259-remove-digit-from-number-to-maximize-result.js

diff --git a/README.md b/README.md
index e672a31c..667590b8 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,848 LeetCode solutions in JavaScript
+# 1,849 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1725,6 +1725,7 @@
 2255|[Count Prefixes of a Given String](./solutions/2255-count-prefixes-of-a-given-string.js)|Easy|
 2256|[Minimum Average Difference](./solutions/2256-minimum-average-difference.js)|Medium|
 2257|[Count Unguarded Cells in the Grid](./solutions/2257-count-unguarded-cells-in-the-grid.js)|Medium|
+2259|[Remove Digit From Number to Maximize Result](./solutions/2259-remove-digit-from-number-to-maximize-result.js)|Easy|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
diff --git a/solutions/2259-remove-digit-from-number-to-maximize-result.js b/solutions/2259-remove-digit-from-number-to-maximize-result.js
new file mode 100644
index 00000000..d9ee4397
--- /dev/null
+++ b/solutions/2259-remove-digit-from-number-to-maximize-result.js
@@ -0,0 +1,31 @@
+/**
+ * 2259. Remove Digit From Number to Maximize Result
+ * https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/
+ * Difficulty: Easy
+ *
+ * You are given a string number representing a positive integer and a character digit.
+ *
+ * Return the resulting string after removing exactly one occurrence of digit from number such that
+ * the value of the resulting string in decimal form is maximized. The test cases are generated such
+ * that digit occurs at least once in number.
+ */
+
+/**
+ * @param {string} number
+ * @param {character} digit
+ * @return {string}
+ */
+var removeDigit = function(number, digit) {
+  let result = '';
+
+  for (let i = 0; i < number.length; i++) {
+    if (number[i] === digit) {
+      const candidate = number.slice(0, i) + number.slice(i + 1);
+      if (candidate > result) {
+        result = candidate;
+      }
+    }
+  }
+
+  return result;
+};

From b72e9d38cbf1c8d8a7eb5174916a97dabfe25d4d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 13:11:28 -0500
Subject: [PATCH 345/495] Add solution #2260

---
 README.md                                     |  3 +-
 ...60-minimum-consecutive-cards-to-pick-up.js | 29 +++++++++++++++++++
 2 files changed, 31 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2260-minimum-consecutive-cards-to-pick-up.js

diff --git a/README.md b/README.md
index 667590b8..9e1c2d16 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,849 LeetCode solutions in JavaScript
+# 1,850 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1726,6 +1726,7 @@
 2256|[Minimum Average Difference](./solutions/2256-minimum-average-difference.js)|Medium|
 2257|[Count Unguarded Cells in the Grid](./solutions/2257-count-unguarded-cells-in-the-grid.js)|Medium|
 2259|[Remove Digit From Number to Maximize Result](./solutions/2259-remove-digit-from-number-to-maximize-result.js)|Easy|
+2260|[Minimum Consecutive Cards to Pick Up](./solutions/2260-minimum-consecutive-cards-to-pick-up.js)|Medium|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
diff --git a/solutions/2260-minimum-consecutive-cards-to-pick-up.js b/solutions/2260-minimum-consecutive-cards-to-pick-up.js
new file mode 100644
index 00000000..4463e10c
--- /dev/null
+++ b/solutions/2260-minimum-consecutive-cards-to-pick-up.js
@@ -0,0 +1,29 @@
+/**
+ * 2260. Minimum Consecutive Cards to Pick Up
+ * https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/
+ * Difficulty: Medium
+ *
+ * You are given an integer array cards where cards[i] represents the value of the ith card. A pair
+ * of cards are matching if the cards have the same value.
+ *
+ * Return the minimum number of consecutive cards you have to pick up to have a pair of matching
+ * cards among the picked cards. If it is impossible to have matching cards, return -1.
+ */
+
+/**
+ * @param {number[]} cards
+ * @return {number}
+ */
+var minimumCardPickup = function(cards) {
+  const map = new Map();
+  let minLength = Infinity;
+
+  for (let i = 0; i < cards.length; i++) {
+    if (map.has(cards[i])) {
+      minLength = Math.min(minLength, i - map.get(cards[i]) + 1);
+    }
+    map.set(cards[i], i);
+  }
+
+  return minLength === Infinity ? -1 : minLength;
+};

From b1ab8f401a9ca70a423fa9662bf19b644d3dc4a1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 17:27:23 -0500
Subject: [PATCH 346/495] Add solution #2261

---
 README.md                                     |  3 +-
 .../2261-k-divisible-elements-subarrays.js    | 41 +++++++++++++++++++
 2 files changed, 43 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2261-k-divisible-elements-subarrays.js

diff --git a/README.md b/README.md
index 9e1c2d16..516965b1 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,850 LeetCode solutions in JavaScript
+# 1,851 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1727,6 +1727,7 @@
 2257|[Count Unguarded Cells in the Grid](./solutions/2257-count-unguarded-cells-in-the-grid.js)|Medium|
 2259|[Remove Digit From Number to Maximize Result](./solutions/2259-remove-digit-from-number-to-maximize-result.js)|Easy|
 2260|[Minimum Consecutive Cards to Pick Up](./solutions/2260-minimum-consecutive-cards-to-pick-up.js)|Medium|
+2261|[K Divisible Elements Subarrays](./solutions/2261-k-divisible-elements-subarrays.js)|Medium|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
diff --git a/solutions/2261-k-divisible-elements-subarrays.js b/solutions/2261-k-divisible-elements-subarrays.js
new file mode 100644
index 00000000..72d781d1
--- /dev/null
+++ b/solutions/2261-k-divisible-elements-subarrays.js
@@ -0,0 +1,41 @@
+/**
+ * 2261. K Divisible Elements Subarrays
+ * https://leetcode.com/problems/k-divisible-elements-subarrays/
+ * Difficulty: Medium
+ *
+ * Given an integer array nums and two integers k and p, return the number of distinct subarrays,
+ * which have at most k elements that are divisible by p.
+ *
+ * Two arrays nums1 and nums2 are said to be distinct if:
+ * - They are of different lengths, or
+ * - There exists at least one index i where nums1[i] != nums2[i].
+ *
+ * A subarray is defined as a non-empty contiguous sequence of elements in an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @param {number} p
+ * @return {number}
+ */
+var countDistinct = function(nums, k, p) {
+  const n = nums.length;
+  const seen = new Set();
+
+  for (let start = 0; start < n; start++) {
+    const subarray = [];
+    let divisibleCount = 0;
+
+    for (let end = start; end < n; end++) {
+      subarray.push(nums[end]);
+      if (nums[end] % p === 0) divisibleCount++;
+
+      if (divisibleCount <= k) {
+        seen.add(subarray.join(','));
+      }
+    }
+  }
+
+  return seen.size;
+};

From 0cbecf249ca7343439ff783031d15c9864bb4a31 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 17:28:21 -0500
Subject: [PATCH 347/495] Add solution #2262

---
 README.md                                  |  3 ++-
 solutions/2262-total-appeal-of-a-string.js | 31 ++++++++++++++++++++++
 2 files changed, 33 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2262-total-appeal-of-a-string.js

diff --git a/README.md b/README.md
index 516965b1..de36aef9 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,851 LeetCode solutions in JavaScript
+# 1,852 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1728,6 +1728,7 @@
 2259|[Remove Digit From Number to Maximize Result](./solutions/2259-remove-digit-from-number-to-maximize-result.js)|Easy|
 2260|[Minimum Consecutive Cards to Pick Up](./solutions/2260-minimum-consecutive-cards-to-pick-up.js)|Medium|
 2261|[K Divisible Elements Subarrays](./solutions/2261-k-divisible-elements-subarrays.js)|Medium|
+2262|[Total Appeal of A String](./solutions/2262-total-appeal-of-a-string.js)|Hard|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
diff --git a/solutions/2262-total-appeal-of-a-string.js b/solutions/2262-total-appeal-of-a-string.js
new file mode 100644
index 00000000..20c2e2c3
--- /dev/null
+++ b/solutions/2262-total-appeal-of-a-string.js
@@ -0,0 +1,31 @@
+/**
+ * 2262. Total Appeal of A String
+ * https://leetcode.com/problems/total-appeal-of-a-string/
+ * Difficulty: Hard
+ *
+ * The appeal of a string is the number of distinct characters found in the string.
+ * - For example, the appeal of "abbca" is 3 because it has 3 distinct characters:
+ *   'a', 'b', and 'c'.
+ *
+ * Given a string s, return the total appeal of all of its substrings.
+ *
+ * A substring is a contiguous sequence of characters within a string.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var appealSum = function(s) {
+  const n = s.length;
+  const lastSeen = new Array(26).fill(-1);
+  let result = 0;
+
+  for (let i = 0; i < n; i++) {
+    const charIndex = s.charCodeAt(i) - 97;
+    result += (i - lastSeen[charIndex]) * (n - i);
+    lastSeen[charIndex] = i;
+  }
+
+  return result;
+};

From defd60c32d58459c977db7fbe14afb1b0cffa067 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 17:29:27 -0500
Subject: [PATCH 348/495] Add solution #2264

---
 README.md                                     |  3 +-
 ...4-largest-3-same-digit-number-in-string.js | 35 +++++++++++++++++++
 2 files changed, 37 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2264-largest-3-same-digit-number-in-string.js

diff --git a/README.md b/README.md
index de36aef9..0d15702c 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,852 LeetCode solutions in JavaScript
+# 1,853 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1729,6 +1729,7 @@
 2260|[Minimum Consecutive Cards to Pick Up](./solutions/2260-minimum-consecutive-cards-to-pick-up.js)|Medium|
 2261|[K Divisible Elements Subarrays](./solutions/2261-k-divisible-elements-subarrays.js)|Medium|
 2262|[Total Appeal of A String](./solutions/2262-total-appeal-of-a-string.js)|Hard|
+2264|[Largest 3-Same-Digit Number in String](./solutions/2264-largest-3-same-digit-number-in-string.js)|Easy|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
diff --git a/solutions/2264-largest-3-same-digit-number-in-string.js b/solutions/2264-largest-3-same-digit-number-in-string.js
new file mode 100644
index 00000000..ef1df3a9
--- /dev/null
+++ b/solutions/2264-largest-3-same-digit-number-in-string.js
@@ -0,0 +1,35 @@
+/**
+ * 2264. Largest 3-Same-Digit Number in String
+ * https://leetcode.com/problems/largest-3-same-digit-number-in-string/
+ * Difficulty: Easy
+ *
+ * You are given a string num representing a large integer. An integer is good if it meets
+ * the following conditions:
+ * - It is a substring of num with length 3.
+ * - It consists of only one unique digit.
+ *
+ * Return the maximum good integer as a string or an empty string "" if no such integer exists.
+ *
+ * Note:
+ * - A substring is a contiguous sequence of characters within a string.
+ * - There may be leading zeroes in num or a good integer.
+ */
+
+/**
+ * @param {string} num
+ * @return {string}
+ */
+var largestGoodInteger = function(num) {
+  let result = '';
+
+  for (let i = 0; i <= num.length - 3; i++) {
+    const substring = num.slice(i, i + 3);
+    if (substring[0] === substring[1] && substring[1] === substring[2]) {
+      if (substring > result) {
+        result = substring;
+      }
+    }
+  }
+
+  return result;
+};

From 42ff5b20296aa07617e191f7a6614cf77a64a93f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 17:30:52 -0500
Subject: [PATCH 349/495] Add solution #2265

---
 README.md                                     |  3 +-
 ...count-nodes-equal-to-average-of-subtree.js | 46 +++++++++++++++++++
 2 files changed, 48 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2265-count-nodes-equal-to-average-of-subtree.js

diff --git a/README.md b/README.md
index 0d15702c..ad21ef75 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,853 LeetCode solutions in JavaScript
+# 1,854 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1730,6 +1730,7 @@
 2261|[K Divisible Elements Subarrays](./solutions/2261-k-divisible-elements-subarrays.js)|Medium|
 2262|[Total Appeal of A String](./solutions/2262-total-appeal-of-a-string.js)|Hard|
 2264|[Largest 3-Same-Digit Number in String](./solutions/2264-largest-3-same-digit-number-in-string.js)|Easy|
+2265|[Count Nodes Equal to Average of Subtree](./solutions/2265-count-nodes-equal-to-average-of-subtree.js)|Medium|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
diff --git a/solutions/2265-count-nodes-equal-to-average-of-subtree.js b/solutions/2265-count-nodes-equal-to-average-of-subtree.js
new file mode 100644
index 00000000..2e3f4cb5
--- /dev/null
+++ b/solutions/2265-count-nodes-equal-to-average-of-subtree.js
@@ -0,0 +1,46 @@
+/**
+ * 2265. Count Nodes Equal to Average of Subtree
+ * https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree, return the number of nodes where the value of the node is
+ * equal to the average of the values in its subtree.
+ *
+ * Note:
+ * - The average of n elements is the sum of the n elements divided by n and rounded down to
+ *   the nearest integer.
+ * - A subtree of root is a tree consisting of root and all of its descendants.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ *     this.val = (val===undefined ? 0 : val)
+ *     this.left = (left===undefined ? null : left)
+ *     this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @return {number}
+ */
+var averageOfSubtree = function(root) {
+  let count = 0;
+  traverse(root);
+  return count;
+
+  function traverse(node) {
+    if (!node) return [0, 0];
+
+    const [leftSum, leftCount] = traverse(node.left);
+    const [rightSum, rightCount] = traverse(node.right);
+    const totalSum = leftSum + rightSum + node.val;
+    const totalCount = leftCount + rightCount + 1;
+
+    if (Math.floor(totalSum / totalCount) === node.val) {
+      count++;
+    }
+
+    return [totalSum, totalCount];
+  }
+};

From e26d2c21e5513b34da858c4985f0a9b4f0b7dc88 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 17:33:01 -0500
Subject: [PATCH 350/495] Add solution #2266

---
 README.md                               |  3 +-
 solutions/2266-count-number-of-texts.js | 57 +++++++++++++++++++++++++
 2 files changed, 59 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2266-count-number-of-texts.js

diff --git a/README.md b/README.md
index ad21ef75..7fb2b1a2 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,854 LeetCode solutions in JavaScript
+# 1,855 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1731,6 +1731,7 @@
 2262|[Total Appeal of A String](./solutions/2262-total-appeal-of-a-string.js)|Hard|
 2264|[Largest 3-Same-Digit Number in String](./solutions/2264-largest-3-same-digit-number-in-string.js)|Easy|
 2265|[Count Nodes Equal to Average of Subtree](./solutions/2265-count-nodes-equal-to-average-of-subtree.js)|Medium|
+2266|[Count Number of Texts](./solutions/2266-count-number-of-texts.js)|Medium|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
diff --git a/solutions/2266-count-number-of-texts.js b/solutions/2266-count-number-of-texts.js
new file mode 100644
index 00000000..d2f9cf84
--- /dev/null
+++ b/solutions/2266-count-number-of-texts.js
@@ -0,0 +1,57 @@
+/**
+ * 2266. Count Number of Texts
+ * https://leetcode.com/problems/count-number-of-texts/
+ * Difficulty: Medium
+ *
+ * Alice is texting Bob using her phone. The mapping of digits to letters is shown in the
+ * figure below.
+ *
+ * In order to add a letter, Alice has to press the key of the corresponding digit i times,
+ * where i is the position of the letter in the key.
+ * - For example, to add the letter 's', Alice has to press '7' four times. Similarly, to
+ *   add the letter 'k', Alice has to press '5' twice.
+ * - Note that the digits '0' and '1' do not map to any letters, so Alice does not use them.
+ *
+ * However, due to an error in transmission, Bob did not receive Alice's text message but
+ * received a string of pressed keys instead.
+ * - For example, when Alice sent the message "bob", Bob received the string "2266622".
+ *
+ * Given a string pressedKeys representing the string received by Bob, return the total
+ * number of possible text messages Alice could have sent.
+ *
+ * Since the answer may be very large, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {string} pressedKeys
+ * @return {number}
+ */
+var countTexts = function(pressedKeys) {
+  const mod = 1e9 + 7;
+  const maxGroup = pressedKeys.length;
+  const dp = new Array(maxGroup + 1).fill(0);
+  dp[0] = 1;
+
+  const map = new Map([
+    ['2', 3], ['3', 3], ['4', 3], ['5', 3],
+    ['6', 3], ['7', 4], ['8', 3], ['9', 4]
+  ]);
+
+  for (let i = 1; i <= maxGroup; i++) {
+    dp[i] = dp[i - 1];
+    if (i >= 2 && pressedKeys[i - 1] === pressedKeys[i - 2]) {
+      dp[i] = (dp[i] + dp[i - 2]) % mod;
+    }
+    if (i >= 3 && pressedKeys[i - 1] === pressedKeys[i - 2]
+        && pressedKeys[i - 2] === pressedKeys[i - 3]) {
+      dp[i] = (dp[i] + dp[i - 3]) % mod;
+    }
+    if (i >= 4 && pressedKeys[i - 1] === pressedKeys[i - 2]
+        && pressedKeys[i - 2] === pressedKeys[i - 3]
+        && pressedKeys[i - 3] === pressedKeys[i - 4] && map.get(pressedKeys[i - 1]) === 4) {
+      dp[i] = (dp[i] + dp[i - 4]) % mod;
+    }
+  }
+
+  return dp[maxGroup];
+};

From f3626d68faa42436fcf1e27e1de1d463a354c3c8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 17:42:20 -0500
Subject: [PATCH 351/495] Add solution #2269

---
 README.md                                     |  3 +-
 .../2269-find-the-k-beauty-of-a-number.js     | 37 +++++++++++++++++++
 2 files changed, 39 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2269-find-the-k-beauty-of-a-number.js

diff --git a/README.md b/README.md
index 7fb2b1a2..9e1649b8 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,855 LeetCode solutions in JavaScript
+# 1,856 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1732,6 +1732,7 @@
 2264|[Largest 3-Same-Digit Number in String](./solutions/2264-largest-3-same-digit-number-in-string.js)|Easy|
 2265|[Count Nodes Equal to Average of Subtree](./solutions/2265-count-nodes-equal-to-average-of-subtree.js)|Medium|
 2266|[Count Number of Texts](./solutions/2266-count-number-of-texts.js)|Medium|
+2269|[Find the K-Beauty of a Number](./solutions/2269-find-the-k-beauty-of-a-number.js)|Easy|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
diff --git a/solutions/2269-find-the-k-beauty-of-a-number.js b/solutions/2269-find-the-k-beauty-of-a-number.js
new file mode 100644
index 00000000..3027e4d4
--- /dev/null
+++ b/solutions/2269-find-the-k-beauty-of-a-number.js
@@ -0,0 +1,37 @@
+/**
+ * 2269. Find the K-Beauty of a Number
+ * https://leetcode.com/problems/find-the-k-beauty-of-a-number/
+ * Difficulty: Easy
+ *
+ * The k-beauty of an integer num is defined as the number of substrings of num when it is
+ * read as a string that meet the following conditions:
+ * - It has a length of k.
+ * - It is a divisor of num.
+ *
+ * Given integers num and k, return the k-beauty of num.
+ *
+ * Note:
+ * - Leading zeros are allowed.
+ * - 0 is not a divisor of any value.
+ *
+ * A substring is a contiguous sequence of characters in a string.
+ */
+
+/**
+ * @param {number} num
+ * @param {number} k
+ * @return {number}
+ */
+var divisorSubstrings = function(num, k) {
+  const numStr = num.toString();
+  let result = 0;
+
+  for (let i = 0; i <= numStr.length - k; i++) {
+    const substring = parseInt(numStr.slice(i, i + k));
+    if (substring !== 0 && num % substring === 0) {
+      result++;
+    }
+  }
+
+  return result;
+};

From 9695466262b7891e8b4f53c85afb43be96af83eb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 17:44:59 -0500
Subject: [PATCH 352/495] Add solution #2272

---
 README.md                                     |  3 +-
 .../2272-substring-with-largest-variance.js   | 84 +++++++++++++++++++
 2 files changed, 86 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2272-substring-with-largest-variance.js

diff --git a/README.md b/README.md
index 9e1649b8..13de9226 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,856 LeetCode solutions in JavaScript
+# 1,857 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1734,6 +1734,7 @@
 2266|[Count Number of Texts](./solutions/2266-count-number-of-texts.js)|Medium|
 2269|[Find the K-Beauty of a Number](./solutions/2269-find-the-k-beauty-of-a-number.js)|Easy|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
+2272|[Substring With Largest Variance](./solutions/2272-substring-with-largest-variance.js)|Hard|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2272-substring-with-largest-variance.js b/solutions/2272-substring-with-largest-variance.js
new file mode 100644
index 00000000..f11361c2
--- /dev/null
+++ b/solutions/2272-substring-with-largest-variance.js
@@ -0,0 +1,84 @@
+/**
+ * 2272. Substring With Largest Variance
+ * https://leetcode.com/problems/substring-with-largest-variance/
+ * Difficulty: Hard
+ *
+ * The variance of a string is defined as the largest difference between the number of occurrences
+ * of any 2 characters present in the string. Note the two characters may or may not be the same.
+ *
+ * Given a string s consisting of lowercase English letters only, return the largest variance
+ * possible among all substrings of s.
+ *
+ * A substring is a contiguous sequence of characters within a string.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var largestVariance = function(s) {
+  const map = new Set(s);
+  let result = 0;
+
+  for (const charA of map) {
+    for (const charB of map) {
+      if (charA === charB) continue;
+
+      let countA = 0;
+      let countB = 0;
+      let hasA = false;
+      let hasB = false;
+
+      for (const char of s) {
+        if (char === charA) {
+          countA++;
+          hasA = true;
+        }
+        if (char === charB) {
+          countB++;
+          hasB = true;
+        }
+
+        if (hasA && hasB) {
+          result = Math.max(result, Math.abs(countA - countB));
+        }
+
+        if (countA < countB) {
+          countA = 0;
+          countB = 0;
+          hasA = false;
+          hasB = false;
+        }
+      }
+
+      countA = 0;
+      countB = 0;
+      hasA = false;
+      hasB = false;
+
+      for (let i = s.length - 1; i >= 0; i--) {
+        if (s[i] === charA) {
+          countA++;
+          hasA = true;
+        }
+        if (s[i] === charB) {
+          countB++;
+          hasB = true;
+        }
+
+        if (hasA && hasB) {
+          result = Math.max(result, Math.abs(countA - countB));
+        }
+
+        if (countA < countB) {
+          countA = 0;
+          countB = 0;
+          hasA = false;
+          hasB = false;
+        }
+      }
+    }
+  }
+
+  return result;
+};

From aa1ed0680013994315853869e6b90801d4e6352c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 19:45:44 -0500
Subject: [PATCH 353/495] Add solution #2273

---
 README.md                                     |  3 +-
 ...resultant-array-after-removing-anagrams.js | 38 +++++++++++++++++++
 2 files changed, 40 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2273-find-resultant-array-after-removing-anagrams.js

diff --git a/README.md b/README.md
index 13de9226..5320448f 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,857 LeetCode solutions in JavaScript
+# 1,858 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1735,6 +1735,7 @@
 2269|[Find the K-Beauty of a Number](./solutions/2269-find-the-k-beauty-of-a-number.js)|Easy|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2272|[Substring With Largest Variance](./solutions/2272-substring-with-largest-variance.js)|Hard|
+2273|[Find Resultant Array After Removing Anagrams](./solutions/2273-find-resultant-array-after-removing-anagrams.js)|Easy|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2273-find-resultant-array-after-removing-anagrams.js b/solutions/2273-find-resultant-array-after-removing-anagrams.js
new file mode 100644
index 00000000..8e0ef746
--- /dev/null
+++ b/solutions/2273-find-resultant-array-after-removing-anagrams.js
@@ -0,0 +1,38 @@
+/**
+ * 2273. Find Resultant Array After Removing Anagrams
+ * https://leetcode.com/problems/find-resultant-array-after-removing-anagrams/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed string array words, where words[i] consists of lowercase
+ * English letters.
+ *
+ * In one operation, select any index i such that 0 < i < words.length and words[i - 1] and
+ * words[i] are anagrams, and delete words[i] from words. Keep performing this operation as
+ * long as you can select an index that satisfies the conditions.
+ *
+ * Return words after performing all operations. It can be shown that selecting the indices
+ * for each operation in any arbitrary order will lead to the same result.
+ *
+ * An Anagram is a word or phrase formed by rearranging the letters of a different word or
+ * phrase using all the original letters exactly once. For example, "dacb" is an anagram of
+ * "abdc".
+ */
+
+/**
+ * @param {string[]} words
+ * @return {string[]}
+ */
+var removeAnagrams = function(words) {
+  const result = [words[0]];
+
+  for (let i = 1; i < words.length; i++) {
+    const prevSorted = result[result.length - 1].split('').sort().join('');
+    const currSorted = words[i].split('').sort().join('');
+
+    if (prevSorted !== currSorted) {
+      result.push(words[i]);
+    }
+  }
+
+  return result;
+};

From e7d058473e363fa4d11135d2b0a1691ffaf1e768 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 19:46:47 -0500
Subject: [PATCH 354/495] Add solution #2274

---
 README.md                                     |  3 +-
 ...nsecutive-floors-without-special-floors.js | 31 +++++++++++++++++++
 2 files changed, 33 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2274-maximum-consecutive-floors-without-special-floors.js

diff --git a/README.md b/README.md
index 5320448f..fe861daa 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,858 LeetCode solutions in JavaScript
+# 1,859 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1736,6 +1736,7 @@
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2272|[Substring With Largest Variance](./solutions/2272-substring-with-largest-variance.js)|Hard|
 2273|[Find Resultant Array After Removing Anagrams](./solutions/2273-find-resultant-array-after-removing-anagrams.js)|Easy|
+2274|[Maximum Consecutive Floors Without Special Floors](./solutions/2274-maximum-consecutive-floors-without-special-floors.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2274-maximum-consecutive-floors-without-special-floors.js b/solutions/2274-maximum-consecutive-floors-without-special-floors.js
new file mode 100644
index 00000000..6ccb00f4
--- /dev/null
+++ b/solutions/2274-maximum-consecutive-floors-without-special-floors.js
@@ -0,0 +1,31 @@
+/**
+ * 2274. Maximum Consecutive Floors Without Special Floors
+ * https://leetcode.com/problems/maximum-consecutive-floors-without-special-floors/
+ * Difficulty: Medium
+ *
+ * Alice manages a company and has rented some floors of a building as office space. Alice has
+ * decided some of these floors should be special floors, used for relaxation only.
+ *
+ * You are given two integers bottom and top, which denote that Alice has rented all the floors
+ * from bottom to top (inclusive). You are also given the integer array special, where special[i]
+ * denotes a special floor that Alice has designated for relaxation.
+ *
+ * Return the maximum number of consecutive floors without a special floor.
+ */
+
+/**
+ * @param {number} bottom
+ * @param {number} top
+ * @param {number[]} special
+ * @return {number}
+ */
+var maxConsecutive = function(bottom, top, special) {
+  special.sort((a, b) => a - b);
+  let result = Math.max(special[0] - bottom, top - special[special.length - 1]);
+
+  for (let i = 1; i < special.length; i++) {
+    result = Math.max(result, special[i] - special[i - 1] - 1);
+  }
+
+  return result;
+};

From 26ced39ff1fc97515b16926ae7bb4d22df399b19 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 19:47:48 -0500
Subject: [PATCH 355/495] Add solution #2275

---
 README.md                                     |  3 +-
 ...tion-with-bitwise-and-greater-than-zero.js | 37 +++++++++++++++++++
 2 files changed, 39 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2275-largest-combination-with-bitwise-and-greater-than-zero.js

diff --git a/README.md b/README.md
index fe861daa..8b8fcb01 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,859 LeetCode solutions in JavaScript
+# 1,860 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1737,6 +1737,7 @@
 2272|[Substring With Largest Variance](./solutions/2272-substring-with-largest-variance.js)|Hard|
 2273|[Find Resultant Array After Removing Anagrams](./solutions/2273-find-resultant-array-after-removing-anagrams.js)|Easy|
 2274|[Maximum Consecutive Floors Without Special Floors](./solutions/2274-maximum-consecutive-floors-without-special-floors.js)|Medium|
+2275|[Largest Combination With Bitwise AND Greater Than Zero](./solutions/2275-largest-combination-with-bitwise-and-greater-than-zero.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2275-largest-combination-with-bitwise-and-greater-than-zero.js b/solutions/2275-largest-combination-with-bitwise-and-greater-than-zero.js
new file mode 100644
index 00000000..e75f68d3
--- /dev/null
+++ b/solutions/2275-largest-combination-with-bitwise-and-greater-than-zero.js
@@ -0,0 +1,37 @@
+/**
+ * 2275. Largest Combination With Bitwise AND Greater Than Zero
+ * https://leetcode.com/problems/largest-combination-with-bitwise-and-greater-than-zero/
+ * Difficulty: Medium
+ *
+ * The bitwise AND of an array nums is the bitwise AND of all integers in nums.
+ * - For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1.
+ * - Also, for nums = [7], the bitwise AND is 7.
+ *
+ * You are given an array of positive integers candidates. Compute the bitwise AND for all
+ * possible combinations of elements in the candidates array.
+ *
+ * Return the size of the largest combination of candidates with a bitwise AND greater than 0.
+ */
+
+/**
+ * @param {number[]} candidates
+ * @return {number}
+ */
+var largestCombination = function(candidates) {
+  const bitCounts = new Array(32).fill(0);
+  let result = 0;
+
+  for (const num of candidates) {
+    for (let i = 0; i < 32; i++) {
+      if (num & (1 << i)) {
+        bitCounts[i]++;
+      }
+    }
+  }
+
+  for (const count of bitCounts) {
+    result = Math.max(result, count);
+  }
+
+  return result;
+};

From 603ea0f88924c1b90c6a6b86575e44e3cfbec614 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 20:40:10 -0500
Subject: [PATCH 356/495] Add solution #2278

---
 README.md                                       |  3 ++-
 .../2278-percentage-of-letter-in-string.js      | 17 +++++++++++++++++
 2 files changed, 19 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2278-percentage-of-letter-in-string.js

diff --git a/README.md b/README.md
index 8b8fcb01..07cfcb95 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,860 LeetCode solutions in JavaScript
+# 1,861 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1738,6 +1738,7 @@
 2273|[Find Resultant Array After Removing Anagrams](./solutions/2273-find-resultant-array-after-removing-anagrams.js)|Easy|
 2274|[Maximum Consecutive Floors Without Special Floors](./solutions/2274-maximum-consecutive-floors-without-special-floors.js)|Medium|
 2275|[Largest Combination With Bitwise AND Greater Than Zero](./solutions/2275-largest-combination-with-bitwise-and-greater-than-zero.js)|Medium|
+2278|[Percentage of Letter in String](./solutions/2278-percentage-of-letter-in-string.js)|Easy|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2278-percentage-of-letter-in-string.js b/solutions/2278-percentage-of-letter-in-string.js
new file mode 100644
index 00000000..fb3dfdbb
--- /dev/null
+++ b/solutions/2278-percentage-of-letter-in-string.js
@@ -0,0 +1,17 @@
+/**
+ * 2278. Percentage of Letter in String
+ * https://leetcode.com/problems/percentage-of-letter-in-string/
+ * Difficulty: Easy
+ *
+ * Given a string s and a character letter, return the percentage of characters in s that equal
+ * letter rounded down to the nearest whole percent.
+ */
+
+/**
+ * @param {string} s
+ * @param {character} letter
+ * @return {number}
+ */
+var percentageLetter = function(s, letter) {
+  return Math.floor((s.split('').filter(char => char === letter).length / s.length) * 100);
+};

From 10285bf610a2d9291473bcf5f3f13cfdbd25aecc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 20:41:09 -0500
Subject: [PATCH 357/495] Add solution #2279

---
 README.md                                     |  3 +-
 ...aximum-bags-with-full-capacity-of-rocks.js | 38 +++++++++++++++++++
 2 files changed, 40 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2279-maximum-bags-with-full-capacity-of-rocks.js

diff --git a/README.md b/README.md
index 07cfcb95..a4a55b76 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,861 LeetCode solutions in JavaScript
+# 1,862 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1739,6 +1739,7 @@
 2274|[Maximum Consecutive Floors Without Special Floors](./solutions/2274-maximum-consecutive-floors-without-special-floors.js)|Medium|
 2275|[Largest Combination With Bitwise AND Greater Than Zero](./solutions/2275-largest-combination-with-bitwise-and-greater-than-zero.js)|Medium|
 2278|[Percentage of Letter in String](./solutions/2278-percentage-of-letter-in-string.js)|Easy|
+2279|[Maximum Bags With Full Capacity of Rocks](./solutions/2279-maximum-bags-with-full-capacity-of-rocks.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2279-maximum-bags-with-full-capacity-of-rocks.js b/solutions/2279-maximum-bags-with-full-capacity-of-rocks.js
new file mode 100644
index 00000000..77d36c1a
--- /dev/null
+++ b/solutions/2279-maximum-bags-with-full-capacity-of-rocks.js
@@ -0,0 +1,38 @@
+/**
+ * 2279. Maximum Bags With Full Capacity of Rocks
+ * https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/
+ * Difficulty: Medium
+ *
+ * You have n bags numbered from 0 to n - 1. You are given two 0-indexed integer arrays capacity
+ * and rocks. The ith bag can hold a maximum of capacity[i] rocks and currently contains rocks[i]
+ * rocks. You are also given an integer additionalRocks, the number of additional rocks you can
+ * place in any of the bags.
+ *
+ * Return the maximum number of bags that could have full capacity after placing the additional
+ * rocks in some bags.
+ */
+
+/**
+ * @param {number[]} capacity
+ * @param {number[]} rocks
+ * @param {number} additionalRocks
+ * @return {number}
+ */
+var maximumBags = function(capacity, rocks, additionalRocks) {
+  const remaining = capacity.map((cap, i) => cap - rocks[i]);
+  remaining.sort((a, b) => a - b);
+
+  let result = 0;
+  let rocksLeft = additionalRocks;
+
+  for (const needed of remaining) {
+    if (needed <= rocksLeft) {
+      result++;
+      rocksLeft -= needed;
+    } else {
+      break;
+    }
+  }
+
+  return result;
+};

From b2ac97eff0c92379f9e6a7516c69336594800c98 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 20:41:59 -0500
Subject: [PATCH 358/495] Add solution #2283

---
 README.md                                     |  3 +-
 ...r-has-equal-digit-count-and-digit-value.js | 30 +++++++++++++++++++
 2 files changed, 32 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2283-check-if-number-has-equal-digit-count-and-digit-value.js

diff --git a/README.md b/README.md
index a4a55b76..8b2a5cbb 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,862 LeetCode solutions in JavaScript
+# 1,863 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1740,6 +1740,7 @@
 2275|[Largest Combination With Bitwise AND Greater Than Zero](./solutions/2275-largest-combination-with-bitwise-and-greater-than-zero.js)|Medium|
 2278|[Percentage of Letter in String](./solutions/2278-percentage-of-letter-in-string.js)|Easy|
 2279|[Maximum Bags With Full Capacity of Rocks](./solutions/2279-maximum-bags-with-full-capacity-of-rocks.js)|Medium|
+2283|[Check if Number Has Equal Digit Count and Digit Value](./solutions/2283-check-if-number-has-equal-digit-count-and-digit-value.js)|Easy|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2283-check-if-number-has-equal-digit-count-and-digit-value.js b/solutions/2283-check-if-number-has-equal-digit-count-and-digit-value.js
new file mode 100644
index 00000000..ea342877
--- /dev/null
+++ b/solutions/2283-check-if-number-has-equal-digit-count-and-digit-value.js
@@ -0,0 +1,30 @@
+/**
+ * 2283. Check if Number Has Equal Digit Count and Digit Value
+ * https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed string num of length n consisting of digits.
+ *
+ * Return true if for every index i in the range 0 <= i < n, the digit i occurs num[i] times in num,
+ * otherwise return false.
+ */
+
+/**
+ * @param {string} num
+ * @return {boolean}
+ */
+var digitCount = function(num) {
+  const frequency = new Array(10).fill(0);
+
+  for (const digit of num) {
+    frequency[digit]++;
+  }
+
+  for (let i = 0; i < num.length; i++) {
+    if (frequency[i] !== Number(num[i])) {
+      return false;
+    }
+  }
+
+  return true;
+};

From 9c6840c5bd51f1af749efd13ace93dd91487e070 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 20:43:25 -0500
Subject: [PATCH 359/495] Add solution #2284

---
 README.md                                     |  3 +-
 .../2284-sender-with-largest-word-count.js    | 44 +++++++++++++++++++
 2 files changed, 46 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2284-sender-with-largest-word-count.js

diff --git a/README.md b/README.md
index 8b2a5cbb..1b1545d5 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,863 LeetCode solutions in JavaScript
+# 1,864 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1741,6 +1741,7 @@
 2278|[Percentage of Letter in String](./solutions/2278-percentage-of-letter-in-string.js)|Easy|
 2279|[Maximum Bags With Full Capacity of Rocks](./solutions/2279-maximum-bags-with-full-capacity-of-rocks.js)|Medium|
 2283|[Check if Number Has Equal Digit Count and Digit Value](./solutions/2283-check-if-number-has-equal-digit-count-and-digit-value.js)|Easy|
+2284|[Sender With Largest Word Count](./solutions/2284-sender-with-largest-word-count.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2284-sender-with-largest-word-count.js b/solutions/2284-sender-with-largest-word-count.js
new file mode 100644
index 00000000..d4c02260
--- /dev/null
+++ b/solutions/2284-sender-with-largest-word-count.js
@@ -0,0 +1,44 @@
+/**
+ * 2284. Sender With Largest Word Count
+ * https://leetcode.com/problems/sender-with-largest-word-count/
+ * Difficulty: Medium
+ *
+ * You have a chat log of n messages. You are given two string arrays messages and senders
+ * where messages[i] is a message sent by senders[i].
+ *
+ * A message is list of words that are separated by a single space with no leading or trailing
+ * spaces. The word count of a sender is the total number of words sent by the sender. Note
+ * that a sender may send more than one message.
+ *
+ * Return the sender with the largest word count. If there is more than one sender with the
+ * largest word count, return the one with the lexicographically largest name.
+ *
+ * Note:
+ * - Uppercase letters come before lowercase letters in lexicographical order.
+ * - "Alice" and "alice" are distinct.
+ */
+
+/**
+ * @param {string[]} messages
+ * @param {string[]} senders
+ * @return {string}
+ */
+var largestWordCount = function(messages, senders) {
+  const map = new Map();
+  let maxWords = 0;
+  let result = '';
+
+  for (let i = 0; i < messages.length; i++) {
+    const wordCount = messages[i].split(' ').length;
+    const sender = senders[i];
+    const totalWords = (map.get(sender) || 0) + wordCount;
+    map.set(sender, totalWords);
+
+    if (totalWords > maxWords || (totalWords === maxWords && sender > result)) {
+      maxWords = totalWords;
+      result = sender;
+    }
+  }
+
+  return result;
+};

From f9a5eae08cb8c4cc0c3bc31ae007295fd79d7bec Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 20:45:14 -0500
Subject: [PATCH 360/495] Add solution #2287

---
 README.md                                     |  3 +-
 ...rrange-characters-to-make-target-string.js | 38 +++++++++++++++++++
 2 files changed, 40 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2287-rearrange-characters-to-make-target-string.js

diff --git a/README.md b/README.md
index 1b1545d5..5586cabc 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,864 LeetCode solutions in JavaScript
+# 1,865 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1742,6 +1742,7 @@
 2279|[Maximum Bags With Full Capacity of Rocks](./solutions/2279-maximum-bags-with-full-capacity-of-rocks.js)|Medium|
 2283|[Check if Number Has Equal Digit Count and Digit Value](./solutions/2283-check-if-number-has-equal-digit-count-and-digit-value.js)|Easy|
 2284|[Sender With Largest Word Count](./solutions/2284-sender-with-largest-word-count.js)|Medium|
+2287|[Rearrange Characters to Make Target String](./solutions/2287-rearrange-characters-to-make-target-string.js)|Easy|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2287-rearrange-characters-to-make-target-string.js b/solutions/2287-rearrange-characters-to-make-target-string.js
new file mode 100644
index 00000000..310eb5a2
--- /dev/null
+++ b/solutions/2287-rearrange-characters-to-make-target-string.js
@@ -0,0 +1,38 @@
+/**
+ * 2287. Rearrange Characters to Make Target String
+ * https://leetcode.com/problems/rearrange-characters-to-make-target-string/
+ * Difficulty: Easy
+ *
+ * You are given two 0-indexed strings s and target. You can take some letters from s and
+ * rearrange them to form new strings.
+ *
+ * Return the maximum number of copies of target that can be formed by taking letters from
+ * s and rearranging them.
+ */
+
+/**
+ * @param {string} s
+ * @param {string} target
+ * @return {number}
+ */
+var rearrangeCharacters = function(s, target) {
+  const sourceFreq = new Array(26).fill(0);
+  const targetFreq = new Array(26).fill(0);
+
+  for (const char of s) {
+    sourceFreq[char.charCodeAt(0) - 97]++;
+  }
+
+  for (const char of target) {
+    targetFreq[char.charCodeAt(0) - 97]++;
+  }
+
+  let result = Infinity;
+  for (let i = 0; i < 26; i++) {
+    if (targetFreq[i] > 0) {
+      result = Math.min(result, Math.floor(sourceFreq[i] / targetFreq[i]));
+    }
+  }
+
+  return result;
+};

From 5d98f1105e783c3cc8efb75adef5be770c6d0d08 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 20:53:39 -0500
Subject: [PATCH 361/495] Add solution #2293

---
 README.md                      |  3 ++-
 solutions/2293-min-max-game.js | 43 ++++++++++++++++++++++++++++++++++
 2 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2293-min-max-game.js

diff --git a/README.md b/README.md
index 5586cabc..20098bd8 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,865 LeetCode solutions in JavaScript
+# 1,866 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1743,6 +1743,7 @@
 2283|[Check if Number Has Equal Digit Count and Digit Value](./solutions/2283-check-if-number-has-equal-digit-count-and-digit-value.js)|Easy|
 2284|[Sender With Largest Word Count](./solutions/2284-sender-with-largest-word-count.js)|Medium|
 2287|[Rearrange Characters to Make Target String](./solutions/2287-rearrange-characters-to-make-target-string.js)|Easy|
+2293|[Min Max Game](./solutions/2293-min-max-game.js)|Easy|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2293-min-max-game.js b/solutions/2293-min-max-game.js
new file mode 100644
index 00000000..b6952f9c
--- /dev/null
+++ b/solutions/2293-min-max-game.js
@@ -0,0 +1,43 @@
+/**
+ * 2293. Min Max Game
+ * https://leetcode.com/problems/min-max-game/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums whose length is a power of 2.
+ *
+ * Apply the following algorithm on nums:
+ * 1. Let n be the length of nums. If n == 1, end the process. Otherwise, create a new 0-indexed
+ *    integer array newNums of length n / 2.
+ * 2. For every even index i where 0 <= i < n / 2, assign the value of newNums[i] as
+ *    min(nums[2 * i], nums[2 * i + 1]).
+ * 3. For every odd index i where 0 <= i < n / 2, assign the value of newNums[i] as
+ *    max(nums[2 * i], nums[2 * i + 1]).
+ * 4. Replace the array nums with newNums.
+ * 5. Repeat the entire process starting from step 1.
+ *
+ * Return the last number that remains in nums after applying the algorithm.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minMaxGame = function(nums) {
+  let array = nums.slice();
+
+  while (array.length > 1) {
+    const newArray = new Array(array.length / 2);
+
+    for (let i = 0; i < newArray.length; i++) {
+      if (i % 2 === 0) {
+        newArray[i] = Math.min(array[2 * i], array[2 * i + 1]);
+      } else {
+        newArray[i] = Math.max(array[2 * i], array[2 * i + 1]);
+      }
+    }
+
+    array = newArray;
+  }
+
+  return array[0];
+};

From 9560c8e8ab9ca1c761aa48f57c06955670b9b620 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 20:55:00 -0500
Subject: [PATCH 362/495] Add solution #2294

---
 README.md                                     |  3 +-
 ...array-such-that-maximum-difference-is-k.js | 34 +++++++++++++++++++
 2 files changed, 36 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2294-partition-array-such-that-maximum-difference-is-k.js

diff --git a/README.md b/README.md
index 20098bd8..123afe93 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,866 LeetCode solutions in JavaScript
+# 1,867 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1744,6 +1744,7 @@
 2284|[Sender With Largest Word Count](./solutions/2284-sender-with-largest-word-count.js)|Medium|
 2287|[Rearrange Characters to Make Target String](./solutions/2287-rearrange-characters-to-make-target-string.js)|Easy|
 2293|[Min Max Game](./solutions/2293-min-max-game.js)|Easy|
+2294|[Partition Array Such That Maximum Difference Is K](./solutions/2294-partition-array-such-that-maximum-difference-is-k.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2294-partition-array-such-that-maximum-difference-is-k.js b/solutions/2294-partition-array-such-that-maximum-difference-is-k.js
new file mode 100644
index 00000000..06cad3ae
--- /dev/null
+++ b/solutions/2294-partition-array-such-that-maximum-difference-is-k.js
@@ -0,0 +1,34 @@
+/**
+ * 2294. Partition Array Such That Maximum Difference Is K
+ * https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums and an integer k. You may partition nums into one or more
+ * subsequences such that each element in nums appears in exactly one of the subsequences.
+ *
+ * Return the minimum number of subsequences needed such that the difference between the maximum
+ * and minimum values in each subsequence is at most k.
+ *
+ * A subsequence is a sequence that can be derived from another sequence by deleting some or no
+ * elements without changing the order of the remaining elements.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var partitionArray = function(nums, k) {
+  nums.sort((a, b) => a - b);
+  let result = 1;
+  let minValue = nums[0];
+
+  for (let i = 1; i < nums.length; i++) {
+    if (nums[i] - minValue > k) {
+      result++;
+      minValue = nums[i];
+    }
+  }
+
+  return result;
+};

From e4944229a30788511a4a51cf79d39a01918d367b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 20:56:26 -0500
Subject: [PATCH 363/495] Add solution #2295

---
 README.md                                     |  3 +-
 .../2295-replace-elements-in-an-array.js      | 36 +++++++++++++++++++
 2 files changed, 38 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2295-replace-elements-in-an-array.js

diff --git a/README.md b/README.md
index 123afe93..face1ea6 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,867 LeetCode solutions in JavaScript
+# 1,868 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1745,6 +1745,7 @@
 2287|[Rearrange Characters to Make Target String](./solutions/2287-rearrange-characters-to-make-target-string.js)|Easy|
 2293|[Min Max Game](./solutions/2293-min-max-game.js)|Easy|
 2294|[Partition Array Such That Maximum Difference Is K](./solutions/2294-partition-array-such-that-maximum-difference-is-k.js)|Medium|
+2295|[Replace Elements in an Array](./solutions/2295-replace-elements-in-an-array.js)|Medium|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2295-replace-elements-in-an-array.js b/solutions/2295-replace-elements-in-an-array.js
new file mode 100644
index 00000000..de3bbad0
--- /dev/null
+++ b/solutions/2295-replace-elements-in-an-array.js
@@ -0,0 +1,36 @@
+/**
+ * 2295. Replace Elements in an Array
+ * https://leetcode.com/problems/replace-elements-in-an-array/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array nums that consists of n distinct positive integers.
+ * Apply m operations to this array, where in the ith operation you replace the number
+ * operations[i][0] with operations[i][1].
+ *
+ * It is guaranteed that in the ith operation:
+ * - operations[i][0] exists in nums.
+ * - operations[i][1] does not exist in nums.
+ *
+ * Return the array obtained after applying all the operations.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[][]} operations
+ * @return {number[]}
+ */
+var arrayChange = function(nums, operations) {
+  const map = new Map();
+  for (let i = 0; i < nums.length; i++) {
+    map.set(nums[i], i);
+  }
+
+  for (const [oldVal, newVal] of operations) {
+    const index = map.get(oldVal);
+    nums[index] = newVal;
+    map.set(newVal, index);
+    map.delete(oldVal);
+  }
+
+  return nums;
+};

From 76e54c83cef14fd7345d5da70daeadb0e2e33347 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 21:01:28 -0500
Subject: [PATCH 364/495] Add solution #2296

---
 README.md                              |  3 +-
 solutions/2296-design-a-text-editor.js | 78 ++++++++++++++++++++++++++
 2 files changed, 80 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2296-design-a-text-editor.js

diff --git a/README.md b/README.md
index face1ea6..ad76b866 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,868 LeetCode solutions in JavaScript
+# 1,869 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1746,6 +1746,7 @@
 2293|[Min Max Game](./solutions/2293-min-max-game.js)|Easy|
 2294|[Partition Array Such That Maximum Difference Is K](./solutions/2294-partition-array-such-that-maximum-difference-is-k.js)|Medium|
 2295|[Replace Elements in an Array](./solutions/2295-replace-elements-in-an-array.js)|Medium|
+2296|[Design a Text Editor](./solutions/2296-design-a-text-editor.js)|Hard|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2296-design-a-text-editor.js b/solutions/2296-design-a-text-editor.js
new file mode 100644
index 00000000..6020598d
--- /dev/null
+++ b/solutions/2296-design-a-text-editor.js
@@ -0,0 +1,78 @@
+/**
+ * 2296. Design a Text Editor
+ * https://leetcode.com/problems/design-a-text-editor/
+ * Difficulty: Hard
+ *
+ * Design a text editor with a cursor that can do the following:
+ * - Add text to where the cursor is.
+ * - Delete text from where the cursor is (simulating the backspace key).
+ * - Move the cursor either left or right.
+ *
+ * When deleting text, only characters to the left of the cursor will be deleted. The cursor
+ * will also remain within the actual text and cannot be moved beyond it. More formally,
+ * we have that 0 <= cursor.position <= currentText.length always holds.
+ *
+ * Implement the TextEditor class:
+ * - TextEditor() Initializes the object with empty text.
+ * - void addText(string text) Appends text to where the cursor is. The cursor ends to the
+ *   right of text.
+ * - int deleteText(int k) Deletes k characters to the left of the cursor. Returns the number
+ *   of characters actually deleted.
+ * - string cursorLeft(int k) Moves the cursor to the left k times. Returns the last
+ *   min(10, len) characters to the left of the cursor, where len is the number of characters
+ *   to the left of the cursor.
+ * - string cursorRight(int k) Moves the cursor to the right k times. Returns the last
+ *   min(10, len) characters to the left of the cursor, where len is the number of characters
+ *   to the left of the cursor.
+ */
+
+var TextEditor = function() {
+  this.left = [];
+  this.right = [];
+};
+
+/**
+ * @param {string} text
+ * @return {void}
+ */
+TextEditor.prototype.addText = function(text) {
+  for (const char of text) {
+    this.left.push(char);
+  }
+};
+
+/**
+ * @param {number} k
+ * @return {number}
+ */
+TextEditor.prototype.deleteText = function(k) {
+  const deleteCount = Math.min(k, this.left.length);
+  for (let i = 0; i < deleteCount; i++) {
+    this.left.pop();
+  }
+  return deleteCount;
+};
+
+/**
+ * @param {number} k
+ * @return {string}
+ */
+TextEditor.prototype.cursorLeft = function(k) {
+  for (let i = 0; i < k && this.left.length; i++) {
+    this.right.push(this.left.pop());
+  }
+  const start = Math.max(0, this.left.length - 10);
+  return this.left.slice(start).join('');
+};
+
+/**
+ * @param {number} k
+ * @return {string}
+ */
+TextEditor.prototype.cursorRight = function(k) {
+  for (let i = 0; i < k && this.right.length; i++) {
+    this.left.push(this.right.pop());
+  }
+  const start = Math.max(0, this.left.length - 10);
+  return this.left.slice(start).join('');
+};

From 7911c57fd8519c070d505ee481a0e9757f718d41 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 17 May 2025 21:03:05 -0500
Subject: [PATCH 365/495] Add solution #2299

---
 README.md                                    |  3 +-
 solutions/2299-strong-password-checker-ii.js | 43 ++++++++++++++++++++
 2 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2299-strong-password-checker-ii.js

diff --git a/README.md b/README.md
index ad76b866..d89e94ae 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,869 LeetCode solutions in JavaScript
+# 1,870 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1747,6 +1747,7 @@
 2294|[Partition Array Such That Maximum Difference Is K](./solutions/2294-partition-array-such-that-maximum-difference-is-k.js)|Medium|
 2295|[Replace Elements in an Array](./solutions/2295-replace-elements-in-an-array.js)|Medium|
 2296|[Design a Text Editor](./solutions/2296-design-a-text-editor.js)|Hard|
+2299|[Strong Password Checker II](./solutions/2299-strong-password-checker-ii.js)|Easy|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2299-strong-password-checker-ii.js b/solutions/2299-strong-password-checker-ii.js
new file mode 100644
index 00000000..f96fac07
--- /dev/null
+++ b/solutions/2299-strong-password-checker-ii.js
@@ -0,0 +1,43 @@
+/**
+ * 2299. Strong Password Checker II
+ * https://leetcode.com/problems/strong-password-checker-ii/
+ * Difficulty: Easy
+ *
+ * A password is said to be strong if it satisfies all the following criteria:
+ * - It has at least 8 characters.
+ * - It contains at least one lowercase letter.
+ * - It contains at least one uppercase letter.
+ * - It contains at least one digit.
+ * - It contains at least one special character. The special characters are the characters
+ *   in the following string: "!@#$%^&*()-+".
+ * - It does not contain 2 of the same character in adjacent positions (i.e., "aab" violates
+ *   this condition, but "aba" does not).
+ *
+ * Given a string password, return true if it is a strong password. Otherwise, return false.
+ */
+
+/**
+ * @param {string} password
+ * @return {boolean}
+ */
+var strongPasswordCheckerII = function(password) {
+  if (password.length < 8) return false;
+
+  let hasLower = false;
+  let hasUpper = false;
+  let hasDigit = false;
+  let hasSpecial = false;
+  const set = new Set(['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+']);
+
+  for (let i = 0; i < password.length; i++) {
+    if (i > 0 && password[i] === password[i - 1]) return false;
+
+    const char = password[i];
+    if (/[a-z]/.test(char)) hasLower = true;
+    else if (/[A-Z]/.test(char)) hasUpper = true;
+    else if (/\d/.test(char)) hasDigit = true;
+    else if (set.has(char)) hasSpecial = true;
+  }
+
+  return hasLower && hasUpper && hasDigit && hasSpecial;
+};

From f844ba96ba27b17fb5c0b1c84e6707c4555287f8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 18 May 2025 00:17:57 -0500
Subject: [PATCH 366/495] Add solution #2301

---
 README.md                                     |  3 +-
 .../2301-match-substring-after-replacement.js | 50 +++++++++++++++++++
 2 files changed, 52 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2301-match-substring-after-replacement.js

diff --git a/README.md b/README.md
index d89e94ae..68498fe0 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,870 LeetCode solutions in JavaScript
+# 1,871 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1749,6 +1749,7 @@
 2296|[Design a Text Editor](./solutions/2296-design-a-text-editor.js)|Hard|
 2299|[Strong Password Checker II](./solutions/2299-strong-password-checker-ii.js)|Easy|
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
+2301|[Match Substring After Replacement](./solutions/2301-match-substring-after-replacement.js)|Hard|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
diff --git a/solutions/2301-match-substring-after-replacement.js b/solutions/2301-match-substring-after-replacement.js
new file mode 100644
index 00000000..fc7e5a91
--- /dev/null
+++ b/solutions/2301-match-substring-after-replacement.js
@@ -0,0 +1,50 @@
+/**
+ * 2301. Match Substring After Replacement
+ * https://leetcode.com/problems/match-substring-after-replacement/
+ * Difficulty: Hard
+ *
+ * You are given two strings s and sub. You are also given a 2D character array mappings where
+ * mappings[i] = [oldi, newi] indicates that you may perform the following operation any number
+ * of times:
+ * - Replace a character oldi of sub with newi.
+ *
+ * Each character in sub cannot be replaced more than once.
+ *
+ * Return true if it is possible to make sub a substring of s by replacing zero or more characters
+ * according to mappings. Otherwise, return false.
+ *
+ * A substring is a contiguous non-empty sequence of characters within a string.
+ */
+
+/**
+ * @param {string} s
+ * @param {string} sub
+ * @param {character[][]} mappings
+ * @return {boolean}
+ */
+var matchReplacement = function(s, sub, mappings) {
+  const map = new Map();
+
+  for (const [oldChar, newChar] of mappings) {
+    if (!map.has(oldChar)) {
+      map.set(oldChar, new Set());
+    }
+    map.get(oldChar).add(newChar);
+  }
+
+  const subLen = sub.length;
+  for (let i = 0; i <= s.length - subLen; i++) {
+    let isValid = true;
+    for (let j = 0; j < subLen; j++) {
+      const sChar = s[i + j];
+      const subChar = sub[j];
+      if (sChar !== subChar && (!map.has(subChar) || !map.get(subChar).has(sChar))) {
+        isValid = false;
+        break;
+      }
+    }
+    if (isValid) return true;
+  }
+
+  return false;
+};

From b4518be735c88b5c3602aada4981c05914422c3c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 18 May 2025 00:19:20 -0500
Subject: [PATCH 367/495] Add solution #2303

---
 README.md                                     |  3 +-
 .../2303-calculate-amount-paid-in-taxes.js    | 41 +++++++++++++++++++
 2 files changed, 43 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2303-calculate-amount-paid-in-taxes.js

diff --git a/README.md b/README.md
index 68498fe0..12e9be04 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,871 LeetCode solutions in JavaScript
+# 1,872 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1751,6 +1751,7 @@
 2300|[Successful Pairs of Spells and Potions](./solutions/2300-successful-pairs-of-spells-and-potions.js)|Medium|
 2301|[Match Substring After Replacement](./solutions/2301-match-substring-after-replacement.js)|Hard|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
+2303|[Calculate Amount Paid in Taxes](./solutions/2303-calculate-amount-paid-in-taxes.js)|Easy|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2303-calculate-amount-paid-in-taxes.js b/solutions/2303-calculate-amount-paid-in-taxes.js
new file mode 100644
index 00000000..6944f54b
--- /dev/null
+++ b/solutions/2303-calculate-amount-paid-in-taxes.js
@@ -0,0 +1,41 @@
+/**
+ * 2303. Calculate Amount Paid in Taxes
+ * https://leetcode.com/problems/calculate-amount-paid-in-taxes/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed 2D integer array brackets where brackets[i] = [upperi, percenti]
+ * means that the ith tax bracket has an upper bound of upperi and is taxed at a rate of percenti.
+ * The brackets are sorted by upper bound (i.e. upperi-1 < upperi for 0 < i < brackets.length).
+ *
+ * Tax is calculated as follows:
+ * - The first upper0 dollars earned are taxed at a rate of percent0.
+ * - The next upper1 - upper0 dollars earned are taxed at a rate of percent1.
+ * - The next upper2 - upper1 dollars earned are taxed at a rate of percent2.
+ * - And so on.
+ *
+ * You are given an integer income representing the amount of money you earned. Return the
+ * amount of money that you have to pay in taxes. Answers within 10-5 of the actual answer
+ * will be accepted.
+ */
+
+/**
+ * @param {number[][]} brackets
+ * @param {number} income
+ * @return {number}
+ */
+var calculateTax = function(brackets, income) {
+  let result = 0;
+  let previousUpper = 0;
+
+  for (const [upper, percent] of brackets) {
+    if (income > previousUpper) {
+      const taxable = Math.min(income, upper) - previousUpper;
+      result += taxable * (percent / 100);
+      previousUpper = upper;
+    } else {
+      break;
+    }
+  }
+
+  return result;
+};

From 97b909a586ddd254920186ffb9861a98a72ea3e1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 18 May 2025 00:20:51 -0500
Subject: [PATCH 368/495] Add solution #2304

---
 README.md                                     |  3 +-
 solutions/2304-minimum-path-cost-in-a-grid.js | 48 +++++++++++++++++++
 2 files changed, 50 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2304-minimum-path-cost-in-a-grid.js

diff --git a/README.md b/README.md
index 12e9be04..afd9131f 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,872 LeetCode solutions in JavaScript
+# 1,873 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1752,6 +1752,7 @@
 2301|[Match Substring After Replacement](./solutions/2301-match-substring-after-replacement.js)|Hard|
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2303|[Calculate Amount Paid in Taxes](./solutions/2303-calculate-amount-paid-in-taxes.js)|Easy|
+2304|[Minimum Path Cost in a Grid](./solutions/2304-minimum-path-cost-in-a-grid.js)|Medium|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2304-minimum-path-cost-in-a-grid.js b/solutions/2304-minimum-path-cost-in-a-grid.js
new file mode 100644
index 00000000..eb1f10c4
--- /dev/null
+++ b/solutions/2304-minimum-path-cost-in-a-grid.js
@@ -0,0 +1,48 @@
+/**
+ * 2304. Minimum Path Cost in a Grid
+ * https://leetcode.com/problems/minimum-path-cost-in-a-grid/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from
+ * 0 to m * n - 1. You can move in this matrix from a cell to any other cell in the next row.
+ * That is, if you are in cell (x, y) such that x < m - 1, you can move to any of the cells
+ * (x + 1, 0), (x + 1, 1), ..., (x + 1, n - 1). Note that it is not possible to move from
+ * cells in the last row.
+ *
+ * Each possible move has a cost given by a 0-indexed 2D array moveCost of size (m * n) x n,
+ * where moveCost[i][j] is the cost of moving from a cell with value i to a cell in column j
+ * of the next row. The cost of moving from cells in the last row of grid can be ignored.
+ *
+ * The cost of a path in grid is the sum of all values of cells visited plus the sum of costs
+ * of all the moves made. Return the minimum cost of a path that starts from any cell in the
+ * first row and ends at any cell in the last row.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @param {number[][]} moveCost
+ * @return {number}
+ */
+var minPathCost = function(grid, moveCost) {
+  const m = grid.length;
+  const n = grid[0].length;
+  const dp = Array.from({ length: m }, () => new Array(n).fill(Infinity));
+
+  for (let j = 0; j < n; j++) {
+    dp[0][j] = grid[0][j];
+  }
+
+  for (let i = 0; i < m - 1; i++) {
+    for (let j = 0; j < n; j++) {
+      const value = grid[i][j];
+      for (let k = 0; k < n; k++) {
+        dp[i + 1][k] = Math.min(
+          dp[i + 1][k],
+          dp[i][j] + grid[i + 1][k] + moveCost[value][k]
+        );
+      }
+    }
+  }
+
+  return Math.min(...dp[m - 1]);
+};

From 46a9758a35c9d76c06c698b5d73fa67e09240369 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 18 May 2025 00:22:11 -0500
Subject: [PATCH 369/495] Add solution #2305

---
 README.md                                     |  3 +-
 .../2305-fair-distribution-of-cookies.js      | 46 +++++++++++++++++++
 2 files changed, 48 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2305-fair-distribution-of-cookies.js

diff --git a/README.md b/README.md
index afd9131f..b8a45bb2 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,873 LeetCode solutions in JavaScript
+# 1,874 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1753,6 +1753,7 @@
 2302|[Count Subarrays With Score Less Than K](./solutions/2302-count-subarrays-with-score-less-than-k.js)|Hard|
 2303|[Calculate Amount Paid in Taxes](./solutions/2303-calculate-amount-paid-in-taxes.js)|Easy|
 2304|[Minimum Path Cost in a Grid](./solutions/2304-minimum-path-cost-in-a-grid.js)|Medium|
+2305|[Fair Distribution of Cookies](./solutions/2305-fair-distribution-of-cookies.js)|Medium|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2305-fair-distribution-of-cookies.js b/solutions/2305-fair-distribution-of-cookies.js
new file mode 100644
index 00000000..dffcb4a4
--- /dev/null
+++ b/solutions/2305-fair-distribution-of-cookies.js
@@ -0,0 +1,46 @@
+/**
+ * 2305. Fair Distribution of Cookies
+ * https://leetcode.com/problems/fair-distribution-of-cookies/
+ * Difficulty: Medium
+ *
+ * You are given an integer array cookies, where cookies[i] denotes the number of cookies in the
+ * ith bag. You are also given an integer k that denotes the number of children to distribute
+ * all the bags of cookies to. All the cookies in the same bag must go to the same child and
+ * cannot be split up.
+ *
+ * The unfairness of a distribution is defined as the maximum total cookies obtained by a single
+ * child in the distribution.
+ *
+ * Return the minimum unfairness of all distributions.
+ */
+
+/**
+ * @param {number[]} cookies
+ * @param {number} k
+ * @return {number}
+ */
+var distributeCookies = function(cookies, k) {
+  const distribution = new Array(k).fill(0);
+  let result = Infinity;
+
+  distribute(0);
+
+  return result;
+
+  function distribute(index) {
+    if (index === cookies.length) {
+      result = Math.min(result, Math.max(...distribution));
+      return;
+    }
+
+    for (let i = 0; i < k; i++) {
+      distribution[i] += cookies[index];
+      if (distribution[i] < result) {
+        distribute(index + 1);
+      }
+      distribution[i] -= cookies[index];
+
+      if (distribution[i] === 0) break;
+    }
+  }
+};

From 3fab53cef94f423a41a392554c25dc950e04f3f1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 18 May 2025 00:23:24 -0500
Subject: [PATCH 370/495] Add solution #2306

---
 README.md                          |  3 ++-
 solutions/2306-naming-a-company.js | 37 ++++++++++++++++++++++++++++++
 2 files changed, 39 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2306-naming-a-company.js

diff --git a/README.md b/README.md
index b8a45bb2..cbcc7ee4 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,874 LeetCode solutions in JavaScript
+# 1,875 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1754,6 +1754,7 @@
 2303|[Calculate Amount Paid in Taxes](./solutions/2303-calculate-amount-paid-in-taxes.js)|Easy|
 2304|[Minimum Path Cost in a Grid](./solutions/2304-minimum-path-cost-in-a-grid.js)|Medium|
 2305|[Fair Distribution of Cookies](./solutions/2305-fair-distribution-of-cookies.js)|Medium|
+2306|[Naming a Company](./solutions/2306-naming-a-company.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2306-naming-a-company.js b/solutions/2306-naming-a-company.js
new file mode 100644
index 00000000..bef81dfe
--- /dev/null
+++ b/solutions/2306-naming-a-company.js
@@ -0,0 +1,37 @@
+/**
+ * 2306. Naming a Company
+ * https://leetcode.com/problems/naming-a-company/
+ * Difficulty: Hard
+ *
+ * You are given an array of strings ideas that represents a list of names to be used in the
+ * process of naming a company. The process of naming a company is as follows:
+ * 1. Choose 2 distinct names from ideas, call them ideaA and ideaB.
+ * 2. Swap the first letters of ideaA and ideaB with each other.
+ * 3. If both of the new names are not found in the original ideas, then the name ideaA ideaB
+ *    (the concatenation of ideaA and ideaB, separated by a space) is a valid company name.
+ * 4. Otherwise, it is not a valid name.
+ *
+ * Return the number of distinct valid names for the company.
+ */
+
+/**
+ * @param {string[]} ideas
+ * @return {number}
+ */
+var distinctNames = function(ideas) {
+  const groups = Array.from({ length: 26 }, () => new Set());
+  let result = 0;
+
+  for (const idea of ideas) {
+    groups[idea.charCodeAt(0) - 97].add(idea.slice(1));
+  }
+
+  for (let i = 0; i < 25; i++) {
+    for (let j = i + 1; j < 26; j++) {
+      const mutualCount = [...groups[i]].filter(suffix => groups[j].has(suffix)).length;
+      result += 2 * (groups[i].size - mutualCount) * (groups[j].size - mutualCount);
+    }
+  }
+
+  return result;
+};

From 2b2576103509fc0d0a2429074e49f2a410f36e42 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 18 May 2025 00:25:20 -0500
Subject: [PATCH 371/495] Add solution #2309

---
 README.md                                     |  3 +-
 ...-english-letter-in-upper-and-lower-case.js | 38 +++++++++++++++++++
 2 files changed, 40 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2309-greatest-english-letter-in-upper-and-lower-case.js

diff --git a/README.md b/README.md
index cbcc7ee4..bbd36085 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,875 LeetCode solutions in JavaScript
+# 1,876 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1755,6 +1755,7 @@
 2304|[Minimum Path Cost in a Grid](./solutions/2304-minimum-path-cost-in-a-grid.js)|Medium|
 2305|[Fair Distribution of Cookies](./solutions/2305-fair-distribution-of-cookies.js)|Medium|
 2306|[Naming a Company](./solutions/2306-naming-a-company.js)|Hard|
+2309|[Greatest English Letter in Upper and Lower Case](./solutions/2309-greatest-english-letter-in-upper-and-lower-case.js)|Easy|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2309-greatest-english-letter-in-upper-and-lower-case.js b/solutions/2309-greatest-english-letter-in-upper-and-lower-case.js
new file mode 100644
index 00000000..b86b8f8b
--- /dev/null
+++ b/solutions/2309-greatest-english-letter-in-upper-and-lower-case.js
@@ -0,0 +1,38 @@
+/**
+ * 2309. Greatest English Letter in Upper and Lower Case
+ * https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case/
+ * Difficulty: Easy
+ *
+ * Given a string of English letters s, return the greatest English letter which occurs as both
+ * a lowercase and uppercase letter in s. The returned letter should be in uppercase. If no such
+ * letter exists, return an empty string.
+ *
+ * An English letter b is greater than another letter a if b appears after a in the English
+ * alphabet.
+ */
+
+/**
+ * @param {string} s
+ * @return {string}
+ */
+var greatestLetter = function(s) {
+  const lowerSet = new Set();
+  const upperSet = new Set();
+
+  for (const char of s) {
+    if (char >= 'a' && char <= 'z') {
+      lowerSet.add(char);
+    } else {
+      upperSet.add(char.toLowerCase());
+    }
+  }
+
+  let maxLetter = '';
+  for (const char of lowerSet) {
+    if (upperSet.has(char) && char > maxLetter) {
+      maxLetter = char;
+    }
+  }
+
+  return maxLetter.toUpperCase();
+};

From 86cdd1521196ed5c580fcbf78284bdd8fab92d51 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 18 May 2025 00:26:27 -0500
Subject: [PATCH 372/495] Add solution #2312

---
 README.md                                |  3 +-
 solutions/2312-selling-pieces-of-wood.js | 46 ++++++++++++++++++++++++
 2 files changed, 48 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2312-selling-pieces-of-wood.js

diff --git a/README.md b/README.md
index bbd36085..a5724555 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,876 LeetCode solutions in JavaScript
+# 1,877 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1756,6 +1756,7 @@
 2305|[Fair Distribution of Cookies](./solutions/2305-fair-distribution-of-cookies.js)|Medium|
 2306|[Naming a Company](./solutions/2306-naming-a-company.js)|Hard|
 2309|[Greatest English Letter in Upper and Lower Case](./solutions/2309-greatest-english-letter-in-upper-and-lower-case.js)|Easy|
+2312|[Selling Pieces of Wood](./solutions/2312-selling-pieces-of-wood.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2312-selling-pieces-of-wood.js b/solutions/2312-selling-pieces-of-wood.js
new file mode 100644
index 00000000..6edab3a0
--- /dev/null
+++ b/solutions/2312-selling-pieces-of-wood.js
@@ -0,0 +1,46 @@
+/**
+ * 2312. Selling Pieces of Wood
+ * https://leetcode.com/problems/selling-pieces-of-wood/
+ * Difficulty: Hard
+ *
+ * You are given two integers m and n that represent the height and width of a rectangular piece
+ * of wood. You are also given a 2D integer array prices, where prices[i] = [hi, wi, pricei]
+ * indicates you can sell a rectangular piece of wood of height hi and width wi for pricei dollars.
+ *
+ * To cut a piece of wood, you must make a vertical or horizontal cut across the entire height
+ * or width of the piece to split it into two smaller pieces. After cutting a piece of wood into
+ * some number of smaller pieces, you can sell pieces according to prices. You may sell multiple
+ * pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood
+ * makes a difference, so you cannot rotate a piece to swap its height and width.
+ *
+ * Return the maximum money you can earn after cutting an m x n piece of wood.
+ *
+ * Note that you can cut the piece of wood as many times as you want.
+ */
+
+/**
+ * @param {number} m
+ * @param {number} n
+ * @param {number[][]} prices
+ * @return {number}
+ */
+var sellingWood = function(m, n, prices) {
+  const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
+
+  for (const [h, w, price] of prices) {
+    dp[h][w] = price;
+  }
+
+  for (let i = 1; i <= m; i++) {
+    for (let j = 1; j <= n; j++) {
+      for (let k = 1; k < i; k++) {
+        dp[i][j] = Math.max(dp[i][j], dp[k][j] + dp[i - k][j]);
+      }
+      for (let k = 1; k < j; k++) {
+        dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[i][j - k]);
+      }
+    }
+  }
+
+  return dp[m][n];
+};

From cd91566e2a9954db0977430d1e21a8b4bba0e370 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 18 May 2025 00:27:46 -0500
Subject: [PATCH 373/495] Add solution #2315

---
 README.md                         |  3 ++-
 solutions/2315-count-asterisks.js | 32 +++++++++++++++++++++++++++++++
 2 files changed, 34 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2315-count-asterisks.js

diff --git a/README.md b/README.md
index a5724555..d511a7a2 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,877 LeetCode solutions in JavaScript
+# 1,878 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1757,6 +1757,7 @@
 2306|[Naming a Company](./solutions/2306-naming-a-company.js)|Hard|
 2309|[Greatest English Letter in Upper and Lower Case](./solutions/2309-greatest-english-letter-in-upper-and-lower-case.js)|Easy|
 2312|[Selling Pieces of Wood](./solutions/2312-selling-pieces-of-wood.js)|Hard|
+2315|[Count Asterisks](./solutions/2315-count-asterisks.js)|Easy|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2315-count-asterisks.js b/solutions/2315-count-asterisks.js
new file mode 100644
index 00000000..650055eb
--- /dev/null
+++ b/solutions/2315-count-asterisks.js
@@ -0,0 +1,32 @@
+/**
+ * 2315. Count Asterisks
+ * https://leetcode.com/problems/count-asterisks/
+ * Difficulty: Easy
+ *
+ * You are given a string s, where every two consecutive vertical bars '|' are grouped into
+ * a pair. In other words, the 1st and 2nd '|' make a pair, the 3rd and 4th '|' make a pair,
+ * and so forth.
+ *
+ * Return the number of '*' in s, excluding the '*' between each pair of '|'.
+ *
+ * Note that each '|' will belong to exactly one pair.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var countAsterisks = function(s) {
+  let isInsidePair = false;
+  let result = 0;
+
+  for (const char of s) {
+    if (char === '|') {
+      isInsidePair = !isInsidePair;
+    } else if (char === '*' && !isInsidePair) {
+      result++;
+    }
+  }
+
+  return result;
+};

From 68fe034378ffc0b7a7c1c805b9775280a9d9b62e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 18 May 2025 00:28:50 -0500
Subject: [PATCH 374/495] Add solution #2316

---
 README.md                                     |  3 +-
 ...e-pairs-of-nodes-in-an-undirected-graph.js | 48 +++++++++++++++++++
 2 files changed, 50 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.js

diff --git a/README.md b/README.md
index d511a7a2..d0e8eb2f 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,878 LeetCode solutions in JavaScript
+# 1,879 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1758,6 +1758,7 @@
 2309|[Greatest English Letter in Upper and Lower Case](./solutions/2309-greatest-english-letter-in-upper-and-lower-case.js)|Easy|
 2312|[Selling Pieces of Wood](./solutions/2312-selling-pieces-of-wood.js)|Hard|
 2315|[Count Asterisks](./solutions/2315-count-asterisks.js)|Easy|
+2316|[Count Unreachable Pairs of Nodes in an Undirected Graph](./solutions/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.js)|Medium|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.js b/solutions/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.js
new file mode 100644
index 00000000..4de0c07b
--- /dev/null
+++ b/solutions/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.js
@@ -0,0 +1,48 @@
+/**
+ * 2316. Count Unreachable Pairs of Nodes in an Undirected Graph
+ * https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/
+ * Difficulty: Medium
+ *
+ * You are given an integer n. There is an undirected graph with n nodes, numbered from 0
+ * to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that
+ * there exists an undirected edge connecting nodes ai and bi.
+ *
+ * Return the number of pairs of different nodes that are unreachable from each other.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @return {number}
+ */
+var countPairs = function(n, edges) {
+  const graph = Array.from({ length: n }, () => []);
+  for (const [a, b] of edges) {
+    graph[a].push(b);
+    graph[b].push(a);
+  }
+
+  const visited = new Array(n).fill(false);
+  let result = 0;
+
+  let totalNodes = 0;
+  for (let node = 0; node < n; node++) {
+    if (!visited[node]) {
+      const componentSize = exploreComponent(node);
+      result += totalNodes * componentSize;
+      totalNodes += componentSize;
+    }
+  }
+
+  return result;
+
+  function exploreComponent(node) {
+    if (visited[node]) return 0;
+    visited[node] = true;
+    let size = 1;
+    for (const neighbor of graph[node]) {
+      size += exploreComponent(neighbor);
+    }
+    return size;
+  }
+};

From 6674bc66c5873a20ec9e98bfb64ae99f272c87ce Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 18 May 2025 00:30:03 -0500
Subject: [PATCH 375/495] Add solution #2317

---
 README.md                                     |  3 ++-
 .../2317-maximum-xor-after-operations.js      | 27 +++++++++++++++++++
 2 files changed, 29 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2317-maximum-xor-after-operations.js

diff --git a/README.md b/README.md
index d0e8eb2f..5a5c1623 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,879 LeetCode solutions in JavaScript
+# 1,880 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1759,6 +1759,7 @@
 2312|[Selling Pieces of Wood](./solutions/2312-selling-pieces-of-wood.js)|Hard|
 2315|[Count Asterisks](./solutions/2315-count-asterisks.js)|Easy|
 2316|[Count Unreachable Pairs of Nodes in an Undirected Graph](./solutions/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.js)|Medium|
+2317|[Maximum XOR After Operations](./solutions/2317-maximum-xor-after-operations.js)|Medium|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2317-maximum-xor-after-operations.js b/solutions/2317-maximum-xor-after-operations.js
new file mode 100644
index 00000000..7049675b
--- /dev/null
+++ b/solutions/2317-maximum-xor-after-operations.js
@@ -0,0 +1,27 @@
+/**
+ * 2317. Maximum XOR After Operations
+ * https://leetcode.com/problems/maximum-xor-after-operations/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums. In one operation, select any non-negative
+ * integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x).
+ *
+ * Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation.
+ *
+ * Return the maximum possible bitwise XOR of all elements of nums after applying the operation
+ * any number of times.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maximumXOR = function(nums) {
+  let maxXor = 0;
+
+  for (const num of nums) {
+    maxXor |= num;
+  }
+
+  return maxXor;
+};

From 509c9916266212ad54e8cdf781949c9483d724a2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 19 May 2025 18:57:53 -0500
Subject: [PATCH 376/495] Add solution #3024

---
 README.md                          |  3 ++-
 solutions/3024-type-of-triangle.js | 27 +++++++++++++++++++++++++++
 2 files changed, 29 insertions(+), 1 deletion(-)
 create mode 100644 solutions/3024-type-of-triangle.js

diff --git a/README.md b/README.md
index 5a5c1623..3fb04dbe 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,880 LeetCode solutions in JavaScript
+# 1,881 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1855,6 +1855,7 @@
 2962|[Count Subarrays Where Max Element Appears at Least K Times](./solutions/2962-count-subarrays-where-max-element-appears-at-least-k-times.js)|Medium|
 2965|[Find Missing and Repeated Values](./solutions/2965-find-missing-and-repeated-values.js)|Easy|
 2999|[Count the Number of Powerful Integers](./solutions/2999-count-the-number-of-powerful-integers.js)|Hard|
+3024|[Type of Triangle](./solutions/3024-type-of-triangle.js)|Easy|
 3042|[Count Prefix and Suffix Pairs I](./solutions/3042-count-prefix-and-suffix-pairs-i.js)|Easy|
 3066|[Minimum Operations to Exceed Threshold Value II](./solutions/3066-minimum-operations-to-exceed-threshold-value-ii.js)|Medium|
 3105|[Longest Strictly Increasing or Strictly Decreasing Subarray](./solutions/3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js)|Easy|
diff --git a/solutions/3024-type-of-triangle.js b/solutions/3024-type-of-triangle.js
new file mode 100644
index 00000000..0a62411d
--- /dev/null
+++ b/solutions/3024-type-of-triangle.js
@@ -0,0 +1,27 @@
+/**
+ * 3024. Type of Triangle
+ * https://leetcode.com/problems/type-of-triangle/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums of size 3 which can form the sides of a triangle.
+ * - A triangle is called equilateral if it has all sides of equal length.
+ * - A triangle is called isosceles if it has exactly two sides of equal length.
+ * - A triangle is called scalene if all its sides are of different lengths.
+ *
+ * Return a string representing the type of triangle that can be formed or "none" if it cannot
+ * form a triangle.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {string}
+ */
+var triangleType = function(nums) {
+  const [sideA, sideB, sideC] = nums.sort((a, b) => a - b);
+
+  if (sideA + sideB <= sideC) return 'none';
+  if (sideA === sideB && sideB === sideC) return 'equilateral';
+  if (sideA === sideB || sideB === sideC) return 'isosceles';
+
+  return 'scalene';
+};

From 6a179c10160fb674f049602742e98a1207b6a624 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 19 May 2025 18:58:57 -0500
Subject: [PATCH 377/495] Add solution #2319

---
 README.md                                     |  3 +-
 solutions/2319-check-if-matrix-is-x-matrix.js | 32 +++++++++++++++++++
 2 files changed, 34 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2319-check-if-matrix-is-x-matrix.js

diff --git a/README.md b/README.md
index 3fb04dbe..3ee503ce 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,881 LeetCode solutions in JavaScript
+# 1,882 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1760,6 +1760,7 @@
 2315|[Count Asterisks](./solutions/2315-count-asterisks.js)|Easy|
 2316|[Count Unreachable Pairs of Nodes in an Undirected Graph](./solutions/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.js)|Medium|
 2317|[Maximum XOR After Operations](./solutions/2317-maximum-xor-after-operations.js)|Medium|
+2319|[Check if Matrix Is X-Matrix](./solutions/2319-check-if-matrix-is-x-matrix.js)|Easy|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2319-check-if-matrix-is-x-matrix.js b/solutions/2319-check-if-matrix-is-x-matrix.js
new file mode 100644
index 00000000..ee45ca42
--- /dev/null
+++ b/solutions/2319-check-if-matrix-is-x-matrix.js
@@ -0,0 +1,32 @@
+/**
+ * 2319. Check if Matrix Is X-Matrix
+ * https://leetcode.com/problems/check-if-matrix-is-x-matrix/
+ * Difficulty: Easy
+ *
+ * A square matrix is said to be an X-Matrix if both of the following conditions hold:
+ * 1. All the elements in the diagonals of the matrix are non-zero.
+ * 2. All other elements are 0.
+ *
+ * Given a 2D integer array grid of size n x n representing a square matrix, return true if grid
+ * is an X-Matrix. Otherwise, return false.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {boolean}
+ */
+var checkXMatrix = function(grid) {
+  const size = grid.length;
+
+  for (let row = 0; row < size; row++) {
+    for (let col = 0; col < size; col++) {
+      const isDiagonal = row === col || row + col === size - 1;
+      const isNonZero = grid[row][col] !== 0;
+
+      if (isDiagonal && !isNonZero) return false;
+      if (!isDiagonal && isNonZero) return false;
+    }
+  }
+
+  return true;
+};

From 3298f0cc9fb8859dfea7e3f85ebb5e15932d2da3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 19 May 2025 19:00:40 -0500
Subject: [PATCH 378/495] Add solution #2320

---
 README.md                                     |  3 +-
 ...20-count-number-of-ways-to-place-houses.js | 34 +++++++++++++++++++
 2 files changed, 36 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2320-count-number-of-ways-to-place-houses.js

diff --git a/README.md b/README.md
index 3ee503ce..6f303462 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,882 LeetCode solutions in JavaScript
+# 1,883 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1761,6 +1761,7 @@
 2316|[Count Unreachable Pairs of Nodes in an Undirected Graph](./solutions/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.js)|Medium|
 2317|[Maximum XOR After Operations](./solutions/2317-maximum-xor-after-operations.js)|Medium|
 2319|[Check if Matrix Is X-Matrix](./solutions/2319-check-if-matrix-is-x-matrix.js)|Easy|
+2320|[Count Number of Ways to Place Houses](./solutions/2320-count-number-of-ways-to-place-houses.js)|Medium|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2320-count-number-of-ways-to-place-houses.js b/solutions/2320-count-number-of-ways-to-place-houses.js
new file mode 100644
index 00000000..39c28f72
--- /dev/null
+++ b/solutions/2320-count-number-of-ways-to-place-houses.js
@@ -0,0 +1,34 @@
+/**
+ * 2320. Count Number of Ways to Place Houses
+ * https://leetcode.com/problems/count-number-of-ways-to-place-houses/
+ * Difficulty: Medium
+ *
+ * There is a street with n * 2 plots, where there are n plots on each side of the street. The plots
+ * on each side are numbered from 1 to n. On each plot, a house can be placed.
+ *
+ * Return the number of ways houses can be placed such that no two houses are adjacent to each other
+ * on the same side of the street. Since the answer may be very large, return it modulo 109 + 7.
+ *
+ * Note that if a house is placed on the ith plot on one side of the street, a house can also be
+ * placed on the ith plot on the other side of the street.
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var countHousePlacements = function(n) {
+  const MOD = 1e9 + 7;
+  let empty = 1n;
+  let house = 1n;
+
+  for (let i = 2; i <= n; i++) {
+    const nextEmpty = (empty + house) % BigInt(MOD);
+    const nextHouse = empty;
+    empty = nextEmpty;
+    house = nextHouse;
+  }
+
+  const sideWays = (empty + house) % BigInt(MOD);
+  return Number((sideWays * sideWays) % BigInt(MOD));
+};

From 2ed286a058234050fc03b28f06b5a16b968f10fa Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 19 May 2025 19:06:05 -0500
Subject: [PATCH 379/495] Add solution #3355

---
 README.md                                     |  3 +-
 solutions/3355-zero-array-transformation-i.js | 43 +++++++++++++++++++
 2 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 solutions/3355-zero-array-transformation-i.js

diff --git a/README.md b/README.md
index 6f303462..115378bd 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,883 LeetCode solutions in JavaScript
+# 1,884 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1877,6 +1877,7 @@
 3341|[Find Minimum Time to Reach Last Room I](./solutions/3341-find-minimum-time-to-reach-last-room-i.js)|Medium|
 3342|[Find Minimum Time to Reach Last Room II](./solutions/3342-find-minimum-time-to-reach-last-room-ii.js)|Medium|
 3343|[Count Number of Balanced Permutations](./solutions/3343-count-number-of-balanced-permutations.js)|Hard|
+3355|[Zero Array Transformation I](./solutions/3355-zero-array-transformation-i.js)|Medium|
 3356|[Zero Array Transformation II](./solutions/3356-zero-array-transformation-ii.js)|Medium|
 3375|[Minimum Operations to Make Array Values Equal to K](./solutions/3375-minimum-operations-to-make-array-values-equal-to-k.js)|Easy|
 3392|[Count Subarrays of Length Three With a Condition](./solutions/3392-count-subarrays-of-length-three-with-a-condition.js)|Easy|
diff --git a/solutions/3355-zero-array-transformation-i.js b/solutions/3355-zero-array-transformation-i.js
new file mode 100644
index 00000000..21b9bc13
--- /dev/null
+++ b/solutions/3355-zero-array-transformation-i.js
@@ -0,0 +1,43 @@
+/**
+ * 3355. Zero Array Transformation I
+ * https://leetcode.com/problems/zero-array-transformation-i/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums of length n and a 2D array queries, where
+ * queries[i] = [li, ri].
+ *
+ * For each queries[i]:
+ * - Select a subset of indices within the range [li, ri] in nums.
+ * - Decrement the values at the selected indices by 1.
+ *
+ * A Zero Array is an array where all elements are equal to 0.
+ *
+ * Return true if it is possible to transform nums into a Zero Array after processing all the
+ * queries sequentially, otherwise return false.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[][]} queries
+ * @return {boolean}
+ */
+var isZeroArray = function(nums, queries) {
+  const maxDecrements = new Array(nums.length).fill(0);
+
+  for (const [left, right] of queries) {
+    maxDecrements[left]++;
+    if (right + 1 < nums.length) {
+      maxDecrements[right + 1]--;
+    }
+  }
+
+  let currentDecrements = 0;
+  for (let i = 0; i < nums.length; i++) {
+    currentDecrements += maxDecrements[i];
+    if (nums[i] > currentDecrements) {
+      return false;
+    }
+  }
+
+  return true;
+};

From 6858100e893c4cd98c20f35c944ee067288281e6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 19 May 2025 19:08:43 -0500
Subject: [PATCH 380/495] Add solution #2318

---
 README.md                                     |  3 +-
 .../2318-number-of-distinct-roll-sequences.js | 55 +++++++++++++++++++
 2 files changed, 57 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2318-number-of-distinct-roll-sequences.js

diff --git a/README.md b/README.md
index 115378bd..dc05171d 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,884 LeetCode solutions in JavaScript
+# 1,885 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1760,6 +1760,7 @@
 2315|[Count Asterisks](./solutions/2315-count-asterisks.js)|Easy|
 2316|[Count Unreachable Pairs of Nodes in an Undirected Graph](./solutions/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.js)|Medium|
 2317|[Maximum XOR After Operations](./solutions/2317-maximum-xor-after-operations.js)|Medium|
+2318|[Number of Distinct Roll Sequences](./solutions/2318-number-of-distinct-roll-sequences.js)|Hard|
 2319|[Check if Matrix Is X-Matrix](./solutions/2319-check-if-matrix-is-x-matrix.js)|Easy|
 2320|[Count Number of Ways to Place Houses](./solutions/2320-count-number-of-ways-to-place-houses.js)|Medium|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2318-number-of-distinct-roll-sequences.js b/solutions/2318-number-of-distinct-roll-sequences.js
new file mode 100644
index 00000000..5f67f5c0
--- /dev/null
+++ b/solutions/2318-number-of-distinct-roll-sequences.js
@@ -0,0 +1,55 @@
+/**
+ * 2318. Number of Distinct Roll Sequences
+ * https://leetcode.com/problems/number-of-distinct-roll-sequences/
+ * Difficulty: Hard
+ *
+ * You are given an integer n. You roll a fair 6-sided dice n times. Determine the total number
+ * of distinct sequences of rolls possible such that the following conditions are satisfied:
+ * 1. The greatest common divisor of any adjacent values in the sequence is equal to 1.
+ * 2. There is at least a gap of 2 rolls between equal valued rolls. More formally, if the
+ *    value of the ith roll is equal to the value of the jth roll, then abs(i - j) > 2.
+ *
+ * Return the total number of distinct sequences possible. Since the answer may be very large,
+ * return it modulo 109 + 7.
+ *
+ * Two sequences are considered distinct if at least one element is different.
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var distinctSequences = function(n) {
+  const MOD = 1e9 + 7;
+  const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
+
+  const dp = new Array(n + 1)
+    .fill()
+    .map(() => new Array(7).fill().map(() => new Array(7).fill(0)));
+
+  for (let i = 1; i <= 6; i++) {
+    dp[1][i][0] = 1;
+  }
+
+  for (let len = 2; len <= n; len++) {
+    for (let curr = 1; curr <= 6; curr++) {
+      for (let prev = 0; prev <= 6; prev++) {
+        for (let prevPrev = 0; prevPrev <= 6; prevPrev++) {
+          if (dp[len - 1][prev][prevPrev] === 0) continue;
+          if (curr === prev || curr === prevPrev) continue;
+          if (prev !== 0 && gcd(curr, prev) !== 1) continue;
+          dp[len][curr][prev] = (dp[len][curr][prev] + dp[len - 1][prev][prevPrev]) % MOD;
+        }
+      }
+    }
+  }
+
+  let result = 0;
+  for (let curr = 1; curr <= 6; curr++) {
+    for (let prev = 0; prev <= 6; prev++) {
+      result = (result + dp[n][curr][prev]) % MOD;
+    }
+  }
+
+  return result;
+};

From 6280be03be4dbbbce3b3e567674e3300744217e5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 19 May 2025 23:22:06 -0500
Subject: [PATCH 381/495] Add solution #2321

---
 README.md                                     |  3 +-
 .../2321-maximum-score-of-spliced-array.js    | 52 +++++++++++++++++++
 2 files changed, 54 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2321-maximum-score-of-spliced-array.js

diff --git a/README.md b/README.md
index dc05171d..f20841a4 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,885 LeetCode solutions in JavaScript
+# 1,886 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1763,6 +1763,7 @@
 2318|[Number of Distinct Roll Sequences](./solutions/2318-number-of-distinct-roll-sequences.js)|Hard|
 2319|[Check if Matrix Is X-Matrix](./solutions/2319-check-if-matrix-is-x-matrix.js)|Easy|
 2320|[Count Number of Ways to Place Houses](./solutions/2320-count-number-of-ways-to-place-houses.js)|Medium|
+2321|[Maximum Score Of Spliced Array](./solutions/2321-maximum-score-of-spliced-array.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2321-maximum-score-of-spliced-array.js b/solutions/2321-maximum-score-of-spliced-array.js
new file mode 100644
index 00000000..3ecf5068
--- /dev/null
+++ b/solutions/2321-maximum-score-of-spliced-array.js
@@ -0,0 +1,52 @@
+/**
+ * 2321. Maximum Score Of Spliced Array
+ * https://leetcode.com/problems/maximum-score-of-spliced-array/
+ * Difficulty: Hard
+ *
+ * You are given two 0-indexed integer arrays nums1 and nums2, both of length n.
+ *
+ * You can choose two integers left and right where 0 <= left <= right < n and swap the subarray
+ * nums1[left...right] with the subarray nums2[left...right].
+ * - For example, if nums1 = [1,2,3,4,5] and nums2 = [11,12,13,14,15] and you choose left = 1 and
+ *   right = 2, nums1 becomes [1,12,13,4,5] and nums2 becomes [11,2,3,14,15].
+ *
+ * You may choose to apply the mentioned operation once or not do anything.
+ *
+ * The score of the arrays is the maximum of sum(nums1) and sum(nums2), where sum(arr) is the sum
+ * of all the elements in the array arr.
+ *
+ * Return the maximum possible score.
+ *
+ * A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the
+ * subarray that contains the elements of nums between indices left and right (inclusive).
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @return {number}
+ */
+var maximumsSplicedArray = function(nums1, nums2) {
+  const length = nums1.length;
+  let sum1 = 0;
+  let sum2 = 0;
+
+  for (let i = 0; i < length; i++) {
+    sum1 += nums1[i];
+    sum2 += nums2[i];
+  }
+
+  let maxGain1 = 0;
+  let maxGain2 = 0;
+  let currGain1 = 0;
+  let currGain2 = 0;
+
+  for (let i = 0; i < length; i++) {
+    currGain1 = Math.max(0, currGain1 + nums2[i] - nums1[i]);
+    currGain2 = Math.max(0, currGain2 + nums1[i] - nums2[i]);
+    maxGain1 = Math.max(maxGain1, currGain1);
+    maxGain2 = Math.max(maxGain2, currGain2);
+  }
+
+  return Math.max(sum1 + maxGain1, sum2 + maxGain2);
+};

From ce8272ff89d8c1feeb04aae86097d967f789001a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 19 May 2025 23:35:19 -0500
Subject: [PATCH 382/495] Add solution #2322

---
 README.md                                     |   3 +-
 ...-minimum-score-after-removals-on-a-tree.js | 112 ++++++++++++++++++
 2 files changed, 114 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2322-minimum-score-after-removals-on-a-tree.js

diff --git a/README.md b/README.md
index f20841a4..88dcffe8 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,886 LeetCode solutions in JavaScript
+# 1,887 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1764,6 +1764,7 @@
 2319|[Check if Matrix Is X-Matrix](./solutions/2319-check-if-matrix-is-x-matrix.js)|Easy|
 2320|[Count Number of Ways to Place Houses](./solutions/2320-count-number-of-ways-to-place-houses.js)|Medium|
 2321|[Maximum Score Of Spliced Array](./solutions/2321-maximum-score-of-spliced-array.js)|Hard|
+2322|[Minimum Score After Removals on a Tree](./solutions/2322-minimum-score-after-removals-on-a-tree.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2322-minimum-score-after-removals-on-a-tree.js b/solutions/2322-minimum-score-after-removals-on-a-tree.js
new file mode 100644
index 00000000..4b0b6cd0
--- /dev/null
+++ b/solutions/2322-minimum-score-after-removals-on-a-tree.js
@@ -0,0 +1,112 @@
+/**
+ * 2322. Minimum Score After Removals on a Tree
+ * https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/
+ * Difficulty: Hard
+ *
+ * There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
+ *
+ * You are given a 0-indexed integer array nums of length n where nums[i] represents the value
+ * of the ith node. You are also 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.
+ *
+ * Remove two distinct edges of the tree to form three connected components. For a pair of
+ * removed edges, the following steps are defined:
+ * 1. Get the XOR of all the values of the nodes for each of the three components respectively.
+ * 2. The difference between the largest XOR value and the smallest XOR value is the score of
+ *    the pair.
+ * 3. For example, say the three components have the node values: [4,5,7], [1,9], and [3,3,3].
+ *    The three XOR values are 4 ^ 5 ^ 7 = 6, 1 ^ 9 = 8, and 3 ^ 3 ^ 3 = 3. The largest XOR
+ *    value is 8 and the smallest XOR value is 3. The score is then 8 - 3 = 5.
+ *
+ * Return the minimum score of any possible pair of edge removals on the given tree.
+ */
+
+/**
+* @param {number[]} nums
+* @param {number[][]} edges
+* @return {number}
+*/
+var minimumScore = function(nums, edges) {
+  const n = nums.length;
+  const graph = Array.from({ length: n }, () => []);
+
+  for (const [a, b] of edges) {
+    graph[a].push(b);
+    graph[b].push(a);
+  }
+
+  const totalXor = nums.reduce((acc, num) => acc ^ num, 0);
+
+  const subtreeXor = new Array(n).fill(0);
+
+  const tin = new Array(n);
+  const tout = new Array(n);
+  let timer = 0;
+
+  function dfs(node, parent) {
+    tin[node] = timer++;
+    subtreeXor[node] = nums[node];
+
+    for (const neighbor of graph[node]) {
+      if (neighbor !== parent) {
+        dfs(neighbor, node);
+        subtreeXor[node] ^= subtreeXor[neighbor];
+      }
+    }
+
+    tout[node] = timer++;
+  }
+
+  dfs(0, -1);
+
+  function isAncestor(a, b) {
+    return tin[a] <= tin[b] && tout[a] >= tout[b];
+  }
+
+  let result = Infinity;
+  for (let i = 0; i < n - 1; i++) {
+    for (let j = i + 1; j < n - 1; j++) {
+      const edge1 = edges[i];
+      const edge2 = edges[j];
+
+      let node1;
+      if (isAncestor(edge1[0], edge1[1])) {
+        node1 = edge1[1];
+      } else {
+        node1 = edge1[0];
+      }
+      const subtree1 = subtreeXor[node1];
+
+      let node2;
+      if (isAncestor(edge2[0], edge2[1])) {
+        node2 = edge2[1];
+      } else {
+        node2 = edge2[0];
+      }
+      const subtree2 = subtreeXor[node2];
+
+      let component1;
+      let component2;
+      let component3;
+      if (isAncestor(node1, node2)) {
+        component1 = subtree2;
+        component2 = subtree1 ^ component1;
+        component3 = totalXor ^ subtree1;
+      } else if (isAncestor(node2, node1)) {
+        component1 = subtree1;
+        component2 = subtree2 ^ component1;
+        component3 = totalXor ^ subtree2;
+      } else {
+        component1 = subtree1;
+        component2 = subtree2;
+        component3 = totalXor ^ component1 ^ component2;
+      }
+
+      const maxXor = Math.max(component1, component2, component3);
+      const minXor = Math.min(component1, component2, component3);
+      result = Math.min(result, maxXor - minXor);
+    }
+  }
+
+  return result;
+};

From 9dd0030b28d2c412c8ad7cc7b988dbbde589b47b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 19 May 2025 23:36:15 -0500
Subject: [PATCH 383/495] Add solution #2325

---
 README.md                            |  3 +-
 solutions/2325-decode-the-message.js | 41 ++++++++++++++++++++++++++++
 2 files changed, 43 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2325-decode-the-message.js

diff --git a/README.md b/README.md
index 88dcffe8..67d1a520 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,887 LeetCode solutions in JavaScript
+# 1,888 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1765,6 +1765,7 @@
 2320|[Count Number of Ways to Place Houses](./solutions/2320-count-number-of-ways-to-place-houses.js)|Medium|
 2321|[Maximum Score Of Spliced Array](./solutions/2321-maximum-score-of-spliced-array.js)|Hard|
 2322|[Minimum Score After Removals on a Tree](./solutions/2322-minimum-score-after-removals-on-a-tree.js)|Hard|
+2325|[Decode the Message](./solutions/2325-decode-the-message.js)|Easy|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2325-decode-the-message.js b/solutions/2325-decode-the-message.js
new file mode 100644
index 00000000..bde90e23
--- /dev/null
+++ b/solutions/2325-decode-the-message.js
@@ -0,0 +1,41 @@
+/**
+ * 2325. Decode the Message
+ * https://leetcode.com/problems/decode-the-message/
+ * Difficulty: Easy
+ *
+ * You are given the strings key and message, which represent a cipher key and a secret message,
+ * respectively. The steps to decode message are as follows:
+ * 1. Use the first appearance of all 26 lowercase English letters in key as the order of the
+ *    substitution table.
+ * 2. Align the substitution table with the regular English alphabet.
+ * 3. Each letter in message is then substituted using the table.
+ * 4. Spaces ' ' are transformed to themselves.
+ * 5. For example, given key = "happy boy" (actual key would have at least one instance of each
+ *    letter in the alphabet), we have the partial substitution table of ('h' -> 'a', 'a' -> 'b',
+ *    'p' -> 'c', 'y' -> 'd', 'b' -> 'e', 'o' -> 'f').
+ *
+ * Return the decoded message.
+ */
+
+/**
+ * @param {string} key
+ * @param {string} message
+ * @return {string}
+ */
+var decodeMessage = function(key, message) {
+  const substitution = new Map();
+  let alphabetIndex = 0;
+
+  for (const char of key) {
+    if (char !== ' ' && !substitution.has(char)) {
+      substitution.set(char, String.fromCharCode(97 + alphabetIndex++));
+    }
+  }
+
+  let result = '';
+  for (const char of message) {
+    result += char === ' ' ? ' ' : substitution.get(char);
+  }
+
+  return result;
+};

From 170f3eeb4a6d445e16eaf8c7b03c563f113c095d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 19 May 2025 23:37:38 -0500
Subject: [PATCH 384/495] Add solution #2326

---
 README.md                          |  3 +-
 solutions/2326-spiral-matrix-iv.js | 65 ++++++++++++++++++++++++++++++
 2 files changed, 67 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2326-spiral-matrix-iv.js

diff --git a/README.md b/README.md
index 67d1a520..09bbbbca 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,888 LeetCode solutions in JavaScript
+# 1,889 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1766,6 +1766,7 @@
 2321|[Maximum Score Of Spliced Array](./solutions/2321-maximum-score-of-spliced-array.js)|Hard|
 2322|[Minimum Score After Removals on a Tree](./solutions/2322-minimum-score-after-removals-on-a-tree.js)|Hard|
 2325|[Decode the Message](./solutions/2325-decode-the-message.js)|Easy|
+2326|[Spiral Matrix IV](./solutions/2326-spiral-matrix-iv.js)|Medium|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2326-spiral-matrix-iv.js b/solutions/2326-spiral-matrix-iv.js
new file mode 100644
index 00000000..1fa98050
--- /dev/null
+++ b/solutions/2326-spiral-matrix-iv.js
@@ -0,0 +1,65 @@
+/**
+ * 2326. Spiral Matrix IV
+ * https://leetcode.com/problems/spiral-matrix-iv/
+ * Difficulty: Medium
+ *
+ * You are given two integers m and n, which represent the dimensions of a matrix.
+ *
+ * You are also given the head of a linked list of integers.
+ *
+ * Generate an m x n matrix that contains the integers in the linked list presented in spiral
+ * order (clockwise), starting from the top-left of the matrix. If there are remaining empty
+ * spaces, fill them with -1.
+ *
+ * Return the generated matrix.
+ */
+
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val, next) {
+ *     this.val = (val===undefined ? 0 : val)
+ *     this.next = (next===undefined ? null : next)
+ * }
+ */
+/**
+ * @param {number} m
+ * @param {number} n
+ * @param {ListNode} head
+ * @return {number[][]}
+ */
+var spiralMatrix = function(m, n, head) {
+  const matrix = new Array(m).fill().map(() => new Array(n).fill(-1));
+  let top = 0;
+  let bottom = m - 1;
+  let left = 0;
+  let right = n - 1;
+  let current = head;
+
+  while (top <= bottom && left <= right && current) {
+    for (let col = left; col <= right && current; col++) {
+      matrix[top][col] = current.val;
+      current = current.next;
+    }
+    top++;
+
+    for (let row = top; row <= bottom && current; row++) {
+      matrix[row][right] = current.val;
+      current = current.next;
+    }
+    right--;
+
+    for (let col = right; col >= left && current; col--) {
+      matrix[bottom][col] = current.val;
+      current = current.next;
+    }
+    bottom--;
+
+    for (let row = bottom; row >= top && current; row--) {
+      matrix[row][left] = current.val;
+      current = current.next;
+    }
+    left++;
+  }
+
+  return matrix;
+};

From 5c034238bdf96d95dddb195e2c1ac206da9768d3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 19 May 2025 23:39:19 -0500
Subject: [PATCH 385/495] Add solution #2328

---
 README.md                                     |  3 +-
 ...28-number-of-increasing-paths-in-a-grid.js | 53 +++++++++++++++++++
 2 files changed, 55 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2328-number-of-increasing-paths-in-a-grid.js

diff --git a/README.md b/README.md
index 09bbbbca..25a09019 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,889 LeetCode solutions in JavaScript
+# 1,890 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1767,6 +1767,7 @@
 2322|[Minimum Score After Removals on a Tree](./solutions/2322-minimum-score-after-removals-on-a-tree.js)|Hard|
 2325|[Decode the Message](./solutions/2325-decode-the-message.js)|Easy|
 2326|[Spiral Matrix IV](./solutions/2326-spiral-matrix-iv.js)|Medium|
+2328|[Number of Increasing Paths in a Grid](./solutions/2328-number-of-increasing-paths-in-a-grid.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2328-number-of-increasing-paths-in-a-grid.js b/solutions/2328-number-of-increasing-paths-in-a-grid.js
new file mode 100644
index 00000000..f239c80c
--- /dev/null
+++ b/solutions/2328-number-of-increasing-paths-in-a-grid.js
@@ -0,0 +1,53 @@
+/**
+ * 2328. Number of Increasing Paths in a Grid
+ * https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/
+ * Difficulty: Hard
+ *
+ * You are given an m x n integer matrix grid, where you can move from a cell to any adjacent
+ * cell in all 4 directions.
+ *
+ * Return the number of strictly increasing paths in the grid such that you can start from any
+ * cell and end at any cell. Since the answer may be very large, return it modulo 109 + 7.
+ *
+ * Two paths are considered different if they do not have exactly the same sequence of visited
+ * cells.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var countPaths = function(grid) {
+  const MOD = 1e9 + 7;
+  const rows = grid.length;
+  const cols = grid[0].length;
+  const cache = new Array(rows).fill().map(() => new Array(cols).fill(0));
+  const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
+
+  function explore(row, col) {
+    if (cache[row][col]) return cache[row][col];
+
+    let paths = 1;
+    for (const [dr, dc] of directions) {
+      const newRow = row + dr;
+      const newCol = col + dc;
+      if (
+        newRow >= 0 && newRow < rows && newCol >= 0
+        && newCol < cols && grid[newRow][newCol] > grid[row][col]
+      ) {
+        paths = (paths + explore(newRow, newCol)) % MOD;
+      }
+    }
+
+    return cache[row][col] = paths;
+  }
+
+  let total = 0;
+  for (let i = 0; i < rows; i++) {
+    for (let j = 0; j < cols; j++) {
+      total = (total + explore(i, j)) % MOD;
+    }
+  }
+
+  return total;
+};

From 592bcca94fd740c12088872ec24306d56266e117 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 19 May 2025 23:45:30 -0500
Subject: [PATCH 386/495] Add solution #2331

---
 README.md                                     |  3 +-
 .../2331-evaluate-boolean-binary-tree.js      | 42 +++++++++++++++++++
 2 files changed, 44 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2331-evaluate-boolean-binary-tree.js

diff --git a/README.md b/README.md
index 25a09019..81c5cb79 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,890 LeetCode solutions in JavaScript
+# 1,891 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1768,6 +1768,7 @@
 2325|[Decode the Message](./solutions/2325-decode-the-message.js)|Easy|
 2326|[Spiral Matrix IV](./solutions/2326-spiral-matrix-iv.js)|Medium|
 2328|[Number of Increasing Paths in a Grid](./solutions/2328-number-of-increasing-paths-in-a-grid.js)|Hard|
+2331|[Evaluate Boolean Binary Tree](./solutions/2331-evaluate-boolean-binary-tree.js)|Easy|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2331-evaluate-boolean-binary-tree.js b/solutions/2331-evaluate-boolean-binary-tree.js
new file mode 100644
index 00000000..d6f4d851
--- /dev/null
+++ b/solutions/2331-evaluate-boolean-binary-tree.js
@@ -0,0 +1,42 @@
+/**
+ * 2331. Evaluate Boolean Binary Tree
+ * https://leetcode.com/problems/evaluate-boolean-binary-tree/
+ * Difficulty: Easy
+ *
+ * You are given the root of a full binary tree with the following properties:
+ * - Leaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True.
+ * - Non-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents
+ *   the boolean AND.
+ *
+ * The evaluation of a node is as follows:
+ * - If the node is a leaf node, the evaluation is the value of the node, i.e. True or False.
+ * - Otherwise, evaluate the node's two children and apply the boolean operation of its value with
+ *   the children's evaluations.
+ *
+ * Return the boolean result of evaluating the root node.
+ *
+ * A full binary tree is a binary tree where each node has either 0 or 2 children.
+ *
+ * A leaf node is a node that has zero 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 {boolean}
+ */
+var evaluateTree = function(root) {
+  if (!root.left && !root.right) return root.val === 1;
+
+  const leftResult = evaluateTree(root.left);
+  const rightResult = evaluateTree(root.right);
+
+  return root.val === 2 ? leftResult || rightResult : leftResult && rightResult;
+};

From 21f422e158d97269b6a02f5b2efa4788bfe75076 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 19 May 2025 23:47:51 -0500
Subject: [PATCH 387/495] Add solution #2334

---
 README.md                                     |  3 +-
 ...elements-greater-than-varying-threshold.js | 43 +++++++++++++++++++
 2 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2334-subarray-with-elements-greater-than-varying-threshold.js

diff --git a/README.md b/README.md
index 81c5cb79..576739b6 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,891 LeetCode solutions in JavaScript
+# 1,892 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1769,6 +1769,7 @@
 2326|[Spiral Matrix IV](./solutions/2326-spiral-matrix-iv.js)|Medium|
 2328|[Number of Increasing Paths in a Grid](./solutions/2328-number-of-increasing-paths-in-a-grid.js)|Hard|
 2331|[Evaluate Boolean Binary Tree](./solutions/2331-evaluate-boolean-binary-tree.js)|Easy|
+2334|[Subarray With Elements Greater Than Varying Threshold](./solutions/2334-subarray-with-elements-greater-than-varying-threshold.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
diff --git a/solutions/2334-subarray-with-elements-greater-than-varying-threshold.js b/solutions/2334-subarray-with-elements-greater-than-varying-threshold.js
new file mode 100644
index 00000000..789a5ff3
--- /dev/null
+++ b/solutions/2334-subarray-with-elements-greater-than-varying-threshold.js
@@ -0,0 +1,43 @@
+/**
+ * 2334. Subarray With Elements Greater Than Varying Threshold
+ * https://leetcode.com/problems/subarray-with-elements-greater-than-varying-threshold/
+ * Difficulty: Hard
+ *
+ * You are given an integer array nums and an integer threshold.
+ *
+ * Find any subarray of nums of length k such that every element in the subarray is greater
+ * than threshold / k.
+ *
+ * Return the size of any such subarray. If there is no such subarray, return -1.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} threshold
+ * @return {number}
+ */
+var validSubarraySize = function(nums, threshold) {
+  const n = nums.length;
+  const stack = [];
+  const nextSmaller = new Array(n).fill(n);
+  const prevSmaller = new Array(n).fill(-1);
+
+  for (let i = 0; i < n; i++) {
+    while (stack.length && nums[stack[stack.length - 1]] >= nums[i]) {
+      nextSmaller[stack.pop()] = i;
+    }
+    if (stack.length) prevSmaller[i] = stack[stack.length - 1];
+    stack.push(i);
+  }
+
+  for (let i = 0; i < n; i++) {
+    const k = nextSmaller[i] - prevSmaller[i] - 1;
+    if (k > 0 && nums[i] > threshold / k) {
+      return k;
+    }
+  }
+
+  return -1;
+};

From 6fa77e5f691a17d00ce55d80ff8937d07046c274 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 19 May 2025 23:49:01 -0500
Subject: [PATCH 388/495] Add solution #2337

---
 README.md                                     |  3 +-
 .../2337-move-pieces-to-obtain-a-string.js    | 41 +++++++++++++++++++
 2 files changed, 43 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2337-move-pieces-to-obtain-a-string.js

diff --git a/README.md b/README.md
index 576739b6..6ea96646 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,892 LeetCode solutions in JavaScript
+# 1,893 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1771,6 +1771,7 @@
 2331|[Evaluate Boolean Binary Tree](./solutions/2331-evaluate-boolean-binary-tree.js)|Easy|
 2334|[Subarray With Elements Greater Than Varying Threshold](./solutions/2334-subarray-with-elements-greater-than-varying-threshold.js)|Hard|
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
+2337|[Move Pieces to Obtain a String](./solutions/2337-move-pieces-to-obtain-a-string.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
 2349|[Design a Number Container System](./solutions/2349-design-a-number-container-system.js)|Medium|
diff --git a/solutions/2337-move-pieces-to-obtain-a-string.js b/solutions/2337-move-pieces-to-obtain-a-string.js
new file mode 100644
index 00000000..64f29a9a
--- /dev/null
+++ b/solutions/2337-move-pieces-to-obtain-a-string.js
@@ -0,0 +1,41 @@
+/**
+ * 2337. Move Pieces to Obtain a String
+ * https://leetcode.com/problems/move-pieces-to-obtain-a-string/
+ * Difficulty: Medium
+ *
+ * You are given two strings start and target, both of length n. Each string consists only of
+ * the characters 'L', 'R', and '_' where:
+ * - The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if
+ *   there is a blank space directly to its left, and a piece 'R' can move to the right only if
+ *   there is a blank space directly to its right.
+ * - The character '_' represents a blank space that can be occupied by any of the 'L' or 'R'
+ *   pieces.
+ *
+ * Return true if it is possible to obtain the string target by moving the pieces of the string
+ * start any number of times. Otherwise, return false.
+ */
+
+/**
+ * @param {string} start
+ * @param {string} target
+ * @return {boolean}
+ */
+var canChange = function(start, target) {
+  const pieces = [];
+  const targetPieces = [];
+
+  for (let i = 0; i < start.length; i++) {
+    if (start[i] !== '_') pieces.push([start[i], i]);
+    if (target[i] !== '_') targetPieces.push([target[i], i]);
+  }
+
+  if (pieces.length !== targetPieces.length) return false;
+
+  for (let i = 0; i < pieces.length; i++) {
+    if (pieces[i][0] !== targetPieces[i][0]) return false;
+    if (pieces[i][0] === 'L' && pieces[i][1] < targetPieces[i][1]) return false;
+    if (pieces[i][0] === 'R' && pieces[i][1] > targetPieces[i][1]) return false;
+  }
+
+  return true;
+};

From 1fdb40cb99420b157229c8afef70905506d15248 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 19 May 2025 23:50:26 -0500
Subject: [PATCH 389/495] Add solution #2341

---
 README.md                                     |  3 +-
 .../2341-maximum-number-of-pairs-in-array.js  | 35 +++++++++++++++++++
 2 files changed, 37 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2341-maximum-number-of-pairs-in-array.js

diff --git a/README.md b/README.md
index 6ea96646..33118caa 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,893 LeetCode solutions in JavaScript
+# 1,894 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1773,6 +1773,7 @@
 2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
 2337|[Move Pieces to Obtain a String](./solutions/2337-move-pieces-to-obtain-a-string.js)|Medium|
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
+2341|[Maximum Number of Pairs in Array](./solutions/2341-maximum-number-of-pairs-in-array.js)|Easy|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
 2349|[Design a Number Container System](./solutions/2349-design-a-number-container-system.js)|Medium|
 2352|[Equal Row and Column Pairs](./solutions/2352-equal-row-and-column-pairs.js)|Medium|
diff --git a/solutions/2341-maximum-number-of-pairs-in-array.js b/solutions/2341-maximum-number-of-pairs-in-array.js
new file mode 100644
index 00000000..2cdcce2c
--- /dev/null
+++ b/solutions/2341-maximum-number-of-pairs-in-array.js
@@ -0,0 +1,35 @@
+/**
+ * 2341. Maximum Number of Pairs in Array
+ * https://leetcode.com/problems/maximum-number-of-pairs-in-array/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums. In one operation, you may do the following:
+ * - Choose two integers in nums that are equal.
+ * - Remove both integers from nums, forming a pair.
+ *
+ * The operation is done on nums as many times as possible.
+ *
+ * Return a 0-indexed integer array answer of size 2 where answer[0] is the number of pairs that
+ * are formed and answer[1] is the number of leftover integers in nums after doing the operation
+ * as many times as possible.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var numberOfPairs = function(nums) {
+  const frequency = new Map();
+  let pairs = 0;
+
+  for (const num of nums) {
+    frequency.set(num, (frequency.get(num) || 0) + 1);
+    if (frequency.get(num) === 2) {
+      pairs++;
+      frequency.set(num, 0);
+    }
+  }
+
+  const leftovers = nums.length - pairs * 2;
+  return [pairs, leftovers];
+};

From e13fb6acfdf45479f1f82a1f8edf6a6dc507c6cf Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 19 May 2025 23:52:39 -0500
Subject: [PATCH 390/495] Add solution #2347

---
 README.md                         |  3 ++-
 solutions/2347-best-poker-hand.js | 41 +++++++++++++++++++++++++++++++
 2 files changed, 43 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2347-best-poker-hand.js

diff --git a/README.md b/README.md
index 33118caa..92d4f641 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,894 LeetCode solutions in JavaScript
+# 1,895 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1775,6 +1775,7 @@
 2338|[Count the Number of Ideal Arrays](./solutions/2338-count-the-number-of-ideal-arrays.js)|Hard|
 2341|[Maximum Number of Pairs in Array](./solutions/2341-maximum-number-of-pairs-in-array.js)|Easy|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
+2347|[Best Poker Hand](./solutions/2347-best-poker-hand.js)|Easy|
 2349|[Design a Number Container System](./solutions/2349-design-a-number-container-system.js)|Medium|
 2352|[Equal Row and Column Pairs](./solutions/2352-equal-row-and-column-pairs.js)|Medium|
 2364|[Count Number of Bad Pairs](./solutions/2364-count-number-of-bad-pairs.js)|Medium|
diff --git a/solutions/2347-best-poker-hand.js b/solutions/2347-best-poker-hand.js
new file mode 100644
index 00000000..586dcda2
--- /dev/null
+++ b/solutions/2347-best-poker-hand.js
@@ -0,0 +1,41 @@
+/**
+ * 2347. Best Poker Hand
+ * https://leetcode.com/problems/best-poker-hand/
+ * Difficulty: Easy
+ *
+ * You are given an integer array ranks and a character array suits. You have 5 cards where the
+ * ith card has a rank of ranks[i] and a suit of suits[i].
+ *
+ * The following are the types of poker hands you can make from best to worst:
+ * 1. "Flush": Five cards of the same suit.
+ * 2. "Three of a Kind": Three cards of the same rank.
+ * 3. "Pair": Two cards of the same rank.
+ * 4. "High Card": Any single card.
+ *
+ * Return a string representing the best type of poker hand you can make with the given cards.
+ *
+ * Note that the return values are case-sensitive.
+ */
+
+/**
+ * @param {number[]} ranks
+ * @param {character[]} suits
+ * @return {string}
+ */
+var bestHand = function(ranks, suits) {
+  const suitCount = new Map();
+  const rankCount = new Map();
+
+  for (let i = 0; i < 5; i++) {
+    suitCount.set(suits[i], (suitCount.get(suits[i]) || 0) + 1);
+    rankCount.set(ranks[i], (rankCount.get(ranks[i]) || 0) + 1);
+  }
+
+  if (suitCount.size === 1) return 'Flush';
+
+  const maxRankCount = Math.max(...rankCount.values());
+  if (maxRankCount >= 3) return 'Three of a Kind';
+  if (maxRankCount === 2) return 'Pair';
+
+  return 'High Card';
+};

From 9f085ae5b7ab89a49c95329c1cebaf9f24665a91 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 18:32:45 -0500
Subject: [PATCH 391/495] Add solution #2258

---
 README.md                                   |   3 +-
 solutions/2258-escape-the-spreading-fire.js | 118 ++++++++++++++++++++
 2 files changed, 120 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2258-escape-the-spreading-fire.js

diff --git a/README.md b/README.md
index 92d4f641..39ad8d01 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,895 LeetCode solutions in JavaScript
+# 1,896 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1725,6 +1725,7 @@
 2255|[Count Prefixes of a Given String](./solutions/2255-count-prefixes-of-a-given-string.js)|Easy|
 2256|[Minimum Average Difference](./solutions/2256-minimum-average-difference.js)|Medium|
 2257|[Count Unguarded Cells in the Grid](./solutions/2257-count-unguarded-cells-in-the-grid.js)|Medium|
+2258|[Escape the Spreading Fire](./solutions/2258-escape-the-spreading-fire.js)|Hard|
 2259|[Remove Digit From Number to Maximize Result](./solutions/2259-remove-digit-from-number-to-maximize-result.js)|Easy|
 2260|[Minimum Consecutive Cards to Pick Up](./solutions/2260-minimum-consecutive-cards-to-pick-up.js)|Medium|
 2261|[K Divisible Elements Subarrays](./solutions/2261-k-divisible-elements-subarrays.js)|Medium|
diff --git a/solutions/2258-escape-the-spreading-fire.js b/solutions/2258-escape-the-spreading-fire.js
new file mode 100644
index 00000000..7e26720a
--- /dev/null
+++ b/solutions/2258-escape-the-spreading-fire.js
@@ -0,0 +1,118 @@
+/**
+ * 2258. Escape the Spreading Fire
+ * https://leetcode.com/problems/escape-the-spreading-fire/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed 2D integer array grid of size m x n which represents a field.
+ * Each cell has one of three values:
+ * - 0 represents grass,
+ * - 1 represents fire,
+ * - 2 represents a wall that you and fire cannot pass through.
+ *
+ * You are situated in the top-left cell, (0, 0), and you want to travel to the safehouse at the
+ * bottom-right cell, (m - 1, n - 1). Every minute, you may move to an adjacent grass cell. After
+ * your move, every fire cell will spread to all adjacent cells that are not walls.
+ *
+ * Return the maximum number of minutes that you can stay in your initial position before moving
+ * while still safely reaching the safehouse. If this is impossible, return -1. If you can always
+ * reach the safehouse regardless of the minutes stayed, return 109.
+ *
+ * Note that even if the fire spreads to the safehouse immediately after you have reached it, it
+ * will be counted as safely reaching the safehouse.
+ *
+ * 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).
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var maximumMinutes = function(grid) {
+  const m = grid.length;
+  const n = grid[0].length;
+  const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
+  const MAX_ANSWER = 1000000000;
+
+  function isValid(x, y) {
+    return x >= 0 && x < m && y >= 0 && y < n && grid[x][y] === 0;
+  }
+
+  function calculateFireTime() {
+    const fireTime = new Array(m).fill().map(() => new Array(n).fill(Infinity));
+    const queue = [];
+
+    for (let i = 0; i < m; i++) {
+      for (let j = 0; j < n; j++) {
+        if (grid[i][j] === 1) {
+          queue.push([i, j, 0]);
+          fireTime[i][j] = 0;
+        }
+      }
+    }
+
+    while (queue.length > 0) {
+      const [x, y, time] = queue.shift();
+
+      for (const [dx, dy] of directions) {
+        const nx = x + dx;
+        const ny = y + dy;
+
+        if (isValid(nx, ny) && fireTime[nx][ny] === Infinity) {
+          fireTime[nx][ny] = time + 1;
+          queue.push([nx, ny, time + 1]);
+        }
+      }
+    }
+
+    return fireTime;
+  }
+
+  function canReachSafehouse(delay) {
+    const fireTime = calculateFireTime();
+    const visited = new Array(m).fill().map(() => new Array(n).fill(false));
+    const queue = [[0, 0, delay]];
+    visited[0][0] = true;
+
+    while (queue.length > 0) {
+      const [x, y, time] = queue.shift();
+
+      for (const [dx, dy] of directions) {
+        const nx = x + dx;
+        const ny = y + dy;
+
+        if (!isValid(nx, ny) || visited[nx][ny]) continue;
+
+        if (nx === m - 1 && ny === n - 1) {
+          if (time + 1 <= fireTime[nx][ny] || fireTime[nx][ny] === Infinity) {
+            return true;
+          }
+        }
+
+        if (time + 1 < fireTime[nx][ny]) {
+          visited[nx][ny] = true;
+          queue.push([nx, ny, time + 1]);
+        }
+      }
+    }
+
+    return false;
+  }
+
+  let left = 0;
+  let right = MAX_ANSWER;
+  let result = -1;
+
+  while (left <= right) {
+    const mid = Math.floor((left + right) / 2);
+
+    if (canReachSafehouse(mid)) {
+      result = mid;
+      left = mid + 1;
+    } else {
+      right = mid - 1;
+    }
+  }
+
+  return result;
+};

From b69f25da593609a9b2383a55406fe8f722f20aec Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 18:35:22 -0500
Subject: [PATCH 392/495] Add solution #2267

---
 README.md                                     |  3 +-
 ...here-is-a-valid-parentheses-string-path.js | 57 +++++++++++++++++++
 2 files changed, 59 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2267-check-if-there-is-a-valid-parentheses-string-path.js

diff --git a/README.md b/README.md
index 39ad8d01..a2027bde 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,896 LeetCode solutions in JavaScript
+# 1,897 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1733,6 +1733,7 @@
 2264|[Largest 3-Same-Digit Number in String](./solutions/2264-largest-3-same-digit-number-in-string.js)|Easy|
 2265|[Count Nodes Equal to Average of Subtree](./solutions/2265-count-nodes-equal-to-average-of-subtree.js)|Medium|
 2266|[Count Number of Texts](./solutions/2266-count-number-of-texts.js)|Medium|
+2267|[Check if There Is a Valid Parentheses String Path](./solutions/2267-check-if-there-is-a-valid-parentheses-string-path.js)|Hard|
 2269|[Find the K-Beauty of a Number](./solutions/2269-find-the-k-beauty-of-a-number.js)|Easy|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
 2272|[Substring With Largest Variance](./solutions/2272-substring-with-largest-variance.js)|Hard|
diff --git a/solutions/2267-check-if-there-is-a-valid-parentheses-string-path.js b/solutions/2267-check-if-there-is-a-valid-parentheses-string-path.js
new file mode 100644
index 00000000..8dc163ed
--- /dev/null
+++ b/solutions/2267-check-if-there-is-a-valid-parentheses-string-path.js
@@ -0,0 +1,57 @@
+/**
+ * 2267. Check if There Is a Valid Parentheses String Path
+ * https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/
+ * Difficulty: Hard
+ *
+ * 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 an m x n matrix of parentheses grid. A valid parentheses string path in the grid
+ * is a path satisfying all of the following conditions:
+ * - The path starts from the upper left cell (0, 0).
+ * - The path ends at the bottom-right cell (m - 1, n - 1).
+ * - The path only ever moves down or right.
+ * - The resulting parentheses string formed by the path is valid.
+ *
+ * Return true if there exists a valid parentheses string path in the grid. Otherwise, return false.
+ */
+
+/**
+* @param {character[][]} grid
+* @return {boolean}
+*/
+var hasValidPath = function(grid) {
+  const m = grid.length;
+  const n = grid[0].length;
+
+  if ((m + n - 1) % 2 !== 0) {
+    return false;
+  }
+
+  if (grid[0][0] === ')' || grid[m - 1][n - 1] === '(') {
+    return false;
+  }
+
+  const visited = new Set();
+  return dfs(0, 0, 0);
+
+  function dfs(i, j, openCount) {
+    if (i >= m || j >= n || openCount < 0) {
+      return false;
+    }
+    openCount += grid[i][j] === '(' ? 1 : -1;
+    if (i === m - 1 && j === n - 1) {
+      return openCount === 0;
+    }
+    const key = `${i},${j},${openCount}`;
+    if (visited.has(key)) {
+      return false;
+    }
+    visited.add(key);
+
+    return dfs(i + 1, j, openCount) || dfs(i, j + 1, openCount);
+  }
+};

From d9624c85256bb2b8bea911a7bbd2a1b55a6bdb6f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 18:39:40 -0500
Subject: [PATCH 393/495] Add solution #2271

---
 README.md                                     |  3 +-
 ...maximum-white-tiles-covered-by-a-carpet.js | 50 +++++++++++++++++++
 2 files changed, 52 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2271-maximum-white-tiles-covered-by-a-carpet.js

diff --git a/README.md b/README.md
index a2027bde..68703de1 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,897 LeetCode solutions in JavaScript
+# 1,898 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1736,6 +1736,7 @@
 2267|[Check if There Is a Valid Parentheses String Path](./solutions/2267-check-if-there-is-a-valid-parentheses-string-path.js)|Hard|
 2269|[Find the K-Beauty of a Number](./solutions/2269-find-the-k-beauty-of-a-number.js)|Easy|
 2270|[Number of Ways to Split Array](./solutions/2270-number-of-ways-to-split-array.js)|Medium|
+2271|[Maximum White Tiles Covered by a Carpet](./solutions/2271-maximum-white-tiles-covered-by-a-carpet.js)|Medium|
 2272|[Substring With Largest Variance](./solutions/2272-substring-with-largest-variance.js)|Hard|
 2273|[Find Resultant Array After Removing Anagrams](./solutions/2273-find-resultant-array-after-removing-anagrams.js)|Easy|
 2274|[Maximum Consecutive Floors Without Special Floors](./solutions/2274-maximum-consecutive-floors-without-special-floors.js)|Medium|
diff --git a/solutions/2271-maximum-white-tiles-covered-by-a-carpet.js b/solutions/2271-maximum-white-tiles-covered-by-a-carpet.js
new file mode 100644
index 00000000..0af443fc
--- /dev/null
+++ b/solutions/2271-maximum-white-tiles-covered-by-a-carpet.js
@@ -0,0 +1,50 @@
+/**
+ * 2271. Maximum White Tiles Covered by a Carpet
+ * https://leetcode.com/problems/maximum-white-tiles-covered-by-a-carpet/
+ * Difficulty: Medium
+ *
+ * You are given a 2D integer array tiles where tiles[i] = [li, ri] represents that every tile
+ * j in the range li <= j <= ri is colored white.
+ *
+ * You are also given an integer carpetLen, the length of a single carpet that can be placed
+ * anywhere.
+ *
+ * Return the maximum number of white tiles that can be covered by the carpet.
+ */
+
+/**
+ * @param {number[][]} tiles
+ * @param {number} carpetLen
+ * @return {number}
+ */
+var maximumWhiteTiles = function(tiles, carpetLen) {
+  tiles.sort((a, b) => a[0] - b[0]);
+
+  let result = 0;
+  let covered = 0;
+  let j = 0;
+
+  for (let i = 0; i < tiles.length; i++) {
+    const carpetEnd = tiles[i][0] + carpetLen - 1;
+
+    while (j < tiles.length && tiles[j][0] <= carpetEnd) {
+      if (tiles[j][1] <= carpetEnd) {
+        covered += tiles[j][1] - tiles[j][0] + 1;
+        j++;
+      } else {
+        covered += carpetEnd - tiles[j][0] + 1;
+        result = Math.max(result, covered);
+        covered -= carpetEnd - tiles[j][0] + 1;
+        break;
+      }
+    }
+
+    result = Math.max(result, covered);
+
+    if (j === tiles.length) break;
+
+    covered -= tiles[i][1] - tiles[i][0] + 1;
+  }
+
+  return result;
+};

From d3e0b1196e0719a9591721c17f67a9c86cf5078a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 18:56:20 -0500
Subject: [PATCH 394/495] Add solution #2280

---
 README.md                                     |  3 +-
 ...minimum-lines-to-represent-a-line-chart.js | 38 +++++++++++++++++++
 2 files changed, 40 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2280-minimum-lines-to-represent-a-line-chart.js

diff --git a/README.md b/README.md
index 68703de1..e38866ea 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,898 LeetCode solutions in JavaScript
+# 1,899 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1743,6 +1743,7 @@
 2275|[Largest Combination With Bitwise AND Greater Than Zero](./solutions/2275-largest-combination-with-bitwise-and-greater-than-zero.js)|Medium|
 2278|[Percentage of Letter in String](./solutions/2278-percentage-of-letter-in-string.js)|Easy|
 2279|[Maximum Bags With Full Capacity of Rocks](./solutions/2279-maximum-bags-with-full-capacity-of-rocks.js)|Medium|
+2280|[Minimum Lines to Represent a Line Chart](./solutions/2280-minimum-lines-to-represent-a-line-chart.js)|Medium|
 2283|[Check if Number Has Equal Digit Count and Digit Value](./solutions/2283-check-if-number-has-equal-digit-count-and-digit-value.js)|Easy|
 2284|[Sender With Largest Word Count](./solutions/2284-sender-with-largest-word-count.js)|Medium|
 2287|[Rearrange Characters to Make Target String](./solutions/2287-rearrange-characters-to-make-target-string.js)|Easy|
diff --git a/solutions/2280-minimum-lines-to-represent-a-line-chart.js b/solutions/2280-minimum-lines-to-represent-a-line-chart.js
new file mode 100644
index 00000000..ff401c32
--- /dev/null
+++ b/solutions/2280-minimum-lines-to-represent-a-line-chart.js
@@ -0,0 +1,38 @@
+/**
+ * 2280. Minimum Lines to Represent a Line Chart
+ * https://leetcode.com/problems/minimum-lines-to-represent-a-line-chart/
+ * Difficulty: Medium
+ *
+ * You are given a 2D integer array stockPrices where stockPrices[i] = [dayi, pricei] indicates
+ * the price of the stock on day dayi is pricei. A line chart is created from the array by
+ * plotting the points on an XY plane with the X-axis representing the day and the Y-axis
+ * representing the price and connecting adjacent points. One such example is shown below.
+ *
+ * Return the minimum number of lines needed to represent the line chart.
+ */
+
+/**
+ * @param {number[][]} stockPrices
+ * @return {number}
+ */
+var minimumLines = function(stockPrices) {
+  if (stockPrices.length <= 2) return stockPrices.length - 1;
+
+  stockPrices.sort((a, b) => a[0] - b[0]);
+
+  let lines = 1;
+  for (let i = 2; i < stockPrices.length; i++) {
+    const [x0, y0] = stockPrices[i - 2];
+    const [x1, y1] = stockPrices[i - 1];
+    const [x2, y2] = stockPrices[i];
+
+    const dx1 = BigInt(x1 - x0);
+    const dy1 = BigInt(y1 - y0);
+    const dx2 = BigInt(x2 - x1);
+    const dy2 = BigInt(y2 - y1);
+
+    if (dy1 * dx2 !== dy2 * dx1) lines++;
+  }
+
+  return lines;
+};

From 72bd6aecc26e393763a399a20f1fa535edb4c9fb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 18:57:56 -0500
Subject: [PATCH 395/495] Add solution #2288

---
 README.md                                  |  3 +-
 solutions/2288-apply-discount-to-prices.js | 37 ++++++++++++++++++++++
 2 files changed, 39 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2288-apply-discount-to-prices.js

diff --git a/README.md b/README.md
index e38866ea..6c3c2311 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,899 LeetCode solutions in JavaScript
+# 1,900 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1747,6 +1747,7 @@
 2283|[Check if Number Has Equal Digit Count and Digit Value](./solutions/2283-check-if-number-has-equal-digit-count-and-digit-value.js)|Easy|
 2284|[Sender With Largest Word Count](./solutions/2284-sender-with-largest-word-count.js)|Medium|
 2287|[Rearrange Characters to Make Target String](./solutions/2287-rearrange-characters-to-make-target-string.js)|Easy|
+2288|[Apply Discount to Prices](./solutions/2288-apply-discount-to-prices.js)|Medium|
 2293|[Min Max Game](./solutions/2293-min-max-game.js)|Easy|
 2294|[Partition Array Such That Maximum Difference Is K](./solutions/2294-partition-array-such-that-maximum-difference-is-k.js)|Medium|
 2295|[Replace Elements in an Array](./solutions/2295-replace-elements-in-an-array.js)|Medium|
diff --git a/solutions/2288-apply-discount-to-prices.js b/solutions/2288-apply-discount-to-prices.js
new file mode 100644
index 00000000..4645204e
--- /dev/null
+++ b/solutions/2288-apply-discount-to-prices.js
@@ -0,0 +1,37 @@
+/**
+ * 2288. Apply Discount to Prices
+ * https://leetcode.com/problems/apply-discount-to-prices/
+ * Difficulty: Medium
+ *
+ * A sentence is a string of single-space separated words where each word can contain digits,
+ * lowercase letters, and the dollar sign '$'. A word represents a price if it is a sequence
+ * of digits preceded by a dollar sign.
+ * - For example, "$100", "$23", and "$6" represent prices while "100", "$", and "$1e5" do not.
+ *
+ * You are given a string sentence representing a sentence and an integer discount. For each
+ * word representing a price, apply a discount of discount% on the price and update the word
+ * in the sentence. All updated prices should be represented with exactly two decimal places.
+ *
+ * Return a string representing the modified sentence.
+ *
+ * Note that all prices will contain at most 10 digits.
+ */
+
+/**
+ * @param {string} sentence
+ * @param {number} discount
+ * @return {string}
+ */
+var discountPrices = function(sentence, discount) {
+  const words = sentence.split(' ');
+  const discountFactor = 1 - discount / 100;
+
+  for (let i = 0; i < words.length; i++) {
+    if (words[i].startsWith('$') && /^[0-9]+$/.test(words[i].slice(1))) {
+      const price = parseInt(words[i].slice(1)) * discountFactor;
+      words[i] = `$${price.toFixed(2)}`;
+    }
+  }
+
+  return words.join(' ');
+};

From b71de0717b05bac9b340777ba9cfdc94b79a0785 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 22:32:43 -0500
Subject: [PATCH 396/495] Add solution #2348

---
 README.md                                     |  3 +-
 .../2348-number-of-zero-filled-subarrays.js   | 29 +++++++++++++++++++
 2 files changed, 31 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2348-number-of-zero-filled-subarrays.js

diff --git a/README.md b/README.md
index 6c3c2311..13749350 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,900 LeetCode solutions in JavaScript
+# 1,901 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1781,6 +1781,7 @@
 2341|[Maximum Number of Pairs in Array](./solutions/2341-maximum-number-of-pairs-in-array.js)|Easy|
 2342|[Max Sum of a Pair With Equal Sum of Digits](./solutions/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium|
 2347|[Best Poker Hand](./solutions/2347-best-poker-hand.js)|Easy|
+2348|[Number of Zero-Filled Subarrays](./solutions/2348-number-of-zero-filled-subarrays.js)|Medium|
 2349|[Design a Number Container System](./solutions/2349-design-a-number-container-system.js)|Medium|
 2352|[Equal Row and Column Pairs](./solutions/2352-equal-row-and-column-pairs.js)|Medium|
 2364|[Count Number of Bad Pairs](./solutions/2364-count-number-of-bad-pairs.js)|Medium|
diff --git a/solutions/2348-number-of-zero-filled-subarrays.js b/solutions/2348-number-of-zero-filled-subarrays.js
new file mode 100644
index 00000000..fa93ec19
--- /dev/null
+++ b/solutions/2348-number-of-zero-filled-subarrays.js
@@ -0,0 +1,29 @@
+/**
+ * 2348. Number of Zero-Filled Subarrays
+ * https://leetcode.com/problems/number-of-zero-filled-subarrays/
+ * Difficulty: Medium
+ *
+ * Given an integer array nums, return the number of subarrays filled with 0.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var zeroFilledSubarray = function(nums) {
+  let result = 0;
+  let zeroCount = 0;
+
+  for (const num of nums) {
+    if (num === 0) {
+      zeroCount++;
+      result += zeroCount;
+    } else {
+      zeroCount = 0;
+    }
+  }
+
+  return result;
+};

From 7cb8ddc2bf62b7a3064ae08b860687c9d239b144 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 22:35:21 -0500
Subject: [PATCH 397/495] Add solution #2350

---
 README.md                                     |  3 +-
 ...0-shortest-impossible-sequence-of-rolls.js | 32 +++++++++++++++++++
 2 files changed, 34 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2350-shortest-impossible-sequence-of-rolls.js

diff --git a/README.md b/README.md
index 13749350..daa32385 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,901 LeetCode solutions in JavaScript
+# 1,902 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1783,6 +1783,7 @@
 2347|[Best Poker Hand](./solutions/2347-best-poker-hand.js)|Easy|
 2348|[Number of Zero-Filled Subarrays](./solutions/2348-number-of-zero-filled-subarrays.js)|Medium|
 2349|[Design a Number Container System](./solutions/2349-design-a-number-container-system.js)|Medium|
+2350|[Shortest Impossible Sequence of Rolls](./solutions/2350-shortest-impossible-sequence-of-rolls.js)|Hard|
 2352|[Equal Row and Column Pairs](./solutions/2352-equal-row-and-column-pairs.js)|Medium|
 2364|[Count Number of Bad Pairs](./solutions/2364-count-number-of-bad-pairs.js)|Medium|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
diff --git a/solutions/2350-shortest-impossible-sequence-of-rolls.js b/solutions/2350-shortest-impossible-sequence-of-rolls.js
new file mode 100644
index 00000000..ea27a604
--- /dev/null
+++ b/solutions/2350-shortest-impossible-sequence-of-rolls.js
@@ -0,0 +1,32 @@
+/**
+ * 2350. Shortest Impossible Sequence of Rolls
+ * https://leetcode.com/problems/shortest-impossible-sequence-of-rolls/
+ * Difficulty: Hard
+ *
+ * You are given an integer array rolls of length n and an integer k. You roll a k sided dice
+ * numbered from 1 to k, n times, where the result of the ith roll is rolls[i].
+ *
+ * Return the length of the shortest sequence of rolls so that there's no such subsequence in rolls.
+ *
+ * A sequence of rolls of length len is the result of rolling a k sided dice len times.
+ */
+
+/**
+ * @param {number[]} rolls
+ * @param {number} k
+ * @return {number}
+ */
+var shortestSequence = function(rolls, k) {
+  const set = new Set();
+  let sequences = 0;
+
+  for (const roll of rolls) {
+    set.add(roll);
+    if (set.size === k) {
+      sequences++;
+      set.clear();
+    }
+  }
+
+  return sequences + 1;
+};

From cf4a8d071da1fc14a12ce287db7debbdd362fa38 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 22:36:33 -0500
Subject: [PATCH 398/495] Add solution #2351

---
 README.md                                     |  3 ++-
 .../2351-first-letter-to-appear-twice.js      | 26 +++++++++++++++++++
 2 files changed, 28 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2351-first-letter-to-appear-twice.js

diff --git a/README.md b/README.md
index daa32385..caa3439b 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,902 LeetCode solutions in JavaScript
+# 1,903 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1784,6 +1784,7 @@
 2348|[Number of Zero-Filled Subarrays](./solutions/2348-number-of-zero-filled-subarrays.js)|Medium|
 2349|[Design a Number Container System](./solutions/2349-design-a-number-container-system.js)|Medium|
 2350|[Shortest Impossible Sequence of Rolls](./solutions/2350-shortest-impossible-sequence-of-rolls.js)|Hard|
+2351|[First Letter to Appear Twice](./solutions/2351-first-letter-to-appear-twice.js)|Easy|
 2352|[Equal Row and Column Pairs](./solutions/2352-equal-row-and-column-pairs.js)|Medium|
 2364|[Count Number of Bad Pairs](./solutions/2364-count-number-of-bad-pairs.js)|Medium|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
diff --git a/solutions/2351-first-letter-to-appear-twice.js b/solutions/2351-first-letter-to-appear-twice.js
new file mode 100644
index 00000000..b5fff8f5
--- /dev/null
+++ b/solutions/2351-first-letter-to-appear-twice.js
@@ -0,0 +1,26 @@
+/**
+ * 2351. First Letter to Appear Twice
+ * https://leetcode.com/problems/first-letter-to-appear-twice/
+ * Difficulty: Easy
+ *
+ * Given a string s consisting of lowercase English letters, return the first letter
+ * to appear twice.
+ *
+ * Note:
+ * - A letter a appears twice before another letter b if the second occurrence of a is before
+ *   the second occurrence of b.
+ * - s will contain at least one letter that appears twice.
+ */
+
+/**
+ * @param {string} s
+ * @return {character}
+ */
+var repeatedCharacter = function(s) {
+  const set = new Set();
+
+  for (const char of s) {
+    if (set.has(char)) return char;
+    set.add(char);
+  }
+};

From 763f1736e90c3bb9b4d9e18b63ea036722209059 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 22:43:45 -0500
Subject: [PATCH 399/495] Add solution #2354

---
 README.md                                   |  3 +-
 solutions/2354-number-of-excellent-pairs.js | 46 +++++++++++++++++++++
 2 files changed, 48 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2354-number-of-excellent-pairs.js

diff --git a/README.md b/README.md
index caa3439b..8bfec8a3 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,903 LeetCode solutions in JavaScript
+# 1,904 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1786,6 +1786,7 @@
 2350|[Shortest Impossible Sequence of Rolls](./solutions/2350-shortest-impossible-sequence-of-rolls.js)|Hard|
 2351|[First Letter to Appear Twice](./solutions/2351-first-letter-to-appear-twice.js)|Easy|
 2352|[Equal Row and Column Pairs](./solutions/2352-equal-row-and-column-pairs.js)|Medium|
+2354|[Number of Excellent Pairs](./solutions/2354-number-of-excellent-pairs.js)|Hard|
 2364|[Count Number of Bad Pairs](./solutions/2364-count-number-of-bad-pairs.js)|Medium|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
 2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy|
diff --git a/solutions/2354-number-of-excellent-pairs.js b/solutions/2354-number-of-excellent-pairs.js
new file mode 100644
index 00000000..bf60424a
--- /dev/null
+++ b/solutions/2354-number-of-excellent-pairs.js
@@ -0,0 +1,46 @@
+/**
+ * 2354. Number of Excellent Pairs
+ * https://leetcode.com/problems/number-of-excellent-pairs/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed positive integer array nums and a positive integer k.
+ *
+ * A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied:
+ * - Both the numbers num1 and num2 exist in the array nums.
+ * - The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal
+ *   to k, where OR is the bitwise OR operation and AND is the bitwise AND operation.
+ *
+ * Return the number of distinct excellent pairs.
+ *
+ * Two pairs (a, b) and (c, d) are considered distinct if either a != c or b != d. For example,
+ * (1, 2) and (2, 1) are distinct.
+ *
+ * Note that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least
+ * one occurrence of num1 in the array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var countExcellentPairs = function(nums, k) {
+  const map = new Map();
+  const set = new Set(nums);
+
+  for (const num of set) {
+    const bits = num.toString(2).split('0').join('').length;
+    map.set(bits, (map.get(bits) || 0) + 1);
+  }
+
+  let result = 0;
+  for (const [i, countI] of map) {
+    for (const [j, countJ] of map) {
+      if (i + j >= k) {
+        result += countI * countJ;
+      }
+    }
+  }
+
+  return result;
+};

From c74a23edc25eab3047f328edf9760388a9841c5d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 22:45:18 -0500
Subject: [PATCH 400/495] Add solution #2358

---
 README.md                                     |  3 +-
 ...number-of-groups-entering-a-competition.js | 31 +++++++++++++++++++
 2 files changed, 33 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2358-maximum-number-of-groups-entering-a-competition.js

diff --git a/README.md b/README.md
index 8bfec8a3..57a163df 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,904 LeetCode solutions in JavaScript
+# 1,905 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1787,6 +1787,7 @@
 2351|[First Letter to Appear Twice](./solutions/2351-first-letter-to-appear-twice.js)|Easy|
 2352|[Equal Row and Column Pairs](./solutions/2352-equal-row-and-column-pairs.js)|Medium|
 2354|[Number of Excellent Pairs](./solutions/2354-number-of-excellent-pairs.js)|Hard|
+2358|[Maximum Number of Groups Entering a Competition](./solutions/2358-maximum-number-of-groups-entering-a-competition.js)|Medium|
 2364|[Count Number of Bad Pairs](./solutions/2364-count-number-of-bad-pairs.js)|Medium|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
 2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy|
diff --git a/solutions/2358-maximum-number-of-groups-entering-a-competition.js b/solutions/2358-maximum-number-of-groups-entering-a-competition.js
new file mode 100644
index 00000000..2637927b
--- /dev/null
+++ b/solutions/2358-maximum-number-of-groups-entering-a-competition.js
@@ -0,0 +1,31 @@
+/**
+ * 2358. Maximum Number of Groups Entering a Competition
+ * https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/
+ * Difficulty: Medium
+ *
+ * You are given a positive integer array grades which represents the grades of students in
+ * a university. You would like to enter all these students into a competition in ordered
+ * non-empty groups, such that the ordering meets the following conditions:
+ * - The sum of the grades of students in the ith group is less than the sum of the grades of
+ *   students in the (i + 1)th group, for all groups (except the last).
+ * - The total number of students in the ith group is less than the total number of students
+ *   in the (i + 1)th group, for all groups (except the last).
+ *
+ * Return the maximum number of groups that can be formed.
+ */
+
+/**
+ * @param {number[]} grades
+ * @return {number}
+ */
+var maximumGroups = function(grades) {
+  let result = 0;
+  let studentsUsed = 0;
+
+  while (studentsUsed + result + 1 <= grades.length) {
+    result++;
+    studentsUsed += result;
+  }
+
+  return result;
+};

From e7d2b1bc922119c7f066c49d1271e30e9d93fa95 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 22:47:18 -0500
Subject: [PATCH 401/495] Add solution #2359

---
 README.md                                     |  3 +-
 ...59-find-closest-node-to-given-two-nodes.js | 63 +++++++++++++++++++
 2 files changed, 65 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2359-find-closest-node-to-given-two-nodes.js

diff --git a/README.md b/README.md
index 57a163df..f841a548 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,905 LeetCode solutions in JavaScript
+# 1,906 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1788,6 +1788,7 @@
 2352|[Equal Row and Column Pairs](./solutions/2352-equal-row-and-column-pairs.js)|Medium|
 2354|[Number of Excellent Pairs](./solutions/2354-number-of-excellent-pairs.js)|Hard|
 2358|[Maximum Number of Groups Entering a Competition](./solutions/2358-maximum-number-of-groups-entering-a-competition.js)|Medium|
+2359|[Find Closest Node to Given Two Nodes](./solutions/2359-find-closest-node-to-given-two-nodes.js)|Medium|
 2364|[Count Number of Bad Pairs](./solutions/2364-count-number-of-bad-pairs.js)|Medium|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
 2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy|
diff --git a/solutions/2359-find-closest-node-to-given-two-nodes.js b/solutions/2359-find-closest-node-to-given-two-nodes.js
new file mode 100644
index 00000000..c048153f
--- /dev/null
+++ b/solutions/2359-find-closest-node-to-given-two-nodes.js
@@ -0,0 +1,63 @@
+/**
+ * 2359. Find Closest Node to Given Two Nodes
+ * https://leetcode.com/problems/find-closest-node-to-given-two-nodes/
+ * Difficulty: Medium
+ *
+ * You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at
+ * most one outgoing edge.
+ *
+ * The graph is represented with a given 0-indexed array edges of size n, indicating that there
+ * is a directed edge from node i to node edges[i]. If there is no outgoing edge from i, then
+ * edges[i] == -1.
+ *
+ * You are also given two integers node1 and node2.
+ *
+ * Return the index of the node that can be reached from both node1 and node2, such that the maximum
+ * between the distance from node1 to that node, and from node2 to that node is minimized. If there
+ * are multiple answers, return the node with the smallest index, and if no possible answer exists,
+ * return -1.
+ *
+ * Note that edges may contain cycles.
+ */
+
+/**
+ * @param {number[]} edges
+ * @param {number} node1
+ * @param {number} node2
+ * @return {number}
+ */
+var closestMeetingNode = function(edges, node1, node2) {
+  const n = edges.length;
+  const dist1 = new Array(n).fill(Infinity);
+  const dist2 = new Array(n).fill(Infinity);
+
+  computeDistances(node1, dist1);
+  computeDistances(node2, dist2);
+
+  let minDist = Infinity;
+  let result = -1;
+
+  for (let i = 0; i < n; i++) {
+    if (dist1[i] !== Infinity && dist2[i] !== Infinity) {
+      const maxDist = Math.max(dist1[i], dist2[i]);
+      if (maxDist < minDist) {
+        minDist = maxDist;
+        result = i;
+      }
+    }
+  }
+
+  return result;
+
+  function computeDistances(start, distances) {
+    let current = start;
+    let steps = 0;
+    const visited = new Set();
+
+    while (current !== -1 && !visited.has(current)) {
+      distances[current] = steps++;
+      visited.add(current);
+      current = edges[current];
+    }
+  }
+};

From c684d4728355d4a99e5ad5cb631979983eee69c0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 22:48:52 -0500
Subject: [PATCH 402/495] Add solution #2360

---
 README.md                                  |  3 +-
 solutions/2360-longest-cycle-in-a-graph.js | 53 ++++++++++++++++++++++
 2 files changed, 55 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2360-longest-cycle-in-a-graph.js

diff --git a/README.md b/README.md
index f841a548..03b67642 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,906 LeetCode solutions in JavaScript
+# 1,907 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1789,6 +1789,7 @@
 2354|[Number of Excellent Pairs](./solutions/2354-number-of-excellent-pairs.js)|Hard|
 2358|[Maximum Number of Groups Entering a Competition](./solutions/2358-maximum-number-of-groups-entering-a-competition.js)|Medium|
 2359|[Find Closest Node to Given Two Nodes](./solutions/2359-find-closest-node-to-given-two-nodes.js)|Medium|
+2360|[Longest Cycle in a Graph](./solutions/2360-longest-cycle-in-a-graph.js)|Hard|
 2364|[Count Number of Bad Pairs](./solutions/2364-count-number-of-bad-pairs.js)|Medium|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
 2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy|
diff --git a/solutions/2360-longest-cycle-in-a-graph.js b/solutions/2360-longest-cycle-in-a-graph.js
new file mode 100644
index 00000000..6da96750
--- /dev/null
+++ b/solutions/2360-longest-cycle-in-a-graph.js
@@ -0,0 +1,53 @@
+/**
+ * 2360. Longest Cycle in a Graph
+ * https://leetcode.com/problems/longest-cycle-in-a-graph/
+ * Difficulty: Hard
+ *
+ * You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at
+ * most one outgoing edge.
+ *
+ * The graph is represented with a given 0-indexed array edges of size n, indicating that
+ * there is a directed edge from node i to node edges[i]. If there is no outgoing edge from
+ * node i, then edges[i] == -1.
+ *
+ * Return the length of the longest cycle in the graph. If no cycle exists, return -1.
+ *
+ * A cycle is a path that starts and ends at the same node.
+ */
+
+/**
+ * @param {number[]} edges
+ * @return {number}
+ */
+var longestCycle = function(edges) {
+  const n = edges.length;
+  const visited = new Array(n).fill(false);
+  let result = -1;
+
+  for (let i = 0; i < n; i++) {
+    if (!visited[i]) {
+      findCycle(i, 0, []);
+    }
+  }
+
+  return result;
+
+  function findCycle(node, steps, path) {
+    if (visited[node]) {
+      const cycleStart = path.indexOf(node);
+      if (cycleStart !== -1) {
+        result = Math.max(result, steps - cycleStart);
+      }
+      return;
+    }
+
+    visited[node] = true;
+    path.push(node);
+
+    if (edges[node] !== -1) {
+      findCycle(edges[node], steps + 1, path);
+    }
+
+    path.pop();
+  }
+};

From 171a21163d8e5d476520c89bf4e313a4a759b42f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 22:50:04 -0500
Subject: [PATCH 403/495] Add solution #2363

---
 README.md                             |  3 +-
 solutions/2363-merge-similar-items.js | 40 +++++++++++++++++++++++++++
 2 files changed, 42 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2363-merge-similar-items.js

diff --git a/README.md b/README.md
index 03b67642..0a7247f9 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,907 LeetCode solutions in JavaScript
+# 1,908 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1790,6 +1790,7 @@
 2358|[Maximum Number of Groups Entering a Competition](./solutions/2358-maximum-number-of-groups-entering-a-competition.js)|Medium|
 2359|[Find Closest Node to Given Two Nodes](./solutions/2359-find-closest-node-to-given-two-nodes.js)|Medium|
 2360|[Longest Cycle in a Graph](./solutions/2360-longest-cycle-in-a-graph.js)|Hard|
+2363|[Merge Similar Items](./solutions/2363-merge-similar-items.js)|Easy|
 2364|[Count Number of Bad Pairs](./solutions/2364-count-number-of-bad-pairs.js)|Medium|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
 2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy|
diff --git a/solutions/2363-merge-similar-items.js b/solutions/2363-merge-similar-items.js
new file mode 100644
index 00000000..da16c478
--- /dev/null
+++ b/solutions/2363-merge-similar-items.js
@@ -0,0 +1,40 @@
+/**
+ * 2363. Merge Similar Items
+ * https://leetcode.com/problems/merge-similar-items/
+ * Difficulty: Easy
+ *
+ * You are given two 2D integer arrays, items1 and items2, representing two sets of items.
+ * Each array items has the following properties:
+ * - items[i] = [valuei, weighti] where valuei represents the value and weighti represents
+ *   the weight of the ith item.
+ * - The value of each item in items is unique.
+ *
+ * Return a 2D integer array ret where ret[i] = [valuei, weighti], with weighti being the sum of
+ * weights of all items with value valuei.
+ *
+ * Note: ret should be returned in ascending order by value.
+ */
+
+/**
+ * @param {number[][]} items1
+ * @param {number[][]} items2
+ * @return {number[][]}
+ */
+var mergeSimilarItems = function(items1, items2) {
+  const map = new Map();
+
+  for (const [value, weight] of items1) {
+    map.set(value, (map.get(value) || 0) + weight);
+  }
+
+  for (const [value, weight] of items2) {
+    map.set(value, (map.get(value) || 0) + weight);
+  }
+
+  const merged = [];
+  for (const [value, weight] of map) {
+    merged.push([value, weight]);
+  }
+
+  return merged.sort((a, b) => a[0] - b[0]);
+};

From 8dc5e13dce70f12780f2418939e4e733a9693601 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 22:51:20 -0500
Subject: [PATCH 404/495] Add solution #2365

---
 README.md                           |  3 ++-
 solutions/2365-task-scheduler-ii.js | 41 +++++++++++++++++++++++++++++
 2 files changed, 43 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2365-task-scheduler-ii.js

diff --git a/README.md b/README.md
index 0a7247f9..7386af02 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,908 LeetCode solutions in JavaScript
+# 1,909 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1792,6 +1792,7 @@
 2360|[Longest Cycle in a Graph](./solutions/2360-longest-cycle-in-a-graph.js)|Hard|
 2363|[Merge Similar Items](./solutions/2363-merge-similar-items.js)|Easy|
 2364|[Count Number of Bad Pairs](./solutions/2364-count-number-of-bad-pairs.js)|Medium|
+2365|[Task Scheduler II](./solutions/2365-task-scheduler-ii.js)|Medium|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
 2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy|
 2381|[Shifting Letters II](./solutions/2381-shifting-letters-ii.js)|Medium|
diff --git a/solutions/2365-task-scheduler-ii.js b/solutions/2365-task-scheduler-ii.js
new file mode 100644
index 00000000..166fdfdf
--- /dev/null
+++ b/solutions/2365-task-scheduler-ii.js
@@ -0,0 +1,41 @@
+/**
+ * 2365. Task Scheduler II
+ * https://leetcode.com/problems/task-scheduler-ii/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array of positive integers tasks, representing tasks that need
+ * to be completed in order, where tasks[i] represents the type of the ith task.
+ *
+ * You are also given a positive integer space, which represents the minimum number of days
+ * that must pass after the completion of a task before another task of the same type can be
+ * performed.
+ *
+ * Each day, until all tasks have been completed, you must either:
+ * - Complete the next task from tasks, or
+ * - Take a break.
+ *
+ * Return the minimum number of days needed to complete all tasks.
+ */
+
+/**
+ * @param {number[]} tasks
+ * @param {number} space
+ * @return {number}
+ */
+var taskSchedulerII = function(tasks, space) {
+  const map = new Map();
+  let result = 0;
+
+  for (const task of tasks) {
+    result++;
+    if (map.has(task)) {
+      const lastDay = map.get(task);
+      if (result - lastDay <= space) {
+        result = lastDay + space + 1;
+      }
+    }
+    map.set(task, result);
+  }
+
+  return result;
+};

From a69d2e0dbc1faae259d5f6b1ee8816e9acfedfd5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 22:52:17 -0500
Subject: [PATCH 405/495] Add solution #2366

---
 README.md                                     |  3 +-
 ...-minimum-replacements-to-sort-the-array.js | 33 +++++++++++++++++++
 2 files changed, 35 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2366-minimum-replacements-to-sort-the-array.js

diff --git a/README.md b/README.md
index 7386af02..3a3bb6f3 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,909 LeetCode solutions in JavaScript
+# 1,910 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1793,6 +1793,7 @@
 2363|[Merge Similar Items](./solutions/2363-merge-similar-items.js)|Easy|
 2364|[Count Number of Bad Pairs](./solutions/2364-count-number-of-bad-pairs.js)|Medium|
 2365|[Task Scheduler II](./solutions/2365-task-scheduler-ii.js)|Medium|
+2366|[Minimum Replacements to Sort the Array](./solutions/2366-minimum-replacements-to-sort-the-array.js)|Hard|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
 2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy|
 2381|[Shifting Letters II](./solutions/2381-shifting-letters-ii.js)|Medium|
diff --git a/solutions/2366-minimum-replacements-to-sort-the-array.js b/solutions/2366-minimum-replacements-to-sort-the-array.js
new file mode 100644
index 00000000..422d21f6
--- /dev/null
+++ b/solutions/2366-minimum-replacements-to-sort-the-array.js
@@ -0,0 +1,33 @@
+/**
+ * 2366. Minimum Replacements to Sort the Array
+ * https://leetcode.com/problems/minimum-replacements-to-sort-the-array/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed integer array nums. In one operation you can replace any element
+ * of the array with any two elements that sum to it.
+ * - For example, consider nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4
+ *   and convert nums to [5,2,4,7].
+ *
+ * Return the minimum number of operations to make an array that is sorted in non-decreasing order.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimumReplacement = function(nums) {
+  let result = 0;
+  let prev = nums[nums.length - 1];
+
+  for (let i = nums.length - 2; i >= 0; i--) {
+    if (nums[i] > prev) {
+      const splits = Math.ceil(nums[i] / prev);
+      result += splits - 1;
+      prev = Math.floor(nums[i] / splits);
+    } else {
+      prev = nums[i];
+    }
+  }
+
+  return result;
+};

From 30a3a718b6084261428e3897df8949f8c4329f64 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 22:55:44 -0500
Subject: [PATCH 406/495] Add solution #2367

---
 README.md                                     |  3 +-
 .../2367-number-of-arithmetic-triplets.js     | 41 +++++++++++++++++++
 2 files changed, 43 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2367-number-of-arithmetic-triplets.js

diff --git a/README.md b/README.md
index 3a3bb6f3..e477c10b 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,910 LeetCode solutions in JavaScript
+# 1,911 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1794,6 +1794,7 @@
 2364|[Count Number of Bad Pairs](./solutions/2364-count-number-of-bad-pairs.js)|Medium|
 2365|[Task Scheduler II](./solutions/2365-task-scheduler-ii.js)|Medium|
 2366|[Minimum Replacements to Sort the Array](./solutions/2366-minimum-replacements-to-sort-the-array.js)|Hard|
+2367|[Number of Arithmetic Triplets](./solutions/2367-number-of-arithmetic-triplets.js)|Easy|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
 2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy|
 2381|[Shifting Letters II](./solutions/2381-shifting-letters-ii.js)|Medium|
diff --git a/solutions/2367-number-of-arithmetic-triplets.js b/solutions/2367-number-of-arithmetic-triplets.js
new file mode 100644
index 00000000..21c02a86
--- /dev/null
+++ b/solutions/2367-number-of-arithmetic-triplets.js
@@ -0,0 +1,41 @@
+/**
+ * 2367. Number of Arithmetic Triplets
+ * https://leetcode.com/problems/number-of-arithmetic-triplets/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff.
+ * A triplet (i, j, k) is an arithmetic triplet if the following conditions are met:
+ * - i < j < k,
+ * - nums[j] - nums[i] == diff, and
+ * - nums[k] - nums[j] == diff.
+ *
+ * Return the number of unique arithmetic triplets.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} diff
+ * @return {number}
+ */
+var arithmeticTriplets = function(nums, diff) {
+  let result = 0;
+
+  for (let j = 1; j < nums.length - 1; j++) {
+    let i = j - 1;
+    let k = j + 1;
+
+    while (i >= 0 && nums[j] - nums[i] <= diff) {
+      if (nums[j] - nums[i] === diff) {
+        while (k < nums.length && nums[k] - nums[j] <= diff) {
+          if (nums[k] - nums[j] === diff) {
+            result++;
+          }
+          k++;
+        }
+      }
+      i--;
+    }
+  }
+
+  return result;
+};

From 1251590740d8a99658d7d1f9259d3dfb77e3ff18 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 22:57:54 -0500
Subject: [PATCH 407/495] Add solution #2368

---
 README.md                                     |  3 +-
 .../2368-reachable-nodes-with-restrictions.js | 43 +++++++++++++++++++
 2 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2368-reachable-nodes-with-restrictions.js

diff --git a/README.md b/README.md
index e477c10b..846df114 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,911 LeetCode solutions in JavaScript
+# 1,912 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1795,6 +1795,7 @@
 2365|[Task Scheduler II](./solutions/2365-task-scheduler-ii.js)|Medium|
 2366|[Minimum Replacements to Sort the Array](./solutions/2366-minimum-replacements-to-sort-the-array.js)|Hard|
 2367|[Number of Arithmetic Triplets](./solutions/2367-number-of-arithmetic-triplets.js)|Easy|
+2368|[Reachable Nodes With Restrictions](./solutions/2368-reachable-nodes-with-restrictions.js)|Medium|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
 2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy|
 2381|[Shifting Letters II](./solutions/2381-shifting-letters-ii.js)|Medium|
diff --git a/solutions/2368-reachable-nodes-with-restrictions.js b/solutions/2368-reachable-nodes-with-restrictions.js
new file mode 100644
index 00000000..1ecd0821
--- /dev/null
+++ b/solutions/2368-reachable-nodes-with-restrictions.js
@@ -0,0 +1,43 @@
+/**
+ * 2368. Reachable Nodes With Restrictions
+ * https://leetcode.com/problems/reachable-nodes-with-restrictions/
+ * Difficulty: Medium
+ *
+ * There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
+ *
+ * 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. You are also given an integer
+ * array restricted which represents restricted nodes.
+ *
+ * Return the maximum number of nodes you can reach from node 0 without visiting a restricted node.
+ *
+ * Note that node 0 will not be a restricted node.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @param {number[]} restricted
+ * @return {number}
+ */
+var reachableNodes = function(n, edges, restricted) {
+  const graph = Array(n).fill().map(() => []);
+  const restrictedSet = new Set(restricted);
+  const visited = new Set();
+
+  for (const [u, v] of edges) {
+    graph[u].push(v);
+    graph[v].push(u);
+  }
+
+  explore(0);
+  return visited.size;
+
+  function explore(node) {
+    if (visited.has(node) || restrictedSet.has(node)) return;
+    visited.add(node);
+    for (const neighbor of graph[node]) {
+      explore(neighbor);
+    }
+  }
+};

From 49b8e99f546310077efd62313ac012da23360a2c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 22:59:17 -0500
Subject: [PATCH 408/495] Add solution #2369

---
 README.md                                     |  3 +-
 ...here-is-a-valid-partition-for-the-array.js | 44 +++++++++++++++++++
 2 files changed, 46 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2369-check-if-there-is-a-valid-partition-for-the-array.js

diff --git a/README.md b/README.md
index 846df114..8de02670 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,912 LeetCode solutions in JavaScript
+# 1,913 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1796,6 +1796,7 @@
 2366|[Minimum Replacements to Sort the Array](./solutions/2366-minimum-replacements-to-sort-the-array.js)|Hard|
 2367|[Number of Arithmetic Triplets](./solutions/2367-number-of-arithmetic-triplets.js)|Easy|
 2368|[Reachable Nodes With Restrictions](./solutions/2368-reachable-nodes-with-restrictions.js)|Medium|
+2369|[Check if There is a Valid Partition For The Array](./solutions/2369-check-if-there-is-a-valid-partition-for-the-array.js)|Medium|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
 2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy|
 2381|[Shifting Letters II](./solutions/2381-shifting-letters-ii.js)|Medium|
diff --git a/solutions/2369-check-if-there-is-a-valid-partition-for-the-array.js b/solutions/2369-check-if-there-is-a-valid-partition-for-the-array.js
new file mode 100644
index 00000000..be0e9844
--- /dev/null
+++ b/solutions/2369-check-if-there-is-a-valid-partition-for-the-array.js
@@ -0,0 +1,44 @@
+/**
+ * 2369. Check if There is a Valid Partition For The Array
+ * https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums. You have to partition the array into one or
+ * more contiguous subarrays.
+ *
+ * We call a partition of the array valid if each of the obtained subarrays satisfies one of
+ * the following conditions:
+ * 1. The subarray consists of exactly 2, equal elements. For example, the subarray [2,2] is good.
+ * 2. The subarray consists of exactly 3, equal elements. For example, the subarray [4,4,4] is good.
+ * 3. The subarray consists of exactly 3 consecutive increasing elements, that is, the difference
+ *    between adjacent elements is 1. For example, the subarray [3,4,5] is good, but the subarray
+ *    [1,3,5] is not.
+ *
+ * Return true if the array has at least one valid partition. Otherwise, return false.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {boolean}
+ */
+var validPartition = function(nums) {
+  const n = nums.length;
+  const dp = new Array(n + 1).fill(false);
+  dp[0] = true;
+
+  for (let i = 2; i <= n; i++) {
+    if (nums[i - 1] === nums[i - 2]) {
+      dp[i] = dp[i] || dp[i - 2];
+    }
+    if (i >= 3) {
+      if (nums[i - 1] === nums[i - 2] && nums[i - 2] === nums[i - 3]) {
+        dp[i] = dp[i] || dp[i - 3];
+      }
+      if (nums[i - 1] === nums[i - 2] + 1 && nums[i - 2] === nums[i - 3] + 1) {
+        dp[i] = dp[i] || dp[i - 3];
+      }
+    }
+  }
+
+  return dp[n];
+};

From 30326f2c4ba55a276d205fd64fcd2c2281a17422 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 23:00:30 -0500
Subject: [PATCH 409/495] Add solution #2370

---
 README.md                                   |  3 +-
 solutions/2370-longest-ideal-subsequence.js | 43 +++++++++++++++++++++
 2 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2370-longest-ideal-subsequence.js

diff --git a/README.md b/README.md
index 8de02670..33b186cc 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,913 LeetCode solutions in JavaScript
+# 1,914 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1797,6 +1797,7 @@
 2367|[Number of Arithmetic Triplets](./solutions/2367-number-of-arithmetic-triplets.js)|Easy|
 2368|[Reachable Nodes With Restrictions](./solutions/2368-reachable-nodes-with-restrictions.js)|Medium|
 2369|[Check if There is a Valid Partition For The Array](./solutions/2369-check-if-there-is-a-valid-partition-for-the-array.js)|Medium|
+2370|[Longest Ideal Subsequence](./solutions/2370-longest-ideal-subsequence.js)|Medium|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
 2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy|
 2381|[Shifting Letters II](./solutions/2381-shifting-letters-ii.js)|Medium|
diff --git a/solutions/2370-longest-ideal-subsequence.js b/solutions/2370-longest-ideal-subsequence.js
new file mode 100644
index 00000000..c07e27f9
--- /dev/null
+++ b/solutions/2370-longest-ideal-subsequence.js
@@ -0,0 +1,43 @@
+/**
+ * 2370. Longest Ideal Subsequence
+ * https://leetcode.com/problems/longest-ideal-subsequence/
+ * Difficulty: Medium
+ *
+ * You are given a string s consisting of lowercase letters and an integer k. We call a string
+ * t ideal if the following conditions are satisfied:
+ * - t is a subsequence of the string s.
+ * - The absolute difference in the alphabet order of every two adjacent letters in t is less
+ *   than or equal to k.
+ *
+ * Return the length of the longest ideal string.
+ *
+ * A subsequence is a string that can be derived from another string by deleting some or no
+ * characters without changing the order of the remaining characters.
+ *
+ * Note that the alphabet order is not cyclic. For example, the absolute difference in the
+ * alphabet order of 'a' and 'z' is 25, not 1.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} k
+ * @return {number}
+ */
+var longestIdealString = function(s, k) {
+  const dp = new Array(26).fill(0);
+  let result = 0;
+
+  for (const char of s) {
+    const idx = char.charCodeAt(0) - 97;
+    let currentMax = 0;
+
+    for (let i = Math.max(0, idx - k); i <= Math.min(25, idx + k); i++) {
+      currentMax = Math.max(currentMax, dp[i]);
+    }
+
+    dp[idx] = currentMax + 1;
+    result = Math.max(result, dp[idx]);
+  }
+
+  return result;
+};

From 61ab392d631ddc53e0a877a17427720ab6d38347 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 20 May 2025 23:01:36 -0500
Subject: [PATCH 410/495] Add solution #2373

---
 README.md                                     |  3 +-
 .../2373-largest-local-values-in-a-matrix.js  | 38 +++++++++++++++++++
 2 files changed, 40 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2373-largest-local-values-in-a-matrix.js

diff --git a/README.md b/README.md
index 33b186cc..227abdff 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,914 LeetCode solutions in JavaScript
+# 1,915 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1798,6 +1798,7 @@
 2368|[Reachable Nodes With Restrictions](./solutions/2368-reachable-nodes-with-restrictions.js)|Medium|
 2369|[Check if There is a Valid Partition For The Array](./solutions/2369-check-if-there-is-a-valid-partition-for-the-array.js)|Medium|
 2370|[Longest Ideal Subsequence](./solutions/2370-longest-ideal-subsequence.js)|Medium|
+2373|[Largest Local Values in a Matrix](./solutions/2373-largest-local-values-in-a-matrix.js)|Easy|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
 2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy|
 2381|[Shifting Letters II](./solutions/2381-shifting-letters-ii.js)|Medium|
diff --git a/solutions/2373-largest-local-values-in-a-matrix.js b/solutions/2373-largest-local-values-in-a-matrix.js
new file mode 100644
index 00000000..46a65c45
--- /dev/null
+++ b/solutions/2373-largest-local-values-in-a-matrix.js
@@ -0,0 +1,38 @@
+/**
+ * 2373. Largest Local Values in a Matrix
+ * https://leetcode.com/problems/largest-local-values-in-a-matrix/
+ * Difficulty: Easy
+ *
+ * You are given an n x n integer matrix grid.
+ *
+ * Generate an integer matrix maxLocal of size (n - 2) x (n - 2) such that:
+ * - maxLocal[i][j] is equal to the largest value of the 3 x 3 matrix in grid centered around
+ *   row i + 1 and column j + 1.
+ *
+ * In other words, we want to find the largest value in every contiguous 3 x 3 matrix in grid.
+ *
+ * Return the generated matrix.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number[][]}
+ */
+var largestLocal = function(grid) {
+  const n = grid.length;
+  const result = new Array(n - 2).fill().map(() => new Array(n - 2).fill(0));
+
+  for (let i = 0; i < n - 2; i++) {
+    for (let j = 0; j < n - 2; j++) {
+      let maxVal = 0;
+      for (let r = i; r < i + 3; r++) {
+        for (let c = j; c < j + 3; c++) {
+          maxVal = Math.max(maxVal, grid[r][c]);
+        }
+      }
+      result[i][j] = maxVal;
+    }
+  }
+
+  return result;
+};

From 7db08cea0ff74e5f2b51fcc0835b3f4d03f228f5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 21 May 2025 00:20:07 -0500
Subject: [PATCH 411/495] Add solution #2374

---
 README.md                                     |  3 +-
 .../2374-node-with-highest-edge-score.js      | 39 +++++++++++++++++++
 2 files changed, 41 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2374-node-with-highest-edge-score.js

diff --git a/README.md b/README.md
index 227abdff..950146c4 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,915 LeetCode solutions in JavaScript
+# 1,916 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1799,6 +1799,7 @@
 2369|[Check if There is a Valid Partition For The Array](./solutions/2369-check-if-there-is-a-valid-partition-for-the-array.js)|Medium|
 2370|[Longest Ideal Subsequence](./solutions/2370-longest-ideal-subsequence.js)|Medium|
 2373|[Largest Local Values in a Matrix](./solutions/2373-largest-local-values-in-a-matrix.js)|Easy|
+2374|[Node With Highest Edge Score](./solutions/2374-node-with-highest-edge-score.js)|Medium|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
 2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy|
 2381|[Shifting Letters II](./solutions/2381-shifting-letters-ii.js)|Medium|
diff --git a/solutions/2374-node-with-highest-edge-score.js b/solutions/2374-node-with-highest-edge-score.js
new file mode 100644
index 00000000..b8597422
--- /dev/null
+++ b/solutions/2374-node-with-highest-edge-score.js
@@ -0,0 +1,39 @@
+/**
+ * 2374. Node With Highest Edge Score
+ * https://leetcode.com/problems/node-with-highest-edge-score/
+ * Difficulty: Medium
+ *
+ * You are given a directed graph with n nodes labeled from 0 to n - 1, where each node has
+ * exactly one outgoing edge.
+ *
+ * The graph is represented by a given 0-indexed integer array edges of length n, where edges[i]
+ * indicates that there is a directed edge from node i to node edges[i].
+ *
+ * The edge score of a node i is defined as the sum of the labels of all the nodes that have an
+ * edge pointing to i.
+ *
+ * Return the node with the highest edge score. If multiple nodes have the same edge score, return
+ * the node with the smallest index.
+ */
+
+/**
+ * @param {number[]} edges
+ * @return {number}
+ */
+var edgeScore = function(edges) {
+  const scores = new Array(edges.length).fill(0);
+
+  for (let i = 0; i < edges.length; i++) {
+    scores[edges[i]] += i;
+  }
+  let maxScore = 0;
+  let result = 0;
+  for (let i = 0; i < scores.length; i++) {
+    if (scores[i] > maxScore) {
+      maxScore = scores[i];
+      result = i;
+    }
+  }
+
+  return result;
+};

From 75bb422a0aded22bfa9017164c2f04a69bca968e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 21 May 2025 00:21:18 -0500
Subject: [PATCH 412/495] Add solution #2380

---
 README.md                                     |  3 +-
 ...ime-needed-to-rearrange-a-binary-string.js | 32 +++++++++++++++++++
 2 files changed, 34 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2380-time-needed-to-rearrange-a-binary-string.js

diff --git a/README.md b/README.md
index 950146c4..6027a60c 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,916 LeetCode solutions in JavaScript
+# 1,917 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1802,6 +1802,7 @@
 2374|[Node With Highest Edge Score](./solutions/2374-node-with-highest-edge-score.js)|Medium|
 2375|[Construct Smallest Number From DI String](./solutions/2375-construct-smallest-number-from-di-string.js)|Medium|
 2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy|
+2380|[Time Needed to Rearrange a Binary String](./solutions/2380-time-needed-to-rearrange-a-binary-string.js)|Medium|
 2381|[Shifting Letters II](./solutions/2381-shifting-letters-ii.js)|Medium|
 2390|[Removing Stars From a String](./solutions/2390-removing-stars-from-a-string.js)|Medium|
 2396|[Strictly Palindromic Number](./solutions/2396-strictly-palindromic-number.js)|Medium|
diff --git a/solutions/2380-time-needed-to-rearrange-a-binary-string.js b/solutions/2380-time-needed-to-rearrange-a-binary-string.js
new file mode 100644
index 00000000..d85d2234
--- /dev/null
+++ b/solutions/2380-time-needed-to-rearrange-a-binary-string.js
@@ -0,0 +1,32 @@
+/**
+ * 2380. Time Needed to Rearrange a Binary String
+ * https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/
+ * Difficulty: Medium
+ *
+ * You are given a binary string s. In one second, all occurrences of "01" are simultaneously
+ * replaced with "10". This process repeats until no occurrences of "01" exist.
+ *
+ * Return the number of seconds needed to complete this process.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var secondsToRemoveOccurrences = function(s) {
+  const binary = s.split('');
+  let result = 0;
+
+  while (binary.join('').includes('01')) {
+    for (let i = 0; i < binary.length - 1; i++) {
+      if (binary[i] === '0' && binary[i + 1] === '1') {
+        binary[i] = '1';
+        binary[i + 1] = '0';
+        i++;
+      }
+    }
+    result++;
+  }
+
+  return result;
+};

From c2d44e6c8f2e5a026afb311fddb42bde653c6da0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 21 May 2025 00:25:01 -0500
Subject: [PATCH 413/495] Add solution #2382

---
 README.md                                     |  3 +-
 ...2382-maximum-segment-sum-after-removals.js | 84 +++++++++++++++++++
 2 files changed, 86 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2382-maximum-segment-sum-after-removals.js

diff --git a/README.md b/README.md
index 6027a60c..67895454 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,917 LeetCode solutions in JavaScript
+# 1,918 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1804,6 +1804,7 @@
 2379|[Minimum Recolors to Get K Consecutive Black Blocks](./solutions/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy|
 2380|[Time Needed to Rearrange a Binary String](./solutions/2380-time-needed-to-rearrange-a-binary-string.js)|Medium|
 2381|[Shifting Letters II](./solutions/2381-shifting-letters-ii.js)|Medium|
+2382|[Maximum Segment Sum After Removals](./solutions/2382-maximum-segment-sum-after-removals.js)|Hard|
 2390|[Removing Stars From a String](./solutions/2390-removing-stars-from-a-string.js)|Medium|
 2396|[Strictly Palindromic Number](./solutions/2396-strictly-palindromic-number.js)|Medium|
 2401|[Longest Nice Subarray](./solutions/2401-longest-nice-subarray.js)|Medium|
diff --git a/solutions/2382-maximum-segment-sum-after-removals.js b/solutions/2382-maximum-segment-sum-after-removals.js
new file mode 100644
index 00000000..78065c5e
--- /dev/null
+++ b/solutions/2382-maximum-segment-sum-after-removals.js
@@ -0,0 +1,84 @@
+/**
+ * 2382. Maximum Segment Sum After Removals
+ * https://leetcode.com/problems/maximum-segment-sum-after-removals/
+ * Difficulty: Hard
+ *
+ * You are given two 0-indexed integer arrays nums and removeQueries, both of length n. For
+ * the ith query, the element in nums at the index removeQueries[i] is removed, splitting
+ * nums into different segments.
+ *
+ * A segment is a contiguous sequence of positive integers in nums. A segment sum is the sum
+ * of every element in a segment.
+ *
+ * Return an integer array answer, of length n, where answer[i] is the maximum segment sum after
+ * applying the ith removal.
+ *
+ * Note: The same index will not be removed more than once.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[]} removeQueries
+ * @return {number[]}
+ */
+var maximumSegmentSum = function(nums, removeQueries) {
+  const n = nums.length;
+  const result = new Array(n);
+  const prefixSum = new Array(n + 1).fill(0);
+  const parents = new Array(n).fill(-1);
+  const sizes = new Array(n).fill(0);
+  const sums = new Array(n).fill(0);
+  let maxSum = 0;
+
+  for (let i = 0; i < n; i++) {
+    prefixSum[i + 1] = prefixSum[i] + nums[i];
+  }
+
+  for (let i = n - 1; i >= 0; i--) {
+    result[i] = maxSum;
+    const index = removeQueries[i];
+
+    parents[index] = index;
+    sizes[index] = 1;
+    sums[index] = nums[index];
+
+    if (index > 0 && parents[index - 1] !== -1) {
+      const leftRoot = findRoot(parents, index - 1);
+      const segmentSum = sums[leftRoot] + sums[index];
+
+      parents[index] = leftRoot;
+      sizes[leftRoot] += sizes[index];
+      sums[leftRoot] = segmentSum;
+    }
+
+    if (index < n - 1 && parents[index + 1] !== -1) {
+      const root = findRoot(parents, index);
+      const rightRoot = findRoot(parents, index + 1);
+
+      if (root !== rightRoot) {
+        const segmentSum = sums[root] + sums[rightRoot];
+
+        if (sizes[root] < sizes[rightRoot]) {
+          parents[root] = rightRoot;
+          sizes[rightRoot] += sizes[root];
+          sums[rightRoot] = segmentSum;
+        } else {
+          parents[rightRoot] = root;
+          sizes[root] += sizes[rightRoot];
+          sums[root] = segmentSum;
+        }
+      }
+    }
+
+    maxSum = Math.max(maxSum, sums[findRoot(parents, index)]);
+  }
+
+  return result;
+};
+
+function findRoot(parents, x) {
+  if (parents[x] !== x) {
+    parents[x] = findRoot(parents, parents[x]);
+  }
+  return parents[x];
+}

From 46585b513e7a5b1ee81d64ce47242223797ff38b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 21 May 2025 00:26:23 -0500
Subject: [PATCH 414/495] Add solution #2383

---
 README.md                                     |  3 +-
 ...-hours-of-training-to-win-a-competition.js | 55 +++++++++++++++++++
 2 files changed, 57 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2383-minimum-hours-of-training-to-win-a-competition.js

diff --git a/README.md b/README.md
index 67895454..ad60c194 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,918 LeetCode solutions in JavaScript
+# 1,919 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1805,6 +1805,7 @@
 2380|[Time Needed to Rearrange a Binary String](./solutions/2380-time-needed-to-rearrange-a-binary-string.js)|Medium|
 2381|[Shifting Letters II](./solutions/2381-shifting-letters-ii.js)|Medium|
 2382|[Maximum Segment Sum After Removals](./solutions/2382-maximum-segment-sum-after-removals.js)|Hard|
+2383|[Minimum Hours of Training to Win a Competition](./solutions/2383-minimum-hours-of-training-to-win-a-competition.js)|Easy|
 2390|[Removing Stars From a String](./solutions/2390-removing-stars-from-a-string.js)|Medium|
 2396|[Strictly Palindromic Number](./solutions/2396-strictly-palindromic-number.js)|Medium|
 2401|[Longest Nice Subarray](./solutions/2401-longest-nice-subarray.js)|Medium|
diff --git a/solutions/2383-minimum-hours-of-training-to-win-a-competition.js b/solutions/2383-minimum-hours-of-training-to-win-a-competition.js
new file mode 100644
index 00000000..0699fdcc
--- /dev/null
+++ b/solutions/2383-minimum-hours-of-training-to-win-a-competition.js
@@ -0,0 +1,55 @@
+/**
+ * 2383. Minimum Hours of Training to Win a Competition
+ * https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/
+ * Difficulty: Easy
+ *
+ * You are entering a competition, and are given two positive integers initialEnergy and
+ * initialExperience denoting your initial energy and initial experience respectively.
+ *
+ * You are also given two 0-indexed integer arrays energy and experience, both of length n.
+ *
+ * You will face n opponents in order. The energy and experience of the ith opponent is
+ * denoted by energy[i] and experience[i] respectively. When you face an opponent, you need
+ * to have both strictly greater experience and energy to defeat them and move to the next
+ * opponent if available.
+ *
+ * Defeating the ith opponent increases your experience by experience[i], but decreases your
+ * energy by energy[i].
+ *
+ * Before starting the competition, you can train for some number of hours. After each hour
+ * of training, you can either choose to increase your initial experience by one, or increase
+ * your initial energy by one.
+ *
+ * Return the minimum number of training hours required to defeat all n opponents.
+ */
+
+/**
+ * @param {number} initialEnergy
+ * @param {number} initialExperience
+ * @param {number[]} energy
+ * @param {number[]} experience
+ * @return {number}
+ */
+var minNumberOfHours = function(initialEnergy, initialExperience, energy, experience) {
+  let energyNeeded = 0;
+  let experienceNeeded = 0;
+  let currentEnergy = initialEnergy;
+  let currentExperience = initialExperience;
+
+  for (let i = 0; i < energy.length; i++) {
+    if (currentEnergy <= energy[i]) {
+      const deficit = energy[i] - currentEnergy + 1;
+      energyNeeded += deficit;
+      currentEnergy += deficit;
+    }
+    if (currentExperience <= experience[i]) {
+      const deficit = experience[i] - currentExperience + 1;
+      experienceNeeded += deficit;
+      currentExperience += deficit;
+    }
+    currentEnergy -= energy[i];
+    currentExperience += experience[i];
+  }
+
+  return energyNeeded + experienceNeeded;
+};

From e0dd87855ffa251d536439a84c9ddb688f15306e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 21 May 2025 00:28:30 -0500
Subject: [PATCH 415/495] Add solution #2385

---
 README.md                                     |  3 +-
 ...-of-time-for-binary-tree-to-be-infected.js | 70 +++++++++++++++++++
 2 files changed, 72 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2385-amount-of-time-for-binary-tree-to-be-infected.js

diff --git a/README.md b/README.md
index ad60c194..3654f15f 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,919 LeetCode solutions in JavaScript
+# 1,920 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1806,6 +1806,7 @@
 2381|[Shifting Letters II](./solutions/2381-shifting-letters-ii.js)|Medium|
 2382|[Maximum Segment Sum After Removals](./solutions/2382-maximum-segment-sum-after-removals.js)|Hard|
 2383|[Minimum Hours of Training to Win a Competition](./solutions/2383-minimum-hours-of-training-to-win-a-competition.js)|Easy|
+2385|[Amount of Time for Binary Tree to Be Infected](./solutions/2385-amount-of-time-for-binary-tree-to-be-infected.js)|Medium|
 2390|[Removing Stars From a String](./solutions/2390-removing-stars-from-a-string.js)|Medium|
 2396|[Strictly Palindromic Number](./solutions/2396-strictly-palindromic-number.js)|Medium|
 2401|[Longest Nice Subarray](./solutions/2401-longest-nice-subarray.js)|Medium|
diff --git a/solutions/2385-amount-of-time-for-binary-tree-to-be-infected.js b/solutions/2385-amount-of-time-for-binary-tree-to-be-infected.js
new file mode 100644
index 00000000..00bd2ddd
--- /dev/null
+++ b/solutions/2385-amount-of-time-for-binary-tree-to-be-infected.js
@@ -0,0 +1,70 @@
+/**
+ * 2385. Amount of Time for Binary Tree to Be Infected
+ * https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/
+ * Difficulty: Medium
+ *
+ * You are given the root of a binary tree with unique values, and an integer start.
+ * At minute 0, an infection starts from the node with value start.
+ *
+ * Each minute, a node becomes infected if:
+ * - The node is currently uninfected.
+ * - The node is adjacent to an infected node.
+ *
+ * Return the number of minutes needed for the entire tree to be infected.
+ */
+
+/**
+ * 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} start
+ * @return {number}
+ */
+var amountOfTime = function(root, start) {
+  const graph = new Map();
+  const queue = [start];
+  const visited = new Set([start]);
+  let result = -1;
+
+  buildGraph(root, null);
+
+  while (queue.length) {
+    result++;
+    const levelSize = queue.length;
+    for (let i = 0; i < levelSize; i++) {
+      const current = queue.shift();
+      for (const neighbor of graph.get(current) || []) {
+        if (!visited.has(neighbor)) {
+          visited.add(neighbor);
+          queue.push(neighbor);
+        }
+      }
+    }
+  }
+
+  return result;
+
+  function buildGraph(node, parent) {
+    if (!node) return;
+    if (!graph.has(node.val)) graph.set(node.val, []);
+    if (parent) graph.get(node.val).push(parent.val);
+    if (node.left) {
+      graph.get(node.val).push(node.left.val);
+      graph.set(node.left.val, graph.get(node.left.val) || []);
+      graph.get(node.left.val).push(node.val);
+    }
+    if (node.right) {
+      graph.get(node.val).push(node.right.val);
+      graph.set(node.right.val, graph.get(node.right.val) || []);
+      graph.get(node.right.val).push(node.val);
+    }
+    buildGraph(node.left, node);
+    buildGraph(node.right, node);
+  }
+};

From d3f050a9a7d3f73a036a91a7c1eee0bd4b9573f7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 00:37:04 -0500
Subject: [PATCH 416/495] Add solution #2389

---
 README.md                                     |  3 +-
 ...89-longest-subsequence-with-limited-sum.js | 43 +++++++++++++++++++
 2 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2389-longest-subsequence-with-limited-sum.js

diff --git a/README.md b/README.md
index 3654f15f..8b6e8cf2 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,920 LeetCode solutions in JavaScript
+# 1,921 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1807,6 +1807,7 @@
 2382|[Maximum Segment Sum After Removals](./solutions/2382-maximum-segment-sum-after-removals.js)|Hard|
 2383|[Minimum Hours of Training to Win a Competition](./solutions/2383-minimum-hours-of-training-to-win-a-competition.js)|Easy|
 2385|[Amount of Time for Binary Tree to Be Infected](./solutions/2385-amount-of-time-for-binary-tree-to-be-infected.js)|Medium|
+2389|[Longest Subsequence With Limited Sum](./solutions/2389-longest-subsequence-with-limited-sum.js)|Easy|
 2390|[Removing Stars From a String](./solutions/2390-removing-stars-from-a-string.js)|Medium|
 2396|[Strictly Palindromic Number](./solutions/2396-strictly-palindromic-number.js)|Medium|
 2401|[Longest Nice Subarray](./solutions/2401-longest-nice-subarray.js)|Medium|
diff --git a/solutions/2389-longest-subsequence-with-limited-sum.js b/solutions/2389-longest-subsequence-with-limited-sum.js
new file mode 100644
index 00000000..a498b7c8
--- /dev/null
+++ b/solutions/2389-longest-subsequence-with-limited-sum.js
@@ -0,0 +1,43 @@
+/**
+ * 2389. Longest Subsequence With Limited Sum
+ * https://leetcode.com/problems/longest-subsequence-with-limited-sum/
+ * Difficulty: Easy
+ *
+ * You are given an integer array nums of length n, and an integer array queries of length m.
+ *
+ * Return an array answer of length m where answer[i] is the maximum size of a subsequence that
+ * you can take from nums such that the sum of its elements is less than or equal to queries[i].
+ *
+ * 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[]} queries
+ * @return {number[]}
+ */
+var answerQueries = function(nums, queries) {
+  nums.sort((a, b) => a - b);
+  const prefixSums = [0];
+  for (const num of nums) {
+    prefixSums.push(prefixSums.at(-1) + num);
+  }
+
+  const result = new Array(queries.length);
+  for (let i = 0; i < queries.length; i++) {
+    let left = 0;
+    let right = nums.length;
+    while (left < right) {
+      const mid = Math.floor((left + right + 1) / 2);
+      if (prefixSums[mid] <= queries[i]) {
+        left = mid;
+      } else {
+        right = mid - 1;
+      }
+    }
+    result[i] = left;
+  }
+
+  return result;
+};

From 30f7bee1afd6a898b1afb4767c28eab0749fa7a0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 00:39:15 -0500
Subject: [PATCH 417/495] Add solution #2391

---
 README.md                                     |  3 +-
 ...nimum-amount-of-time-to-collect-garbage.js | 50 +++++++++++++++++++
 2 files changed, 52 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2391-minimum-amount-of-time-to-collect-garbage.js

diff --git a/README.md b/README.md
index 8b6e8cf2..66bef67e 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,921 LeetCode solutions in JavaScript
+# 1,922 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1809,6 +1809,7 @@
 2385|[Amount of Time for Binary Tree to Be Infected](./solutions/2385-amount-of-time-for-binary-tree-to-be-infected.js)|Medium|
 2389|[Longest Subsequence With Limited Sum](./solutions/2389-longest-subsequence-with-limited-sum.js)|Easy|
 2390|[Removing Stars From a String](./solutions/2390-removing-stars-from-a-string.js)|Medium|
+2391|[Minimum Amount of Time to Collect Garbage](./solutions/2391-minimum-amount-of-time-to-collect-garbage.js)|Medium|
 2396|[Strictly Palindromic Number](./solutions/2396-strictly-palindromic-number.js)|Medium|
 2401|[Longest Nice Subarray](./solutions/2401-longest-nice-subarray.js)|Medium|
 2413|[Smallest Even Multiple](./solutions/2413-smallest-even-multiple.js)|Easy|
diff --git a/solutions/2391-minimum-amount-of-time-to-collect-garbage.js b/solutions/2391-minimum-amount-of-time-to-collect-garbage.js
new file mode 100644
index 00000000..bbddfc01
--- /dev/null
+++ b/solutions/2391-minimum-amount-of-time-to-collect-garbage.js
@@ -0,0 +1,50 @@
+/**
+ * 2391. Minimum Amount of Time to Collect Garbage
+ * https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment
+ * of garbage at the ith house. garbage[i] consists only of the characters 'M', 'P' and 'G'
+ * representing one unit of metal, paper and glass garbage respectively. Picking up one unit of
+ * any type of garbage takes 1 minute.
+ *
+ * You are also given a 0-indexed integer array travel where travel[i] is the number of minutes
+ * needed to go from house i to house i + 1.
+ *
+ * There are three garbage trucks in the city, each responsible for picking up one type of garbage.
+ * Each garbage truck starts at house 0 and must visit each house in order; however, they do not
+ * need to visit every house.
+ *
+ * Only one garbage truck may be used at any given moment. While one truck is driving or picking up
+ * garbage, the other two trucks cannot do anything.
+ *
+ * Return the minimum number of minutes needed to pick up all the garbage.
+ */
+
+/**
+ * @param {string[]} garbage
+ * @param {number[]} travel
+ * @return {number}
+ */
+var garbageCollection = function(garbage, travel) {
+  let result = 0;
+  const lastHouse = {'M': 0, 'P': 0, 'G': 0};
+
+  for (let i = 0; i < garbage.length; i++) {
+    result += garbage[i].length;
+    for (const type of garbage[i]) {
+      lastHouse[type] = i;
+    }
+  }
+
+  const prefixTravel = [0];
+  for (const time of travel) {
+    prefixTravel.push(prefixTravel.at(-1) + time);
+  }
+
+  Object.keys(lastHouse).forEach(type => {
+    result += prefixTravel[lastHouse[type]];
+  });
+
+  return result;
+};

From 92d1ae40437e560c7a616199b431e7db036f361e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 00:47:20 -0500
Subject: [PATCH 418/495] Add solution #2392

---
 README.md                                     |  3 +-
 .../2392-build-a-matrix-with-conditions.js    | 76 +++++++++++++++++++
 2 files changed, 78 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2392-build-a-matrix-with-conditions.js

diff --git a/README.md b/README.md
index 66bef67e..4baa4776 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,922 LeetCode solutions in JavaScript
+# 1,923 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1810,6 +1810,7 @@
 2389|[Longest Subsequence With Limited Sum](./solutions/2389-longest-subsequence-with-limited-sum.js)|Easy|
 2390|[Removing Stars From a String](./solutions/2390-removing-stars-from-a-string.js)|Medium|
 2391|[Minimum Amount of Time to Collect Garbage](./solutions/2391-minimum-amount-of-time-to-collect-garbage.js)|Medium|
+2392|[Build a Matrix With Conditions](./solutions/2392-build-a-matrix-with-conditions.js)|Hard|
 2396|[Strictly Palindromic Number](./solutions/2396-strictly-palindromic-number.js)|Medium|
 2401|[Longest Nice Subarray](./solutions/2401-longest-nice-subarray.js)|Medium|
 2413|[Smallest Even Multiple](./solutions/2413-smallest-even-multiple.js)|Easy|
diff --git a/solutions/2392-build-a-matrix-with-conditions.js b/solutions/2392-build-a-matrix-with-conditions.js
new file mode 100644
index 00000000..b55cdd0f
--- /dev/null
+++ b/solutions/2392-build-a-matrix-with-conditions.js
@@ -0,0 +1,76 @@
+/**
+ * 2392. Build a Matrix With Conditions
+ * https://leetcode.com/problems/build-a-matrix-with-conditions/
+ * Difficulty: Hard
+ *
+ * You are given a positive integer k. You are also given:
+ * - a 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and
+ * - a 2D integer array colConditions of size m where colConditions[i] = [lefti, righti].
+ *
+ * The two arrays contain integers from 1 to k.
+ *
+ * You have to build a k x k matrix that contains each of the numbers from 1 to k exactly once.
+ * The remaining cells should have the value 0.
+ *
+ * The matrix should also satisfy the following conditions:
+ * - The number abovei should appear in a row that is strictly above the row at which the number
+ *   belowi appears for all i from 0 to n - 1.
+ * - The number lefti should appear in a column that is strictly left of the column at which the
+ *   number righti appears for all i from 0 to m - 1.
+ *
+ * Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.
+ */
+
+/**
+ * @param {number} k
+ * @param {number[][]} rowConditions
+ * @param {number[][]} colConditions
+ * @return {number[][]}
+ */
+var buildMatrix = function(k, rowConditions, colConditions) {
+  const rowOrder = helper(rowConditions, k);
+  if (!rowOrder.length) return [];
+
+  const colOrder = helper(colConditions, k);
+  if (!colOrder.length) return [];
+
+  const matrix = Array.from({ length: k }, () => new Array(k).fill(0));
+  const rowIndex = new Array(k + 1).fill(0);
+  const colIndex = new Array(k + 1).fill(0);
+
+  for (let i = 0; i < k; i++) {
+    rowIndex[rowOrder[i]] = i;
+    colIndex[colOrder[i]] = i;
+  }
+
+  for (let num = 1; num <= k; num++) {
+    matrix[rowIndex[num]][colIndex[num]] = num;
+  }
+
+  return matrix;
+
+  function helper(edges, size) {
+    const graph = Array.from({ length: size + 1 }, () => []);
+    const inDegree = new Array(size + 1).fill(0);
+    for (const [u, v] of edges) {
+      graph[u].push(v);
+      inDegree[v]++;
+    }
+
+    const queue = [];
+    for (let i = 1; i <= size; i++) {
+      if (inDegree[i] === 0) queue.push(i);
+    }
+
+    const order = [];
+    while (queue.length) {
+      const node = queue.shift();
+      order.push(node);
+      for (const next of graph[node]) {
+        if (--inDegree[next] === 0) queue.push(next);
+      }
+    }
+
+    return order.length === size ? order : [];
+  }
+};

From c77c198fbbc67850a81853eabf03e8cf52fd14a1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 00:48:39 -0500
Subject: [PATCH 419/495] Add solution #2395

---
 README.md                                     |  3 +-
 .../2395-find-subarrays-with-equal-sum.js     | 28 +++++++++++++++++++
 2 files changed, 30 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2395-find-subarrays-with-equal-sum.js

diff --git a/README.md b/README.md
index 4baa4776..98e8beb3 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,923 LeetCode solutions in JavaScript
+# 1,924 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1811,6 +1811,7 @@
 2390|[Removing Stars From a String](./solutions/2390-removing-stars-from-a-string.js)|Medium|
 2391|[Minimum Amount of Time to Collect Garbage](./solutions/2391-minimum-amount-of-time-to-collect-garbage.js)|Medium|
 2392|[Build a Matrix With Conditions](./solutions/2392-build-a-matrix-with-conditions.js)|Hard|
+2395|[Find Subarrays With Equal Sum](./solutions/2395-find-subarrays-with-equal-sum.js)|Easy|
 2396|[Strictly Palindromic Number](./solutions/2396-strictly-palindromic-number.js)|Medium|
 2401|[Longest Nice Subarray](./solutions/2401-longest-nice-subarray.js)|Medium|
 2413|[Smallest Even Multiple](./solutions/2413-smallest-even-multiple.js)|Easy|
diff --git a/solutions/2395-find-subarrays-with-equal-sum.js b/solutions/2395-find-subarrays-with-equal-sum.js
new file mode 100644
index 00000000..9b4ec520
--- /dev/null
+++ b/solutions/2395-find-subarrays-with-equal-sum.js
@@ -0,0 +1,28 @@
+/**
+ * 2395. Find Subarrays With Equal Sum
+ * https://leetcode.com/problems/find-subarrays-with-equal-sum/
+ * Difficulty: Easy
+ *
+ * Given a 0-indexed integer array nums, determine whether there exist two subarrays of length
+ * 2 with equal sum. Note that the two subarrays must begin at different indices.
+ *
+ * Return true if these subarrays exist, and false otherwise.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {boolean}
+ */
+var findSubarrays = function(nums) {
+  const set = new Set();
+
+  for (let i = 0; i < nums.length - 1; i++) {
+    const sum = nums[i] + nums[i + 1];
+    if (set.has(sum)) return true;
+    set.add(sum);
+  }
+
+  return false;
+};

From 888178229ae997e06c8c6e8cdcea7686b4cfee2c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 00:50:21 -0500
Subject: [PATCH 420/495] Add solution #2397

---
 README.md                                     |  3 +-
 .../2397-maximum-rows-covered-by-columns.js   | 61 +++++++++++++++++++
 2 files changed, 63 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2397-maximum-rows-covered-by-columns.js

diff --git a/README.md b/README.md
index 98e8beb3..ae51f11f 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,924 LeetCode solutions in JavaScript
+# 1,925 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1813,6 +1813,7 @@
 2392|[Build a Matrix With Conditions](./solutions/2392-build-a-matrix-with-conditions.js)|Hard|
 2395|[Find Subarrays With Equal Sum](./solutions/2395-find-subarrays-with-equal-sum.js)|Easy|
 2396|[Strictly Palindromic Number](./solutions/2396-strictly-palindromic-number.js)|Medium|
+2397|[Maximum Rows Covered by Columns](./solutions/2397-maximum-rows-covered-by-columns.js)|Medium|
 2401|[Longest Nice Subarray](./solutions/2401-longest-nice-subarray.js)|Medium|
 2413|[Smallest Even Multiple](./solutions/2413-smallest-even-multiple.js)|Easy|
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
diff --git a/solutions/2397-maximum-rows-covered-by-columns.js b/solutions/2397-maximum-rows-covered-by-columns.js
new file mode 100644
index 00000000..0fa68a2b
--- /dev/null
+++ b/solutions/2397-maximum-rows-covered-by-columns.js
@@ -0,0 +1,61 @@
+/**
+ * 2397. Maximum Rows Covered by Columns
+ * https://leetcode.com/problems/maximum-rows-covered-by-columns/
+ * Difficulty: Medium
+ *
+ * You are given an m x n binary matrix matrix and an integer numSelect.
+ *
+ * Your goal is to select exactly numSelect distinct columns from matrix such that you cover
+ * as many rows as possible.
+ *
+ * A row is considered covered if all the 1's in that row are also part of a column that you
+ * have selected. If a row does not have any 1s, it is also considered covered.
+ *
+ * More formally, let us consider selected = {c1, c2, ...., cnumSelect} as the set of columns
+ * selected by you. A row i is covered by selected if:
+ * - For each cell where matrix[i][j] == 1, the column j is in selected.
+ * - Or, no cell in row i has a value of 1.
+ *
+ * Return the maximum number of rows that can be covered by a set of numSelect columns.
+ */
+
+/**
+ * @param {number[][]} matrix
+ * @param {number} numSelect
+ * @return {number}
+ */
+var maximumRows = function(matrix, numSelect) {
+  const rows = matrix.length;
+  const cols = matrix[0].length;
+  let result = 0;
+
+  backtrack(0, 0, 0);
+
+  return result;
+
+  function countCovered(selected) {
+    let covered = 0;
+    for (let i = 0; i < rows; i++) {
+      let isCovered = true;
+      for (let j = 0; j < cols; j++) {
+        if (matrix[i][j] === 1 && !(selected & (1 << j))) {
+          isCovered = false;
+          break;
+        }
+      }
+      if (isCovered) covered++;
+    }
+    return covered;
+  }
+
+  function backtrack(index, selected, count) {
+    if (count === numSelect) {
+      result = Math.max(result, countCovered(selected));
+      return;
+    }
+    if (index >= cols || cols - index + count < numSelect) return;
+
+    backtrack(index + 1, selected | (1 << index), count + 1);
+    backtrack(index + 1, selected, count);
+  }
+};

From f74e3a968570fd75886c1669dff0fad9461c0274 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 01:03:08 -0500
Subject: [PATCH 421/495] Add solution #2399

---
 README.md                                     |  3 +-
 ...99-check-distances-between-same-letters.js | 44 +++++++++++++++++++
 2 files changed, 46 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2399-check-distances-between-same-letters.js

diff --git a/README.md b/README.md
index ae51f11f..0bbb9b86 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,925 LeetCode solutions in JavaScript
+# 1,926 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1814,6 +1814,7 @@
 2395|[Find Subarrays With Equal Sum](./solutions/2395-find-subarrays-with-equal-sum.js)|Easy|
 2396|[Strictly Palindromic Number](./solutions/2396-strictly-palindromic-number.js)|Medium|
 2397|[Maximum Rows Covered by Columns](./solutions/2397-maximum-rows-covered-by-columns.js)|Medium|
+2399|[Check Distances Between Same Letters](./solutions/2399-check-distances-between-same-letters.js)|Easy|
 2401|[Longest Nice Subarray](./solutions/2401-longest-nice-subarray.js)|Medium|
 2413|[Smallest Even Multiple](./solutions/2413-smallest-even-multiple.js)|Easy|
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
diff --git a/solutions/2399-check-distances-between-same-letters.js b/solutions/2399-check-distances-between-same-letters.js
new file mode 100644
index 00000000..7f977d1e
--- /dev/null
+++ b/solutions/2399-check-distances-between-same-letters.js
@@ -0,0 +1,44 @@
+/**
+ * 2399. Check Distances Between Same Letters
+ * https://leetcode.com/problems/check-distances-between-same-letters/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed string s consisting of only lowercase English letters, where each
+ * letter in s appears exactly twice. You are also given a 0-indexed integer array distance of
+ * length 26.
+ *
+ * Each letter in the alphabet is numbered from 0 to 25 (i.e. 'a' -> 0, 'b' -> 1,
+ * 'c' -> 2, ... , 'z' -> 25).
+ *
+ * In a well-spaced string, the number of letters between the two occurrences of the ith letter
+ * is distance[i]. If the ith letter does not appear in s, then distance[i] can be ignored.
+ *
+ * Return true if s is a well-spaced string, otherwise return false.
+ */
+
+/**
+ * @param {string} s
+ * @param {number[]} distance
+ * @return {boolean}
+ */
+var checkDistances = function(s, distance) {
+  const map = new Map();
+
+  for (let i = 0; i < s.length; i++) {
+    const char = s[i];
+    if (map.has(char)) {
+      map.get(char).push(i);
+    } else {
+      map.set(char, [i]);
+    }
+  }
+
+  for (const [char, positions] of map) {
+    const letterIndex = char.charCodeAt(0) - 'a'.charCodeAt(0);
+    if (positions[1] - positions[0] - 1 !== distance[letterIndex]) {
+      return false;
+    }
+  }
+
+  return true;
+};

From b77b5f6b2c12fddf21f44b88bcaadf35b99bf5d1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 01:05:16 -0500
Subject: [PATCH 422/495] Add solution #2404

---
 README.md                                    |  3 +-
 solutions/2404-most-frequent-even-element.js | 33 ++++++++++++++++++++
 2 files changed, 35 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2404-most-frequent-even-element.js

diff --git a/README.md b/README.md
index 0bbb9b86..32c4149e 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,926 LeetCode solutions in JavaScript
+# 1,927 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1816,6 +1816,7 @@
 2397|[Maximum Rows Covered by Columns](./solutions/2397-maximum-rows-covered-by-columns.js)|Medium|
 2399|[Check Distances Between Same Letters](./solutions/2399-check-distances-between-same-letters.js)|Easy|
 2401|[Longest Nice Subarray](./solutions/2401-longest-nice-subarray.js)|Medium|
+2404|[Most Frequent Even Element](./solutions/2404-most-frequent-even-element.js)|Easy|
 2413|[Smallest Even Multiple](./solutions/2413-smallest-even-multiple.js)|Easy|
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
 2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy|
diff --git a/solutions/2404-most-frequent-even-element.js b/solutions/2404-most-frequent-even-element.js
new file mode 100644
index 00000000..e5fcd0c6
--- /dev/null
+++ b/solutions/2404-most-frequent-even-element.js
@@ -0,0 +1,33 @@
+/**
+ * 2404. Most Frequent Even Element
+ * https://leetcode.com/problems/most-frequent-even-element/
+ * Difficulty: Easy
+ *
+ * Given an integer array nums, return the most frequent even element.
+ *
+ * If there is a tie, return the smallest one. If there is no such element, return -1.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var mostFrequentEven = function(nums) {
+  const map = new Map();
+  let maxCount = 0;
+  let result = -1;
+
+  for (const num of nums) {
+    if (num % 2 === 0) {
+      const count = (map.get(num) || 0) + 1;
+      map.set(num, count);
+      if (count > maxCount || (count === maxCount && num < result)) {
+        maxCount = count;
+        result = num;
+      }
+    }
+  }
+
+  return result;
+};
+

From c2ea326081c748cf689c4b0d14dcc035d13b9f94 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 01:06:44 -0500
Subject: [PATCH 423/495] Add solution #2405

---
 README.md                                     |  3 +-
 solutions/2405-optimal-partition-of-string.js | 31 +++++++++++++++++++
 2 files changed, 33 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2405-optimal-partition-of-string.js

diff --git a/README.md b/README.md
index 32c4149e..3976a369 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,927 LeetCode solutions in JavaScript
+# 1,928 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1817,6 +1817,7 @@
 2399|[Check Distances Between Same Letters](./solutions/2399-check-distances-between-same-letters.js)|Easy|
 2401|[Longest Nice Subarray](./solutions/2401-longest-nice-subarray.js)|Medium|
 2404|[Most Frequent Even Element](./solutions/2404-most-frequent-even-element.js)|Easy|
+2405|[Optimal Partition of String](./solutions/2405-optimal-partition-of-string.js)|Medium|
 2413|[Smallest Even Multiple](./solutions/2413-smallest-even-multiple.js)|Easy|
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
 2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy|
diff --git a/solutions/2405-optimal-partition-of-string.js b/solutions/2405-optimal-partition-of-string.js
new file mode 100644
index 00000000..eb2849bc
--- /dev/null
+++ b/solutions/2405-optimal-partition-of-string.js
@@ -0,0 +1,31 @@
+/**
+ * 2405. Optimal Partition of String
+ * https://leetcode.com/problems/optimal-partition-of-string/
+ * Difficulty: Medium
+ *
+ * Given a string s, partition the string into one or more substrings such that the characters
+ * in each substring are unique. That is, no letter appears in a single substring more than once.
+ *
+ * Return the minimum number of substrings in such a partition.
+ *
+ * Note that each character should belong to exactly one substring in a partition.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var partitionString = function(s) {
+  const set = new Set();
+  let result = 1;
+
+  for (const char of s) {
+    if (set.has(char)) {
+      set.clear();
+      result++;
+    }
+    set.add(char);
+  }
+
+  return result;
+};

From 1a45ae55762c8e0ed6cb4b50f55b1bd6bd0d88af Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 01:07:49 -0500
Subject: [PATCH 424/495] Add solution #2409

---
 README.md                                   |  3 +-
 solutions/2409-count-days-spent-together.js | 48 +++++++++++++++++++++
 2 files changed, 50 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2409-count-days-spent-together.js

diff --git a/README.md b/README.md
index 3976a369..d604ee7c 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,928 LeetCode solutions in JavaScript
+# 1,929 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1818,6 +1818,7 @@
 2401|[Longest Nice Subarray](./solutions/2401-longest-nice-subarray.js)|Medium|
 2404|[Most Frequent Even Element](./solutions/2404-most-frequent-even-element.js)|Easy|
 2405|[Optimal Partition of String](./solutions/2405-optimal-partition-of-string.js)|Medium|
+2409|[Count Days Spent Together](./solutions/2409-count-days-spent-together.js)|Easy|
 2413|[Smallest Even Multiple](./solutions/2413-smallest-even-multiple.js)|Easy|
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
 2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy|
diff --git a/solutions/2409-count-days-spent-together.js b/solutions/2409-count-days-spent-together.js
new file mode 100644
index 00000000..1047ab0b
--- /dev/null
+++ b/solutions/2409-count-days-spent-together.js
@@ -0,0 +1,48 @@
+/**
+ * 2409. Count Days Spent Together
+ * https://leetcode.com/problems/count-days-spent-together/
+ * Difficulty: Easy
+ *
+ * Alice and Bob are traveling to Rome for separate business meetings.
+ *
+ * You are given 4 strings arriveAlice, leaveAlice, arriveBob, and leaveBob. Alice will be in
+ * the city from the dates arriveAlice to leaveAlice (inclusive), while Bob will be in the city
+ * from the dates arriveBob to leaveBob (inclusive). Each will be a 5-character string in the
+ * format "MM-DD", corresponding to the month and day of the date.
+ *
+ * Return the total number of days that Alice and Bob are in Rome together.
+ *
+ * You can assume that all dates occur in the same calendar year, which is not a leap year. Note
+ * that the number of days per month can be represented as: [31, 28, 31, 30, 31, 30, 31, 31, 30,
+ * 31, 30, 31].
+ */
+
+/**
+ * @param {string} arriveAlice
+ * @param {string} leaveAlice
+ * @param {string} arriveBob
+ * @param {string} leaveBob
+ * @return {number}
+ */
+var countDaysTogether = function(arriveAlice, leaveAlice, arriveBob, leaveBob) {
+  const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
+
+  function toDays(date) {
+    const [month, day] = date.split('-').map(Number);
+    let totalDays = 0;
+    for (let i = 0; i < month - 1; i++) {
+      totalDays += daysInMonth[i];
+    }
+    return totalDays + day;
+  }
+
+  const aliceStart = toDays(arriveAlice);
+  const aliceEnd = toDays(leaveAlice);
+  const bobStart = toDays(arriveBob);
+  const bobEnd = toDays(leaveBob);
+
+  const overlapStart = Math.max(aliceStart, bobStart);
+  const overlapEnd = Math.min(aliceEnd, bobEnd);
+
+  return Math.max(0, overlapEnd - overlapStart + 1);
+};

From e8040a90511255a51854967c58bb296a65e448f1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 01:09:53 -0500
Subject: [PATCH 425/495] Add solution #2410

---
 README.md                                     |  3 +-
 ...ximum-matching-of-players-with-trainers.js | 35 +++++++++++++++++++
 2 files changed, 37 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2410-maximum-matching-of-players-with-trainers.js

diff --git a/README.md b/README.md
index d604ee7c..019f142b 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,929 LeetCode solutions in JavaScript
+# 1,930 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1819,6 +1819,7 @@
 2404|[Most Frequent Even Element](./solutions/2404-most-frequent-even-element.js)|Easy|
 2405|[Optimal Partition of String](./solutions/2405-optimal-partition-of-string.js)|Medium|
 2409|[Count Days Spent Together](./solutions/2409-count-days-spent-together.js)|Easy|
+2410|[Maximum Matching of Players With Trainers](./solutions/2410-maximum-matching-of-players-with-trainers.js)|Medium|
 2413|[Smallest Even Multiple](./solutions/2413-smallest-even-multiple.js)|Easy|
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
 2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy|
diff --git a/solutions/2410-maximum-matching-of-players-with-trainers.js b/solutions/2410-maximum-matching-of-players-with-trainers.js
new file mode 100644
index 00000000..885db445
--- /dev/null
+++ b/solutions/2410-maximum-matching-of-players-with-trainers.js
@@ -0,0 +1,35 @@
+/**
+ * 2410. Maximum Matching of Players With Trainers
+ * https://leetcode.com/problems/maximum-matching-of-players-with-trainers/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array players, where players[i] represents the ability of
+ * the ith player. You are also given a 0-indexed integer array trainers, where trainers[j]
+ * represents the training capacity of the jth trainer.
+ *
+ * The ith player can match with the jth trainer if the player's ability is less than or equal
+ * to the trainer's training capacity. Additionally, the ith player can be matched with at most
+ * one trainer, and the jth trainer can be matched with at most one player.
+ *
+ * Return the maximum number of matchings between players and trainers that satisfy these
+ * conditions.
+ */
+
+/**
+ * @param {number[]} players
+ * @param {number[]} trainers
+ * @return {number}
+ */
+var matchPlayersAndTrainers = function(players, trainers) {
+  players.sort((a, b) => a - b);
+  trainers.sort((a, b) => a - b);
+
+  let result = 0;
+  for (let j = 0; result < players.length && j < trainers.length; j++) {
+    if (trainers[j] >= players[result]) {
+      result++;
+    }
+  }
+
+  return result;
+};

From ce703da83613cecb420ff74761553873e6f8c156 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 18:11:08 -0500
Subject: [PATCH 426/495] Add solution #3362

---
 README.md                                     |  3 +-
 .../3362-zero-array-transformation-iii.js     | 53 +++++++++++++++++++
 2 files changed, 55 insertions(+), 1 deletion(-)
 create mode 100644 solutions/3362-zero-array-transformation-iii.js

diff --git a/README.md b/README.md
index 019f142b..208d6c15 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,930 LeetCode solutions in JavaScript
+# 1,931 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1925,6 +1925,7 @@
 3343|[Count Number of Balanced Permutations](./solutions/3343-count-number-of-balanced-permutations.js)|Hard|
 3355|[Zero Array Transformation I](./solutions/3355-zero-array-transformation-i.js)|Medium|
 3356|[Zero Array Transformation II](./solutions/3356-zero-array-transformation-ii.js)|Medium|
+3362|[Zero Array Transformation III](./solutions/3362-zero-array-transformation-iii.js)|Medium|
 3375|[Minimum Operations to Make Array Values Equal to K](./solutions/3375-minimum-operations-to-make-array-values-equal-to-k.js)|Easy|
 3392|[Count Subarrays of Length Three With a Condition](./solutions/3392-count-subarrays-of-length-three-with-a-condition.js)|Easy|
 3394|[Check if Grid can be Cut into Sections](./solutions/3394-check-if-grid-can-be-cut-into-sections.js)|Medium|
diff --git a/solutions/3362-zero-array-transformation-iii.js b/solutions/3362-zero-array-transformation-iii.js
new file mode 100644
index 00000000..f6d979bb
--- /dev/null
+++ b/solutions/3362-zero-array-transformation-iii.js
@@ -0,0 +1,53 @@
+/**
+ * 3362. Zero Array Transformation III
+ * https://leetcode.com/problems/zero-array-transformation-iii/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums of length n and a 2D array queries where
+ * queries[i] = [li, ri].
+ *
+ * Each queries[i] represents the following action on nums:
+ * - Decrement the value at each index in the range [li, ri] in nums by at most 1.
+ * - The amount by which the value is decremented can be chosen independently for each index.
+ *
+ * A Zero Array is an array with all its elements equal to 0.
+ *
+ * Return the maximum number of elements that can be removed from queries, such that nums can
+ * still be converted to a zero array using the remaining queries. If it is not possible to
+ * convert nums to a zero array, return -1.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[][]} queries
+ * @return {number}
+ */
+var maxRemoval = function(nums, queries) {
+  queries.sort((a, b) => a[0] - b[0]);
+  const endIndexHeap = new MaxPriorityQueue();
+  const expiredQueries = new Array(nums.length + 1).fill(0);
+  let operationCount = 0;
+  let queryIndex = 0;
+
+  for (let numIndex = 0; numIndex < nums.length; numIndex++) {
+    operationCount -= expiredQueries[numIndex];
+
+    while (queryIndex < queries.length && queries[queryIndex][0] === numIndex) {
+      endIndexHeap.push(queries[queryIndex][1]);
+      queryIndex++;
+    }
+
+    while (
+      operationCount < nums[numIndex] && !endIndexHeap.isEmpty() && endIndexHeap.front() >= numIndex
+    ) {
+      operationCount++;
+      expiredQueries[endIndexHeap.pop() + 1]++;
+    }
+
+    if (operationCount < nums[numIndex]) {
+      return -1;
+    }
+  }
+
+  return endIndexHeap.size();
+};

From 701cf0bf3f766ef9a7557e18daa000330a09ee22 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 18:13:13 -0500
Subject: [PATCH 427/495] Add solution #2411

---
 README.md                                     |  3 +-
 ...llest-subarrays-with-maximum-bitwise-or.js | 46 +++++++++++++++++++
 2 files changed, 48 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2411-smallest-subarrays-with-maximum-bitwise-or.js

diff --git a/README.md b/README.md
index 208d6c15..c455c8a5 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,931 LeetCode solutions in JavaScript
+# 1,932 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1820,6 +1820,7 @@
 2405|[Optimal Partition of String](./solutions/2405-optimal-partition-of-string.js)|Medium|
 2409|[Count Days Spent Together](./solutions/2409-count-days-spent-together.js)|Easy|
 2410|[Maximum Matching of Players With Trainers](./solutions/2410-maximum-matching-of-players-with-trainers.js)|Medium|
+2411|[Smallest Subarrays With Maximum Bitwise OR](./solutions/2411-smallest-subarrays-with-maximum-bitwise-or.js)|Medium|
 2413|[Smallest Even Multiple](./solutions/2413-smallest-even-multiple.js)|Easy|
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
 2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy|
diff --git a/solutions/2411-smallest-subarrays-with-maximum-bitwise-or.js b/solutions/2411-smallest-subarrays-with-maximum-bitwise-or.js
new file mode 100644
index 00000000..784cf5d2
--- /dev/null
+++ b/solutions/2411-smallest-subarrays-with-maximum-bitwise-or.js
@@ -0,0 +1,46 @@
+/**
+ * 2411. Smallest Subarrays With Maximum Bitwise OR
+ * https://leetcode.com/problems/smallest-subarrays-with-maximum-bitwise-or/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array nums of length n, consisting of non-negative integers. For
+ * each index i from 0 to n - 1, you must determine the size of the minimum sized non-empty
+ * subarray of nums starting at i (inclusive) that has the maximum possible bitwise OR.
+ * - In other words, let Bij be the bitwise OR of the subarray nums[i...j]. You need to find
+ *   the smallest subarray starting at i, such that bitwise OR of this subarray is equal to
+ *   max(Bik) where i <= k <= n - 1.
+ *
+ * The bitwise OR of an array is the bitwise OR of all the numbers in it.
+ *
+ * Return an integer array answer of size n where answer[i] is the length of the minimum sized
+ * subarray starting at i with maximum bitwise OR.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var smallestSubarrays = function(nums) {
+  const n = nums.length;
+  const result = new Array(n).fill(1);
+  const bitPositions = new Array(32).fill(0);
+
+  for (let i = n - 1; i >= 0; i--) {
+    for (let bit = 0; bit < 32; bit++) {
+      if (nums[i] & (1 << bit)) {
+        bitPositions[bit] = i;
+      }
+    }
+
+    let maxIndex = i;
+    for (let bit = 0; bit < 32; bit++) {
+      maxIndex = Math.max(maxIndex, bitPositions[bit]);
+    }
+
+    result[i] = maxIndex - i + 1;
+  }
+
+  return result;
+};

From 35338e8460dbc920bf12786bc02337a01adef03c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 18:14:11 -0500
Subject: [PATCH 428/495] Add solution #2412

---
 README.md                                     |  3 +-
 ...imum-money-required-before-transactions.js | 36 +++++++++++++++++++
 2 files changed, 38 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2412-minimum-money-required-before-transactions.js

diff --git a/README.md b/README.md
index c455c8a5..8abc2edb 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,932 LeetCode solutions in JavaScript
+# 1,933 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1821,6 +1821,7 @@
 2409|[Count Days Spent Together](./solutions/2409-count-days-spent-together.js)|Easy|
 2410|[Maximum Matching of Players With Trainers](./solutions/2410-maximum-matching-of-players-with-trainers.js)|Medium|
 2411|[Smallest Subarrays With Maximum Bitwise OR](./solutions/2411-smallest-subarrays-with-maximum-bitwise-or.js)|Medium|
+2412|[Minimum Money Required Before Transactions](./solutions/2412-minimum-money-required-before-transactions.js)|Hard|
 2413|[Smallest Even Multiple](./solutions/2413-smallest-even-multiple.js)|Easy|
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
 2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy|
diff --git a/solutions/2412-minimum-money-required-before-transactions.js b/solutions/2412-minimum-money-required-before-transactions.js
new file mode 100644
index 00000000..240ca6ca
--- /dev/null
+++ b/solutions/2412-minimum-money-required-before-transactions.js
@@ -0,0 +1,36 @@
+/**
+ * 2412. Minimum Money Required Before Transactions
+ * https://leetcode.com/problems/minimum-money-required-before-transactions/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed 2D integer array transactions, where
+ * transactions[i] = [costi, cashbacki].
+ *
+ * The array describes transactions, where each transaction must be completed exactly once
+ * in some order. At any given moment, you have a certain amount of money. In order to
+ * complete transaction i, money >= costi must hold true. After performing a transaction,
+ * money becomes money - costi + cashbacki.
+ *
+ * Return the minimum amount of money required before any transaction so that all of the
+ * transactions can be completed regardless of the order of the transactions.
+ */
+
+/**
+ * @param {number[][]} transactions
+ * @return {number}
+ */
+var minimumMoney = function(transactions) {
+  let totalLoss = 0;
+  let maxCost = 0;
+
+  for (const [cost, cashback] of transactions) {
+    if (cost > cashback) {
+      totalLoss += cost - cashback;
+      maxCost = Math.max(maxCost, cashback);
+    } else {
+      maxCost = Math.max(maxCost, cost);
+    }
+  }
+
+  return totalLoss + maxCost;
+};

From f3063f84d6c6214bb38ea1ec5e518f335ec65867 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 18:15:21 -0500
Subject: [PATCH 429/495] Add solution #2414

---
 README.md                                     |  3 +-
 ...ngest-alphabetical-continuous-substring.js | 32 +++++++++++++++++++
 2 files changed, 34 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2414-length-of-the-longest-alphabetical-continuous-substring.js

diff --git a/README.md b/README.md
index 8abc2edb..929cedbd 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,933 LeetCode solutions in JavaScript
+# 1,934 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1823,6 +1823,7 @@
 2411|[Smallest Subarrays With Maximum Bitwise OR](./solutions/2411-smallest-subarrays-with-maximum-bitwise-or.js)|Medium|
 2412|[Minimum Money Required Before Transactions](./solutions/2412-minimum-money-required-before-transactions.js)|Hard|
 2413|[Smallest Even Multiple](./solutions/2413-smallest-even-multiple.js)|Easy|
+2414|[Length of the Longest Alphabetical Continuous Substring](./solutions/2414-length-of-the-longest-alphabetical-continuous-substring.js)|Medium|
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
 2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy|
 2429|[Minimize XOR](./solutions/2429-minimize-xor.js)|Medium|
diff --git a/solutions/2414-length-of-the-longest-alphabetical-continuous-substring.js b/solutions/2414-length-of-the-longest-alphabetical-continuous-substring.js
new file mode 100644
index 00000000..afb44c82
--- /dev/null
+++ b/solutions/2414-length-of-the-longest-alphabetical-continuous-substring.js
@@ -0,0 +1,32 @@
+/**
+ * 2414. Length of the Longest Alphabetical Continuous Substring
+ * https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring/
+ * Difficulty: Medium
+ *
+ * An alphabetical continuous string is a string consisting of consecutive letters in the alphabet.
+ * In other words, it is any substring of the string "abcdefghijklmnopqrstuvwxyz".
+ * - For example, "abc" is an alphabetical continuous string, while "acb" and "za" are not.
+ *
+ * Given a string s consisting of lowercase letters only, return the length of the longest
+ * alphabetical continuous substring.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var longestContinuousSubstring = function(s) {
+  let result = 1;
+  let currentLength = 1;
+
+  for (let i = 1; i < s.length; i++) {
+    if (s.charCodeAt(i) - s.charCodeAt(i - 1) === 1) {
+      currentLength++;
+      result = Math.max(result, currentLength);
+    } else {
+      currentLength = 1;
+    }
+  }
+
+  return result;
+};

From 2637e6062f2e85957204b91dd08d7c51a7303be6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 18:16:55 -0500
Subject: [PATCH 430/495] Add solution #2415

---
 README.md                                     |  3 +-
 .../2415-reverse-odd-levels-of-binary-tree.js | 51 +++++++++++++++++++
 2 files changed, 53 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2415-reverse-odd-levels-of-binary-tree.js

diff --git a/README.md b/README.md
index 929cedbd..13148eee 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,934 LeetCode solutions in JavaScript
+# 1,935 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1824,6 +1824,7 @@
 2412|[Minimum Money Required Before Transactions](./solutions/2412-minimum-money-required-before-transactions.js)|Hard|
 2413|[Smallest Even Multiple](./solutions/2413-smallest-even-multiple.js)|Easy|
 2414|[Length of the Longest Alphabetical Continuous Substring](./solutions/2414-length-of-the-longest-alphabetical-continuous-substring.js)|Medium|
+2415|[Reverse Odd Levels of Binary Tree](./solutions/2415-reverse-odd-levels-of-binary-tree.js)|Medium|
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
 2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy|
 2429|[Minimize XOR](./solutions/2429-minimize-xor.js)|Medium|
diff --git a/solutions/2415-reverse-odd-levels-of-binary-tree.js b/solutions/2415-reverse-odd-levels-of-binary-tree.js
new file mode 100644
index 00000000..9c70383b
--- /dev/null
+++ b/solutions/2415-reverse-odd-levels-of-binary-tree.js
@@ -0,0 +1,51 @@
+/**
+ * 2415. Reverse Odd Levels of Binary Tree
+ * https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/
+ * Difficulty: Medium
+ *
+ * Given the root of a perfect binary tree, reverse the node values at each odd level of the tree.
+ * - For example, suppose the node values at level 3 are [2,1,3,4,7,11,29,18], then it should
+ *   become [18,29,11,7,4,3,1,2].
+ *
+ * Return the root of the reversed tree.
+ *
+ * A binary tree is perfect if all parent nodes have two children and all leaves are on the same
+ * level.
+ *
+ * The level of a node is the number of edges along the path between it and the root 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 {TreeNode}
+ */
+var reverseOddLevels = function(root) {
+  reverseLevel([root], 0);
+  return root;
+
+  function reverseLevel(nodes, level) {
+    if (!nodes.length) return;
+
+    if (level % 2 === 1) {
+      for (let i = 0, j = nodes.length - 1; i < j; i++, j--) {
+        [nodes[i].val, nodes[j].val] = [nodes[j].val, nodes[i].val];
+      }
+    }
+
+    const nextLevel = [];
+    for (const node of nodes) {
+      if (node.left) nextLevel.push(node.left);
+      if (node.right) nextLevel.push(node.right);
+    }
+
+    reverseLevel(nextLevel, level + 1);
+  }
+};

From b8c8af56c336d9a8834819d6a99a169508f238ee Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 18:20:06 -0500
Subject: [PATCH 431/495] Add solution #2416

---
 README.md                                     |  3 +-
 .../2416-sum-of-prefix-scores-of-strings.js   | 56 +++++++++++++++++++
 2 files changed, 58 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2416-sum-of-prefix-scores-of-strings.js

diff --git a/README.md b/README.md
index 13148eee..88b52945 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,935 LeetCode solutions in JavaScript
+# 1,936 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1825,6 +1825,7 @@
 2413|[Smallest Even Multiple](./solutions/2413-smallest-even-multiple.js)|Easy|
 2414|[Length of the Longest Alphabetical Continuous Substring](./solutions/2414-length-of-the-longest-alphabetical-continuous-substring.js)|Medium|
 2415|[Reverse Odd Levels of Binary Tree](./solutions/2415-reverse-odd-levels-of-binary-tree.js)|Medium|
+2416|[Sum of Prefix Scores of Strings](./solutions/2416-sum-of-prefix-scores-of-strings.js)|Hard|
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
 2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy|
 2429|[Minimize XOR](./solutions/2429-minimize-xor.js)|Medium|
diff --git a/solutions/2416-sum-of-prefix-scores-of-strings.js b/solutions/2416-sum-of-prefix-scores-of-strings.js
new file mode 100644
index 00000000..45d3a184
--- /dev/null
+++ b/solutions/2416-sum-of-prefix-scores-of-strings.js
@@ -0,0 +1,56 @@
+/**
+ * 2416. Sum of Prefix Scores of Strings
+ * https://leetcode.com/problems/sum-of-prefix-scores-of-strings/
+ * Difficulty: Hard
+ *
+ * You are given an array words of size n consisting of non-empty strings.
+ *
+ * We define the score of a string term as the number of strings words[i] such that term is
+ * a prefix of words[i].
+ * - For example, if words = ["a", "ab", "abc", "cab"], then the score of "ab" is 2, since
+ *   "ab" is a prefix of both "ab" and "abc".
+ *
+ * Return an array answer of size n where answer[i] is the sum of scores of every non-empty
+ * prefix of words[i].
+ *
+ * Note that a string is considered as a prefix of itself.
+ */
+
+/**
+ * @param {string[]} words
+ * @return {number[]}
+ */
+var sumPrefixScores = function(words) {
+  class TrieNode {
+    constructor() {
+      this.children = new Map();
+      this.count = 0;
+    }
+  }
+
+  const root = new TrieNode();
+
+  for (const word of words) {
+    let node = root;
+    for (const char of word) {
+      if (!node.children.has(char)) {
+        node.children.set(char, new TrieNode());
+      }
+      node = node.children.get(char);
+      node.count++;
+    }
+  }
+
+  const result = [];
+  for (const word of words) {
+    let node = root;
+    let score = 0;
+    for (const char of word) {
+      node = node.children.get(char);
+      score += node.count;
+    }
+    result.push(score);
+  }
+
+  return result;
+};

From 07dd5cf774c7656438898a2962fde93421e335e5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 18:20:55 -0500
Subject: [PATCH 432/495] Add solution #2418

---
 README.md                         |  3 ++-
 solutions/2418-sort-the-people.js | 23 +++++++++++++++++++++++
 2 files changed, 25 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2418-sort-the-people.js

diff --git a/README.md b/README.md
index 88b52945..56381df0 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,936 LeetCode solutions in JavaScript
+# 1,937 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1826,6 +1826,7 @@
 2414|[Length of the Longest Alphabetical Continuous Substring](./solutions/2414-length-of-the-longest-alphabetical-continuous-substring.js)|Medium|
 2415|[Reverse Odd Levels of Binary Tree](./solutions/2415-reverse-odd-levels-of-binary-tree.js)|Medium|
 2416|[Sum of Prefix Scores of Strings](./solutions/2416-sum-of-prefix-scores-of-strings.js)|Hard|
+2418|[Sort the People](./solutions/2418-sort-the-people.js)|Easy|
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
 2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy|
 2429|[Minimize XOR](./solutions/2429-minimize-xor.js)|Medium|
diff --git a/solutions/2418-sort-the-people.js b/solutions/2418-sort-the-people.js
new file mode 100644
index 00000000..c0477a6a
--- /dev/null
+++ b/solutions/2418-sort-the-people.js
@@ -0,0 +1,23 @@
+/**
+ * 2418. Sort the People
+ * https://leetcode.com/problems/sort-the-people/
+ * Difficulty: Easy
+ *
+ * You are given an array of strings names, and an array heights that consists of distinct
+ * positive integers. Both arrays are of length n.
+ *
+ * For each index i, names[i] and heights[i] denote the name and height of the ith person.
+ *
+ * Return names sorted in descending order by the people's heights.
+ */
+
+/**
+ * @param {string[]} names
+ * @param {number[]} heights
+ * @return {string[]}
+ */
+var sortPeople = function(names, heights) {
+  const people = names.map((name, index) => ({name, height: heights[index]}));
+  people.sort((a, b) => b.height - a.height);
+  return people.map(person => person.name);
+};

From de4370e8bb77b33e41a2216d44c8309b3cd8ad24 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 18:21:55 -0500
Subject: [PATCH 433/495] Add solution #2419

---
 README.md                                     |  3 +-
 ...ngest-subarray-with-maximum-bitwise-and.js | 38 +++++++++++++++++++
 2 files changed, 40 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2419-longest-subarray-with-maximum-bitwise-and.js

diff --git a/README.md b/README.md
index 56381df0..1e0d537a 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,937 LeetCode solutions in JavaScript
+# 1,938 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1827,6 +1827,7 @@
 2415|[Reverse Odd Levels of Binary Tree](./solutions/2415-reverse-odd-levels-of-binary-tree.js)|Medium|
 2416|[Sum of Prefix Scores of Strings](./solutions/2416-sum-of-prefix-scores-of-strings.js)|Hard|
 2418|[Sort the People](./solutions/2418-sort-the-people.js)|Easy|
+2419|[Longest Subarray With Maximum Bitwise AND](./solutions/2419-longest-subarray-with-maximum-bitwise-and.js)|Medium|
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
 2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy|
 2429|[Minimize XOR](./solutions/2429-minimize-xor.js)|Medium|
diff --git a/solutions/2419-longest-subarray-with-maximum-bitwise-and.js b/solutions/2419-longest-subarray-with-maximum-bitwise-and.js
new file mode 100644
index 00000000..c6a26711
--- /dev/null
+++ b/solutions/2419-longest-subarray-with-maximum-bitwise-and.js
@@ -0,0 +1,38 @@
+/**
+ * 2419. Longest Subarray With Maximum Bitwise AND
+ * https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums of size n.
+ *
+ * Consider a non-empty subarray from nums that has the maximum possible bitwise AND.
+ * - In other words, let k be the maximum value of the bitwise AND of any subarray of nums.
+ *   Then, only subarrays with a bitwise AND equal to k should be considered.
+ *
+ * Return the length of the longest such subarray.
+ *
+ * The bitwise AND of an array is the bitwise AND of all the numbers in it.
+ *
+ * A subarray is a contiguous sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var longestSubarray = function(nums) {
+  const maxValue = Math.max(...nums);
+  let result = 0;
+  let currentLength = 0;
+
+  for (const num of nums) {
+    if (num === maxValue) {
+      currentLength++;
+      result = Math.max(result, currentLength);
+    } else {
+      currentLength = 0;
+    }
+  }
+
+  return result;
+};

From accb59aa6bdfdc3de96b168abcb33ec705ef6b21 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 18:26:11 -0500
Subject: [PATCH 434/495] Add solution #2421

---
 README.md                              |  3 +-
 solutions/2421-number-of-good-paths.js | 86 ++++++++++++++++++++++++++
 2 files changed, 88 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2421-number-of-good-paths.js

diff --git a/README.md b/README.md
index 1e0d537a..54e5c2d1 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,938 LeetCode solutions in JavaScript
+# 1,939 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1828,6 +1828,7 @@
 2416|[Sum of Prefix Scores of Strings](./solutions/2416-sum-of-prefix-scores-of-strings.js)|Hard|
 2418|[Sort the People](./solutions/2418-sort-the-people.js)|Easy|
 2419|[Longest Subarray With Maximum Bitwise AND](./solutions/2419-longest-subarray-with-maximum-bitwise-and.js)|Medium|
+2421|[Number of Good Paths](./solutions/2421-number-of-good-paths.js)|Hard|
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
 2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy|
 2429|[Minimize XOR](./solutions/2429-minimize-xor.js)|Medium|
diff --git a/solutions/2421-number-of-good-paths.js b/solutions/2421-number-of-good-paths.js
new file mode 100644
index 00000000..c0f7d606
--- /dev/null
+++ b/solutions/2421-number-of-good-paths.js
@@ -0,0 +1,86 @@
+/**
+ * 2421. Number of Good Paths
+ * https://leetcode.com/problems/number-of-good-paths/
+ * Difficulty: Hard
+ *
+ * There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n nodes
+ * numbered from 0 to n - 1 and exactly n - 1 edges.
+ *
+ * You are given a 0-indexed integer array vals of length n where vals[i] denotes the value
+ * of the ith node. You are also given a 2D integer array edges where edges[i] = [ai, bi]
+ * denotes that there exists an undirected edge connecting nodes ai and bi.
+ *
+ * A good path is a simple path that satisfies the following conditions:
+ * 1. The starting node and the ending node have the same value.
+ * 2. All nodes between the starting node and the ending node have values less than or equal
+ *    to the starting node (i.e. the starting node's value should be the maximum value along
+ *    the path).
+ *
+ * Return the number of distinct good paths.
+ *
+ * Note that a path and its reverse are counted as the same path. For example, 0 -> 1 is
+ * considered to be the same as 1 -> 0. A single node is also considered as a valid path.
+ */
+
+/**
+ * @param {number[]} vals
+ * @param {number[][]} edges
+ * @return {number}
+ */
+var numberOfGoodPaths = function(vals, edges) {
+  const n = vals.length;
+  const graph = Array.from({length: n}, () => []);
+  for (const [u, v] of edges) {
+    graph[u].push(v);
+    graph[v].push(u);
+  }
+
+  const parent = new Array(n).fill(-1);
+  const rank = new Array(n).fill(0);
+  function find(x) {
+    if (parent[x] === -1) return x;
+    return parent[x] = find(parent[x]);
+  }
+
+  function union(x, y) {
+    let px = find(x);
+    let py = find(y);
+    if (px === py) return;
+    if (rank[px] < rank[py]) [px, py] = [py, px];
+    parent[py] = px;
+    if (rank[px] === rank[py]) rank[px]++;
+  }
+
+  const valueGroups = new Map();
+  for (let i = 0; i < n; i++) {
+    if (!valueGroups.has(vals[i])) {
+      valueGroups.set(vals[i], []);
+    }
+    valueGroups.get(vals[i]).push(i);
+  }
+
+  let result = 0;
+  for (const value of [...valueGroups.keys()].sort((a, b) => a - b)) {
+    const nodes = valueGroups.get(value);
+
+    for (const node of nodes) {
+      for (const neighbor of graph[node]) {
+        if (vals[neighbor] <= value) {
+          union(node, neighbor);
+        }
+      }
+    }
+
+    const groupCount = new Map();
+    for (const node of nodes) {
+      const root = find(node);
+      groupCount.set(root, (groupCount.get(root) || 0) + 1);
+    }
+
+    for (const count of groupCount.values()) {
+      result += (count * (count + 1)) / 2;
+    }
+  }
+
+  return result;
+};

From 779731fbe40e62ee24c73c2e69e57fa5681dcf5b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 18:27:30 -0500
Subject: [PATCH 435/495] Add solution #2426

---
 README.md                                     |  3 +-
 ...6-number-of-pairs-satisfying-inequality.js | 66 +++++++++++++++++++
 2 files changed, 68 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2426-number-of-pairs-satisfying-inequality.js

diff --git a/README.md b/README.md
index 54e5c2d1..91e8f4d7 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,939 LeetCode solutions in JavaScript
+# 1,940 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1830,6 +1830,7 @@
 2419|[Longest Subarray With Maximum Bitwise AND](./solutions/2419-longest-subarray-with-maximum-bitwise-and.js)|Medium|
 2421|[Number of Good Paths](./solutions/2421-number-of-good-paths.js)|Hard|
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
+2426|[Number of Pairs Satisfying Inequality](./solutions/2426-number-of-pairs-satisfying-inequality.js)|Hard|
 2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy|
 2429|[Minimize XOR](./solutions/2429-minimize-xor.js)|Medium|
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
diff --git a/solutions/2426-number-of-pairs-satisfying-inequality.js b/solutions/2426-number-of-pairs-satisfying-inequality.js
new file mode 100644
index 00000000..e24957fd
--- /dev/null
+++ b/solutions/2426-number-of-pairs-satisfying-inequality.js
@@ -0,0 +1,66 @@
+/**
+ * 2426. Number of Pairs Satisfying Inequality
+ * https://leetcode.com/problems/number-of-pairs-satisfying-inequality/
+ * Difficulty: Hard
+ *
+ * You are given two 0-indexed integer arrays nums1 and nums2, each of size n, and an
+ * integer diff. Find the number of pairs (i, j) such that:
+ * - 0 <= i < j <= n - 1 and
+ * - nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff.
+ *
+ * Return the number of pairs that satisfy the conditions.
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @param {number} diff
+ * @return {number}
+ */
+var numberOfPairs = function(nums1, nums2, diff) {
+  const n = nums1.length;
+  const differences = new Array(n);
+  for (let i = 0; i < n; i++) {
+    differences[i] = nums1[i] - nums2[i];
+  }
+  let result = 0;
+  mergeSort(0, n);
+  return result;
+
+  function mergeSort(left, right) {
+    if (right - left <= 1) return;
+
+    const mid = Math.floor((left + right) / 2);
+    mergeSort(left, mid);
+    mergeSort(mid, right);
+
+    let i = left;
+    let j = mid;
+    while (i < mid && j < right) {
+      if (differences[i] <= differences[j] + diff) {
+        result += right - j;
+        i++;
+      } else {
+        j++;
+      }
+    }
+
+    const sorted = new Array(right - left);
+    let k = 0;
+    i = left;
+    j = mid;
+    while (i < mid && j < right) {
+      if (differences[i] <= differences[j]) {
+        sorted[k++] = differences[i++];
+      } else {
+        sorted[k++] = differences[j++];
+      }
+    }
+    while (i < mid) sorted[k++] = differences[i++];
+    while (j < right) sorted[k++] = differences[j++];
+
+    for (let p = 0; p < sorted.length; p++) {
+      differences[left + p] = sorted[p];
+    }
+  }
+};

From aa072920c2d4451fa74a9a230bd82ff0c9b3260f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 18:34:55 -0500
Subject: [PATCH 436/495] Add solution #2428

---
 README.md                                     |  3 +-
 solutions/2428-maximum-sum-of-an-hourglass.js | 33 +++++++++++++++++++
 2 files changed, 35 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2428-maximum-sum-of-an-hourglass.js

diff --git a/README.md b/README.md
index 91e8f4d7..d6989e52 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,940 LeetCode solutions in JavaScript
+# 1,941 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1832,6 +1832,7 @@
 2425|[Bitwise XOR of All Pairings](./solutions/2425-bitwise-xor-of-all-pairings.js)|Medium|
 2426|[Number of Pairs Satisfying Inequality](./solutions/2426-number-of-pairs-satisfying-inequality.js)|Hard|
 2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy|
+2428|[Maximum Sum of an Hourglass](./solutions/2428-maximum-sum-of-an-hourglass.js)|Medium|
 2429|[Minimize XOR](./solutions/2429-minimize-xor.js)|Medium|
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
diff --git a/solutions/2428-maximum-sum-of-an-hourglass.js b/solutions/2428-maximum-sum-of-an-hourglass.js
new file mode 100644
index 00000000..f6cb5a39
--- /dev/null
+++ b/solutions/2428-maximum-sum-of-an-hourglass.js
@@ -0,0 +1,33 @@
+/**
+ * 2428. Maximum Sum of an Hourglass
+ * https://leetcode.com/problems/maximum-sum-of-an-hourglass/
+ * Difficulty: Medium
+ *
+ * You are given an m x n integer matrix grid.
+ *
+ * We define an hourglass as a part of the matrix with the following form.
+ *
+ * Return the maximum sum of the elements of an hourglass.
+ *
+ * Note that an hourglass cannot be rotated and must be entirely contained within the matrix.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var maxSum = function(grid) {
+  let result = 0;
+  const rows = grid.length;
+  const cols = grid[0].length;
+
+  for (let i = 0; i <= rows - 3; i++) {
+    for (let j = 0; j <= cols - 3; j++) {
+      const hourglassSum = grid[i][j] + grid[i][j+1] + grid[i][j+2] + grid[i+1][j+1]
+        + grid[i+2][j] + grid[i+2][j+1] + grid[i+2][j+2];
+      result = Math.max(result, hourglassSum);
+    }
+  }
+
+  return result;
+};

From a5829fa5d912d36ec668a3221d1e8210d40da324 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 18:36:08 -0500
Subject: [PATCH 437/495] Add solution #2432

---
 README.md                                     |  3 +-
 ...mployee-that-worked-on-the-longest-task.js | 40 +++++++++++++++++++
 2 files changed, 42 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2432-the-employee-that-worked-on-the-longest-task.js

diff --git a/README.md b/README.md
index d6989e52..43b4a983 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,941 LeetCode solutions in JavaScript
+# 1,942 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1834,6 +1834,7 @@
 2427|[Number of Common Factors](./solutions/2427-number-of-common-factors.js)|Easy|
 2428|[Maximum Sum of an Hourglass](./solutions/2428-maximum-sum-of-an-hourglass.js)|Medium|
 2429|[Minimize XOR](./solutions/2429-minimize-xor.js)|Medium|
+2432|[The Employee That Worked on the Longest Task](./solutions/2432-the-employee-that-worked-on-the-longest-task.js)|Easy|
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
diff --git a/solutions/2432-the-employee-that-worked-on-the-longest-task.js b/solutions/2432-the-employee-that-worked-on-the-longest-task.js
new file mode 100644
index 00000000..acab1a87
--- /dev/null
+++ b/solutions/2432-the-employee-that-worked-on-the-longest-task.js
@@ -0,0 +1,40 @@
+/**
+ * 2432. The Employee That Worked on the Longest Task
+ * https://leetcode.com/problems/the-employee-that-worked-on-the-longest-task/
+ * Difficulty: Easy
+ *
+ * There are n employees, each with a unique id from 0 to n - 1.
+ *
+ * You are given a 2D integer array logs where logs[i] = [idi, leaveTimei] where:
+ * - idi is the id of the employee that worked on the ith task, and
+ * - leaveTimei is the time at which the employee finished the ith task. All the values
+ *   leaveTimei are unique.
+ *
+ * Note that the ith task starts the moment right after the (i - 1)th task ends, and the 0th
+ * task starts at time 0.
+ *
+ * Return the id of the employee that worked the task with the longest time. If there is a tie
+ * between two or more employees, return the smallest id among them.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} logs
+ * @return {number}
+ */
+var hardestWorker = function(n, logs) {
+  let maxDuration = 0;
+  let result = n;
+  let startTime = 0;
+
+  for (const [employeeId, endTime] of logs) {
+    const duration = endTime - startTime;
+    if (duration > maxDuration || (duration === maxDuration && employeeId < result)) {
+      maxDuration = duration;
+      result = employeeId;
+    }
+    startTime = endTime;
+  }
+
+  return result;
+};

From dc7a1f8fc39b05945ae47d83655926e51d3e26e4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 19:08:50 -0500
Subject: [PATCH 438/495] Add solution #3068

---
 README.md                                     |  3 +-
 ...068-find-the-maximum-sum-of-node-values.js | 52 +++++++++++++++++++
 2 files changed, 54 insertions(+), 1 deletion(-)
 create mode 100644 solutions/3068-find-the-maximum-sum-of-node-values.js

diff --git a/README.md b/README.md
index 43b4a983..80d6f204 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,942 LeetCode solutions in JavaScript
+# 1,943 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1917,6 +1917,7 @@
 3024|[Type of Triangle](./solutions/3024-type-of-triangle.js)|Easy|
 3042|[Count Prefix and Suffix Pairs I](./solutions/3042-count-prefix-and-suffix-pairs-i.js)|Easy|
 3066|[Minimum Operations to Exceed Threshold Value II](./solutions/3066-minimum-operations-to-exceed-threshold-value-ii.js)|Medium|
+3068|[Find the Maximum Sum of Node Values](./solutions/3068-find-the-maximum-sum-of-node-values.js)|Hard|
 3105|[Longest Strictly Increasing or Strictly Decreasing Subarray](./solutions/3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js)|Easy|
 3108|[Minimum Cost Walk in Weighted Graph](./solutions/3108-minimum-cost-walk-in-weighted-graph.js)|Hard|
 3110|[Score of a String](./solutions/3110-score-of-a-string.js)|Easy|
diff --git a/solutions/3068-find-the-maximum-sum-of-node-values.js b/solutions/3068-find-the-maximum-sum-of-node-values.js
new file mode 100644
index 00000000..27666217
--- /dev/null
+++ b/solutions/3068-find-the-maximum-sum-of-node-values.js
@@ -0,0 +1,52 @@
+/**
+ * 3068. Find the Maximum Sum of Node Values
+ * https://leetcode.com/problems/find-the-maximum-sum-of-node-values/
+ * Difficulty: Hard
+ *
+ * There exists an undirected tree with n nodes numbered 0 to n - 1. You are given a 0-indexed
+ * 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an
+ * edge between nodes ui and vi in the tree. You are also given a positive integer k, and a
+ * 0-indexed array of non-negative integers nums of length n, where nums[i] represents the
+ * value of the node numbered i.
+ *
+ * Alice wants the sum of values of tree nodes to be maximum, for which Alice can perform the
+ * following operation any number of times (including zero) on the tree:
+ * - Choose any edge [u, v] connecting the nodes u and v, and update their values as follows:
+ *   - nums[u] = nums[u] XOR k
+ *   - nums[v] = nums[v] XOR k
+ *
+ * Return the maximum possible sum of the values Alice can achieve by performing the operation
+ * any number of times.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @param {number[][]} edges
+ * @return {number}
+ */
+var maximumValueSum = function(nums, k, edges) {
+  let totalSum = 0;
+  let minChange = Infinity;
+  let changeCount = 0;
+
+  for (const num of nums) {
+    const xored = num ^ k;
+    const change = xored - num;
+
+    if (change > 0) {
+      totalSum += xored;
+      changeCount++;
+    } else {
+      totalSum += num;
+    }
+
+    minChange = Math.min(minChange, Math.abs(change));
+  }
+
+  if (changeCount % 2 === 0) {
+    return totalSum;
+  }
+
+  return totalSum - minChange;
+};

From ad8e3a88fd964ecbbdb07e1b4be9323a2d409a3a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 19:10:00 -0500
Subject: [PATCH 439/495] Add solution #2433

---
 README.md                                     |  3 +-
 ...3-find-the-original-array-of-prefix-xor.js | 28 +++++++++++++++++++
 2 files changed, 30 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2433-find-the-original-array-of-prefix-xor.js

diff --git a/README.md b/README.md
index 80d6f204..b1e8a5ae 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,943 LeetCode solutions in JavaScript
+# 1,944 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1835,6 +1835,7 @@
 2428|[Maximum Sum of an Hourglass](./solutions/2428-maximum-sum-of-an-hourglass.js)|Medium|
 2429|[Minimize XOR](./solutions/2429-minimize-xor.js)|Medium|
 2432|[The Employee That Worked on the Longest Task](./solutions/2432-the-employee-that-worked-on-the-longest-task.js)|Easy|
+2433|[Find The Original Array of Prefix Xor](./solutions/2433-find-the-original-array-of-prefix-xor.js)|Medium|
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
diff --git a/solutions/2433-find-the-original-array-of-prefix-xor.js b/solutions/2433-find-the-original-array-of-prefix-xor.js
new file mode 100644
index 00000000..0f41ebeb
--- /dev/null
+++ b/solutions/2433-find-the-original-array-of-prefix-xor.js
@@ -0,0 +1,28 @@
+/**
+ * 2433. Find The Original Array of Prefix Xor
+ * https://leetcode.com/problems/find-the-original-array-of-prefix-xor/
+ * Difficulty: Medium
+ *
+ * You are given an integer array pref of size n. Find and return the array arr of size
+ * n that satisfies:
+ * - pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].
+ *
+ * Note that ^ denotes the bitwise-xor operation.
+ *
+ * It can be proven that the answer is unique.
+ */
+
+/**
+ * @param {number[]} pref
+ * @return {number[]}
+ */
+var findArray = function(pref) {
+  const result = new Array(pref.length);
+  result[0] = pref[0];
+
+  for (let i = 1; i < pref.length; i++) {
+    result[i] = pref[i] ^ pref[i - 1];
+  }
+
+  return result;
+};

From d80c0b0d5926c7b59b83c2629f21e9e7cfd95b31 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 19:11:51 -0500
Subject: [PATCH 440/495] Add solution #2434

---
 README.md                                     |  3 +-
 ...t-the-lexicographically-smallest-string.js | 49 +++++++++++++++++++
 2 files changed, 51 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2434-using-a-robot-to-print-the-lexicographically-smallest-string.js

diff --git a/README.md b/README.md
index b1e8a5ae..183c5fe8 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,944 LeetCode solutions in JavaScript
+# 1,945 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1836,6 +1836,7 @@
 2429|[Minimize XOR](./solutions/2429-minimize-xor.js)|Medium|
 2432|[The Employee That Worked on the Longest Task](./solutions/2432-the-employee-that-worked-on-the-longest-task.js)|Easy|
 2433|[Find The Original Array of Prefix Xor](./solutions/2433-find-the-original-array-of-prefix-xor.js)|Medium|
+2434|[Using a Robot to Print the Lexicographically Smallest String](./solutions/2434-using-a-robot-to-print-the-lexicographically-smallest-string.js)|Medium|
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
diff --git a/solutions/2434-using-a-robot-to-print-the-lexicographically-smallest-string.js b/solutions/2434-using-a-robot-to-print-the-lexicographically-smallest-string.js
new file mode 100644
index 00000000..430e0fa6
--- /dev/null
+++ b/solutions/2434-using-a-robot-to-print-the-lexicographically-smallest-string.js
@@ -0,0 +1,49 @@
+/**
+ * 2434. Using a Robot to Print the Lexicographically Smallest String
+ * https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/
+ * Difficulty: Medium
+ *
+ * You are given a string s and a robot that currently holds an empty string t. Apply one of the
+ * following operations until s and t are both empty:
+ * - Remove the first character of a string s and give it to the robot. The robot will append
+ *   this character to the string t.
+ * - Remove the last character of a string t and give it to the robot. The robot will write
+ *   this character on paper.
+ *
+ * Return the lexicographically smallest string that can be written on the paper.
+ */
+
+/**
+ * @param {string} s
+ * @return {string}
+ */
+var robotWithString = function(s) {
+  const charCount = Array(26).fill(0);
+  for (const char of s) {
+    charCount[char.charCodeAt(0) - 97]++;
+  }
+
+  const stack = [];
+  let minCharIndex = 0;
+  let result = '';
+
+  for (const char of s) {
+    stack.push(char);
+    charCount[char.charCodeAt(0) - 97]--;
+
+    while (minCharIndex < 26 && charCount[minCharIndex] === 0) {
+      minCharIndex++;
+    }
+
+    while (stack.length
+      && (minCharIndex === 26 || stack[stack.length - 1].charCodeAt(0) - 97 <= minCharIndex)) {
+      result += stack.pop();
+    }
+  }
+
+  while (stack.length) {
+    result += stack.pop();
+  }
+
+  return result;
+};

From e433db16b8717733764dd9db0820763ce1a2ff41 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 22:03:24 -0500
Subject: [PATCH 441/495] Add solution #2435

---
 README.md                                     |  3 +-
 ...s-in-matrix-whose-sum-is-divisible-by-k.js | 45 +++++++++++++++++++
 2 files changed, 47 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2435-paths-in-matrix-whose-sum-is-divisible-by-k.js

diff --git a/README.md b/README.md
index 183c5fe8..fc3f3772 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,945 LeetCode solutions in JavaScript
+# 1,946 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1837,6 +1837,7 @@
 2432|[The Employee That Worked on the Longest Task](./solutions/2432-the-employee-that-worked-on-the-longest-task.js)|Easy|
 2433|[Find The Original Array of Prefix Xor](./solutions/2433-find-the-original-array-of-prefix-xor.js)|Medium|
 2434|[Using a Robot to Print the Lexicographically Smallest String](./solutions/2434-using-a-robot-to-print-the-lexicographically-smallest-string.js)|Medium|
+2435|[Paths in Matrix Whose Sum Is Divisible by K](./solutions/2435-paths-in-matrix-whose-sum-is-divisible-by-k.js)|Hard|
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
diff --git a/solutions/2435-paths-in-matrix-whose-sum-is-divisible-by-k.js b/solutions/2435-paths-in-matrix-whose-sum-is-divisible-by-k.js
new file mode 100644
index 00000000..741526c7
--- /dev/null
+++ b/solutions/2435-paths-in-matrix-whose-sum-is-divisible-by-k.js
@@ -0,0 +1,45 @@
+/**
+ * 2435. Paths in Matrix Whose Sum Is Divisible by K
+ * https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed m x n integer matrix grid and an integer k. You are currently at
+ * position (0, 0) and you want to reach position (m - 1, n - 1) moving only down or right.
+ *
+ * Return the number of paths where the sum of the elements on the path is divisible by k.
+ * Since the answer may be very large, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @param {number} k
+ * @return {number}
+ */
+var numberOfPaths = function(grid, k) {
+  const rows = grid.length;
+  const cols = grid[0].length;
+  const modulo = 1e9 + 7;
+  const dp = Array.from({ length: rows }, () => {
+    return Array.from({ length: cols }, () => Array(k).fill(0));
+  });
+
+  dp[0][0][grid[0][0] % k] = 1;
+
+  for (let row = 0; row < rows; row++) {
+    for (let col = 0; col < cols; col++) {
+      const currentValue = grid[row][col] % k;
+      for (let sum = 0; sum < k; sum++) {
+        if (row > 0) {
+          const prevSum = (sum - currentValue + k) % k;
+          dp[row][col][sum] = (dp[row][col][sum] + dp[row - 1][col][prevSum]) % modulo;
+        }
+        if (col > 0) {
+          const prevSum = (sum - currentValue + k) % k;
+          dp[row][col][sum] = (dp[row][col][sum] + dp[row][col - 1][prevSum]) % modulo;
+        }
+      }
+    }
+  }
+
+  return dp[rows - 1][cols - 1][0];
+};

From b9c1752d29a80e6033158a2bf785fcf3d8360c55 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 22:05:55 -0500
Subject: [PATCH 442/495] Add solution #2437

---
 README.md                                     |  3 +-
 solutions/2437-number-of-valid-clock-times.js | 42 +++++++++++++++++++
 2 files changed, 44 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2437-number-of-valid-clock-times.js

diff --git a/README.md b/README.md
index fc3f3772..cf618fe1 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,946 LeetCode solutions in JavaScript
+# 1,947 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1838,6 +1838,7 @@
 2433|[Find The Original Array of Prefix Xor](./solutions/2433-find-the-original-array-of-prefix-xor.js)|Medium|
 2434|[Using a Robot to Print the Lexicographically Smallest String](./solutions/2434-using-a-robot-to-print-the-lexicographically-smallest-string.js)|Medium|
 2435|[Paths in Matrix Whose Sum Is Divisible by K](./solutions/2435-paths-in-matrix-whose-sum-is-divisible-by-k.js)|Hard|
+2437|[Number of Valid Clock Times](./solutions/2437-number-of-valid-clock-times.js)|Easy|
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
diff --git a/solutions/2437-number-of-valid-clock-times.js b/solutions/2437-number-of-valid-clock-times.js
new file mode 100644
index 00000000..8b4d26bb
--- /dev/null
+++ b/solutions/2437-number-of-valid-clock-times.js
@@ -0,0 +1,42 @@
+/**
+ * 2437. Number of Valid Clock Times
+ * https://leetcode.com/problems/number-of-valid-clock-times/
+ * Difficulty: Easy
+ *
+ * You are given a string of length 5 called time, representing the current time on a digital
+ * clock in the format "hh:mm". The earliest possible time is "00:00" and the latest possible
+ * time is "23:59".
+ *
+ * In the string time, the digits represented by the ? symbol are unknown, and must be replaced
+ * with a digit from 0 to 9.
+ *
+ * Return an integer answer, the number of valid clock times that can be created by replacing
+ * every ? with a digit from 0 to 9.
+ */
+
+/**
+ * @param {string} time
+ * @return {number}
+ */
+var countTime = function(time) {
+  let hourChoices = 1;
+  let minuteChoices = 1;
+
+  if (time[0] === '?' && time[1] === '?') {
+    hourChoices = 24;
+  } else if (time[0] === '?') {
+    hourChoices = time[1] <= '3' ? 3 : 2;
+  } else if (time[1] === '?') {
+    hourChoices = time[0] === '2' ? 4 : 10;
+  }
+
+  if (time[3] === '?' && time[4] === '?') {
+    minuteChoices = 60;
+  } else if (time[3] === '?') {
+    minuteChoices = 6;
+  } else if (time[4] === '?') {
+    minuteChoices = 10;
+  }
+
+  return hourChoices * minuteChoices;
+};

From 11b057e2ff1b1cea398436abede73dd1cd361c16 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 22:07:04 -0500
Subject: [PATCH 443/495] Add solution #2438

---
 README.md                                     |  3 +-
 .../2438-range-product-queries-of-powers.js   | 45 +++++++++++++++++++
 2 files changed, 47 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2438-range-product-queries-of-powers.js

diff --git a/README.md b/README.md
index cf618fe1..d11dad8b 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,947 LeetCode solutions in JavaScript
+# 1,948 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1839,6 +1839,7 @@
 2434|[Using a Robot to Print the Lexicographically Smallest String](./solutions/2434-using-a-robot-to-print-the-lexicographically-smallest-string.js)|Medium|
 2435|[Paths in Matrix Whose Sum Is Divisible by K](./solutions/2435-paths-in-matrix-whose-sum-is-divisible-by-k.js)|Hard|
 2437|[Number of Valid Clock Times](./solutions/2437-number-of-valid-clock-times.js)|Easy|
+2438|[Range Product Queries of Powers](./solutions/2438-range-product-queries-of-powers.js)|Medium|
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
diff --git a/solutions/2438-range-product-queries-of-powers.js b/solutions/2438-range-product-queries-of-powers.js
new file mode 100644
index 00000000..ebebead8
--- /dev/null
+++ b/solutions/2438-range-product-queries-of-powers.js
@@ -0,0 +1,45 @@
+/**
+ * 2438. Range Product Queries of Powers
+ * https://leetcode.com/problems/range-product-queries-of-powers/
+ * Difficulty: Medium
+ *
+ * Given a positive integer n, there exists a 0-indexed array called powers, composed of the
+ * minimum number of powers of 2 that sum to n. The array is sorted in non-decreasing order,
+ * and there is only one way to form the array.
+ *
+ * You are also given a 0-indexed 2D integer array queries, where queries[i] = [lefti, righti].
+ * Each queries[i] represents a query where you have to find the product of all powers[j] with
+ * lefti <= j <= righti.
+ *
+ * Return an array answers, equal in length to queries, where answers[i] is the answer to the
+ * ith query. Since the answer to the ith query may be too large, each answers[i] should be
+ * returned modulo 109 + 7.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} queries
+ * @return {number[]}
+ */
+var productQueries = function(n, queries) {
+  const modulo = 1e9 + 7;
+  const powers = [];
+  while (n > 0) {
+    const power = Math.floor(Math.log2(n));
+    powers.push(1 << power);
+    n -= 1 << power;
+  }
+  powers.reverse();
+
+  const result = new Array(queries.length);
+  for (let i = 0; i < queries.length; i++) {
+    const [start, end] = queries[i];
+    let product = 1;
+    for (let j = start; j <= end; j++) {
+      product = (product * powers[j]) % modulo;
+    }
+    result[i] = product;
+  }
+
+  return result;
+};

From 770ed7cdebc786ef7a51b25b882673339aa108bd Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 22:08:04 -0500
Subject: [PATCH 444/495] Add solution #2439

---
 README.md                                   |  3 +-
 solutions/2439-minimize-maximum-of-array.js | 53 +++++++++++++++++++++
 2 files changed, 55 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2439-minimize-maximum-of-array.js

diff --git a/README.md b/README.md
index d11dad8b..40a8c7fc 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,948 LeetCode solutions in JavaScript
+# 1,949 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1840,6 +1840,7 @@
 2435|[Paths in Matrix Whose Sum Is Divisible by K](./solutions/2435-paths-in-matrix-whose-sum-is-divisible-by-k.js)|Hard|
 2437|[Number of Valid Clock Times](./solutions/2437-number-of-valid-clock-times.js)|Easy|
 2438|[Range Product Queries of Powers](./solutions/2438-range-product-queries-of-powers.js)|Medium|
+2439|[Minimize Maximum of Array](./solutions/2439-minimize-maximum-of-array.js)|Medium|
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
diff --git a/solutions/2439-minimize-maximum-of-array.js b/solutions/2439-minimize-maximum-of-array.js
new file mode 100644
index 00000000..5d147f37
--- /dev/null
+++ b/solutions/2439-minimize-maximum-of-array.js
@@ -0,0 +1,53 @@
+/**
+ * 2439. Minimize Maximum of Array
+ * https://leetcode.com/problems/minimize-maximum-of-array/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array nums comprising of n non-negative integers.
+ *
+ * In one operation, you must:
+ * - Choose an integer i such that 1 <= i < n and nums[i] > 0.
+ * - Decrease nums[i] by 1.
+ * - Increase nums[i - 1] by 1.
+ *
+ * Return the minimum possible value of the maximum integer of nums after performing
+ * any number of operations.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimizeArrayValue = function(nums) {
+  let left = 0;
+  let right = Math.max(...nums);
+  let result = right;
+
+  while (left <= right) {
+    const mid = Math.floor((left + right) / 2);
+    let carry = 0;
+    let valid = true;
+
+    for (let i = nums.length - 1; i >= 0; i--) {
+      const total = nums[i] + carry;
+      if (total > mid) {
+        if (i === 0) {
+          valid = false;
+          break;
+        }
+        carry = total - mid;
+      } else {
+        carry = 0;
+      }
+    }
+
+    if (valid) {
+      result = mid;
+      right = mid - 1;
+    } else {
+      left = mid + 1;
+    }
+  }
+
+  return result;
+};

From cd8ab2b7487267d2b29136ecb66ca84867c2c9ac Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 22 May 2025 22:09:17 -0500
Subject: [PATCH 445/495] Add solution #2440

---
 README.md                                     |  3 +-
 .../2440-create-components-with-same-value.js | 64 +++++++++++++++++++
 2 files changed, 66 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2440-create-components-with-same-value.js

diff --git a/README.md b/README.md
index 40a8c7fc..e63f8d99 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,949 LeetCode solutions in JavaScript
+# 1,950 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1841,6 +1841,7 @@
 2437|[Number of Valid Clock Times](./solutions/2437-number-of-valid-clock-times.js)|Easy|
 2438|[Range Product Queries of Powers](./solutions/2438-range-product-queries-of-powers.js)|Medium|
 2439|[Minimize Maximum of Array](./solutions/2439-minimize-maximum-of-array.js)|Medium|
+2440|[Create Components With Same Value](./solutions/2440-create-components-with-same-value.js)|Hard|
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
diff --git a/solutions/2440-create-components-with-same-value.js b/solutions/2440-create-components-with-same-value.js
new file mode 100644
index 00000000..d0a6391f
--- /dev/null
+++ b/solutions/2440-create-components-with-same-value.js
@@ -0,0 +1,64 @@
+/**
+ * 2440. Create Components With Same Value
+ * https://leetcode.com/problems/create-components-with-same-value/
+ * Difficulty: Hard
+ *
+ * There is an undirected tree with n nodes labeled from 0 to n - 1.
+ *
+ * You are given a 0-indexed integer array nums of length n where nums[i] represents the value
+ * of the ith node. You are also 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.
+ *
+ * You are allowed to delete some edges, splitting the tree into multiple connected components.
+ * Let the value of a component be the sum of all nums[i] for which node i is in the component.
+ *
+ * Return the maximum number of edges you can delete, such that every connected component in
+ * the tree has the same value.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[][]} edges
+ * @return {number}
+ */
+var componentValue = function(nums, edges) {
+  const n = nums.length;
+  const graph = Array.from({ length: n }, () => []);
+  const totalSum = nums.reduce((sum, val) => sum + val, 0);
+
+  for (const [u, v] of edges) {
+    graph[u].push(v);
+    graph[v].push(u);
+  }
+
+  for (let i = n; i >= 1; i--) {
+    if (totalSum % i === 0) {
+      const target = totalSum / i;
+      const [, components] = countNodes(0, -1, target);
+      if (components === i) {
+        return i - 1;
+      }
+    }
+  }
+
+  return 0;
+
+  function countNodes(node, parent, target) {
+    let sum = nums[node];
+    let components = 0;
+
+    for (const neighbor of graph[node]) {
+      if (neighbor !== parent) {
+        const [childSum, childComponents] = countNodes(neighbor, node, target);
+        sum += childSum;
+        components += childComponents;
+      }
+    }
+
+    if (sum === target) {
+      return [0, components + 1];
+    }
+
+    return [sum, components];
+  }
+};

From ab77bf6f0472c42f8f0446dbddf60d8f3371fef6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 00:18:43 -0500
Subject: [PATCH 446/495] Add solution #2441

---
 README.md                                     |  3 +-
 ...e-integer-that-exists-with-its-negative.js | 28 +++++++++++++++++++
 2 files changed, 30 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2441-largest-positive-integer-that-exists-with-its-negative.js

diff --git a/README.md b/README.md
index e63f8d99..c2030a16 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,950 LeetCode solutions in JavaScript
+# 1,951 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1842,6 +1842,7 @@
 2438|[Range Product Queries of Powers](./solutions/2438-range-product-queries-of-powers.js)|Medium|
 2439|[Minimize Maximum of Array](./solutions/2439-minimize-maximum-of-array.js)|Medium|
 2440|[Create Components With Same Value](./solutions/2440-create-components-with-same-value.js)|Hard|
+2441|[Largest Positive Integer That Exists With Its Negative](./solutions/2441-largest-positive-integer-that-exists-with-its-negative.js)|Easy|
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
diff --git a/solutions/2441-largest-positive-integer-that-exists-with-its-negative.js b/solutions/2441-largest-positive-integer-that-exists-with-its-negative.js
new file mode 100644
index 00000000..e80f0ac9
--- /dev/null
+++ b/solutions/2441-largest-positive-integer-that-exists-with-its-negative.js
@@ -0,0 +1,28 @@
+/**
+ * 2441. Largest Positive Integer That Exists With Its Negative
+ * https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/
+ * Difficulty: Easy
+ *
+ * Given an integer array nums that does not contain any zeros, find the largest positive
+ * integer k such that -k also exists in the array.
+ *
+ * Return the positive integer k. If there is no such integer, return -1.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var findMaxK = function(nums) {
+  const set = new Set();
+  let result = -1;
+
+  for (const num of nums) {
+    if (set.has(-num)) {
+      result = Math.max(result, Math.abs(num));
+    }
+    set.add(num);
+  }
+
+  return result;
+};

From 27c675b4f6df1f17ef893c069e5a5e903287cddc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 00:19:42 -0500
Subject: [PATCH 447/495] Add solution #2442

---
 README.md                                     |  3 +-
 ...tinct-integers-after-reverse-operations.js | 32 +++++++++++++++++++
 2 files changed, 34 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2442-count-number-of-distinct-integers-after-reverse-operations.js

diff --git a/README.md b/README.md
index c2030a16..ec4a6e14 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,951 LeetCode solutions in JavaScript
+# 1,952 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1843,6 +1843,7 @@
 2439|[Minimize Maximum of Array](./solutions/2439-minimize-maximum-of-array.js)|Medium|
 2440|[Create Components With Same Value](./solutions/2440-create-components-with-same-value.js)|Hard|
 2441|[Largest Positive Integer That Exists With Its Negative](./solutions/2441-largest-positive-integer-that-exists-with-its-negative.js)|Easy|
+2442|[Count Number of Distinct Integers After Reverse Operations](./solutions/2442-count-number-of-distinct-integers-after-reverse-operations.js)|Medium|
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
diff --git a/solutions/2442-count-number-of-distinct-integers-after-reverse-operations.js b/solutions/2442-count-number-of-distinct-integers-after-reverse-operations.js
new file mode 100644
index 00000000..d1cc0abd
--- /dev/null
+++ b/solutions/2442-count-number-of-distinct-integers-after-reverse-operations.js
@@ -0,0 +1,32 @@
+/**
+ * 2442. Count Number of Distinct Integers After Reverse Operations
+ * https://leetcode.com/problems/count-number-of-distinct-integers-after-reverse-operations/
+ * Difficulty: Medium
+ *
+ * You are given an array nums consisting of positive integers.
+ *
+ * You have to take each integer in the array, reverse its digits, and add it to the end of the
+ * array. You should apply this operation to the original integers in nums.
+ *
+ * Return the number of distinct integers in the final array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var countDistinctIntegers = function(nums) {
+  const set = new Set(nums);
+
+  for (const num of nums) {
+    let reversed = 0;
+    let temp = num;
+    while (temp > 0) {
+      reversed = reversed * 10 + temp % 10;
+      temp = Math.floor(temp / 10);
+    }
+    set.add(reversed);
+  }
+
+  return set.size;
+};

From 9b1871da67230c419e06254637200dc7b65b09b5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 00:20:57 -0500
Subject: [PATCH 448/495] Add solution #2443

---
 README.md                                     |  3 +-
 .../2443-sum-of-number-and-its-reverse.js     | 28 +++++++++++++++++++
 2 files changed, 30 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2443-sum-of-number-and-its-reverse.js

diff --git a/README.md b/README.md
index ec4a6e14..31544f21 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,952 LeetCode solutions in JavaScript
+# 1,953 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1844,6 +1844,7 @@
 2440|[Create Components With Same Value](./solutions/2440-create-components-with-same-value.js)|Hard|
 2441|[Largest Positive Integer That Exists With Its Negative](./solutions/2441-largest-positive-integer-that-exists-with-its-negative.js)|Easy|
 2442|[Count Number of Distinct Integers After Reverse Operations](./solutions/2442-count-number-of-distinct-integers-after-reverse-operations.js)|Medium|
+2443|[Sum of Number and Its Reverse](./solutions/2443-sum-of-number-and-its-reverse.js)|Medium|
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
diff --git a/solutions/2443-sum-of-number-and-its-reverse.js b/solutions/2443-sum-of-number-and-its-reverse.js
new file mode 100644
index 00000000..7e17944a
--- /dev/null
+++ b/solutions/2443-sum-of-number-and-its-reverse.js
@@ -0,0 +1,28 @@
+/**
+ * 2443. Sum of Number and Its Reverse
+ * https://leetcode.com/problems/sum-of-number-and-its-reverse/
+ * Difficulty: Medium
+ *
+ * Given a non-negative integer num, return true if num can be expressed as the sum of any
+ * non-negative integer and its reverse, or false otherwise.
+ */
+
+/**
+ * @param {number} num
+ * @return {boolean}
+ */
+var sumOfNumberAndReverse = function(num) {
+  for (let i = 0; i <= num; i++) {
+    let reversed = 0;
+    let temp = i;
+    while (temp > 0) {
+      reversed = reversed * 10 + temp % 10;
+      temp = Math.floor(temp / 10);
+    }
+    if (i + reversed === num) {
+      return true;
+    }
+  }
+
+  return false;
+};

From 25cf456fbee5377395e8137372192b4215c17492 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 00:21:59 -0500
Subject: [PATCH 449/495] Add solution #2446

---
 README.md                                     |  3 +-
 ...6-determine-if-two-events-have-conflict.js | 28 +++++++++++++++++++
 2 files changed, 30 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2446-determine-if-two-events-have-conflict.js

diff --git a/README.md b/README.md
index 31544f21..9f7aa368 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,953 LeetCode solutions in JavaScript
+# 1,954 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1846,6 +1846,7 @@
 2442|[Count Number of Distinct Integers After Reverse Operations](./solutions/2442-count-number-of-distinct-integers-after-reverse-operations.js)|Medium|
 2443|[Sum of Number and Its Reverse](./solutions/2443-sum-of-number-and-its-reverse.js)|Medium|
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
+2446|[Determine if Two Events Have Conflict](./solutions/2446-determine-if-two-events-have-conflict.js)|Easy|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
 2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium|
diff --git a/solutions/2446-determine-if-two-events-have-conflict.js b/solutions/2446-determine-if-two-events-have-conflict.js
new file mode 100644
index 00000000..3a70a834
--- /dev/null
+++ b/solutions/2446-determine-if-two-events-have-conflict.js
@@ -0,0 +1,28 @@
+/**
+ * 2446. Determine if Two Events Have Conflict
+ * https://leetcode.com/problems/determine-if-two-events-have-conflict/
+ * Difficulty: Easy
+ *
+ * You are given two arrays of strings that represent two inclusive events that happened on the
+ * same day, event1 and event2, where:
+ * - event1 = [startTime1, endTime1] and
+ * - event2 = [startTime2, endTime2].
+ *
+ * Event times are valid 24 hours format in the form of HH:MM.
+ *
+ * A conflict happens when two events have some non-empty intersection (i.e., some moment is common
+ * to both events).
+ *
+ * Return true if there is a conflict between two events. Otherwise, return false.
+ */
+
+/**
+ * @param {string[]} event1
+ * @param {string[]} event2
+ * @return {boolean}
+ */
+var haveConflict = function(event1, event2) {
+  const [start1, end1] = event1;
+  const [start2, end2] = event2;
+  return start1 <= end2 && start2 <= end1;
+};

From 0d50f5939d46ba5dde51878f5937ea07dcd7639a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 00:23:08 -0500
Subject: [PATCH 450/495] Add solution #2447

---
 README.md                                     |  3 +-
 ...number-of-subarrays-with-gcd-equal-to-k.js | 41 +++++++++++++++++++
 2 files changed, 43 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2447-number-of-subarrays-with-gcd-equal-to-k.js

diff --git a/README.md b/README.md
index 9f7aa368..13a53b4e 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,954 LeetCode solutions in JavaScript
+# 1,955 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1847,6 +1847,7 @@
 2443|[Sum of Number and Its Reverse](./solutions/2443-sum-of-number-and-its-reverse.js)|Medium|
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
 2446|[Determine if Two Events Have Conflict](./solutions/2446-determine-if-two-events-have-conflict.js)|Easy|
+2447|[Number of Subarrays With GCD Equal to K](./solutions/2447-number-of-subarrays-with-gcd-equal-to-k.js)|Medium|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
 2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium|
diff --git a/solutions/2447-number-of-subarrays-with-gcd-equal-to-k.js b/solutions/2447-number-of-subarrays-with-gcd-equal-to-k.js
new file mode 100644
index 00000000..efc4339c
--- /dev/null
+++ b/solutions/2447-number-of-subarrays-with-gcd-equal-to-k.js
@@ -0,0 +1,41 @@
+/**
+ * 2447. Number of Subarrays With GCD Equal to K
+ * https://leetcode.com/problems/number-of-subarrays-with-gcd-equal-to-k/
+ * Difficulty: Medium
+ *
+ * Given an integer array nums and an integer k, return the number of subarrays of nums where
+ * the greatest common divisor of the subarray's elements is k.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ *
+ * The greatest common divisor of an array is the largest integer that evenly divides all the
+ * array elements.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var subarrayGCD = function(nums, k) {
+  let result = 0;
+  for (let start = 0; start < nums.length; start++) {
+    let currentGCD = nums[start];
+    for (let end = start; end < nums.length; end++) {
+      currentGCD = gcd(currentGCD, nums[end]);
+      if (currentGCD === k) {
+        result++;
+      }
+    }
+  }
+
+  return result;
+
+  function gcd(a, b) {
+    while (b) {
+      a %= b;
+      [a, b] = [b, a];
+    }
+    return a;
+  }
+};

From 90acab560a1f75f46fe5f2df072757a153d9f7df Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 00:24:32 -0500
Subject: [PATCH 451/495] Add solution #2448

---
 README.md                                     |  3 +-
 .../2448-minimum-cost-to-make-array-equal.js  | 45 +++++++++++++++++++
 2 files changed, 47 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2448-minimum-cost-to-make-array-equal.js

diff --git a/README.md b/README.md
index 13a53b4e..defa0dd6 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,955 LeetCode solutions in JavaScript
+# 1,956 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1848,6 +1848,7 @@
 2444|[Count Subarrays With Fixed Bounds](./solutions/2444-count-subarrays-with-fixed-bounds.js)|Hard|
 2446|[Determine if Two Events Have Conflict](./solutions/2446-determine-if-two-events-have-conflict.js)|Easy|
 2447|[Number of Subarrays With GCD Equal to K](./solutions/2447-number-of-subarrays-with-gcd-equal-to-k.js)|Medium|
+2448|[Minimum Cost to Make Array Equal](./solutions/2448-minimum-cost-to-make-array-equal.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
 2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium|
diff --git a/solutions/2448-minimum-cost-to-make-array-equal.js b/solutions/2448-minimum-cost-to-make-array-equal.js
new file mode 100644
index 00000000..1bf9d6fd
--- /dev/null
+++ b/solutions/2448-minimum-cost-to-make-array-equal.js
@@ -0,0 +1,45 @@
+/**
+ * 2448. Minimum Cost to Make Array Equal
+ * https://leetcode.com/problems/minimum-cost-to-make-array-equal/
+ * Difficulty: Hard
+ *
+ * You are given two 0-indexed arrays nums and cost consisting each of n positive integers.
+ *
+ * You can do the following operation any number of times:
+ * - Increase or decrease any element of the array nums by 1.
+ *
+ * The cost of doing one operation on the ith element is cost[i].
+ *
+ * Return the minimum total cost such that all the elements of the array nums become equal.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[]} cost
+ * @return {number}
+ */
+var minCost = function(nums, cost) {
+  const pairs = nums.map((num, i) => [num, cost[i]]).sort((a, b) => a[0] - b[0]);
+  const n = nums.length;
+  const prefixSum = Array(n).fill(0);
+  const prefixCost = Array(n).fill(0);
+
+  prefixSum[0] = pairs[0][0] * pairs[0][1];
+  prefixCost[0] = pairs[0][1];
+
+  for (let i = 1; i < n; i++) {
+    prefixSum[i] = prefixSum[i - 1] + pairs[i][0] * pairs[i][1];
+    prefixCost[i] = prefixCost[i - 1] + pairs[i][1];
+  }
+
+  let result = Infinity;
+  for (let i = 0; i < n; i++) {
+    const target = pairs[i][0];
+    const leftCost = i > 0 ? target * prefixCost[i - 1] - prefixSum[i - 1] : 0;
+    const rightCost = i < n - 1 ? prefixSum[n - 1] - prefixSum[i]
+      - target * (prefixCost[n - 1] - prefixCost[i]) : 0;
+    result = Math.min(result, leftCost + rightCost);
+  }
+
+  return result;
+};

From 868a948d1cee184a72c211aab0e5f3de51802b71 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 00:28:46 -0500
Subject: [PATCH 452/495] Add solution #2449

---
 README.md                                     |  3 +-
 ...er-of-operations-to-make-arrays-similar.js | 44 +++++++++++++++++++
 2 files changed, 46 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2449-minimum-number-of-operations-to-make-arrays-similar.js

diff --git a/README.md b/README.md
index defa0dd6..3b2952a9 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,956 LeetCode solutions in JavaScript
+# 1,957 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1849,6 +1849,7 @@
 2446|[Determine if Two Events Have Conflict](./solutions/2446-determine-if-two-events-have-conflict.js)|Easy|
 2447|[Number of Subarrays With GCD Equal to K](./solutions/2447-number-of-subarrays-with-gcd-equal-to-k.js)|Medium|
 2448|[Minimum Cost to Make Array Equal](./solutions/2448-minimum-cost-to-make-array-equal.js)|Hard|
+2449|[Minimum Number of Operations to Make Arrays Similar](./solutions/2449-minimum-number-of-operations-to-make-arrays-similar.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
 2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium|
diff --git a/solutions/2449-minimum-number-of-operations-to-make-arrays-similar.js b/solutions/2449-minimum-number-of-operations-to-make-arrays-similar.js
new file mode 100644
index 00000000..29c2cacf
--- /dev/null
+++ b/solutions/2449-minimum-number-of-operations-to-make-arrays-similar.js
@@ -0,0 +1,44 @@
+/**
+ * 2449. Minimum Number of Operations to Make Arrays Similar
+ * https://leetcode.com/problems/minimum-number-of-operations-to-make-arrays-similar/
+ * Difficulty: Hard
+ *
+ * You are given two positive integer arrays nums and target, of the same length.
+ *
+ * In one operation, you can choose any two distinct indices i and j where 0 <= i,
+ * j < nums.length and:
+ * - set nums[i] = nums[i] + 2 and
+ * - set nums[j] = nums[j] - 2.
+ *
+ * Two arrays are considered to be similar if the frequency of each element is the same.
+ *
+ * Return the minimum number of operations required to make nums similar to target. The
+ * test cases are generated such that nums can always be similar to target.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[]} target
+ * @return {number}
+ */
+var makeSimilar = function(nums, target) {
+  const evenNums = nums.filter(num => num % 2 === 0).sort((a, b) => a - b);
+  const oddNums = nums.filter(num => num % 2 === 1).sort((a, b) => a - b);
+  const evenTarget = target.filter(num => num % 2 === 0).sort((a, b) => a - b);
+  const oddTarget = target.filter(num => num % 2 === 1).sort((a, b) => a - b);
+
+  let result = 0;
+  for (let i = 0; i < evenNums.length; i++) {
+    if (evenNums[i] > evenTarget[i]) {
+      result += (evenNums[i] - evenTarget[i]) / 2;
+    }
+  }
+
+  for (let i = 0; i < oddNums.length; i++) {
+    if (oddNums[i] > oddTarget[i]) {
+      result += (oddNums[i] - oddTarget[i]) / 2;
+    }
+  }
+
+  return result;
+};

From 500c5fd929257612ba720ebcbd7a5c3905d05ff2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 00:30:29 -0500
Subject: [PATCH 453/495] Add solution #2451

---
 README.md                               |  3 +-
 solutions/2451-odd-string-difference.js | 53 +++++++++++++++++++++++++
 2 files changed, 55 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2451-odd-string-difference.js

diff --git a/README.md b/README.md
index 3b2952a9..c5f530b2 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,957 LeetCode solutions in JavaScript
+# 1,958 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1850,6 +1850,7 @@
 2447|[Number of Subarrays With GCD Equal to K](./solutions/2447-number-of-subarrays-with-gcd-equal-to-k.js)|Medium|
 2448|[Minimum Cost to Make Array Equal](./solutions/2448-minimum-cost-to-make-array-equal.js)|Hard|
 2449|[Minimum Number of Operations to Make Arrays Similar](./solutions/2449-minimum-number-of-operations-to-make-arrays-similar.js)|Hard|
+2451|[Odd String Difference](./solutions/2451-odd-string-difference.js)|Easy|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
 2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium|
diff --git a/solutions/2451-odd-string-difference.js b/solutions/2451-odd-string-difference.js
new file mode 100644
index 00000000..8556415c
--- /dev/null
+++ b/solutions/2451-odd-string-difference.js
@@ -0,0 +1,53 @@
+/**
+ * 2451. Odd String Difference
+ * https://leetcode.com/problems/odd-string-difference/
+ * Difficulty: Easy
+ *
+ * You are given an array of equal-length strings words. Assume that the length of each
+ * string is n.
+ *
+ * Each string words[i] can be converted into a difference integer array difference[i] of
+ * length n - 1 where difference[i][j] = words[i][j+1] - words[i][j] where 0 <= j <= n - 2.
+ * Note that the difference between two letters is the difference between their positions in
+ * the alphabet i.e. the position of 'a' is 0, 'b' is 1, and 'z' is 25.
+ * - For example, for the string "acb", the difference integer array is [2 - 0, 1 - 2] = [2, -1].
+ *
+ * All the strings in words have the same difference integer array, except one. You should find
+ * that string.
+ *
+ * Return the string in words that has different difference integer array.
+ */
+
+/**
+ * @param {string[]} words
+ * @return {string}
+ */
+var oddString = function(words) {
+  const map = new Map();
+  for (const word of words) {
+    const diff = getDiff(word);
+    map.set(diff, (map.get(diff) || 0) + 1);
+  }
+
+  let oddDiff;
+  for (const [diff, count] of map) {
+    if (count === 1) {
+      oddDiff = diff;
+      break;
+    }
+  }
+
+  for (const word of words) {
+    if (getDiff(word) === oddDiff) {
+      return word;
+    }
+  }
+
+  function getDiff(word) {
+    const diff = [];
+    for (let i = 1; i < word.length; i++) {
+      diff.push(word.charCodeAt(i) - word.charCodeAt(i - 1));
+    }
+    return diff.join(',');
+  }
+};

From 72983738e6d848745bf5a9107e6a3627d40f26af Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 00:31:26 -0500
Subject: [PATCH 454/495] Add solution #2452

---
 README.md                                     |  3 +-
 ...52-words-within-two-edits-of-dictionary.js | 41 +++++++++++++++++++
 2 files changed, 43 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2452-words-within-two-edits-of-dictionary.js

diff --git a/README.md b/README.md
index c5f530b2..ff56b66b 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,958 LeetCode solutions in JavaScript
+# 1,959 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1851,6 +1851,7 @@
 2448|[Minimum Cost to Make Array Equal](./solutions/2448-minimum-cost-to-make-array-equal.js)|Hard|
 2449|[Minimum Number of Operations to Make Arrays Similar](./solutions/2449-minimum-number-of-operations-to-make-arrays-similar.js)|Hard|
 2451|[Odd String Difference](./solutions/2451-odd-string-difference.js)|Easy|
+2452|[Words Within Two Edits of Dictionary](./solutions/2452-words-within-two-edits-of-dictionary.js)|Medium|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
 2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium|
diff --git a/solutions/2452-words-within-two-edits-of-dictionary.js b/solutions/2452-words-within-two-edits-of-dictionary.js
new file mode 100644
index 00000000..237dac21
--- /dev/null
+++ b/solutions/2452-words-within-two-edits-of-dictionary.js
@@ -0,0 +1,41 @@
+/**
+ * 2452. Words Within Two Edits of Dictionary
+ * https://leetcode.com/problems/words-within-two-edits-of-dictionary/
+ * Difficulty: Medium
+ *
+ * You are given two string arrays, queries and dictionary. All words in each array comprise of
+ * lowercase English letters and have the same length.
+ *
+ * In one edit you can take a word from queries, and change any letter in it to any other letter.
+ * Find all words from queries that, after a maximum of two edits, equal some word from dictionary.
+ *
+ * Return a list of all words from queries, that match with some word from dictionary after a
+ * maximum of two edits. Return the words in the same order they appear in queries.
+ */
+
+/**
+ * @param {string[]} queries
+ * @param {string[]} dictionary
+ * @return {string[]}
+ */
+var twoEditWords = function(queries, dictionary) {
+  const result = [];
+
+  for (const query of queries) {
+    for (const word of dictionary) {
+      let edits = 0;
+      for (let i = 0; i < query.length; i++) {
+        if (query[i] !== word[i]) {
+          edits++;
+          if (edits > 2) break;
+        }
+      }
+      if (edits <= 2) {
+        result.push(query);
+        break;
+      }
+    }
+  }
+
+  return result;
+};

From 510a5650673479b89d4d80c90d00799a9f7fa21f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 00:32:38 -0500
Subject: [PATCH 455/495] Add solution #2453

---
 README.md                                    |  3 +-
 solutions/2453-destroy-sequential-targets.js | 40 ++++++++++++++++++++
 2 files changed, 42 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2453-destroy-sequential-targets.js

diff --git a/README.md b/README.md
index ff56b66b..d647a56a 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,959 LeetCode solutions in JavaScript
+# 1,960 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1852,6 +1852,7 @@
 2449|[Minimum Number of Operations to Make Arrays Similar](./solutions/2449-minimum-number-of-operations-to-make-arrays-similar.js)|Hard|
 2451|[Odd String Difference](./solutions/2451-odd-string-difference.js)|Easy|
 2452|[Words Within Two Edits of Dictionary](./solutions/2452-words-within-two-edits-of-dictionary.js)|Medium|
+2453|[Destroy Sequential Targets](./solutions/2453-destroy-sequential-targets.js)|Medium|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
 2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium|
diff --git a/solutions/2453-destroy-sequential-targets.js b/solutions/2453-destroy-sequential-targets.js
new file mode 100644
index 00000000..d1c9f856
--- /dev/null
+++ b/solutions/2453-destroy-sequential-targets.js
@@ -0,0 +1,40 @@
+/**
+ * 2453. Destroy Sequential Targets
+ * https://leetcode.com/problems/destroy-sequential-targets/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array nums consisting of positive integers, representing targets
+ * on a number line. You are also given an integer space.
+ *
+ * You have a machine which can destroy targets. Seeding the machine with some nums[i] allows
+ * it to destroy all targets with values that can be represented as nums[i] + c * space, where
+ * c is any non-negative integer. You want to destroy the maximum number of targets in nums.
+ *
+ * Return the minimum value of nums[i] you can seed the machine with to destroy the maximum
+ * number of targets.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} space
+ * @return {number}
+ */
+var destroyTargets = function(nums, space) {
+  const map = new Map();
+  let maxCount = 0;
+
+  for (const num of nums) {
+    const remainder = num % space;
+    map.set(remainder, (map.get(remainder) || 0) + 1);
+    maxCount = Math.max(maxCount, map.get(remainder));
+  }
+
+  let result = Infinity;
+  for (const num of nums) {
+    if (map.get(num % space) === maxCount) {
+      result = Math.min(result, num);
+    }
+  }
+
+  return result;
+};

From 04330081667c5066f6c8fc09160e8c742e851d57 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 09:53:47 -0500
Subject: [PATCH 456/495] Add solution #2455

---
 README.md                                     |  3 +-
 ...ven-numbers-that-are-divisible-by-three.js | 29 +++++++++++++++++++
 2 files changed, 31 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2455-average-value-of-even-numbers-that-are-divisible-by-three.js

diff --git a/README.md b/README.md
index d647a56a..1ff3b80d 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,960 LeetCode solutions in JavaScript
+# 1,961 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1853,6 +1853,7 @@
 2451|[Odd String Difference](./solutions/2451-odd-string-difference.js)|Easy|
 2452|[Words Within Two Edits of Dictionary](./solutions/2452-words-within-two-edits-of-dictionary.js)|Medium|
 2453|[Destroy Sequential Targets](./solutions/2453-destroy-sequential-targets.js)|Medium|
+2455|[Average Value of Even Numbers That Are Divisible by Three](./solutions/2455-average-value-of-even-numbers-that-are-divisible-by-three.js)|Easy|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
 2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium|
diff --git a/solutions/2455-average-value-of-even-numbers-that-are-divisible-by-three.js b/solutions/2455-average-value-of-even-numbers-that-are-divisible-by-three.js
new file mode 100644
index 00000000..e793e8fe
--- /dev/null
+++ b/solutions/2455-average-value-of-even-numbers-that-are-divisible-by-three.js
@@ -0,0 +1,29 @@
+/**
+ * 2455. Average Value of Even Numbers That Are Divisible by Three
+ * https://leetcode.com/problems/average-value-of-even-numbers-that-are-divisible-by-three/
+ * Difficulty: Easy
+ *
+ * Given an integer array nums of positive integers, return the average value of all even integers
+ * that are divisible by 3.
+ *
+ * Note that the average of n elements is the sum of the n elements divided by n and rounded down
+ * to the nearest integer.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var averageValue = function(nums) {
+  let sum = 0;
+  let count = 0;
+
+  for (const num of nums) {
+    if (num % 2 === 0 && num % 3 === 0) {
+      sum += num;
+      count++;
+    }
+  }
+
+  return count > 0 ? Math.floor(sum / count) : 0;
+};

From 6c997d4778eeb7fb58adf989e318cf82aaa04a47 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 09:56:18 -0500
Subject: [PATCH 457/495] Add solution #2458

---
 README.md                                     |  3 +-
 ...nary-tree-after-subtree-removal-queries.js | 68 +++++++++++++++++++
 2 files changed, 70 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2458-height-of-binary-tree-after-subtree-removal-queries.js

diff --git a/README.md b/README.md
index 1ff3b80d..64a2f07a 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,961 LeetCode solutions in JavaScript
+# 1,962 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1854,6 +1854,7 @@
 2452|[Words Within Two Edits of Dictionary](./solutions/2452-words-within-two-edits-of-dictionary.js)|Medium|
 2453|[Destroy Sequential Targets](./solutions/2453-destroy-sequential-targets.js)|Medium|
 2455|[Average Value of Even Numbers That Are Divisible by Three](./solutions/2455-average-value-of-even-numbers-that-are-divisible-by-three.js)|Easy|
+2458|[Height of Binary Tree After Subtree Removal Queries](./solutions/2458-height-of-binary-tree-after-subtree-removal-queries.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
 2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium|
diff --git a/solutions/2458-height-of-binary-tree-after-subtree-removal-queries.js b/solutions/2458-height-of-binary-tree-after-subtree-removal-queries.js
new file mode 100644
index 00000000..418ee0ff
--- /dev/null
+++ b/solutions/2458-height-of-binary-tree-after-subtree-removal-queries.js
@@ -0,0 +1,68 @@
+/**
+ * 2458. Height of Binary Tree After Subtree Removal Queries
+ * https://leetcode.com/problems/height-of-binary-tree-after-subtree-removal-queries/
+ * Difficulty: Hard
+ *
+ * You are given the root of a binary tree with n nodes. Each node is assigned a unique value
+ * from 1 to n. You are also given an array queries of size m.
+ *
+ * You have to perform m independent queries on the tree where in the ith query you do the
+ * following:
+ * - Remove the subtree rooted at the node with the value queries[i] from the tree. It is
+ *   guaranteed that queries[i] will not be equal to the value of the root.
+ *
+ * Return an array answer of size m where answer[i] is the height of the tree after performing
+ * the ith query.
+ *
+ * Note:
+ * - The queries are independent, so the tree returns to its initial state after each query.
+ * - The height of a tree is the number of edges in the longest simple path from the root to
+ *   some node 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[]} queries
+ * @return {number[]}
+ */
+var treeQueries = function(root, queries) {
+  const heights = new Map();
+  const maxHeightWithout = new Map();
+
+  computeHeight(root);
+  computeMaxHeight(root, 0, -1);
+
+  const result = new Array(queries.length);
+  for (let i = 0; i < queries.length; i++) {
+    result[i] = maxHeightWithout.get(queries[i]);
+  }
+
+  return result;
+
+  function computeHeight(node) {
+    if (!node) return -1;
+    const leftHeight = computeHeight(node.left);
+    const rightHeight = computeHeight(node.right);
+    heights.set(node.val, Math.max(leftHeight, rightHeight) + 1);
+    return heights.get(node.val);
+  }
+
+  function computeMaxHeight(node, depth, cousinHeight) {
+    if (!node) return;
+    const leftHeight = node.left ? heights.get(node.left.val) : -1;
+    const rightHeight = node.right ? heights.get(node.right.val) : -1;
+    const maxAlternative = Math.max(cousinHeight, depth - 1);
+    maxHeightWithout.set(node.val, maxAlternative);
+
+    computeMaxHeight(node.left, depth + 1, Math.max(cousinHeight, rightHeight + depth + 1));
+    computeMaxHeight(node.right, depth + 1, Math.max(cousinHeight, leftHeight + depth + 1));
+  }
+};

From fbed85a0fa57961fce2292e72f6a72974a76d6df Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 09:57:24 -0500
Subject: [PATCH 458/495] Add solution #2461

---
 README.md                                     |  3 +-
 ...sum-of-distinct-subarrays-with-length-k.js | 45 +++++++++++++++++++
 2 files changed, 47 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2461-maximum-sum-of-distinct-subarrays-with-length-k.js

diff --git a/README.md b/README.md
index 64a2f07a..5614d09c 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,962 LeetCode solutions in JavaScript
+# 1,963 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1856,6 +1856,7 @@
 2455|[Average Value of Even Numbers That Are Divisible by Three](./solutions/2455-average-value-of-even-numbers-that-are-divisible-by-three.js)|Easy|
 2458|[Height of Binary Tree After Subtree Removal Queries](./solutions/2458-height-of-binary-tree-after-subtree-removal-queries.js)|Hard|
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
+2461|[Maximum Sum of Distinct Subarrays With Length K](./solutions/2461-maximum-sum-of-distinct-subarrays-with-length-k.js)|Medium|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
 2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium|
 2469|[Convert the Temperature](./solutions/2469-convert-the-temperature.js)|Easy|
diff --git a/solutions/2461-maximum-sum-of-distinct-subarrays-with-length-k.js b/solutions/2461-maximum-sum-of-distinct-subarrays-with-length-k.js
new file mode 100644
index 00000000..a1212952
--- /dev/null
+++ b/solutions/2461-maximum-sum-of-distinct-subarrays-with-length-k.js
@@ -0,0 +1,45 @@
+/**
+ * 2461. Maximum Sum of Distinct Subarrays With Length K
+ * https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums and an integer k. Find the maximum subarray sum of all the
+ * subarrays of nums that meet the following conditions:
+ * - The length of the subarray is k, and
+ * - All the elements of the subarray are distinct.
+ *
+ * Return the maximum subarray sum of all the subarrays that meet the conditions. If no subarray
+ * meets the conditions, return 0.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var maximumSubarraySum = function(nums, k) {
+  let result = 0;
+  const seen = new Map();
+  let windowSum = 0;
+
+  for (let i = 0; i < nums.length; i++) {
+    seen.set(nums[i], (seen.get(nums[i]) || 0) + 1);
+    windowSum += nums[i];
+
+    if (i >= k - 1) {
+      if (seen.size === k) {
+        result = Math.max(result, windowSum);
+      }
+      const leftNum = nums[i - k + 1];
+      windowSum -= leftNum;
+      seen.set(leftNum, seen.get(leftNum) - 1);
+      if (seen.get(leftNum) === 0) {
+        seen.delete(leftNum);
+      }
+    }
+  }
+
+  return result;
+};

From 2f21fdd8abfb3020a0676a3adfe55eac799f24c2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 10:52:28 -0500
Subject: [PATCH 459/495] Add solution #2463

---
 README.md                                     |  3 +-
 .../2463-minimum-total-distance-traveled.js   | 71 +++++++++++++++++++
 2 files changed, 73 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2463-minimum-total-distance-traveled.js

diff --git a/README.md b/README.md
index 5614d09c..f7d97698 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,963 LeetCode solutions in JavaScript
+# 1,964 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1858,6 +1858,7 @@
 2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
 2461|[Maximum Sum of Distinct Subarrays With Length K](./solutions/2461-maximum-sum-of-distinct-subarrays-with-length-k.js)|Medium|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
+2463|[Minimum Total Distance Traveled](./solutions/2463-minimum-total-distance-traveled.js)|Hard|
 2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium|
 2469|[Convert the Temperature](./solutions/2469-convert-the-temperature.js)|Easy|
 2482|[Difference Between Ones and Zeros in Row and Column](./solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium|
diff --git a/solutions/2463-minimum-total-distance-traveled.js b/solutions/2463-minimum-total-distance-traveled.js
new file mode 100644
index 00000000..cb71bbc0
--- /dev/null
+++ b/solutions/2463-minimum-total-distance-traveled.js
@@ -0,0 +1,71 @@
+/**
+ * 2463. Minimum Total Distance Traveled
+ * https://leetcode.com/problems/minimum-total-distance-traveled/
+ * Difficulty: Hard
+ *
+ * There are some robots and factories on the X-axis. You are given an integer array robot where
+ * robot[i] is the position of the ith robot. You are also given a 2D integer array factory where
+ * factory[j] = [positionj, limitj] indicates that positionj is the position of the jth factory
+ * and that the jth factory can repair at most limitj robots.
+ *
+ * The positions of each robot are unique. The positions of each factory are also unique. Note
+ * that a robot can be in the same position as a factory initially.
+ *
+ * All the robots are initially broken; they keep moving in one direction. The direction could be
+ * the negative or the positive direction of the X-axis. When a robot reaches a factory that did
+ * not reach its limit, the factory repairs the robot, and it stops moving.
+ *
+ * At any moment, you can set the initial direction of moving for some robot. Your target is to
+ * minimize the total distance traveled by all the robots.
+ *
+ * Return the minimum total distance traveled by all the robots. The test cases are generated
+ * such that all the robots can be repaired.
+ *
+ * Note that:
+ * - All robots move at the same speed.
+ * - If two robots move in the same direction, they will never collide.
+ * - If two robots move in opposite directions and they meet at some point, they do not collide.
+ *   They cross each other.
+ * - If a robot passes by a factory that reached its limits, it crosses it as if it does not exist.
+ * - If the robot moved from a position x to a position y, the distance it moved is |y - x|.
+ */
+
+/**
+ * @param {number[]} robot
+ * @param {number[][]} factory
+ * @return {number}
+ */
+var minimumTotalDistance = function(robot, factory) {
+  robot.sort((a, b) => a - b);
+  factory.sort((a, b) => a[0] - b[0]);
+
+  const robotCount = robot.length;
+  const factoryCount = factory.length;
+  const memo = new Array(robotCount + 1).fill(null).map(() => new Array(factoryCount + 1).fill(-1));
+
+  return calculateMinDistance(0, 0);
+
+  function calculateMinDistance(robotIndex, factoryIndex) {
+    if (robotIndex === robotCount) return 0;
+    if (factoryIndex === factoryCount) return 1e18;
+
+    if (memo[robotIndex][factoryIndex] !== -1) {
+      return memo[robotIndex][factoryIndex];
+    }
+
+    let result = calculateMinDistance(robotIndex, factoryIndex + 1);
+
+    let totalDistance = 0;
+    for (let robotsTaken = 0; robotsTaken < factory[factoryIndex][1]
+         && robotIndex + robotsTaken < robotCount; robotsTaken++) {
+      totalDistance += Math.abs(robot[robotIndex + robotsTaken] - factory[factoryIndex][0]);
+      result = Math.min(
+        result,
+        totalDistance + calculateMinDistance(robotIndex + robotsTaken + 1, factoryIndex + 1)
+      );
+    }
+
+    memo[robotIndex][factoryIndex] = result;
+    return result;
+  }
+};

From 8e036a2ef91402c6a85d1b0ba903d9eb078748cd Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 10:53:39 -0500
Subject: [PATCH 460/495] Add solution #2465

---
 README.md                                     |  3 +-
 solutions/2465-number-of-distinct-averages.js | 34 +++++++++++++++++++
 2 files changed, 36 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2465-number-of-distinct-averages.js

diff --git a/README.md b/README.md
index f7d97698..1631b276 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,964 LeetCode solutions in JavaScript
+# 1,965 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1859,6 +1859,7 @@
 2461|[Maximum Sum of Distinct Subarrays With Length K](./solutions/2461-maximum-sum-of-distinct-subarrays-with-length-k.js)|Medium|
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
 2463|[Minimum Total Distance Traveled](./solutions/2463-minimum-total-distance-traveled.js)|Hard|
+2465|[Number of Distinct Averages](./solutions/2465-number-of-distinct-averages.js)|Easy|
 2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium|
 2469|[Convert the Temperature](./solutions/2469-convert-the-temperature.js)|Easy|
 2482|[Difference Between Ones and Zeros in Row and Column](./solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium|
diff --git a/solutions/2465-number-of-distinct-averages.js b/solutions/2465-number-of-distinct-averages.js
new file mode 100644
index 00000000..768feffd
--- /dev/null
+++ b/solutions/2465-number-of-distinct-averages.js
@@ -0,0 +1,34 @@
+/**
+ * 2465. Number of Distinct Averages
+ * https://leetcode.com/problems/number-of-distinct-averages/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums of even length.
+ *
+ * As long as nums is not empty, you must repetitively:
+ * - Find the minimum number in nums and remove it.
+ * - Find the maximum number in nums and remove it.
+ * - Calculate the average of the two removed numbers.
+ *
+ * The average of two numbers a and b is (a + b) / 2.
+ * - For example, the average of 2 and 3 is (2 + 3) / 2 = 2.5.
+ *
+ * Return the number of distinct averages calculated using the above process.
+ *
+ * Note that when there is a tie for a minimum or maximum number, any can be removed.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var distinctAverages = function(nums) {
+  nums.sort((a, b) => a - b);
+  const averages = new Set();
+
+  for (let i = 0, j = nums.length - 1; i < j; i++, j--) {
+    averages.add((nums[i] + nums[j]) / 2);
+  }
+
+  return averages.size;
+};

From a486fcc0212910f344d1f61b23b20c98bcdbdb09 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 19:23:14 -0500
Subject: [PATCH 461/495] Add solution #2942

---
 README.md                                     |  3 +-
 .../2942-find-words-containing-character.js   | 28 +++++++++++++++++++
 2 files changed, 30 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2942-find-words-containing-character.js

diff --git a/README.md b/README.md
index 1631b276..d2d0fbc1 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,965 LeetCode solutions in JavaScript
+# 1,966 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1932,6 +1932,7 @@
 2900|[Longest Unequal Adjacent Groups Subsequence I](./solutions/2900-longest-unequal-adjacent-groups-subsequence-i.js)|Easy|
 2901|[Longest Unequal Adjacent Groups Subsequence II](./solutions/2901-longest-unequal-adjacent-groups-subsequence-ii.js)|Medium|
 2918|[Minimum Equal Sum of Two Arrays After Replacing Zeros](./solutions/2918-minimum-equal-sum-of-two-arrays-after-replacing-zeros.js)|Medium|
+2942|[Find Words Containing Character](./solutions/2942-find-words-containing-character.js)|Easy|
 2948|[Make Lexicographically Smallest Array by Swapping Elements](./solutions/2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium|
 2962|[Count Subarrays Where Max Element Appears at Least K Times](./solutions/2962-count-subarrays-where-max-element-appears-at-least-k-times.js)|Medium|
 2965|[Find Missing and Repeated Values](./solutions/2965-find-missing-and-repeated-values.js)|Easy|
diff --git a/solutions/2942-find-words-containing-character.js b/solutions/2942-find-words-containing-character.js
new file mode 100644
index 00000000..9fadea6b
--- /dev/null
+++ b/solutions/2942-find-words-containing-character.js
@@ -0,0 +1,28 @@
+/**
+ * 2942. Find Words Containing Character
+ * https://leetcode.com/problems/find-words-containing-character/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed array of strings words and a character x.
+ *
+ * Return an array of indices representing the words that contain the character x.
+ *
+ * Note that the returned array may be in any order.
+ */
+
+/**
+ * @param {string[]} words
+ * @param {character} x
+ * @return {number[]}
+ */
+var findWordsContaining = function(words, x) {
+  const result = [];
+
+  for (let i = 0; i < words.length; i++) {
+    if (words[i].includes(x)) {
+      result.push(i);
+    }
+  }
+
+  return result;
+};

From cde99b20edad28516305c3d1ceb3159f04466afb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 19:24:46 -0500
Subject: [PATCH 462/495] Add solution #2466

---
 README.md                                     |  3 +-
 .../2466-count-ways-to-build-good-strings.js  | 47 +++++++++++++++++++
 2 files changed, 49 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2466-count-ways-to-build-good-strings.js

diff --git a/README.md b/README.md
index d2d0fbc1..e72e4c92 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,966 LeetCode solutions in JavaScript
+# 1,967 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1860,6 +1860,7 @@
 2462|[Total Cost to Hire K Workers](./solutions/2462-total-cost-to-hire-k-workers.js)|Medium|
 2463|[Minimum Total Distance Traveled](./solutions/2463-minimum-total-distance-traveled.js)|Hard|
 2465|[Number of Distinct Averages](./solutions/2465-number-of-distinct-averages.js)|Easy|
+2466|[Count Ways To Build Good Strings](./solutions/2466-count-ways-to-build-good-strings.js)|Medium|
 2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium|
 2469|[Convert the Temperature](./solutions/2469-convert-the-temperature.js)|Easy|
 2482|[Difference Between Ones and Zeros in Row and Column](./solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium|
diff --git a/solutions/2466-count-ways-to-build-good-strings.js b/solutions/2466-count-ways-to-build-good-strings.js
new file mode 100644
index 00000000..5bea8af2
--- /dev/null
+++ b/solutions/2466-count-ways-to-build-good-strings.js
@@ -0,0 +1,47 @@
+/**
+ * 2466. Count Ways To Build Good Strings
+ * https://leetcode.com/problems/count-ways-to-build-good-strings/
+ * Difficulty: Medium
+ *
+ * Given the integers zero, one, low, and high, we can construct a string by starting with an
+ * empty string, and then at each step perform either of the following:
+ * - Append the character '0' zero times.
+ * - Append the character '1' one times.
+ *
+ * This can be performed any number of times.
+ *
+ * A good string is a string constructed by the above process having a length between low and
+ * high (inclusive).
+ *
+ * Return the number of different good strings that can be constructed satisfying these properties.
+ * Since the answer can be large, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {number} low
+ * @param {number} high
+ * @param {number} zero
+ * @param {number} one
+ * @return {number}
+ */
+var countGoodStrings = function(low, high, zero, one) {
+  const modulo = 1e9 + 7;
+  const dp = new Array(high + 1).fill(0);
+  dp[0] = 1;
+
+  for (let length = 1; length <= high; length++) {
+    if (length >= zero) {
+      dp[length] = (dp[length] + dp[length - zero]) % modulo;
+    }
+    if (length >= one) {
+      dp[length] = (dp[length] + dp[length - one]) % modulo;
+    }
+  }
+
+  let result = 0;
+  for (let length = low; length <= high; length++) {
+    result = (result + dp[length]) % modulo;
+  }
+
+  return result;
+};

From f965dc0b5bf2c60409b262aa90e5d3168fdef6e6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 19:38:43 -0500
Subject: [PATCH 463/495] Add solution #2468

---
 README.md                                     |  3 +-
 .../2468-split-message-based-on-limit.js      | 52 +++++++++++++++++++
 2 files changed, 54 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2468-split-message-based-on-limit.js

diff --git a/README.md b/README.md
index e72e4c92..437de0d8 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,967 LeetCode solutions in JavaScript
+# 1,968 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1862,6 +1862,7 @@
 2465|[Number of Distinct Averages](./solutions/2465-number-of-distinct-averages.js)|Easy|
 2466|[Count Ways To Build Good Strings](./solutions/2466-count-ways-to-build-good-strings.js)|Medium|
 2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium|
+2468|[Split Message Based on Limit](./solutions/2468-split-message-based-on-limit.js)|Hard|
 2469|[Convert the Temperature](./solutions/2469-convert-the-temperature.js)|Easy|
 2482|[Difference Between Ones and Zeros in Row and Column](./solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium|
 2490|[Circular Sentence](./solutions/2490-circular-sentence.js)|Easy|
diff --git a/solutions/2468-split-message-based-on-limit.js b/solutions/2468-split-message-based-on-limit.js
new file mode 100644
index 00000000..71fc5d00
--- /dev/null
+++ b/solutions/2468-split-message-based-on-limit.js
@@ -0,0 +1,52 @@
+/**
+ * 2468. Split Message Based on Limit
+ * https://leetcode.com/problems/split-message-based-on-limit/
+ * Difficulty: Hard
+ *
+ * You are given a string, message, and a positive integer, limit.
+ *
+ * You must split message into one or more parts based on limit. Each resulting part should have
+ * the suffix "", where "b" is to be replaced with the total number of parts and "a" is to
+ * be replaced with the index of the part, starting from 1 and going up to b. Additionally, the
+ * length of each resulting part (including its suffix) should be equal to limit, except for the
+ * last part whose length can be at most limit.
+ *
+ * The resulting parts should be formed such that when their suffixes are removed and they are
+ * all concatenated in order, they should be equal to message. Also, the result should contain
+ * as few parts as possible.
+ *
+ * Return the parts message would be split into as an array of strings. If it is impossible to
+ * split message as required, return an empty array.
+ */
+
+/**
+ * @param {string} message
+ * @param {number} limit
+ * @return {string[]}
+ */
+var splitMessage = function(message, limit) {
+  const n = message.length;
+  let digitSum = 0;
+
+  for (let parts = 1; parts <= n; parts++) {
+    digitSum += String(parts).length;
+    const indexLength = String(parts).length * parts;
+    const formatLength = 3 * parts;
+
+    if (limit * parts - (digitSum + indexLength + formatLength) >= n) {
+      const result = [];
+      let index = 0;
+
+      for (let i = 1; i <= parts; i++) {
+        const suffix = `<${i}/${parts}>`;
+        const chars = limit - suffix.length;
+        result.push(message.slice(index, index + chars) + suffix);
+        index += chars;
+      }
+
+      return result;
+    }
+  }
+
+  return [];
+};

From 0f27dc353ccd1a65926d57a393bcfecfb15d1154 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 19:39:46 -0500
Subject: [PATCH 464/495] Add solution #2471

---
 README.md                                     |  3 +-
 ...erations-to-sort-a-binary-tree-by-level.js | 66 +++++++++++++++++++
 2 files changed, 68 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2471-minimum-number-of-operations-to-sort-a-binary-tree-by-level.js

diff --git a/README.md b/README.md
index 437de0d8..97598acd 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,968 LeetCode solutions in JavaScript
+# 1,969 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1864,6 +1864,7 @@
 2467|[Most Profitable Path in a Tree](./solutions/2467-most-profitable-path-in-a-tree.js)|Medium|
 2468|[Split Message Based on Limit](./solutions/2468-split-message-based-on-limit.js)|Hard|
 2469|[Convert the Temperature](./solutions/2469-convert-the-temperature.js)|Easy|
+2471|[Minimum Number of Operations to Sort a Binary Tree by Level](./solutions/2471-minimum-number-of-operations-to-sort-a-binary-tree-by-level.js)|Medium|
 2482|[Difference Between Ones and Zeros in Row and Column](./solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium|
 2490|[Circular Sentence](./solutions/2490-circular-sentence.js)|Easy|
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
diff --git a/solutions/2471-minimum-number-of-operations-to-sort-a-binary-tree-by-level.js b/solutions/2471-minimum-number-of-operations-to-sort-a-binary-tree-by-level.js
new file mode 100644
index 00000000..7d26a4c1
--- /dev/null
+++ b/solutions/2471-minimum-number-of-operations-to-sort-a-binary-tree-by-level.js
@@ -0,0 +1,66 @@
+/**
+ * 2471. Minimum Number of Operations to Sort a Binary Tree by Level
+ * https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/
+ * Difficulty: Medium
+ *
+ * You are given the root of a binary tree with unique values.
+ *
+ * In one operation, you can choose any two nodes at the same level and swap their values.
+ *
+ * Return the minimum number of operations needed to make the values at each level sorted in a
+ * strictly increasing order.
+ *
+ * The level of a node is the number of edges along the path between it and the root 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 minimumOperations = function(root) {
+  let result = 0;
+  const queue = [root];
+  const levelValues = [];
+
+  while (queue.length) {
+    const levelSize = queue.length;
+    const values = [];
+
+    for (let i = 0; i < levelSize; i++) {
+      const node = queue.shift();
+      values.push(node.val);
+      if (node.left) queue.push(node.left);
+      if (node.right) queue.push(node.right);
+    }
+
+    levelValues.push(values);
+  }
+
+  for (const values of levelValues) {
+    const sorted = [...values].sort((a, b) => a - b);
+    const indexMap = new Map(values.map((val, i) => [val, i]));
+    let swaps = 0;
+
+    for (let i = 0; i < values.length; i++) {
+      if (values[i] !== sorted[i]) {
+        const targetIndex = indexMap.get(sorted[i]);
+        [values[i], values[targetIndex]] = [values[targetIndex], values[i]];
+        indexMap.set(values[targetIndex], targetIndex);
+        indexMap.set(values[i], i);
+        swaps++;
+      }
+    }
+
+    result += swaps;
+  }
+
+  return result;
+};

From c2cb1f07d328f2fb7a18ed82a34183268f37235c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 19:44:06 -0500
Subject: [PATCH 465/495] Add solution #2472

---
 README.md                                     |  3 +-
 ...f-non-overlapping-palindrome-substrings.js | 51 +++++++++++++++++++
 2 files changed, 53 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2472-maximum-number-of-non-overlapping-palindrome-substrings.js

diff --git a/README.md b/README.md
index 97598acd..31adc273 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,969 LeetCode solutions in JavaScript
+# 1,970 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1865,6 +1865,7 @@
 2468|[Split Message Based on Limit](./solutions/2468-split-message-based-on-limit.js)|Hard|
 2469|[Convert the Temperature](./solutions/2469-convert-the-temperature.js)|Easy|
 2471|[Minimum Number of Operations to Sort a Binary Tree by Level](./solutions/2471-minimum-number-of-operations-to-sort-a-binary-tree-by-level.js)|Medium|
+2472|[Maximum Number of Non-overlapping Palindrome Substrings](./solutions/2472-maximum-number-of-non-overlapping-palindrome-substrings.js)|Hard|
 2482|[Difference Between Ones and Zeros in Row and Column](./solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium|
 2490|[Circular Sentence](./solutions/2490-circular-sentence.js)|Easy|
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
diff --git a/solutions/2472-maximum-number-of-non-overlapping-palindrome-substrings.js b/solutions/2472-maximum-number-of-non-overlapping-palindrome-substrings.js
new file mode 100644
index 00000000..6244a364
--- /dev/null
+++ b/solutions/2472-maximum-number-of-non-overlapping-palindrome-substrings.js
@@ -0,0 +1,51 @@
+/**
+ * 2472. Maximum Number of Non-overlapping Palindrome Substrings
+ * https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/
+ * Difficulty: Hard
+ *
+ * You are given a string s and a positive integer k.
+ *
+ * Select a set of non-overlapping substrings from the string s that satisfy the following
+ * conditions:
+ * - The length of each substring is at least k.
+ * - Each substring is a palindrome.
+ *
+ * Return the maximum number of substrings in an optimal selection.
+ *
+ * A substring is a contiguous sequence of characters within a string.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} k
+ * @return {number}
+ */
+var maxPalindromes = function(s, k) {
+  const n = s.length;
+  const isPal = new Array(n).fill().map(() => new Array(n).fill(false));
+  const dp = new Array(n + 1).fill(0);
+
+  for (let len = 1; len <= n; len++) {
+    for (let start = 0; start + len <= n; start++) {
+      const end = start + len - 1;
+      if (len === 1) {
+        isPal[start][end] = true;
+      } else if (len === 2) {
+        isPal[start][end] = s[start] === s[end];
+      } else {
+        isPal[start][end] = s[start] === s[end] && isPal[start + 1][end - 1];
+      }
+    }
+  }
+
+  for (let end = k; end <= n; end++) {
+    dp[end] = dp[end - 1];
+    for (let start = end - k; start >= 0; start--) {
+      if (isPal[start][end - 1]) {
+        dp[end] = Math.max(dp[end], dp[start] + 1);
+      }
+    }
+  }
+
+  return dp[n];
+};

From ca02c837210d876f3f2b820e1470df46b7a2888b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 19:49:26 -0500
Subject: [PATCH 466/495] Add solution #2475

---
 README.md                                     |  3 +-
 ...475-number-of-unequal-triplets-in-array.js | 36 +++++++++++++++++++
 2 files changed, 38 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2475-number-of-unequal-triplets-in-array.js

diff --git a/README.md b/README.md
index 31adc273..bfca4a5b 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,970 LeetCode solutions in JavaScript
+# 1,971 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1866,6 +1866,7 @@
 2469|[Convert the Temperature](./solutions/2469-convert-the-temperature.js)|Easy|
 2471|[Minimum Number of Operations to Sort a Binary Tree by Level](./solutions/2471-minimum-number-of-operations-to-sort-a-binary-tree-by-level.js)|Medium|
 2472|[Maximum Number of Non-overlapping Palindrome Substrings](./solutions/2472-maximum-number-of-non-overlapping-palindrome-substrings.js)|Hard|
+2475|[Number of Unequal Triplets in Array](./solutions/2475-number-of-unequal-triplets-in-array.js)|Easy|
 2482|[Difference Between Ones and Zeros in Row and Column](./solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium|
 2490|[Circular Sentence](./solutions/2490-circular-sentence.js)|Easy|
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
diff --git a/solutions/2475-number-of-unequal-triplets-in-array.js b/solutions/2475-number-of-unequal-triplets-in-array.js
new file mode 100644
index 00000000..8717363b
--- /dev/null
+++ b/solutions/2475-number-of-unequal-triplets-in-array.js
@@ -0,0 +1,36 @@
+/**
+ * 2475. Number of Unequal Triplets in Array
+ * https://leetcode.com/problems/number-of-unequal-triplets-in-array/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed array of positive integers nums. Find the number of
+ * triplets (i, j, k) that meet the following conditions:
+ * - 0 <= i < j < k < nums.length
+ * - nums[i], nums[j], and nums[k] are pairwise distinct.
+ *   - In other words, nums[i] != nums[j], nums[i] != nums[k], and nums[j] != nums[k].
+ *
+ * Return the number of triplets that meet the conditions.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var unequalTriplets = function(nums) {
+  const map = new Map();
+  for (const num of nums) {
+    map.set(num, (map.get(num) || 0) + 1);
+  }
+
+  let result = 0;
+  let left = 0;
+  const total = nums.length;
+
+  for (const count of map.values()) {
+    const right = total - count - left;
+    result += left * count * right;
+    left += count;
+  }
+
+  return result;
+};

From 62689a51e932a23e28290597181d2d2f86318306 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 19:50:39 -0500
Subject: [PATCH 467/495] Add solution #2476

---
 README.md                                     |  3 +-
 ...t-nodes-queries-in-a-binary-search-tree.js | 67 +++++++++++++++++++
 2 files changed, 69 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2476-closest-nodes-queries-in-a-binary-search-tree.js

diff --git a/README.md b/README.md
index bfca4a5b..ccdb7740 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,971 LeetCode solutions in JavaScript
+# 1,972 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1867,6 +1867,7 @@
 2471|[Minimum Number of Operations to Sort a Binary Tree by Level](./solutions/2471-minimum-number-of-operations-to-sort-a-binary-tree-by-level.js)|Medium|
 2472|[Maximum Number of Non-overlapping Palindrome Substrings](./solutions/2472-maximum-number-of-non-overlapping-palindrome-substrings.js)|Hard|
 2475|[Number of Unequal Triplets in Array](./solutions/2475-number-of-unequal-triplets-in-array.js)|Easy|
+2476|[Closest Nodes Queries in a Binary Search Tree](./solutions/2476-closest-nodes-queries-in-a-binary-search-tree.js)|Medium|
 2482|[Difference Between Ones and Zeros in Row and Column](./solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium|
 2490|[Circular Sentence](./solutions/2490-circular-sentence.js)|Easy|
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
diff --git a/solutions/2476-closest-nodes-queries-in-a-binary-search-tree.js b/solutions/2476-closest-nodes-queries-in-a-binary-search-tree.js
new file mode 100644
index 00000000..8f9a487a
--- /dev/null
+++ b/solutions/2476-closest-nodes-queries-in-a-binary-search-tree.js
@@ -0,0 +1,67 @@
+/**
+ * 2476. Closest Nodes Queries in a Binary Search Tree
+ * https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree/
+ * Difficulty: Medium
+ *
+ * You are given the root of a binary search tree and an array queries of size n consisting of
+ * positive integers.
+ *
+ * Find a 2D array answer of size n where answer[i] = [mini, maxi]:
+ * - mini is the largest value in the tree that is smaller than or equal to queries[i]. If a such
+ *   value does not exist, add -1 instead.
+ * - maxi is the smallest value in the tree that is greater than or equal to queries[i]. If a such
+ *   value does not exist, add -1 instead.
+ *
+ * Return the array answer.
+ */
+
+/**
+ * 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[]} queries
+ * @return {number[][]}
+ */
+var closestNodes = function(root, queries) {
+  const values = [];
+
+  inorder(root);
+
+  const result = queries.map(query => {
+    let minVal = -1;
+    let maxVal = -1;
+
+    let left = 0;
+    let right = values.length - 1;
+
+    while (left <= right) {
+      const mid = Math.floor((left + right) / 2);
+      if (values[mid] === query) {
+        return [query, query];
+      } else if (values[mid] < query) {
+        minVal = values[mid];
+        left = mid + 1;
+      } else {
+        maxVal = values[mid];
+        right = mid - 1;
+      }
+    }
+
+    return [minVal, maxVal];
+  });
+
+  return result;
+
+  function inorder(node) {
+    if (!node) return;
+    inorder(node.left);
+    values.push(node.val);
+    inorder(node.right);
+  }
+};

From bfae659e56a1fc68170ee58ad98c1d36a1ef4382 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 19:52:04 -0500
Subject: [PATCH 468/495] Add solution #2477

---
 README.md                                     |  3 +-
 ...imum-fuel-cost-to-report-to-the-capital.js | 51 +++++++++++++++++++
 2 files changed, 53 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2477-minimum-fuel-cost-to-report-to-the-capital.js

diff --git a/README.md b/README.md
index ccdb7740..29dbb008 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,972 LeetCode solutions in JavaScript
+# 1,973 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1868,6 +1868,7 @@
 2472|[Maximum Number of Non-overlapping Palindrome Substrings](./solutions/2472-maximum-number-of-non-overlapping-palindrome-substrings.js)|Hard|
 2475|[Number of Unequal Triplets in Array](./solutions/2475-number-of-unequal-triplets-in-array.js)|Easy|
 2476|[Closest Nodes Queries in a Binary Search Tree](./solutions/2476-closest-nodes-queries-in-a-binary-search-tree.js)|Medium|
+2477|[Minimum Fuel Cost to Report to the Capital](./solutions/2477-minimum-fuel-cost-to-report-to-the-capital.js)|Medium|
 2482|[Difference Between Ones and Zeros in Row and Column](./solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium|
 2490|[Circular Sentence](./solutions/2490-circular-sentence.js)|Easy|
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
diff --git a/solutions/2477-minimum-fuel-cost-to-report-to-the-capital.js b/solutions/2477-minimum-fuel-cost-to-report-to-the-capital.js
new file mode 100644
index 00000000..fe195062
--- /dev/null
+++ b/solutions/2477-minimum-fuel-cost-to-report-to-the-capital.js
@@ -0,0 +1,51 @@
+/**
+ * 2477. Minimum Fuel Cost to Report to the Capital
+ * https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/
+ * Difficulty: Medium
+ *
+ * There is a tree (i.e., a connected, undirected graph with no cycles) structure country network
+ * consisting of n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is
+ * city 0. You are given a 2D integer array roads where roads[i] = [ai, bi] denotes that there
+ * exists a bidirectional road connecting cities ai and bi.
+ *
+ * There is a meeting for the representatives of each city. The meeting is in the capital city.
+ *
+ * There is a car in each city. You are given an integer seats that indicates the number of seats
+ * in each car.
+ *
+ * A representative can use the car in their city to travel or change the car and ride with another
+ * representative. The cost of traveling between two cities is one liter of fuel.
+ *
+ * Return the minimum number of liters of fuel to reach the capital city.
+ */
+
+/**
+ * @param {number[][]} roads
+ * @param {number} seats
+ * @return {number}
+ */
+var minimumFuelCost = function(roads, seats) {
+  const n = roads.length + 1;
+  const graph = Array.from({ length: n }, () => []);
+  for (const [a, b] of roads) {
+    graph[a].push(b);
+    graph[b].push(a);
+  }
+
+  let fuel = 0;
+  dfs(0, -1);
+  return fuel;
+
+  function dfs(node, parent) {
+    let representatives = 1;
+    for (const neighbor of graph[node]) {
+      if (neighbor !== parent) {
+        representatives += dfs(neighbor, node);
+      }
+    }
+    if (node !== 0) {
+      fuel += Math.ceil(representatives / seats);
+    }
+    return representatives;
+  }
+};

From 0ec81f86992d57819415463a22e0ab443d5513c7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 19:53:35 -0500
Subject: [PATCH 469/495] Add solution #2481

---
 README.md                                     |  3 ++-
 .../2481-minimum-cuts-to-divide-a-circle.js   | 24 +++++++++++++++++++
 2 files changed, 26 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2481-minimum-cuts-to-divide-a-circle.js

diff --git a/README.md b/README.md
index 29dbb008..b70650e0 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,973 LeetCode solutions in JavaScript
+# 1,974 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1869,6 +1869,7 @@
 2475|[Number of Unequal Triplets in Array](./solutions/2475-number-of-unequal-triplets-in-array.js)|Easy|
 2476|[Closest Nodes Queries in a Binary Search Tree](./solutions/2476-closest-nodes-queries-in-a-binary-search-tree.js)|Medium|
 2477|[Minimum Fuel Cost to Report to the Capital](./solutions/2477-minimum-fuel-cost-to-report-to-the-capital.js)|Medium|
+2481|[Minimum Cuts to Divide a Circle](./solutions/2481-minimum-cuts-to-divide-a-circle.js)|Easy|
 2482|[Difference Between Ones and Zeros in Row and Column](./solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium|
 2490|[Circular Sentence](./solutions/2490-circular-sentence.js)|Easy|
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
diff --git a/solutions/2481-minimum-cuts-to-divide-a-circle.js b/solutions/2481-minimum-cuts-to-divide-a-circle.js
new file mode 100644
index 00000000..805ed6ac
--- /dev/null
+++ b/solutions/2481-minimum-cuts-to-divide-a-circle.js
@@ -0,0 +1,24 @@
+/**
+ * 2481. Minimum Cuts to Divide a Circle
+ * https://leetcode.com/problems/minimum-cuts-to-divide-a-circle/
+ * Difficulty: Easy
+ *
+ * A valid cut in a circle can be:
+ * - A cut that is represented by a straight line that touches two points on the edge of the
+ *   circle and passes through its center, or
+ * - A cut that is represented by a straight line that touches one point on the edge of the
+ *   circle and its center.
+ *
+ * Some valid and invalid cuts are shown in the figures below.
+ *
+ * Given the integer n, return the minimum number of cuts needed to divide a circle into n
+ * equal slices.
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var numberOfCuts = function(n) {
+  return n === 1 ? 0 : n % 2 === 0 ? n / 2 : n;
+};

From ba88478a901c93ce3827161bb6909d45ae516312 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 19:54:44 -0500
Subject: [PATCH 470/495] Add solution #2483

---
 README.md                                    |  3 +-
 solutions/2483-minimum-penalty-for-a-shop.js | 38 ++++++++++++++++++++
 2 files changed, 40 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2483-minimum-penalty-for-a-shop.js

diff --git a/README.md b/README.md
index b70650e0..f200dbb9 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,974 LeetCode solutions in JavaScript
+# 1,975 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1871,6 +1871,7 @@
 2477|[Minimum Fuel Cost to Report to the Capital](./solutions/2477-minimum-fuel-cost-to-report-to-the-capital.js)|Medium|
 2481|[Minimum Cuts to Divide a Circle](./solutions/2481-minimum-cuts-to-divide-a-circle.js)|Easy|
 2482|[Difference Between Ones and Zeros in Row and Column](./solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium|
+2483|[Minimum Penalty for a Shop](./solutions/2483-minimum-penalty-for-a-shop.js)|Medium|
 2490|[Circular Sentence](./solutions/2490-circular-sentence.js)|Easy|
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
 2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard|
diff --git a/solutions/2483-minimum-penalty-for-a-shop.js b/solutions/2483-minimum-penalty-for-a-shop.js
new file mode 100644
index 00000000..0819d961
--- /dev/null
+++ b/solutions/2483-minimum-penalty-for-a-shop.js
@@ -0,0 +1,38 @@
+/**
+ * 2483. Minimum Penalty for a Shop
+ * https://leetcode.com/problems/minimum-penalty-for-a-shop/
+ * Difficulty: Medium
+ *
+ * You are given the customer visit log of a shop represented by a 0-indexed string customers
+ * consisting only of characters 'N' and 'Y':
+ * - if the ith character is 'Y', it means that customers come at the ith hour
+ * - whereas 'N' indicates that no customers come at the ith hour.
+ *
+ * If the shop closes at the jth hour (0 <= j <= n), the penalty is calculated as follows:
+ * - For every hour when the shop is open and no customers come, the penalty increases by 1.
+ * - For every hour when the shop is closed and customers come, the penalty increases by 1.
+ *
+ * Return the earliest hour at which the shop must be closed to incur a minimum penalty.
+ *
+ * Note that if a shop closes at the jth hour, it means the shop is closed at the hour j.
+ */
+
+/**
+ * @param {string} customers
+ * @return {number}
+ */
+var bestClosingTime = function(customers) {
+  let minPenalty = 0;
+  let currentPenalty = 0;
+  let result = 0;
+
+  for (let i = 0; i < customers.length; i++) {
+    currentPenalty += customers[i] === 'Y' ? -1 : 1;
+    if (currentPenalty < minPenalty) {
+      minPenalty = currentPenalty;
+      result = i + 1;
+    }
+  }
+
+  return result;
+};

From d06c5d2cf9c23d8063c97a95e090e32f8b9f1a50 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 22:04:33 -0500
Subject: [PATCH 471/495] Add solution #2485

---
 README.md                                |  3 ++-
 solutions/2485-find-the-pivot-integer.js | 22 ++++++++++++++++++++++
 2 files changed, 24 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2485-find-the-pivot-integer.js

diff --git a/README.md b/README.md
index f200dbb9..812317e6 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,975 LeetCode solutions in JavaScript
+# 1,976 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1872,6 +1872,7 @@
 2481|[Minimum Cuts to Divide a Circle](./solutions/2481-minimum-cuts-to-divide-a-circle.js)|Easy|
 2482|[Difference Between Ones and Zeros in Row and Column](./solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium|
 2483|[Minimum Penalty for a Shop](./solutions/2483-minimum-penalty-for-a-shop.js)|Medium|
+2485|[Find the Pivot Integer](./solutions/2485-find-the-pivot-integer.js)|Easy|
 2490|[Circular Sentence](./solutions/2490-circular-sentence.js)|Easy|
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
 2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard|
diff --git a/solutions/2485-find-the-pivot-integer.js b/solutions/2485-find-the-pivot-integer.js
new file mode 100644
index 00000000..73a95a4a
--- /dev/null
+++ b/solutions/2485-find-the-pivot-integer.js
@@ -0,0 +1,22 @@
+/**
+ * 2485. Find the Pivot Integer
+ * https://leetcode.com/problems/find-the-pivot-integer/
+ * Difficulty: Easy
+ *
+ * Given a positive integer n, find the pivot integer x such that:
+ * - The sum of all elements between 1 and x inclusively equals the sum of all elements between
+ *   x and n inclusively.
+ *
+ * Return the pivot integer x. If no such integer exists, return -1. It is guaranteed that there
+ * will be at most one pivot index for the given input.
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var pivotInteger = function(n) {
+  const totalSum = n * (n + 1) / 2;
+  const pivot = Math.sqrt(totalSum);
+  return Number.isInteger(pivot) && pivot <= n ? pivot : -1;
+};

From 079a4a08a964455d463c11f8833706ddff82507a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 22:05:19 -0500
Subject: [PATCH 472/495] Add solution #2486

---
 README.md                                     |  3 +-
 ...haracters-to-string-to-make-subsequence.js | 32 +++++++++++++++++++
 2 files changed, 34 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2486-append-characters-to-string-to-make-subsequence.js

diff --git a/README.md b/README.md
index 812317e6..7d7ba7a5 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,976 LeetCode solutions in JavaScript
+# 1,977 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1873,6 +1873,7 @@
 2482|[Difference Between Ones and Zeros in Row and Column](./solutions/2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium|
 2483|[Minimum Penalty for a Shop](./solutions/2483-minimum-penalty-for-a-shop.js)|Medium|
 2485|[Find the Pivot Integer](./solutions/2485-find-the-pivot-integer.js)|Easy|
+2486|[Append Characters to String to Make Subsequence](./solutions/2486-append-characters-to-string-to-make-subsequence.js)|Medium|
 2490|[Circular Sentence](./solutions/2490-circular-sentence.js)|Easy|
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
 2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard|
diff --git a/solutions/2486-append-characters-to-string-to-make-subsequence.js b/solutions/2486-append-characters-to-string-to-make-subsequence.js
new file mode 100644
index 00000000..09bfb362
--- /dev/null
+++ b/solutions/2486-append-characters-to-string-to-make-subsequence.js
@@ -0,0 +1,32 @@
+/**
+ * 2486. Append Characters to String to Make Subsequence
+ * https://leetcode.com/problems/append-characters-to-string-to-make-subsequence/
+ * Difficulty: Medium
+ *
+ * You are given two strings s and t consisting of only lowercase English letters.
+ *
+ * Return the minimum number of characters that need to be appended to the end of s so that
+ * t becomes a subsequence of s.
+ *
+ * A subsequence is a string that can be derived from another string by deleting some or no
+ * characters without changing the order of the remaining characters.
+ */
+
+/**
+ * @param {string} s
+ * @param {string} t
+ * @return {number}
+ */
+var appendCharacters = function(s, t) {
+  let sIndex = 0;
+  let tIndex = 0;
+
+  while (sIndex < s.length && tIndex < t.length) {
+    if (s[sIndex] === t[tIndex]) {
+      tIndex++;
+    }
+    sIndex++;
+  }
+
+  return t.length - tIndex;
+};

From e4ffe17d35b37a1b1b746ccf2b5526b85180239a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 22:06:23 -0500
Subject: [PATCH 473/495] Add solution #2487

---
 README.md                                     |  3 +-
 .../2487-remove-nodes-from-linked-list.js     | 44 +++++++++++++++++++
 2 files changed, 46 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2487-remove-nodes-from-linked-list.js

diff --git a/README.md b/README.md
index 7d7ba7a5..938a3afe 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,977 LeetCode solutions in JavaScript
+# 1,978 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1874,6 +1874,7 @@
 2483|[Minimum Penalty for a Shop](./solutions/2483-minimum-penalty-for-a-shop.js)|Medium|
 2485|[Find the Pivot Integer](./solutions/2485-find-the-pivot-integer.js)|Easy|
 2486|[Append Characters to String to Make Subsequence](./solutions/2486-append-characters-to-string-to-make-subsequence.js)|Medium|
+2487|[Remove Nodes From Linked List](./solutions/2487-remove-nodes-from-linked-list.js)|Medium|
 2490|[Circular Sentence](./solutions/2490-circular-sentence.js)|Easy|
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
 2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard|
diff --git a/solutions/2487-remove-nodes-from-linked-list.js b/solutions/2487-remove-nodes-from-linked-list.js
new file mode 100644
index 00000000..b6d6cb2c
--- /dev/null
+++ b/solutions/2487-remove-nodes-from-linked-list.js
@@ -0,0 +1,44 @@
+/**
+ * 2487. Remove Nodes From Linked List
+ * https://leetcode.com/problems/remove-nodes-from-linked-list/
+ * Difficulty: Medium
+ *
+ * You are given the head of a linked list.
+ *
+ * Remove every node which has a node with a greater value anywhere to the right side of it.
+ *
+ * Return the head of the modified linked list.
+ */
+
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val, next) {
+ *     this.val = (val===undefined ? 0 : val)
+ *     this.next = (next===undefined ? null : next)
+ * }
+ */
+/**
+ * @param {ListNode} head
+ * @return {ListNode}
+ */
+var removeNodes = function(head) {
+  const stack = [];
+  let current = head;
+
+  while (current) {
+    while (stack.length && stack[stack.length - 1].val < current.val) {
+      stack.pop();
+    }
+    stack.push(current);
+    current = current.next;
+  }
+
+  let result = null;
+  while (stack.length) {
+    current = stack.pop();
+    current.next = result;
+    result = current;
+  }
+
+  return result;
+};

From 36765a30b2d6033aa2891a83d1e271aeef842bd4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 22:13:57 -0500
Subject: [PATCH 474/495] Add solution #2488

---
 README.md                                     |  3 +-
 .../2488-count-subarrays-with-median-k.js     | 43 +++++++++++++++++++
 2 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2488-count-subarrays-with-median-k.js

diff --git a/README.md b/README.md
index 938a3afe..c286179f 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,978 LeetCode solutions in JavaScript
+# 1,979 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1875,6 +1875,7 @@
 2485|[Find the Pivot Integer](./solutions/2485-find-the-pivot-integer.js)|Easy|
 2486|[Append Characters to String to Make Subsequence](./solutions/2486-append-characters-to-string-to-make-subsequence.js)|Medium|
 2487|[Remove Nodes From Linked List](./solutions/2487-remove-nodes-from-linked-list.js)|Medium|
+2488|[Count Subarrays With Median K](./solutions/2488-count-subarrays-with-median-k.js)|Hard|
 2490|[Circular Sentence](./solutions/2490-circular-sentence.js)|Easy|
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
 2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard|
diff --git a/solutions/2488-count-subarrays-with-median-k.js b/solutions/2488-count-subarrays-with-median-k.js
new file mode 100644
index 00000000..694d9ea9
--- /dev/null
+++ b/solutions/2488-count-subarrays-with-median-k.js
@@ -0,0 +1,43 @@
+/**
+ * 2488. Count Subarrays With Median K
+ * https://leetcode.com/problems/count-subarrays-with-median-k/
+ * Difficulty: Hard
+ *
+ * You are given an array nums of size n consisting of distinct integers from 1 to n and
+ * a positive integer k.
+ *
+ * Return the number of non-empty subarrays in nums that have a median equal to k.
+ *
+ * Note:
+ * - The median of an array is the middle element after sorting the array in ascending order.
+ *   If the array is of even length, the median is the left middle element.
+ *   - For example, the median of [2,3,1,4] is 2, and the median of [8,4,3,5,1] is 4.
+ * - A subarray is a contiguous part of an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var countSubarrays = function(nums, k) {
+  const n = nums.length;
+  const kIndex = nums.indexOf(k);
+  const balanceMap = new Map([[0, 1]]);
+  let balance = 0;
+  let result = 0;
+
+  for (let i = kIndex + 1; i < n; i++) {
+    balance += nums[i] > k ? 1 : -1;
+    balanceMap.set(balance, (balanceMap.get(balance) || 0) + 1);
+  }
+
+  balance = 0;
+  for (let i = kIndex; i >= 0; i--) {
+    balance += nums[i] > k ? -1 : nums[i] < k ? 1 : 0;
+    result += balanceMap.get(balance) || 0;
+    result += balanceMap.get(balance + 1) || 0;
+  }
+
+  return result;
+};

From 0aee1c76e5f1f43c7fb33efa24cf2d6df9c8c578 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 23 May 2025 22:15:04 -0500
Subject: [PATCH 475/495] Add solution #2491

---
 README.md                                     |  3 +-
 ...ivide-players-into-teams-of-equal-skill.js | 32 +++++++++++++++++++
 2 files changed, 34 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2491-divide-players-into-teams-of-equal-skill.js

diff --git a/README.md b/README.md
index c286179f..9978339f 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,979 LeetCode solutions in JavaScript
+# 1,980 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1877,6 +1877,7 @@
 2487|[Remove Nodes From Linked List](./solutions/2487-remove-nodes-from-linked-list.js)|Medium|
 2488|[Count Subarrays With Median K](./solutions/2488-count-subarrays-with-median-k.js)|Hard|
 2490|[Circular Sentence](./solutions/2490-circular-sentence.js)|Easy|
+2491|[Divide Players Into Teams of Equal Skill](./solutions/2491-divide-players-into-teams-of-equal-skill.js)|Medium|
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
 2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
diff --git a/solutions/2491-divide-players-into-teams-of-equal-skill.js b/solutions/2491-divide-players-into-teams-of-equal-skill.js
new file mode 100644
index 00000000..5f481cf0
--- /dev/null
+++ b/solutions/2491-divide-players-into-teams-of-equal-skill.js
@@ -0,0 +1,32 @@
+/**
+ * 2491. Divide Players Into Teams of Equal Skill
+ * https://leetcode.com/problems/divide-players-into-teams-of-equal-skill/
+ * Difficulty: Medium
+ *
+ * You are given a positive integer array skill of even length n where skill[i] denotes the
+ * skill of the ith player. Divide the players into n / 2 teams of size 2 such that the total
+ * skill of each team is equal.
+ *
+ * The chemistry of a team is equal to the product of the skills of the players on that team.
+ *
+ * Return the sum of the chemistry of all the teams, or return -1 if there is no way to divide
+ * the players into teams such that the total skill of each team is equal.
+ */
+
+/**
+ * @param {number[]} skill
+ * @return {number}
+ */
+var dividePlayers = function(skill) {
+  skill.sort((a, b) => a - b);
+  const n = skill.length;
+  const targetSum = skill[0] + skill[n - 1];
+  let result = 0;
+
+  for (let i = 0, j = n - 1; i < j; i++, j--) {
+    if (skill[i] + skill[j] !== targetSum) return -1;
+    result += skill[i] * skill[j];
+  }
+
+  return result;
+};

From 52bf15de236cd0315cd26c51de1dc5f956ab9c83 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 12:29:06 -0500
Subject: [PATCH 476/495] Add solution #2492

---
 README.md                                     |  3 +-
 ...imum-score-of-a-path-between-two-cities.js | 53 +++++++++++++++++++
 2 files changed, 55 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2492-minimum-score-of-a-path-between-two-cities.js

diff --git a/README.md b/README.md
index 9978339f..1ce852b5 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,980 LeetCode solutions in JavaScript
+# 1,981 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1878,6 +1878,7 @@
 2488|[Count Subarrays With Median K](./solutions/2488-count-subarrays-with-median-k.js)|Hard|
 2490|[Circular Sentence](./solutions/2490-circular-sentence.js)|Easy|
 2491|[Divide Players Into Teams of Equal Skill](./solutions/2491-divide-players-into-teams-of-equal-skill.js)|Medium|
+2492|[Minimum Score of a Path Between Two Cities](./solutions/2492-minimum-score-of-a-path-between-two-cities.js)|Medium|
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
 2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
diff --git a/solutions/2492-minimum-score-of-a-path-between-two-cities.js b/solutions/2492-minimum-score-of-a-path-between-two-cities.js
new file mode 100644
index 00000000..f5cbc0f5
--- /dev/null
+++ b/solutions/2492-minimum-score-of-a-path-between-two-cities.js
@@ -0,0 +1,53 @@
+/**
+ * 2492. Minimum Score of a Path Between Two Cities
+ * https://leetcode.com/problems/minimum-score-of-a-path-between-two-cities/
+ * Difficulty: Medium
+ *
+ * You are given a positive integer n representing n cities numbered from 1 to n. You are also
+ * given a 2D array roads where roads[i] = [ai, bi, distancei] indicates that there is a
+ * bidirectional road between cities ai and bi with a distance equal to distancei. The cities
+ * graph is not necessarily connected.
+ *
+ * The score of a path between two cities is defined as the minimum distance of a road in this
+ * path.
+ *
+ * Return the minimum possible score of a path between cities 1 and n.
+ *
+ * Note:
+ * - A path is a sequence of roads between two cities.
+ * - It is allowed for a path to contain the same road multiple times, and you can visit cities 1
+ *   and n multiple times along the path.
+ * - The test cases are generated such that there is at least one path between 1 and n.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} roads
+ * @return {number}
+ */
+var minScore = function(n, roads) {
+  const graph = Array.from({ length: n + 1 }, () => []);
+  for (const [a, b, dist] of roads) {
+    graph[a].push([b, dist]);
+    graph[b].push([a, dist]);
+  }
+
+  const visited = new Set();
+  const queue = [1];
+  let result = Infinity;
+
+  while (queue.length) {
+    const city = queue.shift();
+    if (visited.has(city)) continue;
+    visited.add(city);
+
+    for (const [nextCity, dist] of graph[city]) {
+      result = Math.min(result, dist);
+      if (!visited.has(nextCity)) {
+        queue.push(nextCity);
+      }
+    }
+  }
+
+  return result;
+};

From 9d29bad51ec73133c608e7609e753ed4b0129c1e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 12:29:59 -0500
Subject: [PATCH 477/495] Add solution #2496

---
 README.md                                     |  3 ++-
 ...6-maximum-value-of-a-string-in-an-array.js | 27 +++++++++++++++++++
 2 files changed, 29 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2496-maximum-value-of-a-string-in-an-array.js

diff --git a/README.md b/README.md
index 1ce852b5..99b8889e 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,981 LeetCode solutions in JavaScript
+# 1,982 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1880,6 +1880,7 @@
 2491|[Divide Players Into Teams of Equal Skill](./solutions/2491-divide-players-into-teams-of-equal-skill.js)|Medium|
 2492|[Minimum Score of a Path Between Two Cities](./solutions/2492-minimum-score-of-a-path-between-two-cities.js)|Medium|
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
+2496|[Maximum Value of a String in an Array](./solutions/2496-maximum-value-of-a-string-in-an-array.js)|Easy|
 2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
diff --git a/solutions/2496-maximum-value-of-a-string-in-an-array.js b/solutions/2496-maximum-value-of-a-string-in-an-array.js
new file mode 100644
index 00000000..3d78d50f
--- /dev/null
+++ b/solutions/2496-maximum-value-of-a-string-in-an-array.js
@@ -0,0 +1,27 @@
+/**
+ * 2496. Maximum Value of a String in an Array
+ * https://leetcode.com/problems/maximum-value-of-a-string-in-an-array/
+ * Difficulty: Easy
+ *
+ * The value of an alphanumeric string can be defined as:
+ * - The numeric representation of the string in base 10, if it comprises of digits only.
+ * - The length of the string, otherwise.
+ *
+ * Given an array strs of alphanumeric strings, return the maximum value of any string in strs.
+ */
+
+/**
+ * @param {string[]} strs
+ * @return {number}
+ */
+var maximumValue = function(strs) {
+  let result = 0;
+
+  for (const str of strs) {
+    const isNumeric = /^[0-9]+$/.test(str);
+    const value = isNumeric ? parseInt(str) : str.length;
+    result = Math.max(result, value);
+  }
+
+  return result;
+};

From 256d44b9551207e2c9c57806b3ea7bbd11665c0e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 12:31:10 -0500
Subject: [PATCH 478/495] Add solution #2498

---
 README.md                      |  3 ++-
 solutions/2498-frog-jump-ii.js | 33 +++++++++++++++++++++++++++++++++
 2 files changed, 35 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2498-frog-jump-ii.js

diff --git a/README.md b/README.md
index 99b8889e..28f620b3 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,982 LeetCode solutions in JavaScript
+# 1,983 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1881,6 +1881,7 @@
 2492|[Minimum Score of a Path Between Two Cities](./solutions/2492-minimum-score-of-a-path-between-two-cities.js)|Medium|
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
 2496|[Maximum Value of a String in an Array](./solutions/2496-maximum-value-of-a-string-in-an-array.js)|Easy|
+2498|[Frog Jump II](./solutions/2498-frog-jump-ii.js)|Medium|
 2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
diff --git a/solutions/2498-frog-jump-ii.js b/solutions/2498-frog-jump-ii.js
new file mode 100644
index 00000000..573192a9
--- /dev/null
+++ b/solutions/2498-frog-jump-ii.js
@@ -0,0 +1,33 @@
+/**
+ * 2498. Frog Jump II
+ * https://leetcode.com/problems/frog-jump-ii/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array stones sorted in strictly increasing order representing
+ * the positions of stones in a river.
+ *
+ * A frog, initially on the first stone, wants to travel to the last stone and then return to the
+ * first stone. However, it can jump to any stone at most once.
+ *
+ * The length of a jump is the absolute difference between the position of the stone the frog is
+ * currently on and the position of the stone to which the frog jumps.
+ *
+ * - More formally, if the frog is at stones[i] and is jumping to stones[j], the length of the jump
+ *   is |stones[i] - stones[j]|.
+ *
+ * The cost of a path is the maximum length of a jump among all jumps in the path.
+ *
+ * Return the minimum cost of a path for the frog.
+ */
+
+/**
+ * @param {number[]} stones
+ * @return {number}
+ */
+var maxJump = function(stones) {
+  let result = stones[1];
+  for (let i = 2; i < stones.length; i++) {
+    result = Math.max(result, stones[i] - stones[i - 2]);
+  }
+  return result;
+};

From daa2c5f2b367a061b7ccc1857f716ba6f32e9e14 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 12:38:24 -0500
Subject: [PATCH 479/495] Add solution #2499

---
 README.md                                     |  3 +-
 ...nimum-total-cost-to-make-arrays-unequal.js | 69 +++++++++++++++++++
 2 files changed, 71 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2499-minimum-total-cost-to-make-arrays-unequal.js

diff --git a/README.md b/README.md
index 28f620b3..0fa6db4a 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,983 LeetCode solutions in JavaScript
+# 1,984 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1882,6 +1882,7 @@
 2493|[Divide Nodes Into the Maximum Number of Groups](./solutions/2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
 2496|[Maximum Value of a String in an Array](./solutions/2496-maximum-value-of-a-string-in-an-array.js)|Easy|
 2498|[Frog Jump II](./solutions/2498-frog-jump-ii.js)|Medium|
+2499|[Minimum Total Cost to Make Arrays Unequal](./solutions/2499-minimum-total-cost-to-make-arrays-unequal.js)|Hard|
 2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
diff --git a/solutions/2499-minimum-total-cost-to-make-arrays-unequal.js b/solutions/2499-minimum-total-cost-to-make-arrays-unequal.js
new file mode 100644
index 00000000..8a8e8e9a
--- /dev/null
+++ b/solutions/2499-minimum-total-cost-to-make-arrays-unequal.js
@@ -0,0 +1,69 @@
+/**
+ * 2499. Minimum Total Cost to Make Arrays Unequal
+ * https://leetcode.com/problems/minimum-total-cost-to-make-arrays-unequal/
+ * Difficulty: Hard
+ *
+ * You are given two 0-indexed integer arrays nums1 and nums2, of equal length n.
+ *
+ * In one operation, you can swap the values of any two indices of nums1. The cost of this
+ * operation is the sum of the indices.
+ *
+ * Find the minimum total cost of performing the given operation any number of times such
+ * that nums1[i] != nums2[i] for all 0 <= i <= n - 1 after performing all the operations.
+ *
+ * Return the minimum total cost such that nums1 and nums2 satisfy the above condition.
+ * In case it is not possible, return -1.
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @return {number}
+ */
+var minimumTotalCost = function(nums1, nums2) {
+  const n = nums1.length;
+  const conflictIndices = [];
+  const valueCount = new Map();
+
+  for (let i = 0; i < n; i++) {
+    if (nums1[i] === nums2[i]) {
+      conflictIndices.push(i);
+      valueCount.set(nums1[i], (valueCount.get(nums1[i]) || 0) + 1);
+    }
+  }
+
+  if (conflictIndices.length === 0) return 0;
+
+  let dominantValue = -1;
+  let maxCount = 0;
+
+  for (const [value, count] of valueCount) {
+    if (count > maxCount) {
+      maxCount = count;
+      dominantValue = value;
+    }
+  }
+
+  const swapsNeeded = conflictIndices.length;
+  let helpersNeeded = Math.max(0, 2 * maxCount - swapsNeeded);
+
+  const helperIndices = [];
+  for (let i = 0; i < n && helpersNeeded > 0; i++) {
+    if (nums1[i] !== nums2[i] && nums1[i] !== dominantValue && nums2[i] !== dominantValue) {
+      helperIndices.push(i);
+      helpersNeeded--;
+    }
+  }
+
+  if (helpersNeeded > 0) return -1;
+
+  const allIndices = [...conflictIndices, ...helperIndices];
+  allIndices.sort((a, b) => a - b);
+
+  let result = 0;
+  for (let i = 0; i < allIndices.length; i++) {
+    result += allIndices[i];
+  }
+
+  return result;
+};

From 1846d3b62cc33a80eb462c5ba79b1166d594e8d7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 12:39:55 -0500
Subject: [PATCH 480/495] Add solution #2501

---
 README.md                                     |  3 +-
 .../2501-longest-square-streak-in-an-array.js | 41 +++++++++++++++++++
 2 files changed, 43 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2501-longest-square-streak-in-an-array.js

diff --git a/README.md b/README.md
index 0fa6db4a..b8a1b591 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,984 LeetCode solutions in JavaScript
+# 1,985 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1883,6 +1883,7 @@
 2496|[Maximum Value of a String in an Array](./solutions/2496-maximum-value-of-a-string-in-an-array.js)|Easy|
 2498|[Frog Jump II](./solutions/2498-frog-jump-ii.js)|Medium|
 2499|[Minimum Total Cost to Make Arrays Unequal](./solutions/2499-minimum-total-cost-to-make-arrays-unequal.js)|Hard|
+2501|[Longest Square Streak in an Array](./solutions/2501-longest-square-streak-in-an-array.js)|Medium|
 2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
diff --git a/solutions/2501-longest-square-streak-in-an-array.js b/solutions/2501-longest-square-streak-in-an-array.js
new file mode 100644
index 00000000..ee667541
--- /dev/null
+++ b/solutions/2501-longest-square-streak-in-an-array.js
@@ -0,0 +1,41 @@
+/**
+ * 2501. Longest Square Streak in an Array
+ * https://leetcode.com/problems/longest-square-streak-in-an-array/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums. A subsequence of nums is called a square streak if:
+ * - The length of the subsequence is at least 2, and
+ * - after sorting the subsequence, each element (except the first element) is the square of
+ *   the previous number.
+ *
+ * Return the length of the longest square streak in nums, or return -1 if there is no square
+ * streak.
+ *
+ * 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
+ * @return {number}
+ */
+var longestSquareStreak = function(nums) {
+  const set = new Set(nums);
+  let result = -1;
+
+  for (const num of nums) {
+    let current = num;
+    let length = 1;
+
+    while (current <= 100000 && set.has(current * current)) {
+      current *= current;
+      length++;
+    }
+
+    if (length >= 2) {
+      result = Math.max(result, length);
+    }
+  }
+
+  return result;
+};

From d4a7afe2c69600da2c3152d1ed08244dfaf7eb9a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 12:43:15 -0500
Subject: [PATCH 481/495] Add solution #2502

---
 README.md                                 |  3 +-
 solutions/2502-design-memory-allocator.js | 76 +++++++++++++++++++++++
 2 files changed, 78 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2502-design-memory-allocator.js

diff --git a/README.md b/README.md
index b8a1b591..c0d71c2e 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,985 LeetCode solutions in JavaScript
+# 1,986 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1884,6 +1884,7 @@
 2498|[Frog Jump II](./solutions/2498-frog-jump-ii.js)|Medium|
 2499|[Minimum Total Cost to Make Arrays Unequal](./solutions/2499-minimum-total-cost-to-make-arrays-unequal.js)|Hard|
 2501|[Longest Square Streak in an Array](./solutions/2501-longest-square-streak-in-an-array.js)|Medium|
+2502|[Design Memory Allocator](./solutions/2502-design-memory-allocator.js)|Medium|
 2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
diff --git a/solutions/2502-design-memory-allocator.js b/solutions/2502-design-memory-allocator.js
new file mode 100644
index 00000000..b09fcbb0
--- /dev/null
+++ b/solutions/2502-design-memory-allocator.js
@@ -0,0 +1,76 @@
+/**
+ * 2502. Design Memory Allocator
+ * https://leetcode.com/problems/design-memory-allocator/
+ * Difficulty: Medium
+ *
+ * You are given an integer n representing the size of a 0-indexed memory array. All memory
+ * units are initially free.
+ *
+ * You have a memory allocator with the following functionalities:
+ * 1. Allocate a block of size consecutive free memory units and assign it the id mID.
+ * 2. Free all memory units with the given id mID.
+ *
+ * Note that:
+ * - Multiple blocks can be allocated to the same mID.
+ * - You should free all the memory units with mID, even if they were allocated in different blocks.
+ *
+ * Implement the Allocator class:
+ * - Allocator(int n) Initializes an Allocator object with a memory array of size n.
+ * - int allocate(int size, int mID) Find the leftmost block of size consecutive free memory units
+ *   and allocate it with the id mID. Return the block's first index. If such a block does not
+ *   exist, return -1.
+ * - int freeMemory(int mID) Free all memory units with the id mID. Return the number of memory
+ *   units you have freed.
+ */
+
+/**
+ * @param {number} n
+ */
+var Allocator = function(n) {
+  this.memory = Array(n).fill(0);
+};
+
+/**
+ * @param {number} size
+ * @param {number} mID
+ * @return {number}
+ */
+Allocator.prototype.allocate = function(size, mID) {
+  let start = -1;
+  let count = 0;
+
+  for (let i = 0; i < this.memory.length; i++) {
+    if (this.memory[i] === 0) {
+      if (start === -1) start = i;
+      count++;
+      if (count === size) {
+        for (let j = start; j < start + size; j++) {
+          this.memory[j] = mID;
+        }
+        return start;
+      }
+    } else {
+      start = -1;
+      count = 0;
+    }
+  }
+
+  return -1;
+};
+
+/**
+ * @param {number} mID
+ * @return {number}
+ */
+Allocator.prototype.freeMemory = function(mID) {
+  let result = 0;
+
+  for (let i = 0; i < this.memory.length; i++) {
+    if (this.memory[i] === mID) {
+      this.memory[i] = 0;
+      result++;
+    }
+  }
+
+  return result;
+};

From 2ce6a0d2d95f4acb882ac352e3ed673df653ff8c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 12:44:55 -0500
Subject: [PATCH 482/495] Add solution #2506

---
 README.md                                     |  3 +-
 .../2506-count-pairs-of-similar-strings.js    | 36 +++++++++++++++++++
 2 files changed, 38 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2506-count-pairs-of-similar-strings.js

diff --git a/README.md b/README.md
index c0d71c2e..b160eef9 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,986 LeetCode solutions in JavaScript
+# 1,987 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1886,6 +1886,7 @@
 2501|[Longest Square Streak in an Array](./solutions/2501-longest-square-streak-in-an-array.js)|Medium|
 2502|[Design Memory Allocator](./solutions/2502-design-memory-allocator.js)|Medium|
 2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard|
+2506|[Count Pairs Of Similar Strings](./solutions/2506-count-pairs-of-similar-strings.js)|Easy|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
 2535|[Difference Between Element Sum and Digit Sum of an Array](./solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
diff --git a/solutions/2506-count-pairs-of-similar-strings.js b/solutions/2506-count-pairs-of-similar-strings.js
new file mode 100644
index 00000000..3a4d78ef
--- /dev/null
+++ b/solutions/2506-count-pairs-of-similar-strings.js
@@ -0,0 +1,36 @@
+/**
+ * 2506. Count Pairs Of Similar Strings
+ * https://leetcode.com/problems/count-pairs-of-similar-strings/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed string array words.
+ *
+ * Two strings are similar if they consist of the same characters.
+ * - For example, "abca" and "cba" are similar since both consist of characters 'a', 'b', and 'c'.
+ * - However, "abacba" and "bcfd" are not similar since they do not consist of the same characters.
+ *
+ * Return the number of pairs (i, j) such that 0 <= i < j <= word.length - 1 and the two strings
+ * words[i] and words[j] are similar.
+ */
+
+/**
+ * @param {string[]} words
+ * @return {number}
+ */
+var similarPairs = function(words) {
+  const map = new Map();
+  let result = 0;
+
+  for (const word of words) {
+    const charSet = [...new Set(word.split(''))].sort().join('');
+    map.set(charSet, (map.get(charSet) || 0) + 1);
+  }
+
+  for (const count of map.values()) {
+    if (count > 1) {
+      result += (count * (count - 1)) / 2;
+    }
+  }
+
+  return result;
+};

From 7da572c3dc848bb258fbb5b5dfbf440c3e03b7f1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 12:46:01 -0500
Subject: [PATCH 483/495] Add solution #2507

---
 README.md                                     |  3 +-
 ...ter-replacing-with-sum-of-prime-factors.js | 37 +++++++++++++++++++
 2 files changed, 39 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2507-smallest-value-after-replacing-with-sum-of-prime-factors.js

diff --git a/README.md b/README.md
index b160eef9..0d136b9e 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,987 LeetCode solutions in JavaScript
+# 1,988 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1887,6 +1887,7 @@
 2502|[Design Memory Allocator](./solutions/2502-design-memory-allocator.js)|Medium|
 2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard|
 2506|[Count Pairs Of Similar Strings](./solutions/2506-count-pairs-of-similar-strings.js)|Easy|
+2507|[Smallest Value After Replacing With Sum of Prime Factors](./solutions/2507-smallest-value-after-replacing-with-sum-of-prime-factors.js)|Medium|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
 2535|[Difference Between Element Sum and Digit Sum of an Array](./solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
diff --git a/solutions/2507-smallest-value-after-replacing-with-sum-of-prime-factors.js b/solutions/2507-smallest-value-after-replacing-with-sum-of-prime-factors.js
new file mode 100644
index 00000000..d77f5c3a
--- /dev/null
+++ b/solutions/2507-smallest-value-after-replacing-with-sum-of-prime-factors.js
@@ -0,0 +1,37 @@
+/**
+ * 2507. Smallest Value After Replacing With Sum of Prime Factors
+ * https://leetcode.com/problems/smallest-value-after-replacing-with-sum-of-prime-factors/
+ * Difficulty: Medium
+ *
+ * You are given a positive integer n.
+ *
+ * Continuously replace n with the sum of its prime factors.
+ * - Note that if a prime factor divides n multiple times, it should be included in the sum as many
+ *   times as it divides n.
+ *
+ * Return the smallest value n will take on.
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var smallestValue = function(n) {
+  while (true) {
+    const next = sumPrimeFactors(n);
+    if (next === n) return n;
+    n = next;
+  }
+
+  function sumPrimeFactors(num) {
+    let sum = 0;
+    for (let i = 2; i * i <= num; i++) {
+      while (num % i === 0) {
+        sum += i;
+        num /= i;
+      }
+    }
+    if (num > 1) sum += num;
+    return sum;
+  }
+};

From 94cdbd5684966a93649f76e3f92a7e1f67d6801b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 12:48:06 -0500
Subject: [PATCH 484/495] Add solution #2509

---
 README.md                                     |  3 +-
 .../2509-cycle-length-queries-in-a-tree.js    | 54 +++++++++++++++++++
 2 files changed, 56 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2509-cycle-length-queries-in-a-tree.js

diff --git a/README.md b/README.md
index 0d136b9e..62bac55a 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,988 LeetCode solutions in JavaScript
+# 1,989 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1888,6 +1888,7 @@
 2503|[Maximum Number of Points From Grid Queries](./solutions/2503-maximum-number-of-points-from-grid-queries.js)|Hard|
 2506|[Count Pairs Of Similar Strings](./solutions/2506-count-pairs-of-similar-strings.js)|Easy|
 2507|[Smallest Value After Replacing With Sum of Prime Factors](./solutions/2507-smallest-value-after-replacing-with-sum-of-prime-factors.js)|Medium|
+2509|[Cycle Length Queries in a Tree](./solutions/2509-cycle-length-queries-in-a-tree.js)|Hard|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
 2535|[Difference Between Element Sum and Digit Sum of an Array](./solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
diff --git a/solutions/2509-cycle-length-queries-in-a-tree.js b/solutions/2509-cycle-length-queries-in-a-tree.js
new file mode 100644
index 00000000..180c2a6c
--- /dev/null
+++ b/solutions/2509-cycle-length-queries-in-a-tree.js
@@ -0,0 +1,54 @@
+/**
+ * 2509. Cycle Length Queries in a Tree
+ * https://leetcode.com/problems/cycle-length-queries-in-a-tree/
+ * Difficulty: Hard
+ *
+ * You are given an integer n. There is a complete binary tree with 2n - 1 nodes. The root of
+ * that tree is the node with the value 1, and every node with a value val in the range
+ * [1, 2n - 1 - 1] has two children where:
+ * - The left node has the value 2 * val, and
+ * - The right node has the value 2 * val + 1.
+ *
+ * You are also given a 2D integer array queries of length m, where queries[i] = [ai, bi]. For
+ * each query, solve the following problem:
+ * 1. Add an edge between the nodes with values ai and bi.
+ * 2. Find the length of the cycle in the graph.
+ * 3. Remove the added edge between nodes with values ai and bi.
+ *
+ * Note that:
+ * - A cycle is a path that starts and ends at the same node, and each edge in the path is
+ *   visited only once.
+ * - The length of a cycle is the number of edges visited in the cycle.
+ * - There could be multiple edges between two nodes in the tree after adding the edge of
+ *   the query.
+ *
+ * Return an array answer of length m where answer[i] is the answer to the ith query.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} queries
+ * @return {number[]}
+ */
+var cycleLengthQueries = function(n, queries) {
+  const result = [];
+
+  for (const [a, b] of queries) {
+    let x = a;
+    let y = b;
+    let pathLength = 1;
+
+    while (x !== y) {
+      if (x > y) {
+        x = Math.floor(x / 2);
+      } else {
+        y = Math.floor(y / 2);
+      }
+      pathLength++;
+    }
+
+    result.push(pathLength);
+  }
+
+  return result;
+};

From 2508b1cd30f556ecf724c5cb2d3735e8eeaa55fb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 12:49:12 -0500
Subject: [PATCH 485/495] Add solution #2515

---
 README.md                                     |  3 +-
 ...ce-to-target-string-in-a-circular-array.js | 37 +++++++++++++++++++
 2 files changed, 39 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2515-shortest-distance-to-target-string-in-a-circular-array.js

diff --git a/README.md b/README.md
index 62bac55a..e29a5434 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,989 LeetCode solutions in JavaScript
+# 1,990 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1889,6 +1889,7 @@
 2506|[Count Pairs Of Similar Strings](./solutions/2506-count-pairs-of-similar-strings.js)|Easy|
 2507|[Smallest Value After Replacing With Sum of Prime Factors](./solutions/2507-smallest-value-after-replacing-with-sum-of-prime-factors.js)|Medium|
 2509|[Cycle Length Queries in a Tree](./solutions/2509-cycle-length-queries-in-a-tree.js)|Hard|
+2515|[Shortest Distance to Target String in a Circular Array](./solutions/2515-shortest-distance-to-target-string-in-a-circular-array.js)|Easy|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
 2535|[Difference Between Element Sum and Digit Sum of an Array](./solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
diff --git a/solutions/2515-shortest-distance-to-target-string-in-a-circular-array.js b/solutions/2515-shortest-distance-to-target-string-in-a-circular-array.js
new file mode 100644
index 00000000..5c315a34
--- /dev/null
+++ b/solutions/2515-shortest-distance-to-target-string-in-a-circular-array.js
@@ -0,0 +1,37 @@
+/**
+ * 2515. Shortest Distance to Target String in a Circular Array
+ * https://leetcode.com/problems/shortest-distance-to-target-string-in-a-circular-array/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed circular string array words and a string target. A circular array
+ * means that the array's end connects to the array's beginning.
+ * - Formally, the next element of words[i] is words[(i + 1) % n] and the previous element of
+ *   words[i] is words[(i - 1 + n) % n], where n is the length of words.
+ *
+ * Starting from startIndex, you can move to either the next word or the previous word with 1
+ * step at a time.
+ *
+ * Return the shortest distance needed to reach the string target. If the string target does not
+ * exist in words, return -1.
+ */
+
+/**
+ * @param {string[]} words
+ * @param {string} target
+ * @param {number} startIndex
+ * @return {number}
+ */
+var closestTarget = function(words, target, startIndex) {
+  const n = words.length;
+  let minDistance = Infinity;
+
+  for (let i = 0; i < n; i++) {
+    if (words[i] === target) {
+      const forward = Math.abs(i - startIndex);
+      const backward = n - forward;
+      minDistance = Math.min(minDistance, forward, backward);
+    }
+  }
+
+  return minDistance === Infinity ? -1 : minDistance;
+};

From 62a22439bcb80d34cea154f773010ea2789cc949 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 12:53:25 -0500
Subject: [PATCH 486/495] Add solution #2516

---
 README.md                                     |  3 +-
 ...k-of-each-character-from-left-and-right.js | 46 +++++++++++++++++++
 2 files changed, 48 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2516-take-k-of-each-character-from-left-and-right.js

diff --git a/README.md b/README.md
index e29a5434..b5dd30ef 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,990 LeetCode solutions in JavaScript
+# 1,991 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1890,6 +1890,7 @@
 2507|[Smallest Value After Replacing With Sum of Prime Factors](./solutions/2507-smallest-value-after-replacing-with-sum-of-prime-factors.js)|Medium|
 2509|[Cycle Length Queries in a Tree](./solutions/2509-cycle-length-queries-in-a-tree.js)|Hard|
 2515|[Shortest Distance to Target String in a Circular Array](./solutions/2515-shortest-distance-to-target-string-in-a-circular-array.js)|Easy|
+2516|[Take K of Each Character From Left and Right](./solutions/2516-take-k-of-each-character-from-left-and-right.js)|Medium|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
 2535|[Difference Between Element Sum and Digit Sum of an Array](./solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
diff --git a/solutions/2516-take-k-of-each-character-from-left-and-right.js b/solutions/2516-take-k-of-each-character-from-left-and-right.js
new file mode 100644
index 00000000..a37d84a9
--- /dev/null
+++ b/solutions/2516-take-k-of-each-character-from-left-and-right.js
@@ -0,0 +1,46 @@
+/**
+ * 2516. Take K of Each Character From Left and Right
+ * https://leetcode.com/problems/take-k-of-each-character-from-left-and-right/
+ * Difficulty: Medium
+ *
+ * You are given a string s consisting of the characters 'a', 'b', and 'c' and a non-negative
+ * integer k. Each minute, you may take either the leftmost character of s, or the rightmost
+ * character of s.
+ *
+ * Return the minimum number of minutes needed for you to take at least k of each character,
+ * or return -1 if it is not possible to take k of each character.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} k
+ * @return {number}
+ */
+var takeCharacters = function(s, k) {
+  const n = s.length;
+  const counts = { a: 0, b: 0, c: 0 };
+
+  for (const char of s) {
+    counts[char]++;
+  }
+
+  if (counts.a < k || counts.b < k || counts.c < k) return -1;
+
+  let maxWindow = 0;
+  let left = 0;
+  const windowCounts = { a: 0, b: 0, c: 0 };
+
+  for (let right = 0; right < n; right++) {
+    windowCounts[s[right]]++;
+
+    while (windowCounts.a > counts.a - k || windowCounts.b > counts.b - k
+          || windowCounts.c > counts.c - k) {
+      windowCounts[s[left]]--;
+      left++;
+    }
+
+    maxWindow = Math.max(maxWindow, right - left + 1);
+  }
+
+  return n - maxWindow;
+};

From 2210c027f7453727d25ef4896e1b25601a356752 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 12:54:32 -0500
Subject: [PATCH 487/495] Add solution #2517

---
 README.md                                     |  3 +-
 .../2517-maximum-tastiness-of-candy-basket.js | 47 +++++++++++++++++++
 2 files changed, 49 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2517-maximum-tastiness-of-candy-basket.js

diff --git a/README.md b/README.md
index b5dd30ef..0e83cfb4 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,991 LeetCode solutions in JavaScript
+# 1,992 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1891,6 +1891,7 @@
 2509|[Cycle Length Queries in a Tree](./solutions/2509-cycle-length-queries-in-a-tree.js)|Hard|
 2515|[Shortest Distance to Target String in a Circular Array](./solutions/2515-shortest-distance-to-target-string-in-a-circular-array.js)|Easy|
 2516|[Take K of Each Character From Left and Right](./solutions/2516-take-k-of-each-character-from-left-and-right.js)|Medium|
+2517|[Maximum Tastiness of Candy Basket](./solutions/2517-maximum-tastiness-of-candy-basket.js)|Medium|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
 2535|[Difference Between Element Sum and Digit Sum of an Array](./solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
diff --git a/solutions/2517-maximum-tastiness-of-candy-basket.js b/solutions/2517-maximum-tastiness-of-candy-basket.js
new file mode 100644
index 00000000..6ef4a383
--- /dev/null
+++ b/solutions/2517-maximum-tastiness-of-candy-basket.js
@@ -0,0 +1,47 @@
+/**
+ * 2517. Maximum Tastiness of Candy Basket
+ * https://leetcode.com/problems/maximum-tastiness-of-candy-basket/
+ * Difficulty: Medium
+ *
+ * You are given an array of positive integers price where price[i] denotes the price of the ith
+ * candy and a positive integer k.
+ *
+ * The store sells baskets of k distinct candies. The tastiness of a candy basket is the smallest
+ * absolute difference of the prices of any two candies in the basket.
+ *
+ * Return the maximum tastiness of a candy basket.
+ */
+
+/**
+ * @param {number[]} price
+ * @param {number} k
+ * @return {number}
+ */
+var maximumTastiness = function(price, k) {
+  price.sort((a, b) => a - b);
+  let left = 0;
+  let right = price[price.length - 1] - price[0];
+  let result = 0;
+
+  while (left <= right) {
+    const mid = Math.floor((left + right) / 2);
+    let count = 1;
+    let prev = price[0];
+
+    for (let i = 1; i < price.length; i++) {
+      if (price[i] - prev >= mid) {
+        count++;
+        prev = price[i];
+      }
+    }
+
+    if (count >= k) {
+      result = mid;
+      left = mid + 1;
+    } else {
+      right = mid - 1;
+    }
+  }
+
+  return result;
+};

From bdb037a30311457667066f085ecebe03472ca37c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 12:56:09 -0500
Subject: [PATCH 488/495] Add solution #2520

---
 README.md                                     |  3 ++-
 ...0-count-the-digits-that-divide-a-number.js | 25 +++++++++++++++++++
 2 files changed, 27 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2520-count-the-digits-that-divide-a-number.js

diff --git a/README.md b/README.md
index 0e83cfb4..a1fecaaa 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,992 LeetCode solutions in JavaScript
+# 1,993 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1892,6 +1892,7 @@
 2515|[Shortest Distance to Target String in a Circular Array](./solutions/2515-shortest-distance-to-target-string-in-a-circular-array.js)|Easy|
 2516|[Take K of Each Character From Left and Right](./solutions/2516-take-k-of-each-character-from-left-and-right.js)|Medium|
 2517|[Maximum Tastiness of Candy Basket](./solutions/2517-maximum-tastiness-of-candy-basket.js)|Medium|
+2520|[Count the Digits That Divide a Number](./solutions/2520-count-the-digits-that-divide-a-number.js)|Easy|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
 2535|[Difference Between Element Sum and Digit Sum of an Array](./solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
diff --git a/solutions/2520-count-the-digits-that-divide-a-number.js b/solutions/2520-count-the-digits-that-divide-a-number.js
new file mode 100644
index 00000000..614d3add
--- /dev/null
+++ b/solutions/2520-count-the-digits-that-divide-a-number.js
@@ -0,0 +1,25 @@
+/**
+ * 2520. Count the Digits That Divide a Number
+ * https://leetcode.com/problems/count-the-digits-that-divide-a-number/
+ * Difficulty: Easy
+ *
+ * Given an integer num, return the number of digits in num that divide num.
+ *
+ * An integer val divides nums if nums % val == 0.
+ */
+
+/**
+ * @param {number} num
+ * @return {number}
+ */
+var countDigits = function(num) {
+  let result = 0;
+  let n = num;
+
+  while (n > 0) {
+    if (num % (n % 10) === 0) result++;
+    n = Math.floor(n / 10);
+  }
+
+  return result;
+};

From a8ea67bd0c93525f5f00456ad37941908cabe445 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 12:57:36 -0500
Subject: [PATCH 489/495] Add solution #2521

---
 README.md                                     |  3 +-
 ...tinct-prime-factors-of-product-of-array.js | 36 +++++++++++++++++++
 2 files changed, 38 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2521-distinct-prime-factors-of-product-of-array.js

diff --git a/README.md b/README.md
index a1fecaaa..fb0246cc 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,993 LeetCode solutions in JavaScript
+# 1,994 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1893,6 +1893,7 @@
 2516|[Take K of Each Character From Left and Right](./solutions/2516-take-k-of-each-character-from-left-and-right.js)|Medium|
 2517|[Maximum Tastiness of Candy Basket](./solutions/2517-maximum-tastiness-of-candy-basket.js)|Medium|
 2520|[Count the Digits That Divide a Number](./solutions/2520-count-the-digits-that-divide-a-number.js)|Easy|
+2521|[Distinct Prime Factors of Product of Array](./solutions/2521-distinct-prime-factors-of-product-of-array.js)|Medium|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
 2535|[Difference Between Element Sum and Digit Sum of an Array](./solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
diff --git a/solutions/2521-distinct-prime-factors-of-product-of-array.js b/solutions/2521-distinct-prime-factors-of-product-of-array.js
new file mode 100644
index 00000000..6d723c46
--- /dev/null
+++ b/solutions/2521-distinct-prime-factors-of-product-of-array.js
@@ -0,0 +1,36 @@
+/**
+ * 2521. Distinct Prime Factors of Product of Array
+ * https://leetcode.com/problems/distinct-prime-factors-of-product-of-array/
+ * Difficulty: Medium
+ *
+ * Given an array of positive integers nums, return the number of distinct prime factors in the
+ * product of the elements of nums.
+ *
+ * Note that:
+ * - A number greater than 1 is called prime if it is divisible by only 1 and itself.
+ * - An integer val1 is a factor of another integer val2 if val2 / val1 is an integer.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var distinctPrimeFactors = function(nums) {
+  const set = new Set();
+
+  for (const num of nums) {
+    factorize(num);
+  }
+
+  return set.size;
+
+  function factorize(num) {
+    for (let i = 2; i * i <= num; i++) {
+      while (num % i === 0) {
+        set.add(i);
+        num /= i;
+      }
+    }
+    if (num > 1) set.add(num);
+  }
+};

From a95ea86a372cec98fa45eb1bf80947d2f172a1af Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 12:59:10 -0500
Subject: [PATCH 490/495] Add solution #2522

---
 README.md                                     |  3 +-
 ...g-into-substrings-with-values-at-most-k.js | 42 +++++++++++++++++++
 2 files changed, 44 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2522-partition-string-into-substrings-with-values-at-most-k.js

diff --git a/README.md b/README.md
index fb0246cc..433f4bfa 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,994 LeetCode solutions in JavaScript
+# 1,995 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1894,6 +1894,7 @@
 2517|[Maximum Tastiness of Candy Basket](./solutions/2517-maximum-tastiness-of-candy-basket.js)|Medium|
 2520|[Count the Digits That Divide a Number](./solutions/2520-count-the-digits-that-divide-a-number.js)|Easy|
 2521|[Distinct Prime Factors of Product of Array](./solutions/2521-distinct-prime-factors-of-product-of-array.js)|Medium|
+2522|[Partition String Into Substrings With Values at Most K](./solutions/2522-partition-string-into-substrings-with-values-at-most-k.js)|Medium|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
 2535|[Difference Between Element Sum and Digit Sum of an Array](./solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
diff --git a/solutions/2522-partition-string-into-substrings-with-values-at-most-k.js b/solutions/2522-partition-string-into-substrings-with-values-at-most-k.js
new file mode 100644
index 00000000..f5777dcf
--- /dev/null
+++ b/solutions/2522-partition-string-into-substrings-with-values-at-most-k.js
@@ -0,0 +1,42 @@
+/**
+ * 2522. Partition String Into Substrings With Values at Most K
+ * https://leetcode.com/problems/partition-string-into-substrings-with-values-at-most-k/
+ * Difficulty: Medium
+ *
+ * You are given a string s consisting of digits from 1 to 9 and an integer k.
+ *
+ * A partition of a string s is called good if:
+ * - Each digit of s is part of exactly one substring.
+ * - The value of each substring is less than or equal to k.
+ *
+ * Return the minimum number of substrings in a good partition of s. If no good partition of
+ * s exists, return -1.
+ *
+ * Note that:
+ * - The value of a string is its result when interpreted as an integer. For example, the value
+ *   of "123" is 123 and the value of "1" is 1.
+ * - A substring is a contiguous sequence of characters within a string.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} k
+ * @return {number}
+ */
+var minimumPartition = function(s, k) {
+  let result = 1;
+  let current = 0;
+
+  for (const digit of s) {
+    const value = current * 10 + Number(digit);
+    if (value <= k) {
+      current = value;
+    } else {
+      if (Number(digit) > k) return -1;
+      current = Number(digit);
+      result++;
+    }
+  }
+
+  return result;
+};

From 31a3618dec6f2381735d72c06577b6b721695658 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 13:00:33 -0500
Subject: [PATCH 491/495] Add solution #2527

---
 README.md                                  |  3 ++-
 solutions/2527-find-xor-beauty-of-array.js | 30 ++++++++++++++++++++++
 2 files changed, 32 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2527-find-xor-beauty-of-array.js

diff --git a/README.md b/README.md
index 433f4bfa..f886a2a6 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,995 LeetCode solutions in JavaScript
+# 1,996 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1896,6 +1896,7 @@
 2521|[Distinct Prime Factors of Product of Array](./solutions/2521-distinct-prime-factors-of-product-of-array.js)|Medium|
 2522|[Partition String Into Substrings With Values at Most K](./solutions/2522-partition-string-into-substrings-with-values-at-most-k.js)|Medium|
 2523|[Closest Prime Numbers in Range](./solutions/2523-closest-prime-numbers-in-range.js)|Medium|
+2527|[Find Xor-Beauty of Array](./solutions/2527-find-xor-beauty-of-array.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
 2535|[Difference Between Element Sum and Digit Sum of an Array](./solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
 2537|[Count the Number of Good Subarrays](./solutions/2537-count-the-number-of-good-subarrays.js)|Medium|
diff --git a/solutions/2527-find-xor-beauty-of-array.js b/solutions/2527-find-xor-beauty-of-array.js
new file mode 100644
index 00000000..172eb3e2
--- /dev/null
+++ b/solutions/2527-find-xor-beauty-of-array.js
@@ -0,0 +1,30 @@
+/**
+ * 2527. Find Xor-Beauty of Array
+ * https://leetcode.com/problems/find-xor-beauty-of-array/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums.
+ *
+ * The effective value of three indices i, j, and k is defined as ((nums[i] | nums[j]) & nums[k]).
+ *
+ * The xor-beauty of the array is the XORing of the effective values of all the possible triplets
+ * of indices (i, j, k) where 0 <= i, j, k < n.
+ *
+ * Return the xor-beauty of nums.
+ *
+ * Note that:
+ * - val1 | val2 is bitwise OR of val1 and val2.
+ * - val1 & val2 is bitwise AND of val1 and val2.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var xorBeauty = function(nums) {
+  let result = 0;
+  for (const num of nums) {
+    result ^= num;
+  }
+  return result;
+};

From 2614f5d2037953b93892270e37e4ed9c1d161ef9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 13:01:42 -0500
Subject: [PATCH 492/495] Add solution #2536

---
 README.md                                     |  3 +-
 .../2536-increment-submatrices-by-one.js      | 46 +++++++++++++++++++
 2 files changed, 48 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2536-increment-submatrices-by-one.js

diff --git a/README.md b/README.md
index f886a2a6..fac00357 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,996 LeetCode solutions in JavaScript
+# 1,997 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1899,6 +1899,7 @@
 2527|[Find Xor-Beauty of Array](./solutions/2527-find-xor-beauty-of-array.js)|Medium|
 2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
 2535|[Difference Between Element Sum and Digit Sum of an Array](./solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
+2536|[Increment Submatrices by One](./solutions/2536-increment-submatrices-by-one.js)|Medium|
 2537|[Count the Number of Good Subarrays](./solutions/2537-count-the-number-of-good-subarrays.js)|Medium|
 2542|[Maximum Subsequence Score](./solutions/2542-maximum-subsequence-score.js)|Medium|
 2551|[Put Marbles in Bags](./solutions/2551-put-marbles-in-bags.js)|Hard|
diff --git a/solutions/2536-increment-submatrices-by-one.js b/solutions/2536-increment-submatrices-by-one.js
new file mode 100644
index 00000000..c5acdddd
--- /dev/null
+++ b/solutions/2536-increment-submatrices-by-one.js
@@ -0,0 +1,46 @@
+/**
+ * 2536. Increment Submatrices by One
+ * https://leetcode.com/problems/increment-submatrices-by-one/
+ * Difficulty: Medium
+ *
+ * You are given a positive integer n, indicating that we initially have an n x n 0-indexed integer
+ * matrix mat filled with zeroes.
+ *
+ * You are also given a 2D integer array query. For each query[i] = [row1i, col1i, row2i, col2i],
+ * you should do the following operation:
+ * - Add 1 to every element in the submatrix with the top left corner (row1i, col1i) and the bottom
+ *   right corner (row2i, col2i). That is, add 1 to mat[x][y] for all row1i <= x <= row2i and
+ *   col1i <= y <= col2i.
+ *
+ * Return the matrix mat after performing every query.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} queries
+ * @return {number[][]}
+ */
+var rangeAddQueries = function(n, queries) {
+  const matrix = new Array(n).fill().map(() => new Array(n).fill(0));
+
+  for (const [row1, col1, row2, col2] of queries) {
+    matrix[row1][col1]++;
+    if (row2 + 1 < n) matrix[row2 + 1][col1]--;
+    if (col2 + 1 < n) matrix[row1][col2 + 1]--;
+    if (row2 + 1 < n && col2 + 1 < n) matrix[row2 + 1][col2 + 1]++;
+  }
+
+  for (let i = 0; i < n; i++) {
+    for (let j = 1; j < n; j++) {
+      matrix[i][j] += matrix[i][j - 1];
+    }
+  }
+
+  for (let i = 1; i < n; i++) {
+    for (let j = 0; j < n; j++) {
+      matrix[i][j] += matrix[i - 1][j];
+    }
+  }
+
+  return matrix;
+};

From 9412c6701f9aaec7c58991e404fa58023af5458f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 13:02:48 -0500
Subject: [PATCH 493/495] Add solution #2540

---
 README.md                              |  3 ++-
 solutions/2540-minimum-common-value.js | 29 ++++++++++++++++++++++++++
 2 files changed, 31 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2540-minimum-common-value.js

diff --git a/README.md b/README.md
index fac00357..b2bf0e04 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,997 LeetCode solutions in JavaScript
+# 1,998 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1901,6 +1901,7 @@
 2535|[Difference Between Element Sum and Digit Sum of an Array](./solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
 2536|[Increment Submatrices by One](./solutions/2536-increment-submatrices-by-one.js)|Medium|
 2537|[Count the Number of Good Subarrays](./solutions/2537-count-the-number-of-good-subarrays.js)|Medium|
+2540|[Minimum Common Value](./solutions/2540-minimum-common-value.js)|Easy|
 2542|[Maximum Subsequence Score](./solutions/2542-maximum-subsequence-score.js)|Medium|
 2551|[Put Marbles in Bags](./solutions/2551-put-marbles-in-bags.js)|Hard|
 2559|[Count Vowel Strings in Ranges](./solutions/2559-count-vowel-strings-in-ranges.js)|Medium|
diff --git a/solutions/2540-minimum-common-value.js b/solutions/2540-minimum-common-value.js
new file mode 100644
index 00000000..32b8dea1
--- /dev/null
+++ b/solutions/2540-minimum-common-value.js
@@ -0,0 +1,29 @@
+/**
+ * 2540. Minimum Common Value
+ * https://leetcode.com/problems/minimum-common-value/
+ * Difficulty: Easy
+ *
+ * Given two integer arrays nums1 and nums2, sorted in non-decreasing order, return the minimum
+ * integer common to both arrays. If there is no common integer amongst nums1 and nums2, return -1.
+ *
+ * Note that an integer is said to be common to nums1 and nums2 if both arrays have at least one
+ * occurrence of that integer.
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @return {number}
+ */
+var getCommon = function(nums1, nums2) {
+  let i = 0;
+  let j = 0;
+
+  while (i < nums1.length && j < nums2.length) {
+    if (nums1[i] === nums2[j]) return nums1[i];
+    if (nums1[i] < nums2[j]) i++;
+    else j++;
+  }
+
+  return -1;
+};

From 7fb7aa9c6ff121565b9294d6b311e0a39702228d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 13:04:38 -0500
Subject: [PATCH 494/495] Add solution #2543

---
 README.md                                     |  3 +-
 solutions/2543-check-if-point-is-reachable.js | 40 +++++++++++++++++++
 2 files changed, 42 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2543-check-if-point-is-reachable.js

diff --git a/README.md b/README.md
index b2bf0e04..5624c56a 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,998 LeetCode solutions in JavaScript
+# 1,999 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1903,6 +1903,7 @@
 2537|[Count the Number of Good Subarrays](./solutions/2537-count-the-number-of-good-subarrays.js)|Medium|
 2540|[Minimum Common Value](./solutions/2540-minimum-common-value.js)|Easy|
 2542|[Maximum Subsequence Score](./solutions/2542-maximum-subsequence-score.js)|Medium|
+2543|[Check if Point Is Reachable](./solutions/2543-check-if-point-is-reachable.js)|Hard|
 2551|[Put Marbles in Bags](./solutions/2551-put-marbles-in-bags.js)|Hard|
 2559|[Count Vowel Strings in Ranges](./solutions/2559-count-vowel-strings-in-ranges.js)|Medium|
 2560|[House Robber IV](./solutions/2560-house-robber-iv.js)|Medium|
diff --git a/solutions/2543-check-if-point-is-reachable.js b/solutions/2543-check-if-point-is-reachable.js
new file mode 100644
index 00000000..31d51902
--- /dev/null
+++ b/solutions/2543-check-if-point-is-reachable.js
@@ -0,0 +1,40 @@
+/**
+ * 2543. Check if Point Is Reachable
+ * https://leetcode.com/problems/check-if-point-is-reachable/
+ * Difficulty: Hard
+ *
+ * There exists an infinitely large grid. You are currently at point (1, 1), and you need
+ * to reach the point (targetX, targetY) using a finite number of steps.
+ *
+ * In one step, you can move from point (x, y) to any one of the following points:
+ * - (x, y - x)
+ * - (x - y, y)
+ * - (2 * x, y)
+ * - (x, 2 * y)
+ *
+ * Given two integers targetX and targetY representing the X-coordinate and Y-coordinate of
+ * your final position, return true if you can reach the point from (1, 1) using some number
+ * of steps, and false otherwise.
+ */
+
+/**
+ * @param {number} targetX
+ * @param {number} targetY
+ * @return {boolean}
+ */
+var isReachable = function(targetX, targetY) {
+  let g = gcd(targetX, targetY);
+  while (g % 2 === 0) {
+    g /= 2;
+  }
+
+  return g === 1;
+};
+
+function gcd(a, b) {
+  while (b) {
+    a %= b;
+    [a, b] = [b, a];
+  }
+  return a;
+}

From b001f480629975ebcbf394f679ec6954601ada27 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 24 May 2025 13:05:29 -0500
Subject: [PATCH 495/495] Add solution #2544

---
 README.md                               |  3 ++-
 solutions/2544-alternating-digit-sum.js | 29 +++++++++++++++++++++++++
 2 files changed, 31 insertions(+), 1 deletion(-)
 create mode 100644 solutions/2544-alternating-digit-sum.js

diff --git a/README.md b/README.md
index 5624c56a..753dadfe 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 1,999 LeetCode solutions in JavaScript
+# 2,000 LeetCode solutions in JavaScript
 
 [https://leetcodejavascript.com](https://leetcodejavascript.com)
 
@@ -1904,6 +1904,7 @@
 2540|[Minimum Common Value](./solutions/2540-minimum-common-value.js)|Easy|
 2542|[Maximum Subsequence Score](./solutions/2542-maximum-subsequence-score.js)|Medium|
 2543|[Check if Point Is Reachable](./solutions/2543-check-if-point-is-reachable.js)|Hard|
+2544|[Alternating Digit Sum](./solutions/2544-alternating-digit-sum.js)|Easy|
 2551|[Put Marbles in Bags](./solutions/2551-put-marbles-in-bags.js)|Hard|
 2559|[Count Vowel Strings in Ranges](./solutions/2559-count-vowel-strings-in-ranges.js)|Medium|
 2560|[House Robber IV](./solutions/2560-house-robber-iv.js)|Medium|
diff --git a/solutions/2544-alternating-digit-sum.js b/solutions/2544-alternating-digit-sum.js
new file mode 100644
index 00000000..49aa7939
--- /dev/null
+++ b/solutions/2544-alternating-digit-sum.js
@@ -0,0 +1,29 @@
+/**
+ * 2544. Alternating Digit Sum
+ * https://leetcode.com/problems/alternating-digit-sum/
+ * Difficulty: Easy
+ *
+ * You are given a positive integer n. Each digit of n has a sign according to the following rules:
+ * - The most significant digit is assigned a positive sign.
+ * - Each other digit has an opposite sign to its adjacent digits.
+ *
+ * Return the sum of all digits with their corresponding sign.
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var alternateDigitSum = function(n) {
+  let sum = 0;
+  let isPositive = true;
+
+  while (n > 0) {
+    const digit = n % 10;
+    sum += isPositive ? digit : -digit;
+    isPositive = !isPositive;
+    n = Math.floor(n / 10);
+  }
+
+  return isPositive ? -sum : sum;
+};