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 001/994] 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 002/994] 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 003/994] 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 004/994] 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 005/994] 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 006/994] 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 007/994] 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 008/994] 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 009/994] 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 010/994] 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 011/994] 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 012/994] 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 013/994] 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 014/994] 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 015/994] 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 016/994] 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 017/994] 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 018/994] 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 019/994] 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 020/994] 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 021/994] 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 022/994] 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 023/994] 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 024/994] 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 025/994] 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 026/994] 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 027/994] 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 028/994] 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 029/994] 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 030/994] 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 031/994] 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 032/994] 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 033/994] 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 034/994] 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 035/994] 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 036/994] 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 037/994] 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 038/994] 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 039/994] 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 040/994] 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 041/994] 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 042/994] 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 043/994] 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 044/994] 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 045/994] 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 046/994] 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 047/994] 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 048/994] 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 049/994] 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 050/994] 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 051/994] 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 052/994] 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 053/994] 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 054/994] 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 055/994] 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 056/994] 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 057/994] 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 058/994] 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 059/994] 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 060/994] 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 061/994] 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 062/994] 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 063/994] 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 064/994] 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 065/994] 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 066/994] 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 067/994] 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 068/994] 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 069/994] 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 070/994] 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 071/994] 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 072/994] 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 073/994] 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 074/994] 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 075/994] 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 076/994] 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 077/994] 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 078/994] 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 079/994] 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 080/994] 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 081/994] 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 082/994] 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 083/994] 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 084/994] 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 085/994] 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 086/994] 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 087/994] 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 088/994] 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 089/994] 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 090/994] 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 091/994] 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 092/994] 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 093/994] 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 094/994] 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 095/994] 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 096/994] 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 097/994] 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 098/994] 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 099/994] 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 100/994] 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 101/994] 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 102/994] 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 103/994] 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 104/994] 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 105/994] 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 106/994] 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 107/994] 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 108/994] 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 109/994] 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 110/994] 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 111/994] 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 112/994] 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 113/994] 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 114/994] 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 115/994] 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 116/994] 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 117/994] 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 118/994] 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 119/994] 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 120/994] 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 121/994] 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 122/994] 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 123/994] 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 124/994] 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 125/994] 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 126/994] 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 127/994] 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 128/994] 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 129/994] 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 130/994] 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 131/994] 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 132/994] 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 133/994] 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 134/994] 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 135/994] 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 136/994] 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 137/994] 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 138/994] 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 139/994] 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 140/994] 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 141/994] 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 142/994] 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 143/994] 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 144/994] 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 145/994] 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 146/994] 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 147/994] 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 148/994] 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 149/994] 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 150/994] 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 151/994] 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 152/994] 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 153/994] 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 154/994] 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 155/994] 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 156/994] 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 157/994] 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 158/994] 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 159/994] 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 160/994] 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 161/994] 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 162/994] 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 163/994] 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 164/994] 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 165/994] 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 166/994] 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 167/994] 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 168/994] 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 169/994] 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 170/994] 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 171/994] 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 172/994] 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 173/994] 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 174/994] 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 175/994] 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 176/994] 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 177/994] 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 178/994] 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 179/994] 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 180/994] 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 181/994] 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 182/994] 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 183/994] 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 184/994] 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 185/994] 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 186/994] 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 187/994] 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 188/994] 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 189/994] 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 190/994] 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 191/994] 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 192/994] 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 193/994] 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 194/994] 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 195/994] 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 196/994] 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 197/994] 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 198/994] 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 199/994] 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 200/994] 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 201/994] 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 202/994] 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 203/994] 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 204/994] 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 205/994] 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 206/994] 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 207/994] 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 208/994] 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 209/994] 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 210/994] 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 211/994] 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 212/994] 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 213/994] 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 214/994] 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 215/994] 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;
+};
From e244f915c557f017043834cc88c1fd7d3b92f149 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 00:03:15 -0500
Subject: [PATCH 216/994] Add solution #2545
---
README.md | 3 ++-
...45-sort-the-students-by-their-kth-score.js | 23 +++++++++++++++++++
2 files changed, 25 insertions(+), 1 deletion(-)
create mode 100644 solutions/2545-sort-the-students-by-their-kth-score.js
diff --git a/README.md b/README.md
index 753dadfe..4b582e67 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 2,000 LeetCode solutions in JavaScript
+# 2,000+ LeetCode solutions in JavaScript
[https://leetcodejavascript.com](https://leetcodejavascript.com)
@@ -1905,6 +1905,7 @@
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|
+2545|[Sort the Students by Their Kth Score](./solutions/2545-sort-the-students-by-their-kth-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|
2560|[House Robber IV](./solutions/2560-house-robber-iv.js)|Medium|
diff --git a/solutions/2545-sort-the-students-by-their-kth-score.js b/solutions/2545-sort-the-students-by-their-kth-score.js
new file mode 100644
index 00000000..55464ba9
--- /dev/null
+++ b/solutions/2545-sort-the-students-by-their-kth-score.js
@@ -0,0 +1,23 @@
+/**
+ * 2545. Sort the Students by Their Kth Score
+ * https://leetcode.com/problems/sort-the-students-by-their-kth-score/
+ * Difficulty: Medium
+ *
+ * There is a class with m students and n exams. You are given a 0-indexed m x n integer matrix
+ * score, where each row represents one student and score[i][j] denotes the score the ith student
+ * got in the jth exam. The matrix score contains distinct integers only.
+ *
+ * You are also given an integer k. Sort the students (i.e., the rows of the matrix) by their
+ * scores in the kth (0-indexed) exam from the highest to the lowest.
+ *
+ * Return the matrix after sorting it.
+ */
+
+/**
+ * @param {number[][]} score
+ * @param {number} k
+ * @return {number[][]}
+ */
+var sortTheStudents = function(score, k) {
+ return score.sort((studentA, studentB) => studentB[k] - studentA[k]);
+};
From 28b4ba01a68e627abf83631da4d0e63c04a26f6f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 00:04:56 -0500
Subject: [PATCH 217/994] Add solution #2546
---
README.md | 1 +
...itwise-operations-to-make-strings-equal.js | 25 +++++++++++++++++++
2 files changed, 26 insertions(+)
create mode 100644 solutions/2546-apply-bitwise-operations-to-make-strings-equal.js
diff --git a/README.md b/README.md
index 4b582e67..b029b0b5 100644
--- a/README.md
+++ b/README.md
@@ -1906,6 +1906,7 @@
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|
2545|[Sort the Students by Their Kth Score](./solutions/2545-sort-the-students-by-their-kth-score.js)|Medium|
+2546|[Apply Bitwise Operations to Make Strings Equal](./solutions/2546-apply-bitwise-operations-to-make-strings-equal.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|
2560|[House Robber IV](./solutions/2560-house-robber-iv.js)|Medium|
diff --git a/solutions/2546-apply-bitwise-operations-to-make-strings-equal.js b/solutions/2546-apply-bitwise-operations-to-make-strings-equal.js
new file mode 100644
index 00000000..e3b401a5
--- /dev/null
+++ b/solutions/2546-apply-bitwise-operations-to-make-strings-equal.js
@@ -0,0 +1,25 @@
+/**
+ * 2546. Apply Bitwise Operations to Make Strings Equal
+ * https://leetcode.com/problems/apply-bitwise-operations-to-make-strings-equal/
+ * Difficulty: Medium
+ *
+ * You are given two 0-indexed binary strings s and target of the same length n. You can do the
+ * following operation on s any number of times:
+ * - Choose two different indices i and j where 0 <= i, j < n.
+ * - Simultaneously, replace s[i] with (s[i] OR s[j]) and s[j] with (s[i] XOR s[j]).
+ *
+ * For example, if s = "0110", you can choose i = 0 and j = 2, then simultaneously replace s[0]
+ * with (s[0] OR s[2] = 0 OR 1 = 1), and s[2] with (s[0] XOR s[2] = 0 XOR 1 = 1), so we will
+ * have s = "1110".
+ *
+ * Return true if you can make the string s equal to target, or false otherwise.
+ */
+
+/**
+ * @param {string} s
+ * @param {string} target
+ * @return {boolean}
+ */
+var makeStringsEqual = function(s, target) {
+ return (s.includes('1') === target.includes('1'));
+};
From aa1ab97f5002e0baacbe68c9938315f6ffd03cbf Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 00:06:31 -0500
Subject: [PATCH 218/994] Add solution #2547
---
README.md | 1 +
.../2547-minimum-cost-to-split-an-array.js | 48 +++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/2547-minimum-cost-to-split-an-array.js
diff --git a/README.md b/README.md
index b029b0b5..9b13011f 100644
--- a/README.md
+++ b/README.md
@@ -1907,6 +1907,7 @@
2544|[Alternating Digit Sum](./solutions/2544-alternating-digit-sum.js)|Easy|
2545|[Sort the Students by Their Kth Score](./solutions/2545-sort-the-students-by-their-kth-score.js)|Medium|
2546|[Apply Bitwise Operations to Make Strings Equal](./solutions/2546-apply-bitwise-operations-to-make-strings-equal.js)|Medium|
+2547|[Minimum Cost to Split an Array](./solutions/2547-minimum-cost-to-split-an-array.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/2547-minimum-cost-to-split-an-array.js b/solutions/2547-minimum-cost-to-split-an-array.js
new file mode 100644
index 00000000..04732298
--- /dev/null
+++ b/solutions/2547-minimum-cost-to-split-an-array.js
@@ -0,0 +1,48 @@
+/**
+ * 2547. Minimum Cost to Split an Array
+ * https://leetcode.com/problems/minimum-cost-to-split-an-array/
+ * Difficulty: Hard
+ *
+ * You are given an integer array nums and an integer k.
+ *
+ * Split the array into some number of non-empty subarrays. The cost of a split is the sum of
+ * the importance value of each subarray in the split.
+ *
+ * Let trimmed(subarray) be the version of the subarray where all numbers which appear only
+ * once are removed.
+ * - For example, trimmed([3,1,2,4,3,4]) = [3,4,3,4].
+ *
+ * The importance value of a subarray is k + trimmed(subarray).length.
+ * - For example, if a subarray is [1,2,3,3,3,4,4], then trimmed([1,2,3,3,3,4,4]) = [3,3,3,4,4].
+ * The importance value of this subarray will be k + 5.
+ *
+ * Return the minimum possible cost of a split of nums.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var minCost = function(nums, k) {
+ const n = nums.length;
+ const dp = new Array(n + 1).fill(Infinity);
+ dp[0] = 0;
+
+ for (let end = 1; end <= n; end++) {
+ const freq = new Map();
+ let trimLen = 0;
+ for (let start = end - 1; start >= 0; start--) {
+ const num = nums[start];
+ const count = (freq.get(num) || 0) + 1;
+ freq.set(num, count);
+ if (count === 1) trimLen++;
+ if (count === 2) trimLen--;
+ dp[end] = Math.min(dp[end], dp[start] + k + (end - start - trimLen));
+ }
+ }
+
+ return dp[n];
+};
From 8fbd8be7aa92680ec49fb88d4edd5faa4c55f558 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 00:07:37 -0500
Subject: [PATCH 219/994] Add solution #2549
---
README.md | 1 +
.../2549-count-distinct-numbers-on-board.js | 24 +++++++++++++++++++
2 files changed, 25 insertions(+)
create mode 100644 solutions/2549-count-distinct-numbers-on-board.js
diff --git a/README.md b/README.md
index 9b13011f..78281399 100644
--- a/README.md
+++ b/README.md
@@ -1908,6 +1908,7 @@
2545|[Sort the Students by Their Kth Score](./solutions/2545-sort-the-students-by-their-kth-score.js)|Medium|
2546|[Apply Bitwise Operations to Make Strings Equal](./solutions/2546-apply-bitwise-operations-to-make-strings-equal.js)|Medium|
2547|[Minimum Cost to Split an Array](./solutions/2547-minimum-cost-to-split-an-array.js)|Hard|
+2549|[Count Distinct Numbers on Board](./solutions/2549-count-distinct-numbers-on-board.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/2549-count-distinct-numbers-on-board.js b/solutions/2549-count-distinct-numbers-on-board.js
new file mode 100644
index 00000000..861cd59d
--- /dev/null
+++ b/solutions/2549-count-distinct-numbers-on-board.js
@@ -0,0 +1,24 @@
+/**
+ * 2549. Count Distinct Numbers on Board
+ * https://leetcode.com/problems/count-distinct-numbers-on-board/
+ * Difficulty: Easy
+ *
+ * You are given a positive integer n, that is initially placed on a board. Every day, for
+ * 109 days, you perform the following procedure:
+ * - For each number x present on the board, find all numbers 1 <= i <= n such that x % i == 1.
+ * - Then, place those numbers on the board.
+ *
+ * Return the number of distinct integers present on the board after 109 days have elapsed.
+ *
+ * Note:
+ * - Once a number is placed on the board, it will remain on it until the end.
+ * - % stands for the modulo operation. For example, 14 % 3 is 2.
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var distinctIntegers = function(n) {
+ return n === 1 ? 1 : n - 1;
+};
From 0766c03c76f95527af23f7d73040184fcd881a5e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 00:08:34 -0500
Subject: [PATCH 220/994] Add solution #2553
---
README.md | 1 +
.../2553-separate-the-digits-in-an-array.js | 19 +++++++++++++++++++
2 files changed, 20 insertions(+)
create mode 100644 solutions/2553-separate-the-digits-in-an-array.js
diff --git a/README.md b/README.md
index 78281399..80ea1406 100644
--- a/README.md
+++ b/README.md
@@ -1910,6 +1910,7 @@
2547|[Minimum Cost to Split an Array](./solutions/2547-minimum-cost-to-split-an-array.js)|Hard|
2549|[Count Distinct Numbers on Board](./solutions/2549-count-distinct-numbers-on-board.js)|Easy|
2551|[Put Marbles in Bags](./solutions/2551-put-marbles-in-bags.js)|Hard|
+2553|[Separate the Digits in an Array](./solutions/2553-separate-the-digits-in-an-array.js)|Easy|
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|
2563|[Count the Number of Fair Pairs](./solutions/2563-count-the-number-of-fair-pairs.js)|Medium|
diff --git a/solutions/2553-separate-the-digits-in-an-array.js b/solutions/2553-separate-the-digits-in-an-array.js
new file mode 100644
index 00000000..1255dfb6
--- /dev/null
+++ b/solutions/2553-separate-the-digits-in-an-array.js
@@ -0,0 +1,19 @@
+/**
+ * 2553. Separate the Digits in an Array
+ * https://leetcode.com/problems/separate-the-digits-in-an-array/
+ * Difficulty: Easy
+ *
+ * Given an array of positive integers nums, return an array answer that consists of the digits
+ * of each integer in nums after separating them in the same order they appear in nums.
+ *
+ * To separate the digits of an integer is to get all the digits it has in the same order.
+ * - For example, for the integer 10921, the separation of its digits is [1,0,9,2,1].
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var separateDigits = function(nums) {
+ return nums.flatMap(num => String(num).split('').map(Number));
+};
From 241e4ddcd7180cc223b2f843c63f5beb9b87c8ea Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 00:11:31 -0500
Subject: [PATCH 221/994] Add solution #2554
---
README.md | 1 +
...er-of-integers-to-choose-from-a-range-i.js | 35 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/2554-maximum-number-of-integers-to-choose-from-a-range-i.js
diff --git a/README.md b/README.md
index 80ea1406..9ea60fcc 100644
--- a/README.md
+++ b/README.md
@@ -1911,6 +1911,7 @@
2549|[Count Distinct Numbers on Board](./solutions/2549-count-distinct-numbers-on-board.js)|Easy|
2551|[Put Marbles in Bags](./solutions/2551-put-marbles-in-bags.js)|Hard|
2553|[Separate the Digits in an Array](./solutions/2553-separate-the-digits-in-an-array.js)|Easy|
+2554|[Maximum Number of Integers to Choose From a Range I](./solutions/2554-maximum-number-of-integers-to-choose-from-a-range-i.js)|Medium|
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|
2563|[Count the Number of Fair Pairs](./solutions/2563-count-the-number-of-fair-pairs.js)|Medium|
diff --git a/solutions/2554-maximum-number-of-integers-to-choose-from-a-range-i.js b/solutions/2554-maximum-number-of-integers-to-choose-from-a-range-i.js
new file mode 100644
index 00000000..bb160607
--- /dev/null
+++ b/solutions/2554-maximum-number-of-integers-to-choose-from-a-range-i.js
@@ -0,0 +1,35 @@
+/**
+ * 2554. Maximum Number of Integers to Choose From a Range I
+ * https://leetcode.com/problems/maximum-number-of-integers-to-choose-from-a-range-i/
+ * Difficulty: Medium
+ *
+ * You are given an integer array banned and two integers n and maxSum. You are choosing some
+ * number of integers following the below rules:
+ * - The chosen integers have to be in the range [1, n].
+ * - Each integer can be chosen at most once.
+ * - The chosen integers should not be in the array banned.
+ * - The sum of the chosen integers should not exceed maxSum.
+ *
+ * Return the maximum number of integers you can choose following the mentioned rules.
+ */
+
+/**
+ * @param {number[]} banned
+ * @param {number} n
+ * @param {number} maxSum
+ * @return {number}
+ */
+var maxCount = function(banned, n, maxSum) {
+ const set = new Set(banned);
+ let result = 0;
+ let currentSum = 0;
+
+ for (let num = 1; num <= n; num++) {
+ if (!set.has(num) && currentSum + num <= maxSum) {
+ result++;
+ currentSum += num;
+ }
+ }
+
+ return result;
+};
From ecf4e5394b6c79038defc1a3a31f8d9cc74babd3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 00:12:49 -0500
Subject: [PATCH 222/994] Add solution #2562
---
README.md | 1 +
...2562-find-the-array-concatenation-value.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/2562-find-the-array-concatenation-value.js
diff --git a/README.md b/README.md
index 9ea60fcc..afb78bfd 100644
--- a/README.md
+++ b/README.md
@@ -1914,6 +1914,7 @@
2554|[Maximum Number of Integers to Choose From a Range I](./solutions/2554-maximum-number-of-integers-to-choose-from-a-range-i.js)|Medium|
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|
+2562|[Find the Array Concatenation Value](./solutions/2562-find-the-array-concatenation-value.js)|Easy|
2563|[Count the Number of Fair Pairs](./solutions/2563-count-the-number-of-fair-pairs.js)|Medium|
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|
diff --git a/solutions/2562-find-the-array-concatenation-value.js b/solutions/2562-find-the-array-concatenation-value.js
new file mode 100644
index 00000000..b35decfc
--- /dev/null
+++ b/solutions/2562-find-the-array-concatenation-value.js
@@ -0,0 +1,42 @@
+/**
+ * 2562. Find the Array Concatenation Value
+ * https://leetcode.com/problems/find-the-array-concatenation-value/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums.
+ *
+ * The concatenation of two numbers is the number formed by concatenating their numerals.
+ * - For example, the concatenation of 15, 49 is 1549.
+ *
+ * The concatenation value of nums is initially equal to 0. Perform this operation until nums
+ * becomes empty:
+ * - If nums has a size greater than one, add the value of the concatenation of the first and
+ * the last element to the concatenation value of nums, and remove those two elements from
+ * nums. For example, if the nums was [1, 2, 4, 5, 6], add 16 to the concatenation value.
+ * - If only one element exists in nums, add its value to the concatenation value of nums,
+ * then remove it.
+ *
+ * Return the concatenation value of nums.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var findTheArrayConcVal = function(nums) {
+ let result = 0;
+ let left = 0;
+ let right = nums.length - 1;
+
+ while (left <= right) {
+ if (left === right) {
+ result += nums[left];
+ } else {
+ result += Number(`${nums[left]}${nums[right]}`);
+ }
+ left++;
+ right--;
+ }
+
+ return result;
+};
From 0e3229c2d487d334cbd4cdd86c25c70370bd7d05 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 00:13:50 -0500
Subject: [PATCH 223/994] Add solution #2566
---
README.md | 1 +
...maximum-difference-by-remapping-a-digit.js | 40 +++++++++++++++++++
2 files changed, 41 insertions(+)
create mode 100644 solutions/2566-maximum-difference-by-remapping-a-digit.js
diff --git a/README.md b/README.md
index afb78bfd..daeaa7d5 100644
--- a/README.md
+++ b/README.md
@@ -1916,6 +1916,7 @@
2560|[House Robber IV](./solutions/2560-house-robber-iv.js)|Medium|
2562|[Find the Array Concatenation Value](./solutions/2562-find-the-array-concatenation-value.js)|Easy|
2563|[Count the Number of Fair Pairs](./solutions/2563-count-the-number-of-fair-pairs.js)|Medium|
+2566|[Maximum Difference by Remapping a Digit](./solutions/2566-maximum-difference-by-remapping-a-digit.js)|Easy|
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|
diff --git a/solutions/2566-maximum-difference-by-remapping-a-digit.js b/solutions/2566-maximum-difference-by-remapping-a-digit.js
new file mode 100644
index 00000000..55898513
--- /dev/null
+++ b/solutions/2566-maximum-difference-by-remapping-a-digit.js
@@ -0,0 +1,40 @@
+/**
+ * 2566. Maximum Difference by Remapping a Digit
+ * https://leetcode.com/problems/maximum-difference-by-remapping-a-digit/
+ * Difficulty: Easy
+ *
+ * You are given an integer num. You know that Bob will sneakily remap one of the 10 possible
+ * digits (0 to 9) to another digit.
+ *
+ * Return the difference between the maximum and minimum values Bob can make by remapping
+ * exactly one digit in num.
+ *
+ * Notes:
+ * - When Bob remaps a digit d1 to another digit d2, Bob replaces all occurrences of d1 in
+ * num with d2.
+ * - Bob can remap a digit to itself, in which case num does not change.
+ * - Bob can remap different digits for obtaining minimum and maximum values respectively.
+ * - The resulting number after remapping can contain leading zeroes.
+ */
+
+/**
+ * @param {number} num
+ * @return {number}
+ */
+var minMaxDifference = function(num) {
+ const digits = String(num).split('');
+ let maxNum = num;
+ let minNum = num;
+
+ for (let i = 0; i < 10; i++) {
+ const digit = String(i);
+ if (digits.includes(digit)) {
+ const maxCandidate = Number(digits.join('').replaceAll(digit, '9'));
+ const minCandidate = Number(digits.join('').replaceAll(digit, '0'));
+ maxNum = Math.max(maxNum, maxCandidate);
+ minNum = Math.min(minNum, minCandidate);
+ }
+ }
+
+ return maxNum - minNum;
+};
From db3bd6182b99c67d4337ec03db1e2f388fea3293 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 00:15:05 -0500
Subject: [PATCH 224/994] Add solution #2567
---
README.md | 1 +
...-minimum-score-by-changing-two-elements.js | 26 +++++++++++++++++++
2 files changed, 27 insertions(+)
create mode 100644 solutions/2567-minimum-score-by-changing-two-elements.js
diff --git a/README.md b/README.md
index daeaa7d5..0da1f6d5 100644
--- a/README.md
+++ b/README.md
@@ -1917,6 +1917,7 @@
2562|[Find the Array Concatenation Value](./solutions/2562-find-the-array-concatenation-value.js)|Easy|
2563|[Count the Number of Fair Pairs](./solutions/2563-count-the-number-of-fair-pairs.js)|Medium|
2566|[Maximum Difference by Remapping a Digit](./solutions/2566-maximum-difference-by-remapping-a-digit.js)|Easy|
+2567|[Minimum Score by Changing Two Elements](./solutions/2567-minimum-score-by-changing-two-elements.js)|Medium|
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|
diff --git a/solutions/2567-minimum-score-by-changing-two-elements.js b/solutions/2567-minimum-score-by-changing-two-elements.js
new file mode 100644
index 00000000..a5f5d1c5
--- /dev/null
+++ b/solutions/2567-minimum-score-by-changing-two-elements.js
@@ -0,0 +1,26 @@
+/**
+ * 2567. Minimum Score by Changing Two Elements
+ * https://leetcode.com/problems/minimum-score-by-changing-two-elements/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums.
+ * - The low score of nums is the minimum absolute difference between any two integers.
+ * - The high score of nums is the maximum absolute difference between any two integers.
+ * - The score of nums is the sum of the high and low scores.
+ *
+ * Return the minimum score after changing two elements of nums.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimizeSum = function(nums) {
+ const sorted = nums.sort((a, b) => a - b);
+
+ return Math.min(
+ sorted[sorted.length - 2] - sorted[1],
+ sorted[sorted.length - 1] - sorted[2],
+ sorted[sorted.length - 3] - sorted[0]
+ );
+};
From fd4597bacb61adaa360fd861a2671418dbdd70f9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 00:16:25 -0500
Subject: [PATCH 225/994] Add solution #2568
---
README.md | 1 +
solutions/2568-minimum-impossible-or.js | 30 +++++++++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 solutions/2568-minimum-impossible-or.js
diff --git a/README.md b/README.md
index 0da1f6d5..447e564d 100644
--- a/README.md
+++ b/README.md
@@ -1918,6 +1918,7 @@
2563|[Count the Number of Fair Pairs](./solutions/2563-count-the-number-of-fair-pairs.js)|Medium|
2566|[Maximum Difference by Remapping a Digit](./solutions/2566-maximum-difference-by-remapping-a-digit.js)|Easy|
2567|[Minimum Score by Changing Two Elements](./solutions/2567-minimum-score-by-changing-two-elements.js)|Medium|
+2568|[Minimum Impossible OR](./solutions/2568-minimum-impossible-or.js)|Medium|
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|
diff --git a/solutions/2568-minimum-impossible-or.js b/solutions/2568-minimum-impossible-or.js
new file mode 100644
index 00000000..6cb1df58
--- /dev/null
+++ b/solutions/2568-minimum-impossible-or.js
@@ -0,0 +1,30 @@
+/**
+ * 2568. Minimum Impossible OR
+ * https://leetcode.com/problems/minimum-impossible-or/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums.
+ *
+ * We say that an integer x is expressible from nums if there exist some integers
+ * 0 <= index1 < index2 < ... < indexk < nums.length for which
+ * nums[index1] | nums[index2] | ... | nums[indexk] = x. In other words, an
+ * integer is expressible if it can be written as the bitwise OR of some subsequence
+ * of nums.
+ *
+ * Return the minimum positive non-zero integer that is not expressible from nums.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minImpossibleOR = function(nums) {
+ const set = new Set(nums);
+ let result = 1;
+
+ while (set.has(result)) {
+ result <<= 1;
+ }
+
+ return result;
+};
From 3214643fccb6812d32dc24a6290c079ad6d8fb9b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 18:50:50 -0500
Subject: [PATCH 226/994] Add solution #2571
---
README.md | 1 +
...um-operations-to-reduce-an-integer-to-0.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/2571-minimum-operations-to-reduce-an-integer-to-0.js
diff --git a/README.md b/README.md
index 447e564d..1ed2a80c 100644
--- a/README.md
+++ b/README.md
@@ -1920,6 +1920,7 @@
2567|[Minimum Score by Changing Two Elements](./solutions/2567-minimum-score-by-changing-two-elements.js)|Medium|
2568|[Minimum Impossible OR](./solutions/2568-minimum-impossible-or.js)|Medium|
2570|[Merge Two 2D Arrays by Summing Values](./solutions/2570-merge-two-2d-arrays-by-summing-values.js)|Easy|
+2571|[Minimum Operations to Reduce an Integer to 0](./solutions/2571-minimum-operations-to-reduce-an-integer-to-0.js)|Medium|
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|
diff --git a/solutions/2571-minimum-operations-to-reduce-an-integer-to-0.js b/solutions/2571-minimum-operations-to-reduce-an-integer-to-0.js
new file mode 100644
index 00000000..0ee9bb23
--- /dev/null
+++ b/solutions/2571-minimum-operations-to-reduce-an-integer-to-0.js
@@ -0,0 +1,34 @@
+/**
+ * 2571. Minimum Operations to Reduce an Integer to 0
+ * https://leetcode.com/problems/minimum-operations-to-reduce-an-integer-to-0/
+ * Difficulty: Medium
+ *
+ * You are given a positive integer n, you can do the following operation any number of times:
+ * - Add or subtract a power of 2 from n.
+ *
+ * Return the minimum number of operations to make n equal to 0.
+ *
+ * A number x is power of 2 if x == 2i where i >= 0.
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var minOperations = function(n) {
+ let result = 0;
+
+ while (n > 0) {
+ if ((n & 1) === 0) {
+ n >>= 1;
+ } else if ((n & 3) === 3) {
+ n += 1;
+ result++;
+ } else {
+ n -= 1;
+ result++;
+ }
+ }
+
+ return result;
+};
From 757e5194ef14548b5b449f0821343403fb6edbab Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 18:51:56 -0500
Subject: [PATCH 227/994] Add solution #2574
---
README.md | 1 +
.../2574-left-and-right-sum-differences.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/2574-left-and-right-sum-differences.js
diff --git a/README.md b/README.md
index 1ed2a80c..657ad623 100644
--- a/README.md
+++ b/README.md
@@ -1921,6 +1921,7 @@
2568|[Minimum Impossible OR](./solutions/2568-minimum-impossible-or.js)|Medium|
2570|[Merge Two 2D Arrays by Summing Values](./solutions/2570-merge-two-2d-arrays-by-summing-values.js)|Easy|
2571|[Minimum Operations to Reduce an Integer to 0](./solutions/2571-minimum-operations-to-reduce-an-integer-to-0.js)|Medium|
+2574|[Left and Right Sum Differences](./solutions/2574-left-and-right-sum-differences.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|
diff --git a/solutions/2574-left-and-right-sum-differences.js b/solutions/2574-left-and-right-sum-differences.js
new file mode 100644
index 00000000..e3292140
--- /dev/null
+++ b/solutions/2574-left-and-right-sum-differences.js
@@ -0,0 +1,34 @@
+/**
+ * 2574. Left and Right Sum Differences
+ * https://leetcode.com/problems/left-and-right-sum-differences/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums of size n.
+ *
+ * Define two arrays leftSum and rightSum where:
+ * - leftSum[i] is the sum of elements to the left of the index i in the array nums.
+ * If there is no such element, leftSum[i] = 0.
+ * - rightSum[i] is the sum of elements to the right of the index i in the array nums.
+ * If there is no such element, rightSum[i] = 0.
+ *
+ * Return an integer array answer of size n where answer[i] = |leftSum[i] - rightSum[i]|.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var leftRightDifference = function(nums) {
+ const n = nums.length;
+ const result = new Array(n).fill(0);
+ let leftSum = 0;
+ let rightSum = nums.reduce((sum, num) => sum + num, 0);
+
+ for (let i = 0; i < n; i++) {
+ rightSum -= nums[i];
+ result[i] = Math.abs(leftSum - rightSum);
+ leftSum += nums[i];
+ }
+
+ return result;
+};
From 8f0b99341b12c34def1276e1543a7f8b6f3fa615 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 18:53:02 -0500
Subject: [PATCH 228/994] Add solution #2578
---
README.md | 1 +
solutions/2578-split-with-minimum-sum.js | 38 ++++++++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2578-split-with-minimum-sum.js
diff --git a/README.md b/README.md
index 657ad623..0db4269c 100644
--- a/README.md
+++ b/README.md
@@ -1922,6 +1922,7 @@
2570|[Merge Two 2D Arrays by Summing Values](./solutions/2570-merge-two-2d-arrays-by-summing-values.js)|Easy|
2571|[Minimum Operations to Reduce an Integer to 0](./solutions/2571-minimum-operations-to-reduce-an-integer-to-0.js)|Medium|
2574|[Left and Right Sum Differences](./solutions/2574-left-and-right-sum-differences.js)|Easy|
+2578|[Split With Minimum Sum](./solutions/2578-split-with-minimum-sum.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|
diff --git a/solutions/2578-split-with-minimum-sum.js b/solutions/2578-split-with-minimum-sum.js
new file mode 100644
index 00000000..3d81e46c
--- /dev/null
+++ b/solutions/2578-split-with-minimum-sum.js
@@ -0,0 +1,38 @@
+/**
+ * 2578. Split With Minimum Sum
+ * https://leetcode.com/problems/split-with-minimum-sum/
+ * Difficulty: Easy
+ *
+ * Given a positive integer num, split it into two non-negative integers num1 and num2 such that:
+ * - The concatenation of num1 and num2 is a permutation of num.
+ * - In other words, the sum of the number of occurrences of each digit in num1 and num2 is equal
+ * to the number of occurrences of that digit in num.
+ * - num1 and num2 can contain leading zeros.
+ *
+ * Return the minimum possible sum of num1 and num2.
+ *
+ * Notes:
+ * - It is guaranteed that num does not contain any leading zeros.
+ * - The order of occurrence of the digits in num1 and num2 may differ from the order of occurrence
+ * of num.
+ */
+
+/**
+ * @param {number} num
+ * @return {number}
+ */
+var splitNum = function(num) {
+ const digits = String(num).split('').sort((a, b) => a - b);
+ let num1 = '';
+ let num2 = '';
+
+ for (let i = 0; i < digits.length; i++) {
+ if (i % 2 === 0) {
+ num1 += digits[i];
+ } else {
+ num2 += digits[i];
+ }
+ }
+
+ return Number(num1) + Number(num2);
+};
From 8105de04e852f7cf89f37096da1bb81c9045c316 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 18:57:49 -0500
Subject: [PATCH 229/994] Add solution #2581
---
README.md | 1 +
...581-count-number-of-possible-root-nodes.js | 78 +++++++++++++++++++
2 files changed, 79 insertions(+)
create mode 100644 solutions/2581-count-number-of-possible-root-nodes.js
diff --git a/README.md b/README.md
index 0db4269c..d9af0c4b 100644
--- a/README.md
+++ b/README.md
@@ -1924,6 +1924,7 @@
2574|[Left and Right Sum Differences](./solutions/2574-left-and-right-sum-differences.js)|Easy|
2578|[Split With Minimum Sum](./solutions/2578-split-with-minimum-sum.js)|Easy|
2579|[Count Total Number of Colored Cells](./solutions/2579-count-total-number-of-colored-cells.js)|Medium|
+2581|[Count Number of Possible Root Nodes](./solutions/2581-count-number-of-possible-root-nodes.js)|Hard|
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|
diff --git a/solutions/2581-count-number-of-possible-root-nodes.js b/solutions/2581-count-number-of-possible-root-nodes.js
new file mode 100644
index 00000000..4d879928
--- /dev/null
+++ b/solutions/2581-count-number-of-possible-root-nodes.js
@@ -0,0 +1,78 @@
+/**
+ * 2581. Count Number of Possible Root Nodes
+ * https://leetcode.com/problems/count-number-of-possible-root-nodes/
+ * Difficulty: Hard
+ *
+ * Alice has an undirected tree with n nodes labeled from 0 to n - 1. The tree is represented as 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.
+ *
+ * Alice wants Bob to find the root of the tree. She allows Bob to make several guesses about her
+ * tree. In one guess, he does the following:
+ * - Chooses two distinct integers u and v such that there exists an edge [u, v] in the tree.
+ * - He tells Alice that u is the parent of v in the tree.
+ *
+ * Bob's guesses are represented by a 2D integer array guesses where guesses[j] = [uj, vj] indicates
+ * Bob guessed uj to be the parent of vj.
+ *
+ * Alice being lazy, does not reply to each of Bob's guesses, but just says that at least k of his
+ * guesses are true.
+ *
+ * Given the 2D integer arrays edges, guesses and the integer k, return the number of possible
+ * nodes that can be the root of Alice's tree. If there is no such tree, return 0.
+ */
+
+/**
+ * @param {number[][]} edges
+ * @param {number[][]} guesses
+ * @param {number} k
+ * @return {number}
+ */
+var rootCount = function(edges, guesses, k) {
+ const n = edges.length + 1;
+ const adj = Array.from({ length: n }, () => new Set());
+ const set = new Set();
+
+ for (const [u, v] of edges) {
+ adj[u].add(v);
+ adj[v].add(u);
+ }
+
+ for (const [u, v] of guesses) {
+ set.add(u * n + v);
+ }
+
+ const rootCorrect = dfs(0, -1);
+ let result = rootCorrect >= k ? 1 : 0;
+
+ for (const neighbor of adj[0]) {
+ helper(neighbor, 0, rootCorrect);
+ }
+
+ return result;
+
+ function helper(node, parent, parentCorrect) {
+ let count = parentCorrect;
+ if (set.has(parent * n + node)) count--;
+ if (set.has(node * n + parent)) count++;
+
+ if (count >= k) result++;
+
+ for (const neighbor of adj[node]) {
+ if (neighbor !== parent) {
+ helper(neighbor, node, count);
+ }
+ }
+ }
+
+ function dfs(node, parent) {
+ let count = 0;
+ for (const neighbor of adj[node]) {
+ if (neighbor !== parent) {
+ if (set.has(node * n + neighbor)) count++;
+ count += dfs(neighbor, node);
+ }
+ }
+ return count;
+ }
+};
From 344bcdcca7a079fef043b54b5b231e10a1ff0b46 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 18:59:02 -0500
Subject: [PATCH 230/994] Add solution #2582
---
README.md | 1 +
solutions/2582-pass-the-pillow.js | 25 +++++++++++++++++++++++++
2 files changed, 26 insertions(+)
create mode 100644 solutions/2582-pass-the-pillow.js
diff --git a/README.md b/README.md
index d9af0c4b..efbb85dd 100644
--- a/README.md
+++ b/README.md
@@ -1925,6 +1925,7 @@
2578|[Split With Minimum Sum](./solutions/2578-split-with-minimum-sum.js)|Easy|
2579|[Count Total Number of Colored Cells](./solutions/2579-count-total-number-of-colored-cells.js)|Medium|
2581|[Count Number of Possible Root Nodes](./solutions/2581-count-number-of-possible-root-nodes.js)|Hard|
+2582|[Pass the Pillow](./solutions/2582-pass-the-pillow.js)|Easy|
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|
diff --git a/solutions/2582-pass-the-pillow.js b/solutions/2582-pass-the-pillow.js
new file mode 100644
index 00000000..6f1a17a9
--- /dev/null
+++ b/solutions/2582-pass-the-pillow.js
@@ -0,0 +1,25 @@
+/**
+ * 2582. Pass the Pillow
+ * https://leetcode.com/problems/pass-the-pillow/
+ * Difficulty: Easy
+ *
+ * There are n people standing in a line labeled from 1 to n. The first person in the line is
+ * holding a pillow initially. Every second, the person holding the pillow passes it to the
+ * next person standing in the line. Once the pillow reaches the end of the line, the direction
+ * changes, and people continue passing the pillow in the opposite direction.
+ * - For example, once the pillow reaches the nth person they pass it to the n - 1th person,
+ * then to the n - 2th person and so on.
+ *
+ * Given the two positive integers n and time, return the index of the person holding the pillow
+ * after time seconds.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} time
+ * @return {number}
+ */
+var passThePillow = function(n, time) {
+ const position = time % (2 * (n - 1));
+ return position < n ? position + 1 : 2 * n - position - 1;
+};
From c1f2baa3af02d87f22516416628e2d4829752d7a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 19:00:46 -0500
Subject: [PATCH 231/994] Add solution #3178
---
README.md | 1 +
...-child-who-has-the-ball-after-k-seconds.js | 25 +++++++++++++++++++
2 files changed, 26 insertions(+)
create mode 100644 solutions/3178-find-the-child-who-has-the-ball-after-k-seconds.js
diff --git a/README.md b/README.md
index efbb85dd..0520d19e 100644
--- a/README.md
+++ b/README.md
@@ -1997,6 +1997,7 @@
3160|[Find the Number of Distinct Colors Among the Balls](./solutions/3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium|
3169|[Count Days Without Meetings](./solutions/3169-count-days-without-meetings.js)|Medium|
3174|[Clear Digits](./solutions/3174-clear-digits.js)|Easy|
+3178|[Find the Child Who Has the Ball After K Seconds](./solutions/3178-find-the-child-who-has-the-ball-after-k-seconds.js)|Easy|
3191|[Minimum Operations to Make Binary Array Elements Equal to One I](./solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js)|Medium|
3208|[Alternating Groups II](./solutions/3208-alternating-groups-ii.js)|Medium|
3223|[Minimum Length of String After Operations](./solutions/3223-minimum-length-of-string-after-operations.js)|Medium|
diff --git a/solutions/3178-find-the-child-who-has-the-ball-after-k-seconds.js b/solutions/3178-find-the-child-who-has-the-ball-after-k-seconds.js
new file mode 100644
index 00000000..cdbd5d88
--- /dev/null
+++ b/solutions/3178-find-the-child-who-has-the-ball-after-k-seconds.js
@@ -0,0 +1,25 @@
+/**
+ * 3178. Find the Child Who Has the Ball After K Seconds
+ * https://leetcode.com/problems/find-the-child-who-has-the-ball-after-k-seconds/
+ * Difficulty: Easy
+ *
+ * You are given two positive integers n and k. There are n children numbered from 0 to n - 1
+ * standing in a queue in order from left to right.
+ *
+ * Initially, child 0 holds a ball and the direction of passing the ball is towards the right
+ * direction. After each second, the child holding the ball passes it to the child next to
+ * them. Once the ball reaches either end of the line, i.e. child 0 or child n - 1, the direction
+ * of passing is reversed.
+ *
+ * Return the number of the child who receives the ball after k seconds.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} k
+ * @return {number}
+ */
+var numberOfChild = function(n, k) {
+ const position = k % (2 * (n - 1));
+ return position < n ? position : 2 * n - position - 2;
+};
From 2514c7ba4dca47d6b6f5638c3dcf82551f2bb40a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 19:02:36 -0500
Subject: [PATCH 232/994] Add solution #2583
---
README.md | 1 +
.../2583-kth-largest-sum-in-a-binary-tree.js | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/2583-kth-largest-sum-in-a-binary-tree.js
diff --git a/README.md b/README.md
index 0520d19e..1c1bfaa9 100644
--- a/README.md
+++ b/README.md
@@ -1926,6 +1926,7 @@
2579|[Count Total Number of Colored Cells](./solutions/2579-count-total-number-of-colored-cells.js)|Medium|
2581|[Count Number of Possible Root Nodes](./solutions/2581-count-number-of-possible-root-nodes.js)|Hard|
2582|[Pass the Pillow](./solutions/2582-pass-the-pillow.js)|Easy|
+2583|[Kth Largest Sum in a Binary Tree](./solutions/2583-kth-largest-sum-in-a-binary-tree.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|
diff --git a/solutions/2583-kth-largest-sum-in-a-binary-tree.js b/solutions/2583-kth-largest-sum-in-a-binary-tree.js
new file mode 100644
index 00000000..b8759f23
--- /dev/null
+++ b/solutions/2583-kth-largest-sum-in-a-binary-tree.js
@@ -0,0 +1,50 @@
+/**
+ * 2583. Kth Largest Sum in a Binary Tree
+ * https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree/
+ * Difficulty: Medium
+ *
+ * You are given the root of a binary tree and a positive integer k.
+ *
+ * The level sum in the tree is the sum of the values of the nodes that are on the same level.
+ *
+ * Return the kth largest level sum in the tree (not necessarily distinct). If there are fewer
+ * than k levels in the tree, return -1.
+ *
+ * Note that two nodes are on the same level if they have the same distance from the root.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @param {number} k
+ * @return {number}
+ */
+var kthLargestLevelSum = function(root, k) {
+ const levelSums = [];
+ const queue = [root];
+
+ while (queue.length) {
+ let levelSize = queue.length;
+ let levelSum = 0;
+
+ while (levelSize--) {
+ const node = queue.shift();
+ levelSum += node.val;
+ if (node.left) queue.push(node.left);
+ if (node.right) queue.push(node.right);
+ }
+
+ levelSums.push(levelSum);
+ }
+
+ if (levelSums.length < k) return -1;
+
+ return levelSums.sort((a, b) => b - a)[k - 1];
+};
From 1c8707a4fdc3116189783ddd2ef9ae91f6beee6e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 19:03:52 -0500
Subject: [PATCH 233/994] Add solution #2585
---
README.md | 1 +
.../2585-number-of-ways-to-earn-points.js | 37 +++++++++++++++++++
2 files changed, 38 insertions(+)
create mode 100644 solutions/2585-number-of-ways-to-earn-points.js
diff --git a/README.md b/README.md
index 1c1bfaa9..34aac4cb 100644
--- a/README.md
+++ b/README.md
@@ -1927,6 +1927,7 @@
2581|[Count Number of Possible Root Nodes](./solutions/2581-count-number-of-possible-root-nodes.js)|Hard|
2582|[Pass the Pillow](./solutions/2582-pass-the-pillow.js)|Easy|
2583|[Kth Largest Sum in a Binary Tree](./solutions/2583-kth-largest-sum-in-a-binary-tree.js)|Medium|
+2585|[Number of Ways to Earn Points](./solutions/2585-number-of-ways-to-earn-points.js)|Hard|
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|
diff --git a/solutions/2585-number-of-ways-to-earn-points.js b/solutions/2585-number-of-ways-to-earn-points.js
new file mode 100644
index 00000000..a88d5050
--- /dev/null
+++ b/solutions/2585-number-of-ways-to-earn-points.js
@@ -0,0 +1,37 @@
+/**
+ * 2585. Number of Ways to Earn Points
+ * https://leetcode.com/problems/number-of-ways-to-earn-points/
+ * Difficulty: Hard
+ *
+ * There is a test that has n types of questions. You are given an integer target and a 0-indexed
+ * 2D integer array types where types[i] = [counti, marksi] indicates that there are counti
+ * questions of the ith type, and each one of them is worth marksi points.
+ *
+ * Return the number of ways you can earn exactly target points in the exam. Since the answer may
+ * be too large, return it modulo 109 + 7.
+ *
+ * Note that questions of the same type are indistinguishable.
+ * - For example, if there are 3 questions of the same type, then solving the 1st and 2nd questions
+ * is the same as solving the 1st and 3rd questions, or the 2nd and 3rd questions.
+ */
+
+/**
+ * @param {number} target
+ * @param {number[][]} types
+ * @return {number}
+ */
+var waysToReachTarget = function(target, types) {
+ const MOD = 1e9 + 7;
+ const dp = new Array(target + 1).fill(0);
+ dp[0] = 1;
+
+ for (const [count, marks] of types) {
+ for (let points = target; points >= 0; points--) {
+ for (let k = 1; k <= count && points >= k * marks; k++) {
+ dp[points] = (dp[points] + dp[points - k * marks]) % MOD;
+ }
+ }
+ }
+
+ return dp[target];
+};
From dd6ed4095ea355b6509fbbaf03eae6ea15c37e91 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 19:04:54 -0500
Subject: [PATCH 234/994] Add solution #2586
---
README.md | 1 +
...nt-the-number-of-vowel-strings-in-range.js | 32 +++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/2586-count-the-number-of-vowel-strings-in-range.js
diff --git a/README.md b/README.md
index 34aac4cb..6d61e8f2 100644
--- a/README.md
+++ b/README.md
@@ -1928,6 +1928,7 @@
2582|[Pass the Pillow](./solutions/2582-pass-the-pillow.js)|Easy|
2583|[Kth Largest Sum in a Binary Tree](./solutions/2583-kth-largest-sum-in-a-binary-tree.js)|Medium|
2585|[Number of Ways to Earn Points](./solutions/2585-number-of-ways-to-earn-points.js)|Hard|
+2586|[Count the Number of Vowel Strings in Range](./solutions/2586-count-the-number-of-vowel-strings-in-range.js)|Easy|
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|
diff --git a/solutions/2586-count-the-number-of-vowel-strings-in-range.js b/solutions/2586-count-the-number-of-vowel-strings-in-range.js
new file mode 100644
index 00000000..feff0ca4
--- /dev/null
+++ b/solutions/2586-count-the-number-of-vowel-strings-in-range.js
@@ -0,0 +1,32 @@
+/**
+ * 2586. Count the Number of Vowel Strings in Range
+ * https://leetcode.com/problems/count-the-number-of-vowel-strings-in-range/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed array of string words and two integers left and right.
+ *
+ * A string is called a vowel string if it starts with a vowel character and ends with
+ * a vowel character where vowel characters are 'a', 'e', 'i', 'o', and 'u'.
+ *
+ * Return the number of vowel strings words[i] where i belongs to the inclusive range [left, right].
+ */
+
+/**
+ * @param {string[]} words
+ * @param {number} left
+ * @param {number} right
+ * @return {number}
+ */
+var vowelStrings = function(words, left, right) {
+ const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
+ let result = 0;
+
+ for (let i = left; i <= right; i++) {
+ const word = words[i];
+ if (vowels.has(word[0]) && vowels.has(word[word.length - 1])) {
+ result++;
+ }
+ }
+
+ return result;
+};
From 63004b7f9c2153bd37b65cbb6cff4bf14479f377 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 19:06:02 -0500
Subject: [PATCH 235/994] Add solution #2587
---
README.md | 1 +
...earrange-array-to-maximize-prefix-score.js | 32 +++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/2587-rearrange-array-to-maximize-prefix-score.js
diff --git a/README.md b/README.md
index 6d61e8f2..91dc1039 100644
--- a/README.md
+++ b/README.md
@@ -1929,6 +1929,7 @@
2583|[Kth Largest Sum in a Binary Tree](./solutions/2583-kth-largest-sum-in-a-binary-tree.js)|Medium|
2585|[Number of Ways to Earn Points](./solutions/2585-number-of-ways-to-earn-points.js)|Hard|
2586|[Count the Number of Vowel Strings in Range](./solutions/2586-count-the-number-of-vowel-strings-in-range.js)|Easy|
+2587|[Rearrange Array to Maximize Prefix Score](./solutions/2587-rearrange-array-to-maximize-prefix-score.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|
diff --git a/solutions/2587-rearrange-array-to-maximize-prefix-score.js b/solutions/2587-rearrange-array-to-maximize-prefix-score.js
new file mode 100644
index 00000000..585a0d04
--- /dev/null
+++ b/solutions/2587-rearrange-array-to-maximize-prefix-score.js
@@ -0,0 +1,32 @@
+/**
+ * 2587. Rearrange Array to Maximize Prefix Score
+ * https://leetcode.com/problems/rearrange-array-to-maximize-prefix-score/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums. You can rearrange the elements of nums to any
+ * order (including the given order).
+ *
+ * Let prefix be the array containing the prefix sums of nums after rearranging it. In other words,
+ * prefix[i] is the sum of the elements from 0 to i in nums after rearranging it. The score of nums
+ * is the number of positive integers in the array prefix.
+ *
+ * Return the maximum score you can achieve.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maxScore = function(nums) {
+ const sorted = nums.sort((a, b) => b - a);
+ let prefixSum = 0;
+ let result = 0;
+
+ for (const num of sorted) {
+ prefixSum += num;
+ if (prefixSum > 0) result++;
+ else break;
+ }
+
+ return result;
+};
From e68d280d3f6fe1c74595c7699a6afd30b1588d37 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 23:24:04 -0500
Subject: [PATCH 236/994] Add solution #2588
---
README.md | 1 +
...count-the-number-of-beautiful-subarrays.js | 36 +++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/2588-count-the-number-of-beautiful-subarrays.js
diff --git a/README.md b/README.md
index 91dc1039..a4a01905 100644
--- a/README.md
+++ b/README.md
@@ -1930,6 +1930,7 @@
2585|[Number of Ways to Earn Points](./solutions/2585-number-of-ways-to-earn-points.js)|Hard|
2586|[Count the Number of Vowel Strings in Range](./solutions/2586-count-the-number-of-vowel-strings-in-range.js)|Easy|
2587|[Rearrange Array to Maximize Prefix Score](./solutions/2587-rearrange-array-to-maximize-prefix-score.js)|Medium|
+2588|[Count the Number of Beautiful Subarrays](./solutions/2588-count-the-number-of-beautiful-subarrays.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|
diff --git a/solutions/2588-count-the-number-of-beautiful-subarrays.js b/solutions/2588-count-the-number-of-beautiful-subarrays.js
new file mode 100644
index 00000000..122bc329
--- /dev/null
+++ b/solutions/2588-count-the-number-of-beautiful-subarrays.js
@@ -0,0 +1,36 @@
+/**
+ * 2588. Count the Number of Beautiful Subarrays
+ * https://leetcode.com/problems/count-the-number-of-beautiful-subarrays/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums. In one operation, you can:
+ * - Choose two different indices i and j such that 0 <= i, j < nums.length.
+ * - Choose a non-negative integer k such that the kth bit (0-indexed) in the binary representation
+ * of nums[i] and nums[j] is 1.
+ * - Subtract 2k from nums[i] and nums[j].
+ *
+ * A subarray is beautiful if it is possible to make all of its elements equal to 0 after applying
+ * the above operation any number of times.
+ *
+ * Return the number of beautiful subarrays in the array nums.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var beautifulSubarrays = function(nums) {
+ let result = 0;
+ const prefixXOR = new Map([[0, 1]]);
+ let currentXOR = 0;
+
+ for (const num of nums) {
+ currentXOR ^= num;
+ result += prefixXOR.get(currentXOR) || 0;
+ prefixXOR.set(currentXOR, (prefixXOR.get(currentXOR) || 0) + 1);
+ }
+
+ return result;
+};
From 01567c128849e71109278640787f1bbb803ae6b6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 23:25:43 -0500
Subject: [PATCH 237/994] Add solution #2592
---
README.md | 1 +
.../2592-maximize-greatness-of-an-array.js | 36 +++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/2592-maximize-greatness-of-an-array.js
diff --git a/README.md b/README.md
index a4a01905..f742c6b0 100644
--- a/README.md
+++ b/README.md
@@ -1931,6 +1931,7 @@
2586|[Count the Number of Vowel Strings in Range](./solutions/2586-count-the-number-of-vowel-strings-in-range.js)|Easy|
2587|[Rearrange Array to Maximize Prefix Score](./solutions/2587-rearrange-array-to-maximize-prefix-score.js)|Medium|
2588|[Count the Number of Beautiful Subarrays](./solutions/2588-count-the-number-of-beautiful-subarrays.js)|Medium|
+2592|[Maximize Greatness of an Array](./solutions/2592-maximize-greatness-of-an-array.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|
diff --git a/solutions/2592-maximize-greatness-of-an-array.js b/solutions/2592-maximize-greatness-of-an-array.js
new file mode 100644
index 00000000..07b1edea
--- /dev/null
+++ b/solutions/2592-maximize-greatness-of-an-array.js
@@ -0,0 +1,36 @@
+/**
+ * 2592. Maximize Greatness of an Array
+ * https://leetcode.com/problems/maximize-greatness-of-an-array/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums. You are allowed to permute nums into a new
+ * array perm of your choosing.
+ *
+ * We define the greatness of nums be the number of indices 0 <= i < nums.length for which
+ * perm[i] > nums[i].
+ *
+ * Return the maximum possible greatness you can achieve after permuting nums.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maximizeGreatness = function(nums) {
+ nums.sort((a, b) => a - b);
+ let result = 0;
+ let i = 0;
+ let j = 1;
+
+ while (j < nums.length) {
+ if (nums[j] > nums[i]) {
+ result++;
+ i++;
+ j++;
+ } else {
+ j++;
+ }
+ }
+
+ return result;
+};
From 359a6488376320b41f2dba70923d645047b78995 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 23:26:40 -0500
Subject: [PATCH 238/994] Add solution #2595
---
README.md | 1 +
solutions/2595-number-of-even-and-odd-bits.js | 36 +++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/2595-number-of-even-and-odd-bits.js
diff --git a/README.md b/README.md
index f742c6b0..2f9881e8 100644
--- a/README.md
+++ b/README.md
@@ -1933,6 +1933,7 @@
2588|[Count the Number of Beautiful Subarrays](./solutions/2588-count-the-number-of-beautiful-subarrays.js)|Medium|
2592|[Maximize Greatness of an Array](./solutions/2592-maximize-greatness-of-an-array.js)|Medium|
2594|[Minimum Time to Repair Cars](./solutions/2594-minimum-time-to-repair-cars.js)|Medium|
+2595|[Number of Even and Odd Bits](./solutions/2595-number-of-even-and-odd-bits.js)|Easy|
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|
diff --git a/solutions/2595-number-of-even-and-odd-bits.js b/solutions/2595-number-of-even-and-odd-bits.js
new file mode 100644
index 00000000..e4508491
--- /dev/null
+++ b/solutions/2595-number-of-even-and-odd-bits.js
@@ -0,0 +1,36 @@
+/**
+ * 2595. Number of Even and Odd Bits
+ * https://leetcode.com/problems/number-of-even-and-odd-bits/
+ * Difficulty: Easy
+ *
+ * You are given a positive integer n.
+ *
+ * Let even denote the number of even indices in the binary representation of n with value 1.
+ *
+ * Let odd denote the number of odd indices in the binary representation of n with value 1.
+ *
+ * Note that bits are indexed from right to left in the binary representation of a number.
+ *
+ * Return the array [even, odd].
+ */
+
+/**
+ * @param {number} n
+ * @return {number[]}
+ */
+var evenOddBit = function(n) {
+ let evenCount = 0;
+ let oddCount = 0;
+ let index = 0;
+
+ while (n > 0) {
+ if (n & 1) {
+ if (index % 2 === 0) evenCount++;
+ else oddCount++;
+ }
+ n >>= 1;
+ index++;
+ }
+
+ return [evenCount, oddCount];
+};
From b9a2b2f36bcf1cfac4a8c7401ea2f15165791441 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 23:27:52 -0500
Subject: [PATCH 239/994] Add solution #2596
---
README.md | 1 +
.../2596-check-knight-tour-configuration.js | 52 +++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 solutions/2596-check-knight-tour-configuration.js
diff --git a/README.md b/README.md
index 2f9881e8..9f3f6f4d 100644
--- a/README.md
+++ b/README.md
@@ -1934,6 +1934,7 @@
2592|[Maximize Greatness of an Array](./solutions/2592-maximize-greatness-of-an-array.js)|Medium|
2594|[Minimum Time to Repair Cars](./solutions/2594-minimum-time-to-repair-cars.js)|Medium|
2595|[Number of Even and Odd Bits](./solutions/2595-number-of-even-and-odd-bits.js)|Easy|
+2596|[Check Knight Tour Configuration](./solutions/2596-check-knight-tour-configuration.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|
diff --git a/solutions/2596-check-knight-tour-configuration.js b/solutions/2596-check-knight-tour-configuration.js
new file mode 100644
index 00000000..d75bc66a
--- /dev/null
+++ b/solutions/2596-check-knight-tour-configuration.js
@@ -0,0 +1,52 @@
+/**
+ * 2596. Check Knight Tour Configuration
+ * https://leetcode.com/problems/check-knight-tour-configuration/
+ * Difficulty: Medium
+ *
+ * There is a knight on an n x n chessboard. In a valid configuration, the knight starts at the
+ * top-left cell of the board and visits every cell on the board exactly once.
+ *
+ * You are given an n x n integer matrix grid consisting of distinct integers from the range
+ * [0, n * n - 1] where grid[row][col] indicates that the cell (row, col) is the grid[row][col]th
+ * cell that the knight visited. The moves are 0-indexed.
+ *
+ * Return true if grid represents a valid configuration of the knight's movements or false
+ * otherwise.
+ *
+ * Note that a valid knight move consists of moving two squares vertically and one square
+ * horizontally, or two squares horizontally and one square vertically. The figure below
+ * illustrates all the possible eight moves of a knight from some cell.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {boolean}
+ */
+var checkValidGrid = function(grid) {
+ const n = grid.length;
+ const moves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]];
+
+ if (grid[0][0] !== 0) return false;
+
+ const isValidMove = (fromRow, fromCol, toRow, toCol) => {
+ for (const [dr, dc] of moves) {
+ if (fromRow + dr === toRow && fromCol + dc === toCol) return true;
+ }
+ return false;
+ };
+
+ const positions = new Array(n * n).fill(0).map(() => [0, 0]);
+ for (let row = 0; row < n; row++) {
+ for (let col = 0; col < n; col++) {
+ positions[grid[row][col]] = [row, col];
+ }
+ }
+
+ for (let i = 1; i < n * n; i++) {
+ const [prevRow, prevCol] = positions[i - 1];
+ const [currRow, currCol] = positions[i];
+ if (!isValidMove(prevRow, prevCol, currRow, currCol)) return false;
+ }
+
+ return true;
+};
From 801d159953e0058d6252fb215f27cb25411daf56 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 23:29:16 -0500
Subject: [PATCH 240/994] Add solution #2597
---
README.md | 1 +
.../2597-the-number-of-beautiful-subsets.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/2597-the-number-of-beautiful-subsets.js
diff --git a/README.md b/README.md
index 9f3f6f4d..e066bacd 100644
--- a/README.md
+++ b/README.md
@@ -1935,6 +1935,7 @@
2594|[Minimum Time to Repair Cars](./solutions/2594-minimum-time-to-repair-cars.js)|Medium|
2595|[Number of Even and Odd Bits](./solutions/2595-number-of-even-and-odd-bits.js)|Easy|
2596|[Check Knight Tour Configuration](./solutions/2596-check-knight-tour-configuration.js)|Medium|
+2597|[The Number of Beautiful Subsets](./solutions/2597-the-number-of-beautiful-subsets.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|
diff --git a/solutions/2597-the-number-of-beautiful-subsets.js b/solutions/2597-the-number-of-beautiful-subsets.js
new file mode 100644
index 00000000..9f72486d
--- /dev/null
+++ b/solutions/2597-the-number-of-beautiful-subsets.js
@@ -0,0 +1,42 @@
+/**
+ * 2597. The Number of Beautiful Subsets
+ * https://leetcode.com/problems/the-number-of-beautiful-subsets/
+ * Difficulty: Medium
+ *
+ * You are given an array nums of positive integers and a positive integer k.
+ *
+ * A subset of nums is beautiful if it does not contain two integers with an absolute difference
+ * equal to k.
+ *
+ * Return the number of non-empty beautiful subsets of the array nums.
+ *
+ * A subset of nums is an array that can be obtained by deleting some (possibly none) elements
+ * from nums. Two subsets are different if and only if the chosen indices to delete are different.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var beautifulSubsets = function(nums, k) {
+ const n = nums.length;
+ let count = 0;
+ backtrack(0, []);
+ return count;
+
+ function backtrack(index, selected) {
+ if (index === n) {
+ if (selected.length > 0) count++;
+ return;
+ }
+
+ const isValid = selected.every(num => Math.abs(num - nums[index]) !== k);
+
+ backtrack(index + 1, selected);
+
+ if (isValid) {
+ backtrack(index + 1, [...selected, nums[index]]);
+ }
+ }
+};
From ee672d63d5ecee5e6efa14b17eb6e7d4135025bd Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 25 May 2025 23:37:16 -0500
Subject: [PATCH 241/994] Add solution #2600
---
README.md | 1 +
.../2600-k-items-with-the-maximum-sum.js | 38 +++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2600-k-items-with-the-maximum-sum.js
diff --git a/README.md b/README.md
index e066bacd..5ba9cf78 100644
--- a/README.md
+++ b/README.md
@@ -1936,6 +1936,7 @@
2595|[Number of Even and Odd Bits](./solutions/2595-number-of-even-and-odd-bits.js)|Easy|
2596|[Check Knight Tour Configuration](./solutions/2596-check-knight-tour-configuration.js)|Medium|
2597|[The Number of Beautiful Subsets](./solutions/2597-the-number-of-beautiful-subsets.js)|Medium|
+2600|[K Items With the Maximum Sum](./solutions/2600-k-items-with-the-maximum-sum.js)|Easy|
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|
diff --git a/solutions/2600-k-items-with-the-maximum-sum.js b/solutions/2600-k-items-with-the-maximum-sum.js
new file mode 100644
index 00000000..c6952fe3
--- /dev/null
+++ b/solutions/2600-k-items-with-the-maximum-sum.js
@@ -0,0 +1,38 @@
+/**
+ * 2600. K Items With the Maximum Sum
+ * https://leetcode.com/problems/k-items-with-the-maximum-sum/
+ * Difficulty: Easy
+ *
+ * There is a bag that consists of items, each item has a number 1, 0, or -1 written on it.
+ *
+ * You are given four non-negative integers numOnes, numZeros, numNegOnes, and k.
+ *
+ * The bag initially contains:
+ * - numOnes items with 1s written on them.
+ * - numZeroes items with 0s written on them.
+ * - numNegOnes items with -1s written on them.
+ *
+ * We want to pick exactly k items among the available items. Return the maximum possible sum
+ * of numbers written on the items.
+ */
+
+/**
+ * @param {number} numOnes
+ * @param {number} numZeros
+ * @param {number} numNegOnes
+ * @param {number} k
+ * @return {number}
+ */
+var kItemsWithMaximumSum = function(numOnes, numZeros, numNegOnes, k) {
+ let result = 0;
+
+ if (k <= numOnes) {
+ result = k;
+ } else if (k <= numOnes + numZeros) {
+ result = numOnes;
+ } else {
+ result = numOnes - (k - numOnes - numZeros);
+ }
+
+ return result;
+};
From 7e3a06093fa37b7af8e27bb0aa6205dc310274bb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 26 May 2025 22:20:30 -0500
Subject: [PATCH 242/994] Add solution #2894
---
README.md | 1 +
...sible-and-non-divisible-sums-difference.js | 33 +++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/2894-divisible-and-non-divisible-sums-difference.js
diff --git a/README.md b/README.md
index 5ba9cf78..98b6cfb2 100644
--- a/README.md
+++ b/README.md
@@ -1988,6 +1988,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|
+2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
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|
diff --git a/solutions/2894-divisible-and-non-divisible-sums-difference.js b/solutions/2894-divisible-and-non-divisible-sums-difference.js
new file mode 100644
index 00000000..31f068ec
--- /dev/null
+++ b/solutions/2894-divisible-and-non-divisible-sums-difference.js
@@ -0,0 +1,33 @@
+/**
+ * 2894. Divisible and Non-divisible Sums Difference
+ * https://leetcode.com/problems/divisible-and-non-divisible-sums-difference/
+ * Difficulty: Easy
+ *
+ * You are given positive integers n and m.
+ *
+ * Define two integers as follows:
+ * - num1: The sum of all integers in the range [1, n] (both inclusive) that are not divisible by m.
+ * - num2: The sum of all integers in the range [1, n] (both inclusive) that are divisible by m.
+ *
+ * Return the integer num1 - num2.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} m
+ * @return {number}
+ */
+var differenceOfSums = function(n, m) {
+ let nonDivisibleSum = 0;
+ let divisibleSum = 0;
+
+ for (let i = 1; i <= n; i++) {
+ if (i % m === 0) {
+ divisibleSum += i;
+ } else {
+ nonDivisibleSum += i;
+ }
+ }
+
+ return nonDivisibleSum - divisibleSum;
+};
From 48add7a59c781214b4f3df2255787bcce2e49ba0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 26 May 2025 22:27:34 -0500
Subject: [PATCH 243/994] Add solution #2601
---
README.md | 1 +
solutions/2601-prime-subtraction-operation.js | 62 +++++++++++++++++++
2 files changed, 63 insertions(+)
create mode 100644 solutions/2601-prime-subtraction-operation.js
diff --git a/README.md b/README.md
index 98b6cfb2..a369db67 100644
--- a/README.md
+++ b/README.md
@@ -1937,6 +1937,7 @@
2596|[Check Knight Tour Configuration](./solutions/2596-check-knight-tour-configuration.js)|Medium|
2597|[The Number of Beautiful Subsets](./solutions/2597-the-number-of-beautiful-subsets.js)|Medium|
2600|[K Items With the Maximum Sum](./solutions/2600-k-items-with-the-maximum-sum.js)|Easy|
+2601|[Prime Subtraction Operation](./solutions/2601-prime-subtraction-operation.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|
diff --git a/solutions/2601-prime-subtraction-operation.js b/solutions/2601-prime-subtraction-operation.js
new file mode 100644
index 00000000..c9fbc184
--- /dev/null
+++ b/solutions/2601-prime-subtraction-operation.js
@@ -0,0 +1,62 @@
+/**
+ * 2601. Prime Subtraction Operation
+ * https://leetcode.com/problems/prime-subtraction-operation/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums of length n.
+ *
+ * You can perform the following operation as many times as you want:
+ * - Pick an index i that you haven’t picked before, and pick a prime p strictly less than
+ * nums[i], then subtract p from nums[i].
+ *
+ * Return true if you can make nums a strictly increasing array using the above operation
+ * and false otherwise.
+ *
+ * A strictly increasing array is an array whose each element is strictly greater than its
+ * preceding element.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {boolean}
+ */
+var primeSubOperation = function(nums) {
+ const primes = generatePrimes(1000);
+ const adjusted = [...nums];
+ let prev = 0;
+
+ for (let i = 0; i < adjusted.length; i++) {
+ const curr = adjusted[i];
+ let maxPrime = 0;
+
+ for (const prime of primes) {
+ if (prime >= curr) break;
+ if (curr - prime > prev && (i === adjusted.length - 1 || curr - prime < adjusted[i + 1])) {
+ maxPrime = prime;
+ }
+ }
+
+ adjusted[i] -= maxPrime;
+ if (adjusted[i] <= prev) return false;
+ prev = adjusted[i];
+ }
+
+ return true;
+
+ function generatePrimes(limit) {
+ const group = new Array(limit + 1).fill(true);
+ const primes = [];
+ group[0] = group[1] = false;
+
+ for (let i = 2; i <= limit; i++) {
+ if (group[i]) {
+ primes.push(i);
+ for (let j = i * i; j <= limit; j += i) {
+ group[j] = false;
+ }
+ }
+ }
+
+ return primes;
+ }
+};
From 871601b68bd6e3d53e0e7cf5db20d50283c14d3a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 26 May 2025 22:29:13 -0500
Subject: [PATCH 244/994] Add solution #2605
---
README.md | 1 +
...m-smallest-number-from-two-digit-arrays.js | 31 +++++++++++++++++++
2 files changed, 32 insertions(+)
create mode 100644 solutions/2605-form-smallest-number-from-two-digit-arrays.js
diff --git a/README.md b/README.md
index a369db67..34b6862b 100644
--- a/README.md
+++ b/README.md
@@ -1938,6 +1938,7 @@
2597|[The Number of Beautiful Subsets](./solutions/2597-the-number-of-beautiful-subsets.js)|Medium|
2600|[K Items With the Maximum Sum](./solutions/2600-k-items-with-the-maximum-sum.js)|Easy|
2601|[Prime Subtraction Operation](./solutions/2601-prime-subtraction-operation.js)|Medium|
+2605|[Form Smallest Number From Two Digit Arrays](./solutions/2605-form-smallest-number-from-two-digit-arrays.js)|Easy|
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|
diff --git a/solutions/2605-form-smallest-number-from-two-digit-arrays.js b/solutions/2605-form-smallest-number-from-two-digit-arrays.js
new file mode 100644
index 00000000..4892b564
--- /dev/null
+++ b/solutions/2605-form-smallest-number-from-two-digit-arrays.js
@@ -0,0 +1,31 @@
+/**
+ * 2605. Form Smallest Number From Two Digit Arrays
+ * https://leetcode.com/problems/form-smallest-number-from-two-digit-arrays/
+ * Difficulty: Easy
+ *
+ * Given two arrays of unique digits nums1 and nums2, return the smallest number that contains
+ * at least one digit from each array.
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @return {number}
+ */
+var minNumber = function(nums1, nums2) {
+ const set1 = new Set(nums1);
+ const set2 = new Set(nums2);
+ const min1 = Math.min(...nums1);
+ const min2 = Math.min(...nums2);
+ let smallestCommon = 10;
+
+ for (const digit of set1) {
+ if (set2.has(digit) && digit < smallestCommon) {
+ smallestCommon = digit;
+ }
+ }
+
+ if (smallestCommon !== 10) return smallestCommon;
+
+ return min1 < min2 ? min1 * 10 + min2 : min2 * 10 + min1;
+};
From eee204f06b8075effee05749d145d760d4f81f07 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 26 May 2025 22:31:35 -0500
Subject: [PATCH 245/994] Add solution #2606
---
README.md | 1 +
...06-find-the-substring-with-maximum-cost.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/2606-find-the-substring-with-maximum-cost.js
diff --git a/README.md b/README.md
index 34b6862b..234f0af2 100644
--- a/README.md
+++ b/README.md
@@ -1939,6 +1939,7 @@
2600|[K Items With the Maximum Sum](./solutions/2600-k-items-with-the-maximum-sum.js)|Easy|
2601|[Prime Subtraction Operation](./solutions/2601-prime-subtraction-operation.js)|Medium|
2605|[Form Smallest Number From Two Digit Arrays](./solutions/2605-form-smallest-number-from-two-digit-arrays.js)|Easy|
+2606|[Find the Substring With Maximum Cost](./solutions/2606-find-the-substring-with-maximum-cost.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|
diff --git a/solutions/2606-find-the-substring-with-maximum-cost.js b/solutions/2606-find-the-substring-with-maximum-cost.js
new file mode 100644
index 00000000..0a4572c5
--- /dev/null
+++ b/solutions/2606-find-the-substring-with-maximum-cost.js
@@ -0,0 +1,42 @@
+/**
+ * 2606. Find the Substring With Maximum Cost
+ * https://leetcode.com/problems/find-the-substring-with-maximum-cost/
+ * Difficulty: Medium
+ *
+ * You are given a string s, a string chars of distinct characters and an integer array vals of
+ * the same length as chars.
+ *
+ * The cost of the substring is the sum of the values of each character in the substring. The
+ * cost of an empty string is considered 0.
+ *
+ * The value of the character is defined in the following way:
+ * - If the character is not in the string chars, then its value is its corresponding position
+ * (1-indexed) in the alphabet.
+ * - For example, the value of 'a' is 1, the value of 'b' is 2, and so on. The value of 'z' is 26.
+ * - Otherwise, assuming i is the index where the character occurs in the string chars, then its
+ * value is vals[i].
+ *
+ * Return the maximum cost among all substrings of the string s.
+ */
+
+/**
+ * @param {string} s
+ * @param {string} chars
+ * @param {number[]} vals
+ * @return {number}
+ */
+var maximumCostSubstring = function(s, chars, vals) {
+ const charValues = new Array(26).fill().map((_, i) => i + 1);
+ for (let i = 0; i < chars.length; i++) {
+ charValues[chars.charCodeAt(i) - 97] = vals[i];
+ }
+
+ let result = 0;
+ let currentCost = 0;
+ for (const char of s) {
+ currentCost = Math.max(0, currentCost + charValues[char.charCodeAt(0) - 97]);
+ result = Math.max(result, currentCost);
+ }
+
+ return result;
+};
From d913ffec1ca3f4abeec5e2368b5fd74583eb9ddf Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 27 May 2025 23:52:21 -0500
Subject: [PATCH 246/994] Add solution #3372
---
README.md | 1 +
...f-target-nodes-after-connecting-trees-i.js | 87 +++++++++++++++++++
2 files changed, 88 insertions(+)
create mode 100644 solutions/3372-maximize-the-number-of-target-nodes-after-connecting-trees-i.js
diff --git a/README.md b/README.md
index 234f0af2..ce16e526 100644
--- a/README.md
+++ b/README.md
@@ -2025,6 +2025,7 @@
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|
+3372|[Maximize the Number of Target Nodes After Connecting Trees I](./solutions/3372-maximize-the-number-of-target-nodes-after-connecting-trees-i.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/3372-maximize-the-number-of-target-nodes-after-connecting-trees-i.js b/solutions/3372-maximize-the-number-of-target-nodes-after-connecting-trees-i.js
new file mode 100644
index 00000000..c4ce5f98
--- /dev/null
+++ b/solutions/3372-maximize-the-number-of-target-nodes-after-connecting-trees-i.js
@@ -0,0 +1,87 @@
+/**
+ * 3372. Maximize the Number of Target Nodes After Connecting Trees I
+ * https://leetcode.com/problems/maximize-the-number-of-target-nodes-after-connecting-trees-i/
+ * Difficulty: Medium
+ *
+ * There exist two undirected trees with n and m nodes, with distinct labels in ranges [0, n - 1]
+ * and [0, m - 1], respectively.
+ *
+ * You are given two 2D integer arrays edges1 and edges2 of lengths n - 1 and m - 1, respectively,
+ * where edges1[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the first
+ * tree and edges2[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the
+ * second tree. You are also given an integer k.
+ *
+ * Node u is target to node v if the number of edges on the path from u to v is less than or equal
+ * to k. Note that a node is always target to itself.
+ *
+ * Return an array of n integers answer, where answer[i] is the maximum possible number of nodes
+ * target to node i of the first tree if you have to connect one node from the first tree to
+ * another node in the second tree.
+ *
+ * Note that queries are independent from each other. That is, for every query you will remove
+ * the added edge before proceeding to the next query.
+ */
+
+/**
+ * @param {number[][]} edges1
+ * @param {number[][]} edges2
+ * @param {number} k
+ * @return {number[]}
+ */
+var maxTargetNodes = function(edges1, edges2, k) {
+ const graph1 = buildGraph(edges1);
+ const graph2 = buildGraph(edges2);
+ const n = edges1.length + 1;
+ const m = edges2.length + 1;
+
+ let tree2Max = 0;
+ if (k > 0) {
+ tree2Max = Math.max(...Array.from({ length: m }, (_, i) =>
+ countReachable(graph2, i, k - 1)
+ ));
+ }
+
+ const result = [];
+ for (let i = 0; i < n; i++) {
+ const tree1Count = countReachable(graph1, i, k);
+ result.push(tree1Count + tree2Max);
+ }
+
+ return result;
+
+ function buildGraph(edges) {
+ const graph = {};
+ for (const [u, v] of edges) {
+ if (!graph[u]) graph[u] = [];
+ if (!graph[v]) graph[v] = [];
+ graph[u].push(v);
+ graph[v].push(u);
+ }
+ return graph;
+ }
+
+ function countReachable(graph, start, maxDist) {
+ const queue = [start];
+ const visited = new Set([start]);
+ let count = 1;
+ let dist = 0;
+
+ while (queue.length > 0 && dist < maxDist) {
+ const size = queue.length;
+ dist++;
+ for (let i = 0; i < size; i++) {
+ const node = queue.shift();
+ if (graph[node]) {
+ for (const neighbor of graph[node]) {
+ if (!visited.has(neighbor)) {
+ visited.add(neighbor);
+ queue.push(neighbor);
+ count++;
+ }
+ }
+ }
+ }
+ }
+ return count;
+ }
+};
From 08a3758216ac5a47401e7c7c8512206907512272 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 27 May 2025 23:53:55 -0500
Subject: [PATCH 247/994] Add solution #2609
---
README.md | 1 +
...t-balanced-substring-of-a-binary-string.js | 45 +++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/2609-find-the-longest-balanced-substring-of-a-binary-string.js
diff --git a/README.md b/README.md
index ce16e526..e20be8ef 100644
--- a/README.md
+++ b/README.md
@@ -1940,6 +1940,7 @@
2601|[Prime Subtraction Operation](./solutions/2601-prime-subtraction-operation.js)|Medium|
2605|[Form Smallest Number From Two Digit Arrays](./solutions/2605-form-smallest-number-from-two-digit-arrays.js)|Easy|
2606|[Find the Substring With Maximum Cost](./solutions/2606-find-the-substring-with-maximum-cost.js)|Medium|
+2609|[Find the Longest Balanced Substring of a Binary String](./solutions/2609-find-the-longest-balanced-substring-of-a-binary-string.js)|Easy|
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|
diff --git a/solutions/2609-find-the-longest-balanced-substring-of-a-binary-string.js b/solutions/2609-find-the-longest-balanced-substring-of-a-binary-string.js
new file mode 100644
index 00000000..3884e54e
--- /dev/null
+++ b/solutions/2609-find-the-longest-balanced-substring-of-a-binary-string.js
@@ -0,0 +1,45 @@
+/**
+ * 2609. Find the Longest Balanced Substring of a Binary String
+ * https://leetcode.com/problems/find-the-longest-balanced-substring-of-a-binary-string/
+ * Difficulty: Easy
+ *
+ * You are given a binary string s consisting only of zeroes and ones.
+ *
+ * A substring of s is considered balanced if all zeroes are before ones and the number of zeroes
+ * is equal to the number of ones inside the substring. Notice that the empty substring is
+ * considered a balanced substring.
+ *
+ * Return the length of the longest balanced substring of s.
+ *
+ * A substring is a contiguous sequence of characters within a string.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var findTheLongestBalancedSubstring = function(s) {
+ let result = 0;
+ let zeros = 0;
+ let ones = 0;
+
+ for (let i = 0; i < s.length; i++) {
+ if (s[i] === '0') {
+ if (ones > 0) {
+ zeros = 0;
+ ones = 0;
+ }
+ zeros++;
+ } else {
+ if (zeros >= ones + 1) {
+ ones++;
+ result = Math.max(result, 2 * ones);
+ } else {
+ zeros = 0;
+ ones = 0;
+ }
+ }
+ }
+
+ return result;
+};
From 087a594be12978a7141948229a464919e28bbe49 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 27 May 2025 23:55:07 -0500
Subject: [PATCH 248/994] Add solution #2610
---
README.md | 1 +
...n-array-into-a-2d-array-with-conditions.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/2610-convert-an-array-into-a-2d-array-with-conditions.js
diff --git a/README.md b/README.md
index e20be8ef..53856d04 100644
--- a/README.md
+++ b/README.md
@@ -1941,6 +1941,7 @@
2605|[Form Smallest Number From Two Digit Arrays](./solutions/2605-form-smallest-number-from-two-digit-arrays.js)|Easy|
2606|[Find the Substring With Maximum Cost](./solutions/2606-find-the-substring-with-maximum-cost.js)|Medium|
2609|[Find the Longest Balanced Substring of a Binary String](./solutions/2609-find-the-longest-balanced-substring-of-a-binary-string.js)|Easy|
+2610|[Convert an Array Into a 2D Array With Conditions](./solutions/2610-convert-an-array-into-a-2d-array-with-conditions.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|
diff --git a/solutions/2610-convert-an-array-into-a-2d-array-with-conditions.js b/solutions/2610-convert-an-array-into-a-2d-array-with-conditions.js
new file mode 100644
index 00000000..7c584818
--- /dev/null
+++ b/solutions/2610-convert-an-array-into-a-2d-array-with-conditions.js
@@ -0,0 +1,42 @@
+/**
+ * 2610. Convert an Array Into a 2D Array With Conditions
+ * https://leetcode.com/problems/convert-an-array-into-a-2d-array-with-conditions/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums. You need to create a 2D array from nums satisfying
+ * the following conditions:
+ * - The 2D array should contain only the elements of the array nums.
+ * - Each row in the 2D array contains distinct integers.
+ * - The number of rows in the 2D array should be minimal.
+ *
+ * Return the resulting array. If there are multiple answers, return any of them.
+ *
+ * Note that the 2D array can have a different number of elements on each row.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[][]}
+ */
+var findMatrix = function(nums) {
+ const frequency = new Map();
+ for (const num of nums) {
+ frequency.set(num, (frequency.get(num) || 0) + 1);
+ }
+
+ const result = [];
+ while (frequency.size) {
+ const row = [];
+ for (const [num, count] of frequency) {
+ row.push(num);
+ if (count === 1) {
+ frequency.delete(num);
+ } else {
+ frequency.set(num, count - 1);
+ }
+ }
+ result.push(row);
+ }
+
+ return result;
+};
From 5df4e7bdf28edcc5ff71f299d7c6434767c6469d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 27 May 2025 23:56:25 -0500
Subject: [PATCH 249/994] Add solution #2616
---
README.md | 1 +
...inimize-the-maximum-difference-of-pairs.js | 53 +++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/2616-minimize-the-maximum-difference-of-pairs.js
diff --git a/README.md b/README.md
index 53856d04..15946b34 100644
--- a/README.md
+++ b/README.md
@@ -1943,6 +1943,7 @@
2609|[Find the Longest Balanced Substring of a Binary String](./solutions/2609-find-the-longest-balanced-substring-of-a-binary-string.js)|Easy|
2610|[Convert an Array Into a 2D Array With Conditions](./solutions/2610-convert-an-array-into-a-2d-array-with-conditions.js)|Medium|
2615|[Sum of Distances](./solutions/2615-sum-of-distances.js)|Medium|
+2616|[Minimize the Maximum Difference of Pairs](./solutions/2616-minimize-the-maximum-difference-of-pairs.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/2616-minimize-the-maximum-difference-of-pairs.js b/solutions/2616-minimize-the-maximum-difference-of-pairs.js
new file mode 100644
index 00000000..691f2e60
--- /dev/null
+++ b/solutions/2616-minimize-the-maximum-difference-of-pairs.js
@@ -0,0 +1,53 @@
+/**
+ * 2616. Minimize the Maximum Difference of Pairs
+ * https://leetcode.com/problems/minimize-the-maximum-difference-of-pairs/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums and an integer p. Find p pairs of indices
+ * of nums such that the maximum difference amongst all the pairs is minimized. Also, ensure
+ * no index appears more than once amongst the p pairs.
+ *
+ * Note that for a pair of elements at the index i and j, the difference of this pair is
+ * |nums[i] - nums[j]|, where |x| represents the absolute value of x.
+ *
+ * Return the minimum maximum difference among all p pairs. We define the maximum of an empty
+ * set to be zero.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} p
+ * @return {number}
+ */
+var minimizeMax = function(nums, p) {
+ nums.sort((a, b) => a - b);
+ const n = nums.length;
+
+ let left = 0;
+ let right = nums[n - 1] - nums[0];
+ let result = 0;
+
+ while (left <= right) {
+ const mid = Math.floor((left + right) / 2);
+ if (canFormPairs(mid)) {
+ result = mid;
+ right = mid - 1;
+ } else {
+ left = mid + 1;
+ }
+ }
+
+ return result;
+
+ function canFormPairs(maxDiff) {
+ let pairs = 0;
+ for (let i = 0; i < n - 1 && pairs < p; i += 2) {
+ if (nums[i + 1] - nums[i] <= maxDiff) {
+ pairs++;
+ } else {
+ i--;
+ }
+ }
+ return pairs >= p;
+ }
+};
From df1b48592891773ad968e56e3d50732fe88d06b2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 27 May 2025 23:58:28 -0500
Subject: [PATCH 250/994] Add solution #2639
---
README.md | 1 +
...639-find-the-width-of-columns-of-a-grid.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/2639-find-the-width-of-columns-of-a-grid.js
diff --git a/README.md b/README.md
index 15946b34..d7aeb8c8 100644
--- a/README.md
+++ b/README.md
@@ -1960,6 +1960,7 @@
2634|[Filter Elements from Array](./solutions/2634-filter-elements-from-array.js)|Easy|
2635|[Apply Transform Over Each Element in Array](./solutions/2635-apply-transform-over-each-element-in-array.js)|Easy|
2637|[Promise Time Limit](./solutions/2637-promise-time-limit.js)|Medium|
+2639|[Find the Width of Columns of a Grid](./solutions/2639-find-the-width-of-columns-of-a-grid.js)|Easy|
2648|[Generate Fibonacci Sequence](./solutions/2648-generate-fibonacci-sequence.js)|Easy|
2649|[Nested Array Generator](./solutions/2649-nested-array-generator.js)|Medium|
2650|[Design Cancellable Function](./solutions/2650-design-cancellable-function.js)|Hard|
diff --git a/solutions/2639-find-the-width-of-columns-of-a-grid.js b/solutions/2639-find-the-width-of-columns-of-a-grid.js
new file mode 100644
index 00000000..e544bc23
--- /dev/null
+++ b/solutions/2639-find-the-width-of-columns-of-a-grid.js
@@ -0,0 +1,34 @@
+/**
+ * 2639. Find the Width of Columns of a Grid
+ * https://leetcode.com/problems/find-the-width-of-columns-of-a-grid/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed m x n integer matrix grid. The width of a column is the
+ * maximum length of its integers.
+ * - For example, if grid = [[-10], [3], [12]], the width of the only column is 3
+ * since -10 is of length 3.
+ *
+ * Return an integer array ans of size n where ans[i] is the width of the ith column.
+ *
+ * The length of an integer x with len digits is equal to len if x is non-negative, and
+ * len + 1 otherwise.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number[]}
+ */
+var findColumnWidth = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const result = new Array(cols).fill(0);
+
+ for (let col = 0; col < cols; col++) {
+ for (let row = 0; row < rows; row++) {
+ const num = grid[row][col];
+ result[col] = Math.max(result[col], String(num).length);
+ }
+ }
+
+ return result;
+};
From d5fd25111b81552ea3d3478ed7fb853496737ed7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 00:00:31 -0500
Subject: [PATCH 251/994] Add solution #2640
---
README.md | 1 +
...d-the-score-of-all-prefixes-of-an-array.js | 32 +++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/2640-find-the-score-of-all-prefixes-of-an-array.js
diff --git a/README.md b/README.md
index d7aeb8c8..88f071b3 100644
--- a/README.md
+++ b/README.md
@@ -1961,6 +1961,7 @@
2635|[Apply Transform Over Each Element in Array](./solutions/2635-apply-transform-over-each-element-in-array.js)|Easy|
2637|[Promise Time Limit](./solutions/2637-promise-time-limit.js)|Medium|
2639|[Find the Width of Columns of a Grid](./solutions/2639-find-the-width-of-columns-of-a-grid.js)|Easy|
+2640|[Find the Score of All Prefixes of an Array](./solutions/2640-find-the-score-of-all-prefixes-of-an-array.js)|Medium|
2648|[Generate Fibonacci Sequence](./solutions/2648-generate-fibonacci-sequence.js)|Easy|
2649|[Nested Array Generator](./solutions/2649-nested-array-generator.js)|Medium|
2650|[Design Cancellable Function](./solutions/2650-design-cancellable-function.js)|Hard|
diff --git a/solutions/2640-find-the-score-of-all-prefixes-of-an-array.js b/solutions/2640-find-the-score-of-all-prefixes-of-an-array.js
new file mode 100644
index 00000000..9ec56b99
--- /dev/null
+++ b/solutions/2640-find-the-score-of-all-prefixes-of-an-array.js
@@ -0,0 +1,32 @@
+/**
+ * 2640. Find the Score of All Prefixes of an Array
+ * https://leetcode.com/problems/find-the-score-of-all-prefixes-of-an-array/
+ * Difficulty: Medium
+ *
+ * We define the conversion array conver of an array arr as follows:
+ * - conver[i] = arr[i] + max(arr[0..i]) where max(arr[0..i]) is the maximum value of
+ * arr[j] over 0 <= j <= i.
+ *
+ * We also define the score of an array arr as the sum of the values of the conversion array of arr.
+ *
+ * Given a 0-indexed integer array nums of length n, return an array ans of length n where ans[i]
+ * is the score of the prefix nums[0..i].
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var findPrefixScore = function(nums) {
+ const result = new Array(nums.length);
+ let maxSoFar = 0;
+ let total = 0;
+
+ for (let i = 0; i < nums.length; i++) {
+ maxSoFar = Math.max(maxSoFar, nums[i]);
+ total += nums[i] + maxSoFar;
+ result[i] = total;
+ }
+
+ return result;
+};
From 256f59a06c6ada9a3d34121f99f5d7227a0fba8c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 00:02:10 -0500
Subject: [PATCH 252/994] Add solution #2641
---
README.md | 1 +
solutions/2641-cousins-in-binary-tree-ii.js | 53 +++++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/2641-cousins-in-binary-tree-ii.js
diff --git a/README.md b/README.md
index 88f071b3..4685a1b0 100644
--- a/README.md
+++ b/README.md
@@ -1962,6 +1962,7 @@
2637|[Promise Time Limit](./solutions/2637-promise-time-limit.js)|Medium|
2639|[Find the Width of Columns of a Grid](./solutions/2639-find-the-width-of-columns-of-a-grid.js)|Easy|
2640|[Find the Score of All Prefixes of an Array](./solutions/2640-find-the-score-of-all-prefixes-of-an-array.js)|Medium|
+2641|[Cousins in Binary Tree II](./solutions/2641-cousins-in-binary-tree-ii.js)|Medium|
2648|[Generate Fibonacci Sequence](./solutions/2648-generate-fibonacci-sequence.js)|Easy|
2649|[Nested Array Generator](./solutions/2649-nested-array-generator.js)|Medium|
2650|[Design Cancellable Function](./solutions/2650-design-cancellable-function.js)|Hard|
diff --git a/solutions/2641-cousins-in-binary-tree-ii.js b/solutions/2641-cousins-in-binary-tree-ii.js
new file mode 100644
index 00000000..07faea41
--- /dev/null
+++ b/solutions/2641-cousins-in-binary-tree-ii.js
@@ -0,0 +1,53 @@
+/**
+ * 2641. Cousins in Binary Tree II
+ * https://leetcode.com/problems/cousins-in-binary-tree-ii/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree, replace the value of each node in the tree with the
+ * sum of all its cousins' values.
+ *
+ * Two nodes of a binary tree are cousins if they have the same depth with different parents.
+ *
+ * Return the root of the modified tree.
+ *
+ * Note that the depth of a node is the number of edges in the path from the root node to it.
+ */
+
+/**
+ * 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 replaceValueInTree = function(root) {
+ const levelSums = [];
+
+ collectSums(root, 0);
+ replaceValues(root, 0, 0);
+
+ return root;
+
+ function collectSums(node, depth) {
+ if (!node) return;
+ if (levelSums.length <= depth) levelSums.push(0);
+ levelSums[depth] += node.val;
+ collectSums(node.left, depth + 1);
+ collectSums(node.right, depth + 1);
+ }
+
+ function replaceValues(node, depth, siblingSum) {
+ if (!node) return;
+ node.val = levelSums[depth] - node.val - siblingSum;
+
+ const leftVal = node.left ? node.left.val : 0;
+ const rightVal = node.right ? node.right.val : 0;
+ replaceValues(node.left, depth + 1, rightVal);
+ replaceValues(node.right, depth + 1, leftVal);
+ }
+};
From 86120636b5d714f5361551c97d5849992b272dcf Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 00:03:15 -0500
Subject: [PATCH 253/994] Add solution #2643
---
README.md | 1 +
solutions/2643-row-with-maximum-ones.js | 32 +++++++++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/2643-row-with-maximum-ones.js
diff --git a/README.md b/README.md
index 4685a1b0..de4d6d9a 100644
--- a/README.md
+++ b/README.md
@@ -1963,6 +1963,7 @@
2639|[Find the Width of Columns of a Grid](./solutions/2639-find-the-width-of-columns-of-a-grid.js)|Easy|
2640|[Find the Score of All Prefixes of an Array](./solutions/2640-find-the-score-of-all-prefixes-of-an-array.js)|Medium|
2641|[Cousins in Binary Tree II](./solutions/2641-cousins-in-binary-tree-ii.js)|Medium|
+2643|[Row With Maximum Ones](./solutions/2643-row-with-maximum-ones.js)|Easy|
2648|[Generate Fibonacci Sequence](./solutions/2648-generate-fibonacci-sequence.js)|Easy|
2649|[Nested Array Generator](./solutions/2649-nested-array-generator.js)|Medium|
2650|[Design Cancellable Function](./solutions/2650-design-cancellable-function.js)|Hard|
diff --git a/solutions/2643-row-with-maximum-ones.js b/solutions/2643-row-with-maximum-ones.js
new file mode 100644
index 00000000..aaa37e79
--- /dev/null
+++ b/solutions/2643-row-with-maximum-ones.js
@@ -0,0 +1,32 @@
+/**
+ * 2643. Row With Maximum Ones
+ * https://leetcode.com/problems/row-with-maximum-ones/
+ * Difficulty: Easy
+ *
+ * Given a m x n binary matrix mat, find the 0-indexed position of the row that contains
+ * the maximum count of ones, and the number of ones in that row.
+ *
+ * In case there are multiple rows that have the maximum count of ones, the row with the
+ * smallest row number should be selected.
+ *
+ * Return an array containing the index of the row, and the number of ones in it.
+ */
+
+/**
+ * @param {number[][]} mat
+ * @return {number[]}
+ */
+var rowAndMaximumOnes = function(mat) {
+ let maxOnes = 0;
+ let maxRow = 0;
+
+ for (let row = 0; row < mat.length; row++) {
+ const ones = mat[row].reduce((sum, val) => sum + val, 0);
+ if (ones > maxOnes) {
+ maxOnes = ones;
+ maxRow = row;
+ }
+ }
+
+ return [maxRow, maxOnes];
+};
From 3430ee44f15dd64d2535bbb92fe5e7a21d0045a9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 00:04:08 -0500
Subject: [PATCH 254/994] Add solution #2644
---
README.md | 1 +
...644-find-the-maximum-divisibility-score.js | 38 +++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2644-find-the-maximum-divisibility-score.js
diff --git a/README.md b/README.md
index de4d6d9a..1ee91b26 100644
--- a/README.md
+++ b/README.md
@@ -1964,6 +1964,7 @@
2640|[Find the Score of All Prefixes of an Array](./solutions/2640-find-the-score-of-all-prefixes-of-an-array.js)|Medium|
2641|[Cousins in Binary Tree II](./solutions/2641-cousins-in-binary-tree-ii.js)|Medium|
2643|[Row With Maximum Ones](./solutions/2643-row-with-maximum-ones.js)|Easy|
+2644|[Find the Maximum Divisibility Score](./solutions/2644-find-the-maximum-divisibility-score.js)|Easy|
2648|[Generate Fibonacci Sequence](./solutions/2648-generate-fibonacci-sequence.js)|Easy|
2649|[Nested Array Generator](./solutions/2649-nested-array-generator.js)|Medium|
2650|[Design Cancellable Function](./solutions/2650-design-cancellable-function.js)|Hard|
diff --git a/solutions/2644-find-the-maximum-divisibility-score.js b/solutions/2644-find-the-maximum-divisibility-score.js
new file mode 100644
index 00000000..ac5c2e02
--- /dev/null
+++ b/solutions/2644-find-the-maximum-divisibility-score.js
@@ -0,0 +1,38 @@
+/**
+ * 2644. Find the Maximum Divisibility Score
+ * https://leetcode.com/problems/find-the-maximum-divisibility-score/
+ * Difficulty: Easy
+ *
+ * You are given two integer arrays nums and divisors.
+ *
+ * The divisibility score of divisors[i] is the number of indices j such that nums[j] is
+ * divisible by divisors[i].
+ *
+ * Return the integer divisors[i] with the maximum divisibility score. If multiple integers
+ * have the maximum score, return the smallest one.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[]} divisors
+ * @return {number}
+ */
+var maxDivScore = function(nums, divisors) {
+ let maxScore = 0;
+ let result = divisors[0];
+
+ for (const divisor of divisors) {
+ let score = 0;
+ for (const num of nums) {
+ if (num % divisor === 0) {
+ score++;
+ }
+ }
+ if (score > maxScore || (score === maxScore && divisor < result)) {
+ maxScore = score;
+ result = divisor;
+ }
+ }
+
+ return result;
+};
From 2e770add94f1cbcf9da0f397f86ebb9f3d47e5d1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 00:05:03 -0500
Subject: [PATCH 255/994] Add solution #2645
---
README.md | 1 +
...-minimum-additions-to-make-valid-string.js | 49 +++++++++++++++++++
2 files changed, 50 insertions(+)
create mode 100644 solutions/2645-minimum-additions-to-make-valid-string.js
diff --git a/README.md b/README.md
index 1ee91b26..b2365313 100644
--- a/README.md
+++ b/README.md
@@ -1965,6 +1965,7 @@
2641|[Cousins in Binary Tree II](./solutions/2641-cousins-in-binary-tree-ii.js)|Medium|
2643|[Row With Maximum Ones](./solutions/2643-row-with-maximum-ones.js)|Easy|
2644|[Find the Maximum Divisibility Score](./solutions/2644-find-the-maximum-divisibility-score.js)|Easy|
+2645|[Minimum Additions to Make Valid String](./solutions/2645-minimum-additions-to-make-valid-string.js)|Medium|
2648|[Generate Fibonacci Sequence](./solutions/2648-generate-fibonacci-sequence.js)|Easy|
2649|[Nested Array Generator](./solutions/2649-nested-array-generator.js)|Medium|
2650|[Design Cancellable Function](./solutions/2650-design-cancellable-function.js)|Hard|
diff --git a/solutions/2645-minimum-additions-to-make-valid-string.js b/solutions/2645-minimum-additions-to-make-valid-string.js
new file mode 100644
index 00000000..fd6bec83
--- /dev/null
+++ b/solutions/2645-minimum-additions-to-make-valid-string.js
@@ -0,0 +1,49 @@
+/**
+ * 2645. Minimum Additions to Make Valid String
+ * https://leetcode.com/problems/minimum-additions-to-make-valid-string/
+ * Difficulty: Medium
+ *
+ * Given a string word to which you can insert letters "a", "b" or "c" anywhere and any number
+ * of times, return the minimum number of letters that must be inserted so that word becomes valid.
+ *
+ * A string is called valid if it can be formed by concatenating the string "abc" several times.
+ */
+
+/**
+ * @param {string} word
+ * @return {number}
+ */
+var addMinimum = function(word) {
+ let result = 0;
+ let index = 0;
+
+ while (index < word.length) {
+ if (word[index] === 'a') {
+ if (word[index + 1] === 'b' && word[index + 2] === 'c') {
+ index += 3;
+ } else if (word[index + 1] === 'b') {
+ result += 1;
+ index += 2;
+ } else if (word[index + 1] === 'c') {
+ result += 1;
+ index += 2;
+ } else {
+ result += 2;
+ index += 1;
+ }
+ } else if (word[index] === 'b') {
+ if (word[index + 1] === 'c') {
+ result += 1;
+ index += 2;
+ } else {
+ result += 2;
+ index += 1;
+ }
+ } else {
+ result += 2;
+ index += 1;
+ }
+ }
+
+ return result;
+};
From 892f5049b0e6cdd7ce7f609c1d1dfb132c94b104 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 00:06:45 -0500
Subject: [PATCH 256/994] Add solution #2651
---
README.md | 1 +
.../2651-calculate-delayed-arrival-time.js | 21 +++++++++++++++++++
2 files changed, 22 insertions(+)
create mode 100644 solutions/2651-calculate-delayed-arrival-time.js
diff --git a/README.md b/README.md
index b2365313..84370002 100644
--- a/README.md
+++ b/README.md
@@ -1969,6 +1969,7 @@
2648|[Generate Fibonacci Sequence](./solutions/2648-generate-fibonacci-sequence.js)|Easy|
2649|[Nested Array Generator](./solutions/2649-nested-array-generator.js)|Medium|
2650|[Design Cancellable Function](./solutions/2650-design-cancellable-function.js)|Hard|
+2651|[Calculate Delayed Arrival Time](./solutions/2651-calculate-delayed-arrival-time.js)|Easy|
2657|[Find the Prefix Common Array of Two Arrays](./solutions/2657-find-the-prefix-common-array-of-two-arrays.js)|Medium|
2658|[Maximum Number of Fish in a Grid](./solutions/2658-maximum-number-of-fish-in-a-grid.js)|Medium|
2661|[First Completely Painted Row or Column](./solutions/2661-first-completely-painted-row-or-column.js)|Medium|
diff --git a/solutions/2651-calculate-delayed-arrival-time.js b/solutions/2651-calculate-delayed-arrival-time.js
new file mode 100644
index 00000000..09571897
--- /dev/null
+++ b/solutions/2651-calculate-delayed-arrival-time.js
@@ -0,0 +1,21 @@
+/**
+ * 2651. Calculate Delayed Arrival Time
+ * https://leetcode.com/problems/calculate-delayed-arrival-time/
+ * Difficulty: Easy
+ *
+ * You are given a positive integer arrivalTime denoting the arrival time of a train in
+ * hours, and another positive integer delayedTime denoting the amount of delay in hours.
+ *
+ * Return the time when the train will arrive at the station.
+ *
+ * Note that the time in this problem is in 24-hours format.
+ */
+
+/**
+ * @param {number} arrivalTime
+ * @param {number} delayedTime
+ * @return {number}
+ */
+var findDelayedArrivalTime = function(arrivalTime, delayedTime) {
+ return (arrivalTime + delayedTime) % 24;
+};
From 562bdb2a911f65fd46f33dbc2c57b0d1e7575502 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 00:07:42 -0500
Subject: [PATCH 257/994] Add solution #2652
---
README.md | 1 +
solutions/2652-sum-multiples.js | 25 +++++++++++++++++++++++++
2 files changed, 26 insertions(+)
create mode 100644 solutions/2652-sum-multiples.js
diff --git a/README.md b/README.md
index 84370002..7c3c161b 100644
--- a/README.md
+++ b/README.md
@@ -1970,6 +1970,7 @@
2649|[Nested Array Generator](./solutions/2649-nested-array-generator.js)|Medium|
2650|[Design Cancellable Function](./solutions/2650-design-cancellable-function.js)|Hard|
2651|[Calculate Delayed Arrival Time](./solutions/2651-calculate-delayed-arrival-time.js)|Easy|
+2652|[Sum Multiples](./solutions/2652-sum-multiples.js)|Easy|
2657|[Find the Prefix Common Array of Two Arrays](./solutions/2657-find-the-prefix-common-array-of-two-arrays.js)|Medium|
2658|[Maximum Number of Fish in a Grid](./solutions/2658-maximum-number-of-fish-in-a-grid.js)|Medium|
2661|[First Completely Painted Row or Column](./solutions/2661-first-completely-painted-row-or-column.js)|Medium|
diff --git a/solutions/2652-sum-multiples.js b/solutions/2652-sum-multiples.js
new file mode 100644
index 00000000..340dbd2a
--- /dev/null
+++ b/solutions/2652-sum-multiples.js
@@ -0,0 +1,25 @@
+/**
+ * 2652. Sum Multiples
+ * https://leetcode.com/problems/sum-multiples/
+ * Difficulty: Easy
+ *
+ * Given a positive integer n, find the sum of all integers in the range [1, n] inclusive
+ * that are divisible by 3, 5, or 7.
+ *
+ * Return an integer denoting the sum of all numbers in the given range satisfying the constraint.
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var sumOfMultiples = function(n) {
+ return sumDivisibleBy(3) + sumDivisibleBy(5) + sumDivisibleBy(7)
+ - sumDivisibleBy(15) - sumDivisibleBy(21) - sumDivisibleBy(35)
+ + sumDivisibleBy(105);
+
+ function sumDivisibleBy(divisor) {
+ const count = Math.floor(n / divisor);
+ return divisor * count * (count + 1) / 2;
+ }
+};
From bdd342a6b0a8873a0aef8e64c7b7900139d2afe3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 00:08:56 -0500
Subject: [PATCH 258/994] Add solution #2656
---
README.md | 1 +
...656-maximum-sum-with-exactly-k-elements.js | 23 +++++++++++++++++++
2 files changed, 24 insertions(+)
create mode 100644 solutions/2656-maximum-sum-with-exactly-k-elements.js
diff --git a/README.md b/README.md
index 7c3c161b..7cf2e7cd 100644
--- a/README.md
+++ b/README.md
@@ -1971,6 +1971,7 @@
2650|[Design Cancellable Function](./solutions/2650-design-cancellable-function.js)|Hard|
2651|[Calculate Delayed Arrival Time](./solutions/2651-calculate-delayed-arrival-time.js)|Easy|
2652|[Sum Multiples](./solutions/2652-sum-multiples.js)|Easy|
+2656|[Maximum Sum With Exactly K Elements](./solutions/2656-maximum-sum-with-exactly-k-elements.js)|Easy|
2657|[Find the Prefix Common Array of Two Arrays](./solutions/2657-find-the-prefix-common-array-of-two-arrays.js)|Medium|
2658|[Maximum Number of Fish in a Grid](./solutions/2658-maximum-number-of-fish-in-a-grid.js)|Medium|
2661|[First Completely Painted Row or Column](./solutions/2661-first-completely-painted-row-or-column.js)|Medium|
diff --git a/solutions/2656-maximum-sum-with-exactly-k-elements.js b/solutions/2656-maximum-sum-with-exactly-k-elements.js
new file mode 100644
index 00000000..fdac61de
--- /dev/null
+++ b/solutions/2656-maximum-sum-with-exactly-k-elements.js
@@ -0,0 +1,23 @@
+/**
+ * 2656. Maximum Sum With Exactly K Elements
+ * https://leetcode.com/problems/maximum-sum-with-exactly-k-elements/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums and an integer k. Your task is to perform
+ * the following operation exactly k times in order to maximize your score:
+ * 1. Select an element m from nums.
+ * 2. Remove the selected element m from the array.
+ * 3. Add a new element with a value of m + 1 to the array.
+ * 4. Increase your score by m.
+ *
+ * Return the maximum score you can achieve after performing the operation exactly k times.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var maximizeSum = function(nums, k) {
+ return k * Math.max(...nums) + k * (k - 1) / 2;
+};
From be5333dcbbed0808d7d24d946a57019360bd048c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 00:10:30 -0500
Subject: [PATCH 259/994] Add solution #2670
---
README.md | 1 +
...2670-find-the-distinct-difference-array.js | 46 +++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/2670-find-the-distinct-difference-array.js
diff --git a/README.md b/README.md
index 7cf2e7cd..ab290a08 100644
--- a/README.md
+++ b/README.md
@@ -1978,6 +1978,7 @@
2665|[Counter II](./solutions/2665-counter-ii.js)|Easy|
2666|[Allow One Function Call](./solutions/2666-allow-one-function-call.js)|Easy|
2667|[Create Hello World Function](./solutions/2667-create-hello-world-function.js)|Easy|
+2670|[Find the Distinct Difference Array](./solutions/2670-find-the-distinct-difference-array.js)|Easy|
2677|[Chunk Array](./solutions/2677-chunk-array.js)|Easy|
2683|[Neighboring Bitwise XOR](./solutions/2683-neighboring-bitwise-xor.js)|Medium|
2685|[Count the Number of Complete Components](./solutions/2685-count-the-number-of-complete-components.js)|Medium|
diff --git a/solutions/2670-find-the-distinct-difference-array.js b/solutions/2670-find-the-distinct-difference-array.js
new file mode 100644
index 00000000..fc3ddaea
--- /dev/null
+++ b/solutions/2670-find-the-distinct-difference-array.js
@@ -0,0 +1,46 @@
+/**
+ * 2670. Find the Distinct Difference Array
+ * https://leetcode.com/problems/find-the-distinct-difference-array/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed array nums of length n.
+ *
+ * The distinct difference array of nums is an array diff of length n such that diff[i] is
+ * equal to the number of distinct elements in the suffix nums[i + 1, ..., n - 1] subtracted
+ * from the number of distinct elements in the prefix nums[0, ..., i].
+ *
+ * Return the distinct difference array of nums.
+ *
+ * Note that nums[i, ..., j] denotes the subarray of nums starting at index i and ending at
+ * index j inclusive. Particularly, if i > j then nums[i, ..., j] denotes an empty subarray.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var distinctDifferenceArray = function(nums) {
+ const n = nums.length;
+ const result = new Array(n);
+ const prefixSet = new Set();
+ const suffixCount = new Map();
+
+ for (const num of nums) {
+ suffixCount.set(num, (suffixCount.get(num) || 0) + 1);
+ }
+
+ let suffixDistinct = suffixCount.size;
+
+ for (let i = 0; i < n; i++) {
+ prefixSet.add(nums[i]);
+ const count = suffixCount.get(nums[i]);
+ suffixCount.set(nums[i], count - 1);
+ if (count === 1) {
+ suffixCount.delete(nums[i]);
+ suffixDistinct--;
+ }
+ result[i] = prefixSet.size - suffixDistinct;
+ }
+
+ return result;
+};
From 3c26f7583a9768b56d809955ffe59cc4818999a2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 00:11:43 -0500
Subject: [PATCH 260/994] Add solution #2672
---
README.md | 1 +
...f-adjacent-elements-with-the-same-color.js | 44 +++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/2672-number-of-adjacent-elements-with-the-same-color.js
diff --git a/README.md b/README.md
index ab290a08..3a61dbc8 100644
--- a/README.md
+++ b/README.md
@@ -1979,6 +1979,7 @@
2666|[Allow One Function Call](./solutions/2666-allow-one-function-call.js)|Easy|
2667|[Create Hello World Function](./solutions/2667-create-hello-world-function.js)|Easy|
2670|[Find the Distinct Difference Array](./solutions/2670-find-the-distinct-difference-array.js)|Easy|
+2672|[Number of Adjacent Elements With the Same Color](./solutions/2672-number-of-adjacent-elements-with-the-same-color.js)|Medium|
2677|[Chunk Array](./solutions/2677-chunk-array.js)|Easy|
2683|[Neighboring Bitwise XOR](./solutions/2683-neighboring-bitwise-xor.js)|Medium|
2685|[Count the Number of Complete Components](./solutions/2685-count-the-number-of-complete-components.js)|Medium|
diff --git a/solutions/2672-number-of-adjacent-elements-with-the-same-color.js b/solutions/2672-number-of-adjacent-elements-with-the-same-color.js
new file mode 100644
index 00000000..257d4270
--- /dev/null
+++ b/solutions/2672-number-of-adjacent-elements-with-the-same-color.js
@@ -0,0 +1,44 @@
+/**
+ * 2672. Number of Adjacent Elements With the Same Color
+ * https://leetcode.com/problems/number-of-adjacent-elements-with-the-same-color/
+ * Difficulty: Medium
+ *
+ * You are given an integer n representing an array colors of length n where all elements
+ * are set to 0's meaning uncolored. You are also given a 2D integer array queries where
+ * queries[i] = [indexi, colori]. For the ith query:
+ * - Set colors[indexi] to colori.
+ * - Count the number of adjacent pairs in colors which have the same color (regardless of colori).
+ *
+ * Return an array answer of the same length as queries where answer[i] is the answer to the ith
+ * query.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} queries
+ * @return {number[]}
+ */
+var colorTheArray = function(n, queries) {
+ const colors = new Array(n).fill(0);
+ const result = new Array(queries.length).fill(0);
+ let sameColorPairs = 0;
+
+ for (let i = 0; i < queries.length; i++) {
+ const [index, color] = queries[i];
+ const prevColor = colors[index];
+
+ if (prevColor !== 0) {
+ if (index > 0 && colors[index - 1] === prevColor) sameColorPairs--;
+ if (index < n - 1 && colors[index + 1] === prevColor) sameColorPairs--;
+ }
+
+ colors[index] = color;
+
+ if (index > 0 && colors[index - 1] === color) sameColorPairs++;
+ if (index < n - 1 && colors[index + 1] === color) sameColorPairs++;
+
+ result[i] = sameColorPairs;
+ }
+
+ return result;
+};
From 6f116095f42e90385bfe3521d5f57b878c0cfc2b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 23:14:54 -0500
Subject: [PATCH 261/994] Add solution #2673
---
README.md | 1 +
...e-costs-of-paths-equal-in-a-binary-tree.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/2673-make-costs-of-paths-equal-in-a-binary-tree.js
diff --git a/README.md b/README.md
index 3a61dbc8..87ddec71 100644
--- a/README.md
+++ b/README.md
@@ -1980,6 +1980,7 @@
2667|[Create Hello World Function](./solutions/2667-create-hello-world-function.js)|Easy|
2670|[Find the Distinct Difference Array](./solutions/2670-find-the-distinct-difference-array.js)|Easy|
2672|[Number of Adjacent Elements With the Same Color](./solutions/2672-number-of-adjacent-elements-with-the-same-color.js)|Medium|
+2673|[Make Costs of Paths Equal in a Binary Tree](./solutions/2673-make-costs-of-paths-equal-in-a-binary-tree.js)|Medium|
2677|[Chunk Array](./solutions/2677-chunk-array.js)|Easy|
2683|[Neighboring Bitwise XOR](./solutions/2683-neighboring-bitwise-xor.js)|Medium|
2685|[Count the Number of Complete Components](./solutions/2685-count-the-number-of-complete-components.js)|Medium|
diff --git a/solutions/2673-make-costs-of-paths-equal-in-a-binary-tree.js b/solutions/2673-make-costs-of-paths-equal-in-a-binary-tree.js
new file mode 100644
index 00000000..7d60cdb5
--- /dev/null
+++ b/solutions/2673-make-costs-of-paths-equal-in-a-binary-tree.js
@@ -0,0 +1,41 @@
+/**
+ * 2673. Make Costs of Paths Equal in a Binary Tree
+ * https://leetcode.com/problems/make-costs-of-paths-equal-in-a-binary-tree/
+ * Difficulty: Medium
+ *
+ * You are given an integer n representing the number of nodes in a perfect binary tree consisting
+ * of nodes numbered from 1 to n. The root of the tree is node 1 and each node i in the tree has
+ * two children where the left child is the node 2 * i and the right child is 2 * i + 1.
+ *
+ * Each node in the tree also has a cost represented by a given 0-indexed integer array cost of
+ * size n where cost[i] is the cost of node i + 1. You are allowed to increment the cost of any
+ * node by 1 any number of times.
+ *
+ * Return the minimum number of increments you need to make the cost of paths from the root to
+ * each leaf node equal.
+ *
+ * Note:
+ * - A perfect binary tree is a tree where each node, except the leaf nodes, has exactly 2 children.
+ * - The cost of a path is the sum of costs of nodes in the path.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[]} cost
+ * @return {number}
+ */
+var minIncrements = function(n, cost) {
+ let result = 0;
+
+ for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
+ const left = 2 * i + 1;
+ const right = 2 * i + 2;
+ if (left < n && right < n) {
+ const maxChildCost = Math.max(cost[left], cost[right]);
+ result += maxChildCost - cost[left] + maxChildCost - cost[right];
+ cost[i] += maxChildCost;
+ }
+ }
+
+ return result;
+};
From d56f197363cfffa664e112b021ef2a9a9084335d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 23:16:16 -0500
Subject: [PATCH 262/994] Add solution #2678
---
README.md | 1 +
solutions/2678-number-of-senior-citizens.js | 30 +++++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 solutions/2678-number-of-senior-citizens.js
diff --git a/README.md b/README.md
index 87ddec71..cde7900c 100644
--- a/README.md
+++ b/README.md
@@ -1982,6 +1982,7 @@
2672|[Number of Adjacent Elements With the Same Color](./solutions/2672-number-of-adjacent-elements-with-the-same-color.js)|Medium|
2673|[Make Costs of Paths Equal in a Binary Tree](./solutions/2673-make-costs-of-paths-equal-in-a-binary-tree.js)|Medium|
2677|[Chunk Array](./solutions/2677-chunk-array.js)|Easy|
+2678|[Number of Senior Citizens](./solutions/2678-number-of-senior-citizens.js)|Easy|
2683|[Neighboring Bitwise XOR](./solutions/2683-neighboring-bitwise-xor.js)|Medium|
2685|[Count the Number of Complete Components](./solutions/2685-count-the-number-of-complete-components.js)|Medium|
2693|[Call Function with Custom Context](./solutions/2693-call-function-with-custom-context.js)|Medium|
diff --git a/solutions/2678-number-of-senior-citizens.js b/solutions/2678-number-of-senior-citizens.js
new file mode 100644
index 00000000..7c599c9f
--- /dev/null
+++ b/solutions/2678-number-of-senior-citizens.js
@@ -0,0 +1,30 @@
+/**
+ * 2678. Number of Senior Citizens
+ * https://leetcode.com/problems/number-of-senior-citizens/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed array of strings details. Each element of details provides
+ * information about a given passenger compressed into a string of length 15. The system
+ * is such that:
+ * - The first ten characters consist of the phone number of passengers.
+ * - The next character denotes the gender of the person.
+ * - The following two characters are used to indicate the age of the person.
+ * - The last two characters determine the seat allotted to that person.
+ *
+ * Return the number of passengers who are strictly more than 60 years old.
+ */
+
+/**
+ * @param {string[]} details
+ * @return {number}
+ */
+var countSeniors = function(details) {
+ let result = 0;
+
+ for (const detail of details) {
+ const age = parseInt(detail.slice(11, 13));
+ if (age > 60) result++;
+ }
+
+ return result;
+};
From 441c3d01f21d58f9cecfb0c07463c7aa74da0271 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 23:18:10 -0500
Subject: [PATCH 263/994] Add solution #2680
---
README.md | 1 +
solutions/2680-maximum-or.js | 41 ++++++++++++++++++++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/2680-maximum-or.js
diff --git a/README.md b/README.md
index cde7900c..29aaa672 100644
--- a/README.md
+++ b/README.md
@@ -1983,6 +1983,7 @@
2673|[Make Costs of Paths Equal in a Binary Tree](./solutions/2673-make-costs-of-paths-equal-in-a-binary-tree.js)|Medium|
2677|[Chunk Array](./solutions/2677-chunk-array.js)|Easy|
2678|[Number of Senior Citizens](./solutions/2678-number-of-senior-citizens.js)|Easy|
+2680|[Maximum OR](./solutions/2680-maximum-or.js)|Medium|
2683|[Neighboring Bitwise XOR](./solutions/2683-neighboring-bitwise-xor.js)|Medium|
2685|[Count the Number of Complete Components](./solutions/2685-count-the-number-of-complete-components.js)|Medium|
2693|[Call Function with Custom Context](./solutions/2693-call-function-with-custom-context.js)|Medium|
diff --git a/solutions/2680-maximum-or.js b/solutions/2680-maximum-or.js
new file mode 100644
index 00000000..fb53a9c9
--- /dev/null
+++ b/solutions/2680-maximum-or.js
@@ -0,0 +1,41 @@
+/**
+ * 2680. Maximum OR
+ * https://leetcode.com/problems/maximum-or/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums of length n and an integer k. In an operation,
+ * you can choose an element and multiply it by 2.
+ *
+ * Return the maximum possible value of nums[0] | nums[1] | ... | nums[n - 1] that can be obtained
+ * after applying the operation on nums at most k times.
+ *
+ * Note that a | b denotes the bitwise or between two integers a and b.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var maximumOr = function(nums, k) {
+ const n = nums.length;
+ const prefixOr = new Array(n + 1).fill(0n);
+ const suffixOr = new Array(n + 1).fill(0n);
+
+ for (let i = 0; i < n; i++) {
+ prefixOr[i + 1] = prefixOr[i] | BigInt(nums[i]);
+ }
+
+ for (let i = n - 1; i >= 0; i--) {
+ suffixOr[i] = suffixOr[i + 1] | BigInt(nums[i]);
+ }
+
+ let maxOr = 0n;
+ for (let i = 0; i < n; i++) {
+ maxOr = maxOr > (prefixOr[i] | (BigInt(nums[i]) << BigInt(k)) | suffixOr[i + 1])
+ ? maxOr
+ : (prefixOr[i] | (BigInt(nums[i]) << BigInt(k)) | suffixOr[i + 1]);
+ }
+
+ return Number(maxOr);
+};
From b1b981694ac722e4f8ba67a70b63d3ecbc1cb33a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 23:20:29 -0500
Subject: [PATCH 264/994] Add solution #2682
---
README.md | 1 +
...82-find-the-losers-of-the-circular-game.js | 56 +++++++++++++++++++
2 files changed, 57 insertions(+)
create mode 100644 solutions/2682-find-the-losers-of-the-circular-game.js
diff --git a/README.md b/README.md
index 29aaa672..06a8dc9e 100644
--- a/README.md
+++ b/README.md
@@ -1984,6 +1984,7 @@
2677|[Chunk Array](./solutions/2677-chunk-array.js)|Easy|
2678|[Number of Senior Citizens](./solutions/2678-number-of-senior-citizens.js)|Easy|
2680|[Maximum OR](./solutions/2680-maximum-or.js)|Medium|
+2682|[Find the Losers of the Circular Game](./solutions/2682-find-the-losers-of-the-circular-game.js)|Easy|
2683|[Neighboring Bitwise XOR](./solutions/2683-neighboring-bitwise-xor.js)|Medium|
2685|[Count the Number of Complete Components](./solutions/2685-count-the-number-of-complete-components.js)|Medium|
2693|[Call Function with Custom Context](./solutions/2693-call-function-with-custom-context.js)|Medium|
diff --git a/solutions/2682-find-the-losers-of-the-circular-game.js b/solutions/2682-find-the-losers-of-the-circular-game.js
new file mode 100644
index 00000000..8536fa0b
--- /dev/null
+++ b/solutions/2682-find-the-losers-of-the-circular-game.js
@@ -0,0 +1,56 @@
+/**
+ * 2682. Find the Losers of the Circular Game
+ * https://leetcode.com/problems/find-the-losers-of-the-circular-game/
+ * Difficulty: Easy
+ *
+ * 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:
+ *
+ * 1st friend receives the ball.
+ * - After that, 1st friend passes it to the friend who is k steps away from them in the clockwise
+ * direction.
+ * - After that, the friend who receives the ball should pass it to the friend who is 2 * k steps
+ * away from them in the clockwise direction.
+ * - After that, the friend who receives the ball should pass it to the friend who is 3 * k steps
+ * away from them in the clockwise direction, and so on and so forth.
+ *
+ * In other words, on the ith turn, the friend holding the ball should pass it to the friend who
+ * is i * k steps away from them in the clockwise direction.
+ *
+ * The game is finished when some friend receives the ball for the second time.
+ *
+ * The losers of the game are friends who did not receive the ball in the entire game.
+ *
+ * Given the number of friends, n, and an integer k, return the array answer, which contains the
+ * losers of the game in the ascending order.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} k
+ * @return {number[]}
+ */
+var circularGameLosers = function(n, k) {
+ const visited = new Set();
+ let current = 0;
+ let step = 1;
+
+ while (!visited.has(current)) {
+ visited.add(current);
+ current = (current + step * k) % n;
+ step++;
+ }
+
+ const result = [];
+ for (let i = 0; i < n; i++) {
+ if (!visited.has(i)) {
+ result.push(i + 1);
+ }
+ }
+
+ return result;
+};
From aa7a6f24d0ef09b9dce2d0bbb380ef6480bf56d6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 23:28:22 -0500
Subject: [PATCH 265/994] Add solution #3373
---
README.md | 1 +
...-target-nodes-after-connecting-trees-ii.js | 79 +++++++++++++++++++
2 files changed, 80 insertions(+)
create mode 100644 solutions/3373-maximize-the-number-of-target-nodes-after-connecting-trees-ii.js
diff --git a/README.md b/README.md
index 06a8dc9e..49dbbb1f 100644
--- a/README.md
+++ b/README.md
@@ -2044,6 +2044,7 @@
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|
3372|[Maximize the Number of Target Nodes After Connecting Trees I](./solutions/3372-maximize-the-number-of-target-nodes-after-connecting-trees-i.js)|Medium|
+3373|[Maximize the Number of Target Nodes After Connecting Trees II](./solutions/3373-maximize-the-number-of-target-nodes-after-connecting-trees-ii.js)|Hard|
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/3373-maximize-the-number-of-target-nodes-after-connecting-trees-ii.js b/solutions/3373-maximize-the-number-of-target-nodes-after-connecting-trees-ii.js
new file mode 100644
index 00000000..8ac956f1
--- /dev/null
+++ b/solutions/3373-maximize-the-number-of-target-nodes-after-connecting-trees-ii.js
@@ -0,0 +1,79 @@
+/**
+ * 3373. Maximize the Number of Target Nodes After Connecting Trees II
+ * https://leetcode.com/problems/maximize-the-number-of-target-nodes-after-connecting-trees-ii/
+ * Difficulty: Hard
+ *
+ * There exist two undirected trees with n and m nodes, labeled from [0, n - 1] and [0, m - 1],
+ * respectively.
+ *
+ * You are given two 2D integer arrays edges1 and edges2 of lengths n - 1 and m - 1, respectively,
+ * where edges1[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the first
+ * tree and edges2[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the
+ * second tree.
+ *
+ * Node u is target to node v if the number of edges on the path from u to v is even. Note that
+ * a node is always target to itself.
+ *
+ * Return an array of n integers answer, where answer[i] is the maximum possible number of nodes
+ * that are target to node i of the first tree if you had to connect one node from the first tree
+ * to another node in the second tree.
+ *
+ * Note that queries are independent from each other. That is, for every query you will remove the
+ * added edge before proceeding to the next query.
+ */
+
+/**
+ * @param {number[][]} edges1
+ * @param {number[][]} edges2
+ * @return {number[]}
+ */
+var maxTargetNodes = function(edges1, edges2) {
+ const graph1 = buildGraph(edges1);
+ const graph2 = buildGraph(edges2);
+ const n = graph1.length;
+ const { color: color1 } = getBipartiteGroups(graph1);
+ const { maxGroup: maxGroup2 } = getBipartiteGroups(graph2);
+ const group0Count = color1.filter(c => c === 0).length;
+ const group1Count = n - group0Count;
+ const result = new Array(n);
+
+ for (let i = 0; i < n; i++) {
+ result[i] = (color1[i] === 0 ? group0Count : group1Count) + maxGroup2;
+ }
+
+ return result;
+
+ function buildGraph(edges) {
+ const n = edges.length + 1;
+ const graph = Array.from({ length: n }, () => []);
+ for (const [u, v] of edges) {
+ graph[u].push(v);
+ graph[v].push(u);
+ }
+ return graph;
+ }
+
+ function getBipartiteGroups(graph) {
+ const n = graph.length;
+ const color = new Array(n).fill(-1);
+ const groups = [0, 0];
+
+ for (let i = 0; i < n; i++) {
+ if (color[i] === -1) {
+ dfs(i, 0);
+ }
+ }
+
+ return { color, maxGroup: Math.max(groups[0], groups[1]) };
+
+ function dfs(node, c) {
+ color[node] = c;
+ groups[c]++;
+ for (const neighbor of graph[node]) {
+ if (color[neighbor] === -1) {
+ dfs(neighbor, 1 - c);
+ }
+ }
+ }
+ }
+};
From ae23c0b4743b56fbe0d4f560e35f0b592a86faee Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 23:36:34 -0500
Subject: [PATCH 266/994] Add solution #2684
---
README.md | 1 +
.../2684-maximum-number-of-moves-in-a-grid.js | 53 +++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/2684-maximum-number-of-moves-in-a-grid.js
diff --git a/README.md b/README.md
index 49dbbb1f..c80e62f4 100644
--- a/README.md
+++ b/README.md
@@ -1986,6 +1986,7 @@
2680|[Maximum OR](./solutions/2680-maximum-or.js)|Medium|
2682|[Find the Losers of the Circular Game](./solutions/2682-find-the-losers-of-the-circular-game.js)|Easy|
2683|[Neighboring Bitwise XOR](./solutions/2683-neighboring-bitwise-xor.js)|Medium|
+2684|[Maximum Number of Moves in a Grid](./solutions/2684-maximum-number-of-moves-in-a-grid.js)|Medium|
2685|[Count the Number of Complete Components](./solutions/2685-count-the-number-of-complete-components.js)|Medium|
2693|[Call Function with Custom Context](./solutions/2693-call-function-with-custom-context.js)|Medium|
2694|[Event Emitter](./solutions/2694-event-emitter.js)|Medium|
diff --git a/solutions/2684-maximum-number-of-moves-in-a-grid.js b/solutions/2684-maximum-number-of-moves-in-a-grid.js
new file mode 100644
index 00000000..65b4464f
--- /dev/null
+++ b/solutions/2684-maximum-number-of-moves-in-a-grid.js
@@ -0,0 +1,53 @@
+/**
+ * 2684. Maximum Number of Moves in a Grid
+ * https://leetcode.com/problems/maximum-number-of-moves-in-a-grid/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed m x n matrix grid consisting of positive integers.
+ *
+ * You can start at any cell in the first column of the matrix, and traverse the grid in the
+ * following way:
+ * - From a cell (row, col), you can move to any of the cells: (row - 1, col + 1), (row, col + 1)
+ * and (row + 1, col + 1) such that the value of the cell you move to, should be strictly bigger
+ * than the value of the current cell.
+ *
+ * Return the maximum number of moves that you can perform.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var maxMoves = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const memo = Array.from({ length: rows }, () => new Array(cols).fill(-1));
+
+ let result = 0;
+ for (let row = 0; row < rows; row++) {
+ result = Math.max(result, explore(row, 0));
+ }
+
+ return result;
+
+ function explore(row, col) {
+ if (col === cols - 1) return 0;
+ if (memo[row][col] !== -1) return memo[row][col];
+
+ let maxSteps = 0;
+ const current = grid[row][col];
+
+ if (row > 0 && col + 1 < cols && grid[row - 1][col + 1] > current) {
+ maxSteps = Math.max(maxSteps, 1 + explore(row - 1, col + 1));
+ }
+ if (col + 1 < cols && grid[row][col + 1] > current) {
+ maxSteps = Math.max(maxSteps, 1 + explore(row, col + 1));
+ }
+ if (row + 1 < rows && col + 1 < cols && grid[row + 1][col + 1] > current) {
+ maxSteps = Math.max(maxSteps, 1 + explore(row + 1, col + 1));
+ }
+
+ memo[row][col] = maxSteps;
+ return maxSteps;
+ }
+};
From 78a451fdbc886d2daf7d2eee42ee6035b75c18ca Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 23:37:53 -0500
Subject: [PATCH 267/994] Add solution #2696
---
README.md | 1 +
...string-length-after-removing-substrings.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/2696-minimum-string-length-after-removing-substrings.js
diff --git a/README.md b/README.md
index c80e62f4..87d969fa 100644
--- a/README.md
+++ b/README.md
@@ -1991,6 +1991,7 @@
2693|[Call Function with Custom Context](./solutions/2693-call-function-with-custom-context.js)|Medium|
2694|[Event Emitter](./solutions/2694-event-emitter.js)|Medium|
2695|[Array Wrapper](./solutions/2695-array-wrapper.js)|Easy|
+2696|[Minimum String Length After Removing Substrings](./solutions/2696-minimum-string-length-after-removing-substrings.js)|Easy|
2698|[Find the Punishment Number of an Integer](./solutions/2698-find-the-punishment-number-of-an-integer.js)|Medium|
2703|[Return Length of Arguments Passed](./solutions/2703-return-length-of-arguments-passed.js)|Easy|
2704|[To Be Or Not To Be](./solutions/2704-to-be-or-not-to-be.js)|Easy|
diff --git a/solutions/2696-minimum-string-length-after-removing-substrings.js b/solutions/2696-minimum-string-length-after-removing-substrings.js
new file mode 100644
index 00000000..de51fb8f
--- /dev/null
+++ b/solutions/2696-minimum-string-length-after-removing-substrings.js
@@ -0,0 +1,34 @@
+/**
+ * 2696. Minimum String Length After Removing Substrings
+ * https://leetcode.com/problems/minimum-string-length-after-removing-substrings/
+ * Difficulty: Easy
+ *
+ * You are given a string s consisting only of uppercase English letters.
+ *
+ * You can apply some operations to this string where, in one operation, you can remove any
+ * occurrence of one of the substrings "AB" or "CD" from s.
+ *
+ * Return the minimum possible length of the resulting string that you can obtain.
+ *
+ * Note that the string concatenates after removing the substring and could produce new "AB"
+ * or "CD" substrings.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var minLength = function(s) {
+ const stack = [];
+
+ for (const char of s) {
+ if (stack.length && ((stack[stack.length - 1] === 'A' && char === 'B')
+ || (stack[stack.length - 1] === 'C' && char === 'D'))) {
+ stack.pop();
+ } else {
+ stack.push(char);
+ }
+ }
+
+ return stack.length;
+};
From 8aa2e9df4a4e218253695a3e7f7c9e3ce5c5dd5c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 23:39:16 -0500
Subject: [PATCH 268/994] Add solution #2697
---
README.md | 1 +
...7-lexicographically-smallest-palindrome.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/2697-lexicographically-smallest-palindrome.js
diff --git a/README.md b/README.md
index 87d969fa..0b0a089c 100644
--- a/README.md
+++ b/README.md
@@ -1992,6 +1992,7 @@
2694|[Event Emitter](./solutions/2694-event-emitter.js)|Medium|
2695|[Array Wrapper](./solutions/2695-array-wrapper.js)|Easy|
2696|[Minimum String Length After Removing Substrings](./solutions/2696-minimum-string-length-after-removing-substrings.js)|Easy|
+2697|[Lexicographically Smallest Palindrome](./solutions/2697-lexicographically-smallest-palindrome.js)|Easy|
2698|[Find the Punishment Number of an Integer](./solutions/2698-find-the-punishment-number-of-an-integer.js)|Medium|
2703|[Return Length of Arguments Passed](./solutions/2703-return-length-of-arguments-passed.js)|Easy|
2704|[To Be Or Not To Be](./solutions/2704-to-be-or-not-to-be.js)|Easy|
diff --git a/solutions/2697-lexicographically-smallest-palindrome.js b/solutions/2697-lexicographically-smallest-palindrome.js
new file mode 100644
index 00000000..2489eb32
--- /dev/null
+++ b/solutions/2697-lexicographically-smallest-palindrome.js
@@ -0,0 +1,39 @@
+/**
+ * 2697. Lexicographically Smallest Palindrome
+ * https://leetcode.com/problems/lexicographically-smallest-palindrome/
+ * Difficulty: Easy
+ *
+ * You are given a string s consisting of lowercase English letters, and you are allowed to
+ * perform operations on it. In one operation, you can replace a character in s with another
+ * lowercase English letter.
+ *
+ * Your task is to make s a palindrome with the minimum number of operations possible. If there
+ * are multiple palindromes that can be made using the minimum number of operations, make the
+ * lexicographically smallest one.
+ *
+ * A string a is lexicographically smaller than a string b (of the same length) 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.
+ *
+ * Return the resulting palindrome string.
+ */
+
+/**
+ * @param {string} s
+ * @return {string}
+ */
+var makeSmallestPalindrome = function(s) {
+ const chars = s.split('');
+ let left = 0;
+ let right = s.length - 1;
+
+ while (left < right) {
+ if (chars[left] !== chars[right]) {
+ chars[left] = chars[right] = chars[left] < chars[right] ? chars[left] : chars[right];
+ }
+ left++;
+ right--;
+ }
+
+ return chars.join('');
+};
From f97b1a2b0742dc3aa1a5df57bf7cb6c638e9d158 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 23:40:19 -0500
Subject: [PATCH 269/994] Add solution #2706
---
README.md | 1 +
solutions/2706-buy-two-chocolates.js | 28 ++++++++++++++++++++++++++++
2 files changed, 29 insertions(+)
create mode 100644 solutions/2706-buy-two-chocolates.js
diff --git a/README.md b/README.md
index 0b0a089c..06dd2c6d 100644
--- a/README.md
+++ b/README.md
@@ -1997,6 +1997,7 @@
2703|[Return Length of Arguments Passed](./solutions/2703-return-length-of-arguments-passed.js)|Easy|
2704|[To Be Or Not To Be](./solutions/2704-to-be-or-not-to-be.js)|Easy|
2705|[Compact Object](./solutions/2705-compact-object.js)|Medium|
+2706|[Buy Two Chocolates](./solutions/2706-buy-two-chocolates.js)|Easy|
2715|[Timeout Cancellation](./solutions/2715-timeout-cancellation.js)|Easy|
2721|[Execute Asynchronous Functions in Parallel](./solutions/2721-execute-asynchronous-functions-in-parallel.js)|Medium|
2722|[Join Two Arrays by ID](./solutions/2722-join-two-arrays-by-id.js)|Medium|
diff --git a/solutions/2706-buy-two-chocolates.js b/solutions/2706-buy-two-chocolates.js
new file mode 100644
index 00000000..8c77f0e5
--- /dev/null
+++ b/solutions/2706-buy-two-chocolates.js
@@ -0,0 +1,28 @@
+/**
+ * 2706. Buy Two Chocolates
+ * https://leetcode.com/problems/buy-two-chocolates/
+ * Difficulty: Easy
+ *
+ * You are given an integer array prices representing the prices of various chocolates in
+ * a store. You are also given a single integer money, which represents your initial amount
+ * of money.
+ *
+ * You must buy exactly two chocolates in such a way that you still have some non-negative
+ * leftover money. You would like to minimize the sum of the prices of the two chocolates
+ * you buy.
+ *
+ * Return the amount of money you will have leftover after buying the two chocolates. If
+ * there is no way for you to buy two chocolates without ending up in debt, return money.
+ * Note that the leftover must be non-negative.
+ */
+
+/**
+ * @param {number[]} prices
+ * @param {number} money
+ * @return {number}
+ */
+var buyChoco = function(prices, money) {
+ prices.sort((a, b) => a - b);
+ const minCost = prices[0] + prices[1];
+ return minCost <= money ? money - minCost : money;
+};
From 42516260a14bf3e81637e6626bc7a8a2324fa931 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 28 May 2025 23:41:18 -0500
Subject: [PATCH 270/994] Add solution #2707
---
README.md | 1 +
.../2707-extra-characters-in-a-string.js | 35 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/2707-extra-characters-in-a-string.js
diff --git a/README.md b/README.md
index 06dd2c6d..d7421e39 100644
--- a/README.md
+++ b/README.md
@@ -1998,6 +1998,7 @@
2704|[To Be Or Not To Be](./solutions/2704-to-be-or-not-to-be.js)|Easy|
2705|[Compact Object](./solutions/2705-compact-object.js)|Medium|
2706|[Buy Two Chocolates](./solutions/2706-buy-two-chocolates.js)|Easy|
+2707|[Extra Characters in a String](./solutions/2707-extra-characters-in-a-string.js)|Medium|
2715|[Timeout Cancellation](./solutions/2715-timeout-cancellation.js)|Easy|
2721|[Execute Asynchronous Functions in Parallel](./solutions/2721-execute-asynchronous-functions-in-parallel.js)|Medium|
2722|[Join Two Arrays by ID](./solutions/2722-join-two-arrays-by-id.js)|Medium|
diff --git a/solutions/2707-extra-characters-in-a-string.js b/solutions/2707-extra-characters-in-a-string.js
new file mode 100644
index 00000000..2d335169
--- /dev/null
+++ b/solutions/2707-extra-characters-in-a-string.js
@@ -0,0 +1,35 @@
+/**
+ * 2707. Extra Characters in a String
+ * https://leetcode.com/problems/extra-characters-in-a-string/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed string s and a dictionary of words dictionary. You have to break
+ * s into one or more non-overlapping substrings such that each substring is present in
+ * dictionary. There may be some extra characters in s which are not present in any of the
+ * substrings.
+ *
+ * Return the minimum number of extra characters left over if you break up s optimally.
+ */
+
+/**
+ * @param {string} s
+ * @param {string[]} dictionary
+ * @return {number}
+ */
+var minExtraChar = function(s, dictionary) {
+ const n = s.length;
+ const dp = new Array(n + 1).fill(Infinity);
+ dp[0] = 0;
+ const dictSet = new Set(dictionary);
+
+ for (let i = 1; i <= n; i++) {
+ dp[i] = dp[i - 1] + 1;
+ for (let j = 0; j < i; j++) {
+ if (dictSet.has(s.slice(j, i))) {
+ dp[i] = Math.min(dp[i], dp[j]);
+ }
+ }
+ }
+
+ return dp[n];
+};
From 87486ae46efaf4c2d86e47811db28d78741c67fd Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 29 May 2025 23:59:12 -0500
Subject: [PATCH 271/994] Add solution #2710
---
README.md | 1 +
.../2710-remove-trailing-zeros-from-a-string.js | 16 ++++++++++++++++
2 files changed, 17 insertions(+)
create mode 100644 solutions/2710-remove-trailing-zeros-from-a-string.js
diff --git a/README.md b/README.md
index d7421e39..31807b6f 100644
--- a/README.md
+++ b/README.md
@@ -1999,6 +1999,7 @@
2705|[Compact Object](./solutions/2705-compact-object.js)|Medium|
2706|[Buy Two Chocolates](./solutions/2706-buy-two-chocolates.js)|Easy|
2707|[Extra Characters in a String](./solutions/2707-extra-characters-in-a-string.js)|Medium|
+2710|[Remove Trailing Zeros From a String](./solutions/2710-remove-trailing-zeros-from-a-string.js)|Easy|
2715|[Timeout Cancellation](./solutions/2715-timeout-cancellation.js)|Easy|
2721|[Execute Asynchronous Functions in Parallel](./solutions/2721-execute-asynchronous-functions-in-parallel.js)|Medium|
2722|[Join Two Arrays by ID](./solutions/2722-join-two-arrays-by-id.js)|Medium|
diff --git a/solutions/2710-remove-trailing-zeros-from-a-string.js b/solutions/2710-remove-trailing-zeros-from-a-string.js
new file mode 100644
index 00000000..217d4552
--- /dev/null
+++ b/solutions/2710-remove-trailing-zeros-from-a-string.js
@@ -0,0 +1,16 @@
+/**
+ * 2710. Remove Trailing Zeros From a String
+ * https://leetcode.com/problems/remove-trailing-zeros-from-a-string/
+ * Difficulty: Easy
+ *
+ * Given a positive integer num represented as a string, return the integer num without
+ * trailing zeros as a string.
+ */
+
+/**
+ * @param {string} num
+ * @return {string}
+ */
+var removeTrailingZeros = function(num) {
+ return num.replace(/0+$/g, '');
+};
From 2826499845caad36b7018e0adc3dd78ce8f5c7b1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 30 May 2025 00:00:25 -0500
Subject: [PATCH 272/994] Add solution #2716
---
README.md | 1 +
solutions/2716-minimize-string-length.js | 23 +++++++++++++++++++++++
2 files changed, 24 insertions(+)
create mode 100644 solutions/2716-minimize-string-length.js
diff --git a/README.md b/README.md
index 31807b6f..b63ed6c6 100644
--- a/README.md
+++ b/README.md
@@ -2001,6 +2001,7 @@
2707|[Extra Characters in a String](./solutions/2707-extra-characters-in-a-string.js)|Medium|
2710|[Remove Trailing Zeros From a String](./solutions/2710-remove-trailing-zeros-from-a-string.js)|Easy|
2715|[Timeout Cancellation](./solutions/2715-timeout-cancellation.js)|Easy|
+2716|[Minimize String Length](./solutions/2716-minimize-string-length.js)|Easy|
2721|[Execute Asynchronous Functions in Parallel](./solutions/2721-execute-asynchronous-functions-in-parallel.js)|Medium|
2722|[Join Two Arrays by ID](./solutions/2722-join-two-arrays-by-id.js)|Medium|
2723|[Add Two Promises](./solutions/2723-add-two-promises.js)|Easy|
diff --git a/solutions/2716-minimize-string-length.js b/solutions/2716-minimize-string-length.js
new file mode 100644
index 00000000..b16b102b
--- /dev/null
+++ b/solutions/2716-minimize-string-length.js
@@ -0,0 +1,23 @@
+/**
+ * 2716. Minimize String Length
+ * https://leetcode.com/problems/minimize-string-length/
+ * Difficulty: Easy
+ *
+ * Given a string s, you have two types of operation:
+ * 1. Choose an index i in the string, and let c be the character in position i. Delete the
+ * closest occurrence of c to the left of i (if exists).
+ * 2. Choose an index i in the string, and let c be the character in position i. Delete the
+ * closest occurrence of c to the right of i (if exists).
+ *
+ * Your task is to minimize the length of s by performing the above operations zero or more times.
+ *
+ * Return an integer denoting the length of the minimized string.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var minimizedStringLength = function(s) {
+ return new Set(s).size;
+};
From 2f9c25c39ec1ecd3e2cd8f26357878b83441de55 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 09:39:30 -0500
Subject: [PATCH 273/994] Add solution #2711
---
README.md | 1 +
...-number-of-distinct-values-on-diagonals.js | 55 +++++++++++++++++++
2 files changed, 56 insertions(+)
create mode 100644 solutions/2711-difference-of-number-of-distinct-values-on-diagonals.js
diff --git a/README.md b/README.md
index b63ed6c6..3097933b 100644
--- a/README.md
+++ b/README.md
@@ -2000,6 +2000,7 @@
2706|[Buy Two Chocolates](./solutions/2706-buy-two-chocolates.js)|Easy|
2707|[Extra Characters in a String](./solutions/2707-extra-characters-in-a-string.js)|Medium|
2710|[Remove Trailing Zeros From a String](./solutions/2710-remove-trailing-zeros-from-a-string.js)|Easy|
+2711|[Difference of Number of Distinct Values on Diagonals](./solutions/2711-difference-of-number-of-distinct-values-on-diagonals.js)|Medium|
2715|[Timeout Cancellation](./solutions/2715-timeout-cancellation.js)|Easy|
2716|[Minimize String Length](./solutions/2716-minimize-string-length.js)|Easy|
2721|[Execute Asynchronous Functions in Parallel](./solutions/2721-execute-asynchronous-functions-in-parallel.js)|Medium|
diff --git a/solutions/2711-difference-of-number-of-distinct-values-on-diagonals.js b/solutions/2711-difference-of-number-of-distinct-values-on-diagonals.js
new file mode 100644
index 00000000..86d12ee8
--- /dev/null
+++ b/solutions/2711-difference-of-number-of-distinct-values-on-diagonals.js
@@ -0,0 +1,55 @@
+/**
+ * 2711. Difference of Number of Distinct Values on Diagonals
+ * https://leetcode.com/problems/difference-of-number-of-distinct-values-on-diagonals/
+ * Difficulty: Medium
+ *
+ * Given a 2D grid of size m x n, you should find the matrix answer of size m x n.
+ *
+ * The cell answer[r][c] is calculated by looking at the diagonal values of the cell grid[r][c]:
+ * - Let leftAbove[r][c] be the number of distinct values on the diagonal to the left and above
+ * the cell grid[r][c] not including the cell grid[r][c] itself.
+ * - Let rightBelow[r][c] be the number of distinct values on the diagonal to the right and below
+ * the cell grid[r][c], not including the cell grid[r][c] itself.
+ * - Then answer[r][c] = |leftAbove[r][c] - rightBelow[r][c]|.
+ *
+ * A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost
+ * row or leftmost column and going in the bottom-right direction until the end of the matrix
+ * is reached.
+ *
+ * - For example, in the below diagram the diagonal is highlighted using the cell with indices
+ * (2, 3) colored gray:
+ * - Red-colored cells are left and above the cell.
+ * - Blue-colored cells are right and below the cell.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number[][]}
+ */
+var differenceOfDistinctValues = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const result = Array.from({ length: rows }, () => new Array(cols).fill(0));
+
+ for (let r = 0; r < rows; r++) {
+ for (let c = 0; c < cols; c++) {
+ const leftAboveSet = new Set();
+ let i = r - 1;
+ let j = c - 1;
+ while (i >= 0 && j >= 0) {
+ leftAboveSet.add(grid[i--][j--]);
+ }
+
+ const rightBelowSet = new Set();
+ i = r + 1;
+ j = c + 1;
+ while (i < rows && j < cols) {
+ rightBelowSet.add(grid[i++][j++]);
+ }
+
+ result[r][c] = Math.abs(leftAboveSet.size - rightBelowSet.size);
+ }
+ }
+
+ return result;
+};
From 5885e51379e58c10f15ae5a6f951c809050b8462 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 09:40:53 -0500
Subject: [PATCH 274/994] Add solution #2712
---
README.md | 1 +
...nimum-cost-to-make-all-characters-equal.js | 32 +++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/2712-minimum-cost-to-make-all-characters-equal.js
diff --git a/README.md b/README.md
index 3097933b..b676005c 100644
--- a/README.md
+++ b/README.md
@@ -2001,6 +2001,7 @@
2707|[Extra Characters in a String](./solutions/2707-extra-characters-in-a-string.js)|Medium|
2710|[Remove Trailing Zeros From a String](./solutions/2710-remove-trailing-zeros-from-a-string.js)|Easy|
2711|[Difference of Number of Distinct Values on Diagonals](./solutions/2711-difference-of-number-of-distinct-values-on-diagonals.js)|Medium|
+2712|[Minimum Cost to Make All Characters Equal](./solutions/2712-minimum-cost-to-make-all-characters-equal.js)|Medium|
2715|[Timeout Cancellation](./solutions/2715-timeout-cancellation.js)|Easy|
2716|[Minimize String Length](./solutions/2716-minimize-string-length.js)|Easy|
2721|[Execute Asynchronous Functions in Parallel](./solutions/2721-execute-asynchronous-functions-in-parallel.js)|Medium|
diff --git a/solutions/2712-minimum-cost-to-make-all-characters-equal.js b/solutions/2712-minimum-cost-to-make-all-characters-equal.js
new file mode 100644
index 00000000..bc70fa86
--- /dev/null
+++ b/solutions/2712-minimum-cost-to-make-all-characters-equal.js
@@ -0,0 +1,32 @@
+/**
+ * 2712. Minimum Cost to Make All Characters Equal
+ * https://leetcode.com/problems/minimum-cost-to-make-all-characters-equal/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed binary string s of length n on which you can apply two types
+ * of operations:
+ * - Choose an index i and invert all characters from index 0 to index i (both inclusive),
+ * with a cost of i + 1
+ * - Choose an index i and invert all characters from index i to index n - 1 (both inclusive),
+ * with a cost of n - i
+ *
+ * Return the minimum cost to make all characters of the string equal.
+ *
+ * Invert a character means if its value is '0' it becomes '1' and vice-versa.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var minimumCost = function(s) {
+ let result = 0;
+
+ for (let i = 1; i < s.length; i++) {
+ if (s[i] !== s[i - 1]) {
+ result += Math.min(i, s.length - i);
+ }
+ }
+
+ return result;
+};
From 6fac895dc5362953ce472d321d28a91c2e72ae25 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 09:42:16 -0500
Subject: [PATCH 275/994] Add solution #2717
---
README.md | 1 +
solutions/2717-semi-ordered-permutation.js | 33 ++++++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/2717-semi-ordered-permutation.js
diff --git a/README.md b/README.md
index b676005c..af73a983 100644
--- a/README.md
+++ b/README.md
@@ -2004,6 +2004,7 @@
2712|[Minimum Cost to Make All Characters Equal](./solutions/2712-minimum-cost-to-make-all-characters-equal.js)|Medium|
2715|[Timeout Cancellation](./solutions/2715-timeout-cancellation.js)|Easy|
2716|[Minimize String Length](./solutions/2716-minimize-string-length.js)|Easy|
+2717|[Semi-Ordered Permutation](./solutions/2717-semi-ordered-permutation.js)|Easy|
2721|[Execute Asynchronous Functions in Parallel](./solutions/2721-execute-asynchronous-functions-in-parallel.js)|Medium|
2722|[Join Two Arrays by ID](./solutions/2722-join-two-arrays-by-id.js)|Medium|
2723|[Add Two Promises](./solutions/2723-add-two-promises.js)|Easy|
diff --git a/solutions/2717-semi-ordered-permutation.js b/solutions/2717-semi-ordered-permutation.js
new file mode 100644
index 00000000..b1717e3c
--- /dev/null
+++ b/solutions/2717-semi-ordered-permutation.js
@@ -0,0 +1,33 @@
+/**
+ * 2717. Semi-Ordered Permutation
+ * https://leetcode.com/problems/semi-ordered-permutation/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed permutation of n integers nums.
+ *
+ * A permutation is called semi-ordered if the first number equals 1 and the last number equals n.
+ * You can perform the below operation as many times as you want until you make nums a semi-ordered
+ * permutation:
+ * - Pick two adjacent elements in nums, then swap them.
+ *
+ * Return the minimum number of operations to make nums a semi-ordered permutation.
+ *
+ * A permutation is a sequence of integers from 1 to n of length n containing each number exactly
+ * once.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var semiOrderedPermutation = function(nums) {
+ let oneIndex = 0;
+ let nIndex = 0;
+
+ for (let i = 0; i < nums.length; i++) {
+ if (nums[i] === 1) oneIndex = i;
+ if (nums[i] === nums.length) nIndex = i;
+ }
+
+ return oneIndex + (nums.length - 1 - nIndex) - (oneIndex > nIndex ? 1 : 0);
+};
From b0516147fabea7dd2a2e945ea7d42b0b23df36fc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 21:43:31 -0500
Subject: [PATCH 276/994] Add solution #2929
---
README.md | 1 +
...29-distribute-candies-among-children-ii.js | 30 +++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 solutions/2929-distribute-candies-among-children-ii.js
diff --git a/README.md b/README.md
index af73a983..41544340 100644
--- a/README.md
+++ b/README.md
@@ -2023,6 +2023,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|
+2929|[Distribute Candies Among Children II](./solutions/2929-distribute-candies-among-children-ii.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|
diff --git a/solutions/2929-distribute-candies-among-children-ii.js b/solutions/2929-distribute-candies-among-children-ii.js
new file mode 100644
index 00000000..40e830ec
--- /dev/null
+++ b/solutions/2929-distribute-candies-among-children-ii.js
@@ -0,0 +1,30 @@
+/**
+ * 2929. Distribute Candies Among Children II
+ * https://leetcode.com/problems/distribute-candies-among-children-ii/
+ * Difficulty: Medium
+ *
+ * You are given two positive integers n and limit.
+ *
+ * Return the total number of ways to distribute n candies among 3 children such that no child
+ * gets more than limit candies.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} limit
+ * @return {number}
+ */
+var distributeCandies = function(n, limit) {
+ const minCandies = Math.max(0, n - 2 * limit);
+ const maxCandies = Math.min(n, limit);
+ let result = 0;
+
+ for (let i = minCandies; i <= maxCandies; i++) {
+ const remaining = n - i;
+ const minSecond = Math.max(0, remaining - limit);
+ const maxSecond = Math.min(remaining, limit);
+ result += maxSecond - minSecond + 1;
+ }
+
+ return result;
+};
From b7f01aae91f2f7939faac19db321f20826c0d163 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 21:48:20 -0500
Subject: [PATCH 277/994] Add solution #2709
---
README.md | 1 +
.../2709-greatest-common-divisor-traversal.js | 79 +++++++++++++++++++
2 files changed, 80 insertions(+)
create mode 100644 solutions/2709-greatest-common-divisor-traversal.js
diff --git a/README.md b/README.md
index 41544340..bf4c8bc6 100644
--- a/README.md
+++ b/README.md
@@ -1999,6 +1999,7 @@
2705|[Compact Object](./solutions/2705-compact-object.js)|Medium|
2706|[Buy Two Chocolates](./solutions/2706-buy-two-chocolates.js)|Easy|
2707|[Extra Characters in a String](./solutions/2707-extra-characters-in-a-string.js)|Medium|
+2709|[Greatest Common Divisor Traversal](./solutions/2709-greatest-common-divisor-traversal.js)|Hard|
2710|[Remove Trailing Zeros From a String](./solutions/2710-remove-trailing-zeros-from-a-string.js)|Easy|
2711|[Difference of Number of Distinct Values on Diagonals](./solutions/2711-difference-of-number-of-distinct-values-on-diagonals.js)|Medium|
2712|[Minimum Cost to Make All Characters Equal](./solutions/2712-minimum-cost-to-make-all-characters-equal.js)|Medium|
diff --git a/solutions/2709-greatest-common-divisor-traversal.js b/solutions/2709-greatest-common-divisor-traversal.js
new file mode 100644
index 00000000..0db68ad2
--- /dev/null
+++ b/solutions/2709-greatest-common-divisor-traversal.js
@@ -0,0 +1,79 @@
+/**
+ * 2709. Greatest Common Divisor Traversal
+ * https://leetcode.com/problems/greatest-common-divisor-traversal/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed integer array nums, and you are allowed to traverse between its
+ * indices. You can traverse between index i and index j, i != j, if and only if gcd(nums[i],
+ * nums[j]) > 1, where gcd is the greatest common divisor.
+ *
+ * Your task is to determine if for every pair of indices i and j in nums, where i < j, there
+ * exists a sequence of traversals that can take us from i to j.
+ *
+ * Return true if it is possible to traverse between all such pairs of indices, or false otherwise.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {boolean}
+ */
+var canTraverseAllPairs = function(nums) {
+ if (nums.length === 1) return true;
+ const n = nums.length;
+ const maxNum = Math.max(...nums);
+ const parent = new Array(maxNum + 1).fill().map((_, i) => i);
+ const rank = new Array(maxNum + 1).fill(0);
+
+ const primeToIndex = new Map();
+ for (let i = 0; i < n; i++) {
+ if (nums[i] === 1) return false;
+ const factors = getPrimeFactors(nums[i]);
+ for (const prime of factors) {
+ if (primeToIndex.has(prime)) {
+ union(primeToIndex.get(prime), i);
+ } else {
+ primeToIndex.set(prime, i);
+ }
+ }
+ }
+
+ const root = find(0);
+ for (let i = 1; i < n; i++) {
+ if (find(i) !== root) return false;
+ }
+
+ return true;
+
+ function find(x) {
+ if (parent[x] !== x) {
+ parent[x] = find(parent[x]);
+ }
+ return parent[x];
+ }
+
+ function union(x, y) {
+ const px = find(x);
+ const py = find(y);
+ if (px === py) return;
+ if (rank[px] < rank[py]) {
+ parent[px] = py;
+ } else if (rank[px] > rank[py]) {
+ parent[py] = px;
+ } else {
+ parent[py] = px;
+ rank[px]++;
+ }
+ }
+
+ function getPrimeFactors(num) {
+ const factors = [];
+ for (let i = 2; i * i <= num; i++) {
+ if (num % i === 0) {
+ factors.push(i);
+ while (num % i === 0) num /= i;
+ }
+ }
+ if (num > 1) factors.push(num);
+ return factors;
+ }
+};
From 385540f5b0c9b1b29d8e3abe7f2548b430914d90 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 21:49:51 -0500
Subject: [PATCH 278/994] Add solution #2729
---
README.md | 1 +
...2729-check-if-the-number-is-fascinating.js | 26 +++++++++++++++++++
2 files changed, 27 insertions(+)
create mode 100644 solutions/2729-check-if-the-number-is-fascinating.js
diff --git a/README.md b/README.md
index bf4c8bc6..9f34e57a 100644
--- a/README.md
+++ b/README.md
@@ -2013,6 +2013,7 @@
2725|[Interval Cancellation](./solutions/2725-interval-cancellation.js)|Easy|
2726|[Calculator with Method Chaining](./solutions/2726-calculator-with-method-chaining.js)|Easy|
2727|[Is Object Empty](./solutions/2727-is-object-empty.js)|Easy|
+2729|[Check if The Number is Fascinating](./solutions/2729-check-if-the-number-is-fascinating.js)|Easy|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2729-check-if-the-number-is-fascinating.js b/solutions/2729-check-if-the-number-is-fascinating.js
new file mode 100644
index 00000000..12537342
--- /dev/null
+++ b/solutions/2729-check-if-the-number-is-fascinating.js
@@ -0,0 +1,26 @@
+/**
+ * 2729. Check if The Number is Fascinating
+ * https://leetcode.com/problems/check-if-the-number-is-fascinating/
+ * Difficulty: Easy
+ *
+ * You are given an integer n that consists of exactly 3 digits.
+ *
+ * We call the number n fascinating if, after the following modification, the resulting number
+ * contains all the digits from 1 to 9 exactly once and does not contain any 0's:
+ * - Concatenate n with the numbers 2 * n and 3 * n.
+ *
+ * Return true if n is fascinating, or false otherwise.
+ *
+ * Concatenating two numbers means joining them together. For example, the concatenation of 121
+ * and 371 is 121371.
+ */
+
+/**
+ * @param {number} n
+ * @return {boolean}
+ */
+var isFascinating = function(n) {
+ const concatenated = `${n}${2 * n}${3 * n}`;
+ const digitSet = new Set(concatenated);
+ return concatenated.length === 9 && digitSet.size === 9 && !digitSet.has('0');
+};
From 7b39dcc4a0902c338d0feffbe443e314cdcc0f49 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 21:50:59 -0500
Subject: [PATCH 279/994] Add solution #2732
---
README.md | 1 +
.../2732-find-a-good-subset-of-the-matrix.js | 48 +++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/2732-find-a-good-subset-of-the-matrix.js
diff --git a/README.md b/README.md
index 9f34e57a..a92406b8 100644
--- a/README.md
+++ b/README.md
@@ -2014,6 +2014,7 @@
2726|[Calculator with Method Chaining](./solutions/2726-calculator-with-method-chaining.js)|Easy|
2727|[Is Object Empty](./solutions/2727-is-object-empty.js)|Easy|
2729|[Check if The Number is Fascinating](./solutions/2729-check-if-the-number-is-fascinating.js)|Easy|
+2732|[Find a Good Subset of the Matrix](./solutions/2732-find-a-good-subset-of-the-matrix.js)|Hard|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2732-find-a-good-subset-of-the-matrix.js b/solutions/2732-find-a-good-subset-of-the-matrix.js
new file mode 100644
index 00000000..1e13f830
--- /dev/null
+++ b/solutions/2732-find-a-good-subset-of-the-matrix.js
@@ -0,0 +1,48 @@
+/**
+ * 2732. Find a Good Subset of the Matrix
+ * https://leetcode.com/problems/find-a-good-subset-of-the-matrix/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed m x n binary matrix grid.
+ *
+ * Let us call a non-empty subset of rows good if the sum of each column of the subset is at
+ * most half of the length of the subset.
+ *
+ * More formally, if the length of the chosen subset of rows is k, then the sum of each column
+ * should be at most floor(k / 2).
+ *
+ * Return an integer array that contains row indices of a good subset sorted in ascending order.
+ *
+ * If there are multiple good subsets, you can return any of them. If there are no good subsets,
+ * return an empty array.
+ *
+ * A subset of rows of the matrix grid is any matrix that can be obtained by deleting some (possibly
+ * none or all) rows from grid.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number[]}
+ */
+var goodSubsetofBinaryMatrix = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const rowMasks = new Map();
+
+ for (let i = 0; i < rows; i++) {
+ let mask = 0;
+ for (let j = 0; j < cols; j++) {
+ mask |= grid[i][j] << j;
+ }
+ if (mask === 0) return [i];
+ rowMasks.set(mask, i);
+ }
+
+ for (const [mask1, i] of rowMasks) {
+ for (const [mask2, j] of rowMasks) {
+ if ((mask1 & mask2) === 0) return [Math.min(i, j), Math.max(i, j)];
+ }
+ }
+
+ return [];
+};
From b6866c0e9e26def7aeea4f42278cdcb1e2f576b2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 21:51:51 -0500
Subject: [PATCH 280/994] Add solution #2733
---
README.md | 1 +
solutions/2733-neither-minimum-nor-maximum.js | 27 +++++++++++++++++++
2 files changed, 28 insertions(+)
create mode 100644 solutions/2733-neither-minimum-nor-maximum.js
diff --git a/README.md b/README.md
index a92406b8..039fc61e 100644
--- a/README.md
+++ b/README.md
@@ -2015,6 +2015,7 @@
2727|[Is Object Empty](./solutions/2727-is-object-empty.js)|Easy|
2729|[Check if The Number is Fascinating](./solutions/2729-check-if-the-number-is-fascinating.js)|Easy|
2732|[Find a Good Subset of the Matrix](./solutions/2732-find-a-good-subset-of-the-matrix.js)|Hard|
+2733|[Neither Minimum nor Maximum](./solutions/2733-neither-minimum-nor-maximum.js)|Easy|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2733-neither-minimum-nor-maximum.js b/solutions/2733-neither-minimum-nor-maximum.js
new file mode 100644
index 00000000..4dcc9150
--- /dev/null
+++ b/solutions/2733-neither-minimum-nor-maximum.js
@@ -0,0 +1,27 @@
+/**
+ * 2733. Neither Minimum nor Maximum
+ * https://leetcode.com/problems/neither-minimum-nor-maximum/
+ * Difficulty: Easy
+ *
+ * Given an integer array nums containing distinct positive integers, find and return any
+ * number from the array that is neither the minimum nor the maximum value in the array,
+ * or -1 if there is no such number.
+ *
+ * Return the selected integer.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var findNonMinOrMax = function(nums) {
+ if (nums.length < 3) return -1;
+ const minVal = Math.min(nums[0], nums[1], nums[2]);
+ const maxVal = Math.max(nums[0], nums[1], nums[2]);
+
+ for (const num of [nums[0], nums[1], nums[2]]) {
+ if (num !== minVal && num !== maxVal) return num;
+ }
+
+ return -1;
+};
From f289eb44e43c7ef9d9adbdcfe2337f163fdb885d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 21:54:45 -0500
Subject: [PATCH 281/994] Add solution #2739
---
README.md | 1 +
solutions/2739-total-distance-traveled.js | 38 +++++++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2739-total-distance-traveled.js
diff --git a/README.md b/README.md
index 039fc61e..3dc20ef4 100644
--- a/README.md
+++ b/README.md
@@ -2016,6 +2016,7 @@
2729|[Check if The Number is Fascinating](./solutions/2729-check-if-the-number-is-fascinating.js)|Easy|
2732|[Find a Good Subset of the Matrix](./solutions/2732-find-a-good-subset-of-the-matrix.js)|Hard|
2733|[Neither Minimum nor Maximum](./solutions/2733-neither-minimum-nor-maximum.js)|Easy|
+2739|[Total Distance Traveled](./solutions/2739-total-distance-traveled.js)|Easy|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2739-total-distance-traveled.js b/solutions/2739-total-distance-traveled.js
new file mode 100644
index 00000000..2c2d593d
--- /dev/null
+++ b/solutions/2739-total-distance-traveled.js
@@ -0,0 +1,38 @@
+/**
+ * 2739. Total Distance Traveled
+ * https://leetcode.com/problems/total-distance-traveled/
+ * Difficulty: Easy
+ *
+ * A truck has two fuel tanks. You are given two integers, mainTank representing the fuel present
+ * in the main tank in liters and additionalTank representing the fuel present in the additional
+ * tank in liters.
+ *
+ * The truck has a mileage of 10 km per liter. Whenever 5 liters of fuel get used up in the main
+ * tank, if the additional tank has at least 1 liters of fuel, 1 liters of fuel will be transferred
+ * from the additional tank to the main tank.
+ *
+ * Return the maximum distance which can be traveled.
+ *
+ * Note: Injection from the additional tank is not continuous. It happens suddenly and immediately
+ * for every 5 liters consumed.
+ */
+
+/**
+ * @param {number} mainTank
+ * @param {number} additionalTank
+ * @return {number}
+ */
+var distanceTraveled = function(mainTank, additionalTank) {
+ let distance = 0;
+ let fuel = mainTank;
+
+ while (fuel >= 5 && additionalTank > 0) {
+ distance += 50;
+ fuel -= 5;
+ fuel += 1;
+ additionalTank -= 1;
+ }
+
+ distance += fuel * 10;
+ return distance;
+};
From 5d524686784a1b2ab3f83cbabfed18f95e9dba8d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 21:55:55 -0500
Subject: [PATCH 282/994] Add solution #2740
---
README.md | 1 +
.../2740-find-the-value-of-the-partition.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/2740-find-the-value-of-the-partition.js
diff --git a/README.md b/README.md
index 3dc20ef4..1f13529c 100644
--- a/README.md
+++ b/README.md
@@ -2017,6 +2017,7 @@
2732|[Find a Good Subset of the Matrix](./solutions/2732-find-a-good-subset-of-the-matrix.js)|Hard|
2733|[Neither Minimum nor Maximum](./solutions/2733-neither-minimum-nor-maximum.js)|Easy|
2739|[Total Distance Traveled](./solutions/2739-total-distance-traveled.js)|Easy|
+2740|[Find the Value of the Partition](./solutions/2740-find-the-value-of-the-partition.js)|Medium|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2740-find-the-value-of-the-partition.js b/solutions/2740-find-the-value-of-the-partition.js
new file mode 100644
index 00000000..8c1f661e
--- /dev/null
+++ b/solutions/2740-find-the-value-of-the-partition.js
@@ -0,0 +1,34 @@
+/**
+ * 2740. Find the Value of the Partition
+ * https://leetcode.com/problems/find-the-value-of-the-partition/
+ * Difficulty: Medium
+ *
+ * You are given a positive integer array nums.
+ *
+ * Partition nums into two arrays, nums1 and nums2, such that:
+ * - Each element of the array nums belongs to either the array nums1 or the array nums2.
+ * - Both arrays are non-empty.
+ * - The value of the partition is minimized.
+ *
+ * The value of the partition is |max(nums1) - min(nums2)|.
+ *
+ * Here, max(nums1) denotes the maximum element of the array nums1, and min(nums2) denotes the
+ * minimum element of the array nums2.
+ *
+ * Return the integer denoting the value of such partition.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var findValueOfPartition = function(nums) {
+ nums.sort((a, b) => a - b);
+ let result = Infinity;
+
+ for (let i = 1; i < nums.length; i++) {
+ result = Math.min(result, nums[i] - nums[i - 1]);
+ }
+
+ return result;
+};
From 68a19de593fe341fd1d9dd4f570dea8b0b6b7f81 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 21:56:58 -0500
Subject: [PATCH 283/994] Add solution #2742
---
README.md | 1 +
solutions/2742-painting-the-walls.js | 38 ++++++++++++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2742-painting-the-walls.js
diff --git a/README.md b/README.md
index 1f13529c..65a7b884 100644
--- a/README.md
+++ b/README.md
@@ -2018,6 +2018,7 @@
2733|[Neither Minimum nor Maximum](./solutions/2733-neither-minimum-nor-maximum.js)|Easy|
2739|[Total Distance Traveled](./solutions/2739-total-distance-traveled.js)|Easy|
2740|[Find the Value of the Partition](./solutions/2740-find-the-value-of-the-partition.js)|Medium|
+2742|[Painting the Walls](./solutions/2742-painting-the-walls.js)|Hard|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2742-painting-the-walls.js b/solutions/2742-painting-the-walls.js
new file mode 100644
index 00000000..42275242
--- /dev/null
+++ b/solutions/2742-painting-the-walls.js
@@ -0,0 +1,38 @@
+/**
+ * 2742. Painting the Walls
+ * https://leetcode.com/problems/painting-the-walls/
+ * Difficulty: Hard
+ *
+ * You are given two 0-indexed integer arrays, cost and time, of size n representing the costs
+ * and the time taken to paint n different walls respectively. There are two painters available:
+ * - A paid painter that paints the ith wall in time[i] units of time and takes cost[i] units of
+ * money.
+ * - A free painter that paints any wall in 1 unit of time at a cost of 0. But the free painter
+ * can only be used if the paid painter is already occupied.
+ *
+ * Return the minimum amount of money required to paint the n walls.
+ */
+
+/**
+ * @param {number[]} cost
+ * @param {number[]} time
+ * @return {number}
+ */
+var paintWalls = function(cost, time) {
+ const n = cost.length;
+ const dp = new Array(n + 1).fill().map(() => new Array(n + 1).fill(Infinity));
+ dp[0][0] = 0;
+
+ for (let i = 0; i < n; i++) {
+ for (let j = 0; j <= n; j++) {
+ if (dp[i][j] === Infinity) continue;
+
+ dp[i + 1][j] = Math.min(dp[i + 1][j], dp[i][j]);
+
+ const walls = Math.min(n, j + time[i] + 1);
+ dp[i + 1][walls] = Math.min(dp[i + 1][walls], dp[i][j] + cost[i]);
+ }
+ }
+
+ return dp[n][n];
+};
From 86db404d3566ce27bbdc6f645d857634713a74d7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 21:58:11 -0500
Subject: [PATCH 284/994] Add solution #2744
---
README.md | 1 +
...744-find-maximum-number-of-string-pairs.js | 36 +++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/2744-find-maximum-number-of-string-pairs.js
diff --git a/README.md b/README.md
index 65a7b884..740d35cc 100644
--- a/README.md
+++ b/README.md
@@ -2019,6 +2019,7 @@
2739|[Total Distance Traveled](./solutions/2739-total-distance-traveled.js)|Easy|
2740|[Find the Value of the Partition](./solutions/2740-find-the-value-of-the-partition.js)|Medium|
2742|[Painting the Walls](./solutions/2742-painting-the-walls.js)|Hard|
+2744|[Find Maximum Number of String Pairs](./solutions/2744-find-maximum-number-of-string-pairs.js)|Easy|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2744-find-maximum-number-of-string-pairs.js b/solutions/2744-find-maximum-number-of-string-pairs.js
new file mode 100644
index 00000000..b8e9a4ac
--- /dev/null
+++ b/solutions/2744-find-maximum-number-of-string-pairs.js
@@ -0,0 +1,36 @@
+/**
+ * 2744. Find Maximum Number of String Pairs
+ * https://leetcode.com/problems/find-maximum-number-of-string-pairs/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed array words consisting of distinct strings.
+ *
+ * The string words[i] can be paired with the string words[j] if:
+ * - The string words[i] is equal to the reversed string of words[j].
+ * - 0 <= i < j < words.length.
+ *
+ * Return the maximum number of pairs that can be formed from the array words.
+ *
+ * Note that each string can belong in at most one pair.
+ */
+
+/**
+ * @param {string[]} words
+ * @return {number}
+ */
+var maximumNumberOfStringPairs = function(words) {
+ const set = new Set();
+ let result = 0;
+
+ for (const word of words) {
+ const reversed = word[1] + word[0];
+ if (set.has(reversed)) {
+ result++;
+ set.delete(reversed);
+ } else {
+ set.add(word);
+ }
+ }
+
+ return result;
+};
From d0900be9c8aacef0a74b9da829c7d64edc3302d1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 21:59:07 -0500
Subject: [PATCH 285/994] Add solution #2745
---
README.md | 1 +
.../2745-construct-the-longest-new-string.js | 26 +++++++++++++++++++
2 files changed, 27 insertions(+)
create mode 100644 solutions/2745-construct-the-longest-new-string.js
diff --git a/README.md b/README.md
index 740d35cc..360b4e4f 100644
--- a/README.md
+++ b/README.md
@@ -2020,6 +2020,7 @@
2740|[Find the Value of the Partition](./solutions/2740-find-the-value-of-the-partition.js)|Medium|
2742|[Painting the Walls](./solutions/2742-painting-the-walls.js)|Hard|
2744|[Find Maximum Number of String Pairs](./solutions/2744-find-maximum-number-of-string-pairs.js)|Easy|
+2745|[Construct the Longest New String](./solutions/2745-construct-the-longest-new-string.js)|Medium|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2745-construct-the-longest-new-string.js b/solutions/2745-construct-the-longest-new-string.js
new file mode 100644
index 00000000..c5014fa7
--- /dev/null
+++ b/solutions/2745-construct-the-longest-new-string.js
@@ -0,0 +1,26 @@
+/**
+ * 2745. Construct the Longest New String
+ * https://leetcode.com/problems/construct-the-longest-new-string/
+ * Difficulty: Medium
+ *
+ * You are given three integers x, y, and z.
+ *
+ * You have x strings equal to "AA", y strings equal to "BB", and z strings equal to "AB". You
+ * want to choose some (possibly all or none) of these strings and concatenate them in some order
+ * to form a new string. This new string must not contain "AAA" or "BBB" as a substring.
+ *
+ * Return the maximum possible length of the new string.
+ *
+ * A substring is a contiguous non-empty sequence of characters within a string.
+ */
+
+/**
+ * @param {number} x
+ * @param {number} y
+ * @param {number} z
+ * @return {number}
+ */
+var longestString = function(x, y, z) {
+ const minPairs = Math.min(x, y);
+ return 2 * (minPairs * 2 + (x > minPairs ? 1 : 0) + (y > minPairs ? 1 : 0) + z);
+};
From 7f9d5bbb6f5e421a8a972d866d5f3d367ef52552 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 22:30:17 -0500
Subject: [PATCH 286/994] Add solution #2748
---
README.md | 1 +
solutions/2748-number-of-beautiful-pairs.js | 53 +++++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/2748-number-of-beautiful-pairs.js
diff --git a/README.md b/README.md
index 360b4e4f..6c510f97 100644
--- a/README.md
+++ b/README.md
@@ -2021,6 +2021,7 @@
2742|[Painting the Walls](./solutions/2742-painting-the-walls.js)|Hard|
2744|[Find Maximum Number of String Pairs](./solutions/2744-find-maximum-number-of-string-pairs.js)|Easy|
2745|[Construct the Longest New String](./solutions/2745-construct-the-longest-new-string.js)|Medium|
+2748|[Number of Beautiful Pairs](./solutions/2748-number-of-beautiful-pairs.js)|Easy|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2748-number-of-beautiful-pairs.js b/solutions/2748-number-of-beautiful-pairs.js
new file mode 100644
index 00000000..28e7a52f
--- /dev/null
+++ b/solutions/2748-number-of-beautiful-pairs.js
@@ -0,0 +1,53 @@
+/**
+ * 2748. Number of Beautiful Pairs
+ * https://leetcode.com/problems/number-of-beautiful-pairs/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums. A pair of indices i, j where
+ * 0 <= i < j < nums.length is called beautiful if the first digit of nums[i] and
+ * the last digit of nums[j] are coprime.
+ *
+ * Return the total number of beautiful pairs in nums.
+ *
+ * Two integers x and y are coprime if there is no integer greater than 1 that divides
+ * both of them. In other words, x and y are 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 countBeautifulPairs = function(nums) {
+ let result = 0;
+ for (let i = 0; i < nums.length - 1; i++) {
+ for (let j = i + 1; j < nums.length; j++) {
+ const first = getFirstDigit(nums[i]);
+ const last = getLastDigit(nums[j]);
+ if (gcd(first, last) === 1) {
+ result++;
+ }
+ }
+ }
+
+ return result;
+
+ function gcd(a, b) {
+ while (b) {
+ a %= b;
+ [a, b] = [b, a];
+ }
+ return a;
+ }
+
+ function getFirstDigit(num) {
+ while (num >= 10) {
+ num = Math.floor(num / 10);
+ }
+ return num;
+ }
+
+ function getLastDigit(num) {
+ return num % 10;
+ }
+};
From 16f0e41480f4eb48e2b41d043c6f17e1a71109d0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 22:32:44 -0500
Subject: [PATCH 287/994] Add solution #2751
---
README.md | 1 +
solutions/2751-robot-collisions.js | 76 ++++++++++++++++++++++++++++++
2 files changed, 77 insertions(+)
create mode 100644 solutions/2751-robot-collisions.js
diff --git a/README.md b/README.md
index 6c510f97..6628b4cf 100644
--- a/README.md
+++ b/README.md
@@ -2022,6 +2022,7 @@
2744|[Find Maximum Number of String Pairs](./solutions/2744-find-maximum-number-of-string-pairs.js)|Easy|
2745|[Construct the Longest New String](./solutions/2745-construct-the-longest-new-string.js)|Medium|
2748|[Number of Beautiful Pairs](./solutions/2748-number-of-beautiful-pairs.js)|Easy|
+2751|[Robot Collisions](./solutions/2751-robot-collisions.js)|Hard|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2751-robot-collisions.js b/solutions/2751-robot-collisions.js
new file mode 100644
index 00000000..53149178
--- /dev/null
+++ b/solutions/2751-robot-collisions.js
@@ -0,0 +1,76 @@
+/**
+ * 2751. Robot Collisions
+ * https://leetcode.com/problems/robot-collisions/
+ * Difficulty: Hard
+ *
+ * There are n 1-indexed robots, each having a position on a line, health, and movement direction.
+ *
+ * You are given 0-indexed integer arrays positions, healths, and a string directions (directions[i]
+ * is either 'L' for left or 'R' for right). All integers in positions are unique.
+ *
+ * All robots start moving on the line simultaneously at the same speed in their given directions.
+ * If two robots ever share the same position while moving, they will collide.
+ *
+ * If two robots collide, the robot with lower health is removed from the line, and the health of
+ * the other robot decreases by one. The surviving robot continues in the same direction it was
+ * going. If both robots have the same health, they are both removed from the line.
+ *
+ * Your task is to determine the health of the robots that survive the collisions, in the same
+ * order that the robots were given, i.e. final health of robot 1 (if survived), final health
+ * of robot 2 (if survived), and so on. If there are no survivors, return an empty array.
+ *
+ * Return an array containing the health of the remaining robots (in the order they were given
+ * in the input), after no further collisions can occur.
+ *
+ * Note: The positions may be unsorted.
+ */
+
+/**
+ * @param {number[]} positions
+ * @param {number[]} healths
+ * @param {string} directions
+ * @return {number[]}
+ */
+var survivedRobotsHealths = function(positions, healths, directions) {
+ const n = positions.length;
+ const robots = Array.from({ length: n }, (_, i) => ({
+ index: i,
+ position: positions[i],
+ health: healths[i],
+ direction: directions[i]
+ }));
+
+ robots.sort((a, b) => a.position - b.position);
+
+ const stack = [];
+ for (const robot of robots) {
+ if (robot.direction === 'R') {
+ stack.push(robot);
+ continue;
+ }
+
+ while (stack.length && stack[stack.length - 1].direction === 'R' && robot.health > 0) {
+ const last = stack[stack.length - 1];
+ if (last.health === robot.health) {
+ stack.pop();
+ robot.health = 0;
+ } else if (last.health > robot.health) {
+ last.health--;
+ robot.health = 0;
+ } else {
+ stack.pop();
+ robot.health--;
+ }
+ }
+ if (robot.health > 0) {
+ stack.push(robot);
+ }
+ }
+
+ const result = new Array(n).fill(0);
+ for (const robot of stack) {
+ result[robot.index] = robot.health;
+ }
+
+ return result.filter(health => health > 0);
+};
From e2f5b8da71bd8f05f7a4a114b452dfc816a3b38d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 22:35:31 -0500
Subject: [PATCH 288/994] Add solution #2763
---
README.md | 1 +
...m-of-imbalance-numbers-of-all-subarrays.js | 51 +++++++++++++++++++
2 files changed, 52 insertions(+)
create mode 100644 solutions/2763-sum-of-imbalance-numbers-of-all-subarrays.js
diff --git a/README.md b/README.md
index 6628b4cf..c54ae148 100644
--- a/README.md
+++ b/README.md
@@ -2023,6 +2023,7 @@
2745|[Construct the Longest New String](./solutions/2745-construct-the-longest-new-string.js)|Medium|
2748|[Number of Beautiful Pairs](./solutions/2748-number-of-beautiful-pairs.js)|Easy|
2751|[Robot Collisions](./solutions/2751-robot-collisions.js)|Hard|
+2763|[Sum of Imbalance Numbers of All Subarrays](./solutions/2763-sum-of-imbalance-numbers-of-all-subarrays.js)|Hard|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2763-sum-of-imbalance-numbers-of-all-subarrays.js b/solutions/2763-sum-of-imbalance-numbers-of-all-subarrays.js
new file mode 100644
index 00000000..5d7ba4ed
--- /dev/null
+++ b/solutions/2763-sum-of-imbalance-numbers-of-all-subarrays.js
@@ -0,0 +1,51 @@
+/**
+ * 2763. Sum of Imbalance Numbers of All Subarrays
+ * https://leetcode.com/problems/sum-of-imbalance-numbers-of-all-subarrays/
+ * Difficulty: Hard
+ *
+ * The imbalance number of a 0-indexed integer array arr of length n is defined as the number
+ * of indices in sarr = sorted(arr) such that:
+ * - 0 <= i < n - 1, and
+ * - sarr[i+1] - sarr[i] > 1
+ *
+ * Here, sorted(arr) is the function that returns the sorted version of arr.
+ *
+ * Given a 0-indexed integer array nums, return the sum of imbalance numbers of all its subarrays.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var sumImbalanceNumbers = function(nums) {
+ const n = nums.length;
+ let result = 0;
+
+ for (let i = 0; i < n; i++) {
+ const seen = new Set();
+ let imbalance = 0;
+
+ for (let j = i; j < n; j++) {
+ const current = nums[j];
+
+ if (!seen.has(current)) {
+ const hasNext = seen.has(current + 1);
+ const hasPrev = seen.has(current - 1);
+
+ if (hasNext && hasPrev) {
+ imbalance--;
+ } else if (!hasNext && !hasPrev && seen.size > 0) {
+ imbalance++;
+ }
+
+ seen.add(current);
+ }
+
+ result += imbalance;
+ }
+ }
+
+ return result;
+};
From ac9aade558e714121ebba74dd0007d382d2b37ef Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 22:36:38 -0500
Subject: [PATCH 289/994] Add solution #2766
---
README.md | 1 +
solutions/2766-relocate-marbles.js | 34 ++++++++++++++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/2766-relocate-marbles.js
diff --git a/README.md b/README.md
index c54ae148..4280e619 100644
--- a/README.md
+++ b/README.md
@@ -2024,6 +2024,7 @@
2748|[Number of Beautiful Pairs](./solutions/2748-number-of-beautiful-pairs.js)|Easy|
2751|[Robot Collisions](./solutions/2751-robot-collisions.js)|Hard|
2763|[Sum of Imbalance Numbers of All Subarrays](./solutions/2763-sum-of-imbalance-numbers-of-all-subarrays.js)|Hard|
+2766|[Relocate Marbles](./solutions/2766-relocate-marbles.js)|Medium|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2766-relocate-marbles.js b/solutions/2766-relocate-marbles.js
new file mode 100644
index 00000000..08d51e6f
--- /dev/null
+++ b/solutions/2766-relocate-marbles.js
@@ -0,0 +1,34 @@
+/**
+ * 2766. Relocate Marbles
+ * https://leetcode.com/problems/relocate-marbles/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums representing the initial positions of some
+ * marbles. You are also given two 0-indexed integer arrays moveFrom and moveTo of equal length.
+ *
+ * Throughout moveFrom.length steps, you will change the positions of the marbles. On the ith
+ * step, you will move all marbles at position moveFrom[i] to position moveTo[i].
+ *
+ * After completing all the steps, return the sorted list of occupied positions.
+ *
+ * Notes:
+ * - We call a position occupied if there is at least one marble in that position.
+ * - There may be multiple marbles in a single position.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[]} moveFrom
+ * @param {number[]} moveTo
+ * @return {number[]}
+ */
+var relocateMarbles = function(nums, moveFrom, moveTo) {
+ const set = new Set(nums);
+
+ for (let i = 0; i < moveFrom.length; i++) {
+ set.delete(moveFrom[i]);
+ set.add(moveTo[i]);
+ }
+
+ return [...set].sort((a, b) => a - b);
+};
From c5e91924012e3b9bcbc71019c5932d41ec421daf Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 31 May 2025 22:38:05 -0500
Subject: [PATCH 290/994] Add solution #2767
---
README.md | 1 +
...tring-into-minimum-beautiful-substrings.js | 52 +++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 solutions/2767-partition-string-into-minimum-beautiful-substrings.js
diff --git a/README.md b/README.md
index 4280e619..ac7b056c 100644
--- a/README.md
+++ b/README.md
@@ -2025,6 +2025,7 @@
2751|[Robot Collisions](./solutions/2751-robot-collisions.js)|Hard|
2763|[Sum of Imbalance Numbers of All Subarrays](./solutions/2763-sum-of-imbalance-numbers-of-all-subarrays.js)|Hard|
2766|[Relocate Marbles](./solutions/2766-relocate-marbles.js)|Medium|
+2767|[Partition String Into Minimum Beautiful Substrings](./solutions/2767-partition-string-into-minimum-beautiful-substrings.js)|Medium|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2767-partition-string-into-minimum-beautiful-substrings.js b/solutions/2767-partition-string-into-minimum-beautiful-substrings.js
new file mode 100644
index 00000000..45e5b024
--- /dev/null
+++ b/solutions/2767-partition-string-into-minimum-beautiful-substrings.js
@@ -0,0 +1,52 @@
+/**
+ * 2767. Partition String Into Minimum Beautiful Substrings
+ * https://leetcode.com/problems/partition-string-into-minimum-beautiful-substrings/
+ * Difficulty: Medium
+ *
+ * Given a binary string s, partition the string into one or more substrings such that each
+ * substring is beautiful.
+ *
+ * A string is beautiful if:
+ * - It doesn't contain leading zeros.
+ * - It's the binary representation of a number that is a power of 5.
+ *
+ * Return the minimum number of substrings in such partition. If it is impossible to partition
+ * the string s into beautiful substrings, return -1.
+ *
+ * A substring is a contiguous sequence of characters in a string.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var minimumBeautifulSubstrings = function(s) {
+ const n = s.length;
+ const powersOfFive = new Set();
+ let power = 1;
+ while (power.toString(2).length <= n) {
+ powersOfFive.add(power.toString(2));
+ power *= 5;
+ }
+
+ const result = findMinPartitions(0);
+ return result === Infinity ? -1 : result;
+
+ function findMinPartitions(index) {
+ if (index === n) return 0;
+ if (s[index] === '0') return Infinity;
+
+ let minPartitions = Infinity;
+ for (let end = index + 1; end <= n; end++) {
+ const substring = s.slice(index, end);
+ if (powersOfFive.has(substring)) {
+ const next = findMinPartitions(end);
+ if (next !== Infinity) {
+ minPartitions = Math.min(minPartitions, 1 + next);
+ }
+ }
+ }
+
+ return minPartitions;
+ }
+};
From 8c579779c2a397f7b587a9dd3b417843513b6e03 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 1 Jun 2025 17:31:43 -0500
Subject: [PATCH 291/994] Add solution #2511
---
README.md | 1 +
...aximum-enemy-forts-that-can-be-captured.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/2511-maximum-enemy-forts-that-can-be-captured.js
diff --git a/README.md b/README.md
index ac7b056c..1cd18c1d 100644
--- a/README.md
+++ b/README.md
@@ -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|
+2511|[Maximum Enemy Forts That Can Be Captured](./solutions/2511-maximum-enemy-forts-that-can-be-captured.js)|Easy|
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|
diff --git a/solutions/2511-maximum-enemy-forts-that-can-be-captured.js b/solutions/2511-maximum-enemy-forts-that-can-be-captured.js
new file mode 100644
index 00000000..7a7b5045
--- /dev/null
+++ b/solutions/2511-maximum-enemy-forts-that-can-be-captured.js
@@ -0,0 +1,42 @@
+/**
+ * 2511. Maximum Enemy Forts That Can Be Captured
+ * https://leetcode.com/problems/maximum-enemy-forts-that-can-be-captured/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array forts of length n representing the positions of
+ * several forts. forts[i] can be -1, 0, or 1 where:
+ * - -1 represents there is no fort at the ith position.
+ * - 0 indicates there is an enemy fort at the ith position.
+ * - 1 indicates the fort at the ith the position is under your command.
+ *
+ * Now you have decided to move your army from one of your forts at position i to an empty
+ * position j such that:
+ * - 0 <= i, j <= n - 1
+ * - The army travels over enemy forts only. Formally, for all k where min(i,j) < k < max(i,j),
+ * forts[k] == 0.
+ *
+ * While moving the army, all the enemy forts that come in the way are captured.
+ *
+ * Return the maximum number of enemy forts that can be captured. In case it is impossible to
+ * move your army, or you do not have any fort under your command, return 0.
+ */
+
+/**
+ * @param {number[]} forts
+ * @return {number}
+ */
+var captureForts = function(forts) {
+ let result = 0;
+ let start = -1;
+
+ for (let i = 0; i < forts.length; i++) {
+ if (forts[i] === 1 || forts[i] === -1) {
+ if (start !== -1 && forts[start] !== forts[i]) {
+ result = Math.max(result, i - start - 1);
+ }
+ start = i;
+ }
+ }
+
+ return result;
+};
From 579aefc805ad00aad587e16decf314da6cceaafb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 1 Jun 2025 17:38:36 -0500
Subject: [PATCH 292/994] Add solution #2646
---
README.md | 1 +
...6-minimize-the-total-price-of-the-trips.js | 81 +++++++++++++++++++
2 files changed, 82 insertions(+)
create mode 100644 solutions/2646-minimize-the-total-price-of-the-trips.js
diff --git a/README.md b/README.md
index 1cd18c1d..9f85c8b9 100644
--- a/README.md
+++ b/README.md
@@ -1967,6 +1967,7 @@
2643|[Row With Maximum Ones](./solutions/2643-row-with-maximum-ones.js)|Easy|
2644|[Find the Maximum Divisibility Score](./solutions/2644-find-the-maximum-divisibility-score.js)|Easy|
2645|[Minimum Additions to Make Valid String](./solutions/2645-minimum-additions-to-make-valid-string.js)|Medium|
+2646|[Minimize the Total Price of the Trips](./solutions/2646-minimize-the-total-price-of-the-trips.js)|Hard|
2648|[Generate Fibonacci Sequence](./solutions/2648-generate-fibonacci-sequence.js)|Easy|
2649|[Nested Array Generator](./solutions/2649-nested-array-generator.js)|Medium|
2650|[Design Cancellable Function](./solutions/2650-design-cancellable-function.js)|Hard|
diff --git a/solutions/2646-minimize-the-total-price-of-the-trips.js b/solutions/2646-minimize-the-total-price-of-the-trips.js
new file mode 100644
index 00000000..08bb9cfd
--- /dev/null
+++ b/solutions/2646-minimize-the-total-price-of-the-trips.js
@@ -0,0 +1,81 @@
+/**
+ * 2646. Minimize the Total Price of the Trips
+ * https://leetcode.com/problems/minimize-the-total-price-of-the-trips/
+ * Difficulty: Hard
+ *
+ * There exists an undirected and unrooted tree with n nodes indexed from 0 to n - 1. You are
+ * given the integer n and 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.
+ *
+ * Each node has an associated price. You are given an integer array price, where price[i] is
+ * the price of the ith node.
+ *
+ * The price sum of a given path is the sum of the prices of all nodes lying on that path.
+ *
+ * Additionally, you are given a 2D integer array trips, where trips[i] = [starti, endi]
+ * indicates that you start the ith trip from the node starti and travel to the node endi
+ * by any path you like.
+ *
+ * Before performing your first trip, you can choose some non-adjacent nodes and halve the
+ * prices.
+ *
+ * Return the minimum total price sum to perform all the given trips.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @param {number[]} price
+ * @param {number[][]} trips
+ * @return {number}
+ */
+var minimumTotalPrice = function(n, edges, price, trips) {
+ const graph = Array.from({ length: n }, () => []);
+ for (const [u, v] of edges) {
+ graph[u].push(v);
+ graph[v].push(u);
+ }
+
+ const count = new Array(n).fill(0);
+
+ for (const [start, end] of trips) {
+ dfsPath(start, end, -1, []);
+ }
+
+ return dp(0, -1, true)[1];
+
+ function dp(node, parent, canHalve) {
+ const full = count[node] * price[node];
+ const half = full / 2;
+ let childrenFull = 0;
+ let childrenHalf = 0;
+
+ for (const child of graph[node]) {
+ if (child !== parent) {
+ const [childFull, childHalf] = dp(child, node, canHalve && node !== -1);
+ childrenFull += childFull;
+ childrenHalf += childHalf;
+ }
+ }
+
+ if (canHalve) {
+ return [full + childrenHalf, Math.min(full + childrenHalf, half + childrenFull)];
+ }
+ return [full + childrenHalf, full + childrenHalf];
+ }
+
+ function dfsPath(start, end, parent, path) {
+ path.push(start);
+ if (start === end) {
+ for (const node of path) count[node]++;
+ return true;
+ }
+ for (const next of graph[start]) {
+ if (next !== parent && dfsPath(next, end, start, path)) {
+ return true;
+ }
+ }
+ path.pop();
+ return false;
+ }
+};
From 7a9b15c6df430b1ddf2527b72235ba2fcc9dcc65 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 1 Jun 2025 17:39:44 -0500
Subject: [PATCH 293/994] Add solution #2769
---
README.md | 1 +
...2769-find-the-maximum-achievable-number.js | 20 +++++++++++++++++++
2 files changed, 21 insertions(+)
create mode 100644 solutions/2769-find-the-maximum-achievable-number.js
diff --git a/README.md b/README.md
index 9f85c8b9..1da6a1a4 100644
--- a/README.md
+++ b/README.md
@@ -2028,6 +2028,7 @@
2763|[Sum of Imbalance Numbers of All Subarrays](./solutions/2763-sum-of-imbalance-numbers-of-all-subarrays.js)|Hard|
2766|[Relocate Marbles](./solutions/2766-relocate-marbles.js)|Medium|
2767|[Partition String Into Minimum Beautiful Substrings](./solutions/2767-partition-string-into-minimum-beautiful-substrings.js)|Medium|
+2769|[Find the Maximum Achievable Number](./solutions/2769-find-the-maximum-achievable-number.js)|Easy|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2769-find-the-maximum-achievable-number.js b/solutions/2769-find-the-maximum-achievable-number.js
new file mode 100644
index 00000000..cfd60aeb
--- /dev/null
+++ b/solutions/2769-find-the-maximum-achievable-number.js
@@ -0,0 +1,20 @@
+/**
+ * 2769. Find the Maximum Achievable Number
+ * https://leetcode.com/problems/find-the-maximum-achievable-number/
+ * Difficulty: Easy
+ *
+ * Given two integers, num and t. A number x is achievable if it can become equal to num
+ * after applying the following operation at most t times:
+ * - Increase or decrease x by 1, and simultaneously increase or decrease num by 1.
+ *
+ * Return the maximum possible value of x.
+ */
+
+/**
+ * @param {number} num
+ * @param {number} t
+ * @return {number}
+ */
+var theMaximumAchievableX = function(num, t) {
+ return num + 2 * t;
+};
From 5f1ea45a9f3a26e5972e5b7e6b9a76fdd03ff8d8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 1 Jun 2025 17:41:02 -0500
Subject: [PATCH 294/994] Add solution #2778
---
README.md | 1 +
...2778-sum-of-squares-of-special-elements.js | 28 +++++++++++++++++++
2 files changed, 29 insertions(+)
create mode 100644 solutions/2778-sum-of-squares-of-special-elements.js
diff --git a/README.md b/README.md
index 1da6a1a4..1f80891a 100644
--- a/README.md
+++ b/README.md
@@ -2029,6 +2029,7 @@
2766|[Relocate Marbles](./solutions/2766-relocate-marbles.js)|Medium|
2767|[Partition String Into Minimum Beautiful Substrings](./solutions/2767-partition-string-into-minimum-beautiful-substrings.js)|Medium|
2769|[Find the Maximum Achievable Number](./solutions/2769-find-the-maximum-achievable-number.js)|Easy|
+2778|[Sum of Squares of Special Elements](./solutions/2778-sum-of-squares-of-special-elements.js)|Easy|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2778-sum-of-squares-of-special-elements.js b/solutions/2778-sum-of-squares-of-special-elements.js
new file mode 100644
index 00000000..fbac7766
--- /dev/null
+++ b/solutions/2778-sum-of-squares-of-special-elements.js
@@ -0,0 +1,28 @@
+/**
+ * 2778. Sum of Squares of Special Elements
+ * https://leetcode.com/problems/sum-of-squares-of-special-elements/
+ * Difficulty: Easy
+ *
+ * You are given a 1-indexed integer array nums of length n.
+ *
+ * An element nums[i] of nums is called special if i divides n, i.e. n % i == 0.
+ *
+ * Return the sum of the squares of all special elements of nums.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var sumOfSquares = function(nums) {
+ const n = nums.length;
+ let total = 0;
+
+ for (let i = 1; i <= n; i++) {
+ if (n % i === 0) {
+ total += nums[i - 1] * nums[i - 1];
+ }
+ }
+
+ return total;
+};
From a49d3f66e3021c37648dc424f51e9b9174703b13 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 1 Jun 2025 17:42:17 -0500
Subject: [PATCH 295/994] Add solution #2779
---
README.md | 1 +
...ty-of-an-array-after-applying-operation.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/2779-maximum-beauty-of-an-array-after-applying-operation.js
diff --git a/README.md b/README.md
index 1f80891a..cff29355 100644
--- a/README.md
+++ b/README.md
@@ -2030,6 +2030,7 @@
2767|[Partition String Into Minimum Beautiful Substrings](./solutions/2767-partition-string-into-minimum-beautiful-substrings.js)|Medium|
2769|[Find the Maximum Achievable Number](./solutions/2769-find-the-maximum-achievable-number.js)|Easy|
2778|[Sum of Squares of Special Elements](./solutions/2778-sum-of-squares-of-special-elements.js)|Easy|
+2779|[Maximum Beauty of an Array After Applying Operation](./solutions/2779-maximum-beauty-of-an-array-after-applying-operation.js)|Medium|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2779-maximum-beauty-of-an-array-after-applying-operation.js b/solutions/2779-maximum-beauty-of-an-array-after-applying-operation.js
new file mode 100644
index 00000000..1015482b
--- /dev/null
+++ b/solutions/2779-maximum-beauty-of-an-array-after-applying-operation.js
@@ -0,0 +1,41 @@
+/**
+ * 2779. Maximum Beauty of an Array After Applying Operation
+ * https://leetcode.com/problems/maximum-beauty-of-an-array-after-applying-operation/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array nums and a non-negative integer k.
+ *
+ * In one operation, you can do the following:
+ * - Choose an index i that hasn't been chosen before from the range [0, nums.length - 1].
+ * - Replace nums[i] with any integer from the range [nums[i] - k, nums[i] + k].
+ *
+ * The beauty of the array is the length of the longest subsequence consisting of equal elements.
+ *
+ * Return the maximum possible beauty of the array nums after applying the operation any number
+ * of times.
+ *
+ * Note that you can apply the operation to each index only once.
+ *
+ * A subsequence of an array is a new array generated from the original array by deleting some
+ * elements (possibly none) without changing the order of the remaining elements.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var maximumBeauty = function(nums, k) {
+ nums.sort((a, b) => a - b);
+ let result = 0;
+ let left = 0;
+
+ for (let right = 0; right < nums.length; right++) {
+ while (nums[right] - nums[left] > 2 * k) {
+ left++;
+ }
+ result = Math.max(result, right - left + 1);
+ }
+
+ return result;
+};
From 619803c9be494402109fe1e38390bd307ca6965e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 1 Jun 2025 17:46:43 -0500
Subject: [PATCH 296/994] Add solution #2784
---
README.md | 1 +
solutions/2784-check-if-array-is-good.js | 36 ++++++++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/2784-check-if-array-is-good.js
diff --git a/README.md b/README.md
index cff29355..cc6cc769 100644
--- a/README.md
+++ b/README.md
@@ -2032,6 +2032,7 @@
2778|[Sum of Squares of Special Elements](./solutions/2778-sum-of-squares-of-special-elements.js)|Easy|
2779|[Maximum Beauty of an Array After Applying Operation](./solutions/2779-maximum-beauty-of-an-array-after-applying-operation.js)|Medium|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
+2784|[Check if Array is Good](./solutions/2784-check-if-array-is-good.js)|Easy|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
diff --git a/solutions/2784-check-if-array-is-good.js b/solutions/2784-check-if-array-is-good.js
new file mode 100644
index 00000000..289edd0d
--- /dev/null
+++ b/solutions/2784-check-if-array-is-good.js
@@ -0,0 +1,36 @@
+/**
+ * 2784. Check if Array is Good
+ * https://leetcode.com/problems/check-if-array-is-good/
+ * Difficulty: Easy
+ *
+ * You are given an integer array nums. We consider an array good if it is a permutation of
+ * an array base[n].
+ *
+ * base[n] = [1, 2, ..., n - 1, n, n] (in other words, it is an array of length n + 1 which
+ * contains 1 to n - 1 exactly once, plus two occurrences of n). For example, base[1] = [1, 1]
+ * and base[3] = [1, 2, 3, 3].
+ *
+ * Return true if the given array is good, otherwise return false.
+ *
+ * Note: A permutation of integers represents an arrangement of these numbers.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {boolean}
+ */
+var isGood = function(nums) {
+ const n = Math.max(...nums);
+ if (nums.length !== n + 1) return false;
+
+ const frequency = new Array(n + 1).fill(0);
+ for (const num of nums) {
+ if (num > n) return false;
+ frequency[num]++;
+ }
+
+ for (let i = 1; i < n; i++) {
+ if (frequency[i] !== 1) return false;
+ }
+ return frequency[n] === 2;
+};
From ec3c0b5bb3dbde5c2ee707c0762585f24ba7887c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 1 Jun 2025 17:48:38 -0500
Subject: [PATCH 297/994] Add solution #2785
---
README.md | 1 +
solutions/2785-sort-vowels-in-a-string.js | 45 +++++++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/2785-sort-vowels-in-a-string.js
diff --git a/README.md b/README.md
index cc6cc769..1c27cb70 100644
--- a/README.md
+++ b/README.md
@@ -2033,6 +2033,7 @@
2779|[Maximum Beauty of an Array After Applying Operation](./solutions/2779-maximum-beauty-of-an-array-after-applying-operation.js)|Medium|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2784|[Check if Array is Good](./solutions/2784-check-if-array-is-good.js)|Easy|
+2785|[Sort Vowels in a String](./solutions/2785-sort-vowels-in-a-string.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
diff --git a/solutions/2785-sort-vowels-in-a-string.js b/solutions/2785-sort-vowels-in-a-string.js
new file mode 100644
index 00000000..d4a25c7e
--- /dev/null
+++ b/solutions/2785-sort-vowels-in-a-string.js
@@ -0,0 +1,45 @@
+/**
+ * 2785. Sort Vowels in a String
+ * https://leetcode.com/problems/sort-vowels-in-a-string/
+ * Difficulty: Medium
+ *
+ * Given a 0-indexed string s, permute s to get a new string t such that:
+ * - All consonants remain in their original places. More formally, if there is an index i
+ * with 0 <= i < s.length such that s[i] is a consonant, then t[i] = s[i].
+ * - The vowels must be sorted in the nondecreasing order of their ASCII values. More formally,
+ * for pairs of indices i, j with 0 <= i < j < s.length such that s[i] and s[j] are vowels,
+ * then t[i] must not have a higher ASCII value than t[j].
+ *
+ * Return the resulting string.
+ *
+ * The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in lowercase or uppercase.
+ * Consonants comprise all letters that are not vowels.
+ */
+
+/**
+ * @param {string} s
+ * @return {string}
+ */
+var sortVowels = function(s) {
+ const vowels = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']);
+ const vowelChars = [];
+
+ for (const char of s) {
+ if (vowels.has(char)) {
+ vowelChars.push(char);
+ }
+ }
+
+ vowelChars.sort();
+
+ const result = [...s];
+ let vowelIndex = 0;
+
+ for (let i = 0; i < s.length; i++) {
+ if (vowels.has(s[i])) {
+ result[i] = vowelChars[vowelIndex++];
+ }
+ }
+
+ return result.join('');
+};
From e3ea156a24ccf3e62740b5a741fbf118376117a6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 1 Jun 2025 17:50:02 -0500
Subject: [PATCH 298/994] Add solution #2788
---
README.md | 1 +
solutions/2788-split-strings-by-separator.js | 31 ++++++++++++++++++++
2 files changed, 32 insertions(+)
create mode 100644 solutions/2788-split-strings-by-separator.js
diff --git a/README.md b/README.md
index 1c27cb70..a2acdd43 100644
--- a/README.md
+++ b/README.md
@@ -2034,6 +2034,7 @@
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
2784|[Check if Array is Good](./solutions/2784-check-if-array-is-good.js)|Easy|
2785|[Sort Vowels in a String](./solutions/2785-sort-vowels-in-a-string.js)|Medium|
+2788|[Split Strings by Separator](./solutions/2788-split-strings-by-separator.js)|Easy|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
diff --git a/solutions/2788-split-strings-by-separator.js b/solutions/2788-split-strings-by-separator.js
new file mode 100644
index 00000000..6681bef2
--- /dev/null
+++ b/solutions/2788-split-strings-by-separator.js
@@ -0,0 +1,31 @@
+/**
+ * 2788. Split Strings by Separator
+ * https://leetcode.com/problems/split-strings-by-separator/
+ * Difficulty: Easy
+ *
+ * Given an array of strings words and a character separator, split each string in words by
+ * separator.
+ *
+ * Return an array of strings containing the new strings formed after the splits, excluding
+ * empty strings.
+ *
+ * Notes
+ * - separator is used to determine where the split should occur, but it is not included as
+ * part of the resulting strings.
+ * - A split may result in more than two strings.
+ * - The resulting strings must maintain the same order as they were initially given.
+ */
+
+/**
+ * @param {string[]} words
+ * @param {character} separator
+ * @return {string[]}
+ */
+var splitWordsBySeparator = function(words, separator) {
+ const result = [];
+ for (const word of words) {
+ const splitWords = word.split(separator).filter(part => part !== '');
+ result.push(...splitWords);
+ }
+ return result;
+};
From d3755ebc3f1c5179ec0ac86028996a156ff7ea44 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 1 Jun 2025 17:51:18 -0500
Subject: [PATCH 299/994] Add solution #2789
---
README.md | 1 +
...ment-in-an-array-after-merge-operations.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/2789-largest-element-in-an-array-after-merge-operations.js
diff --git a/README.md b/README.md
index a2acdd43..eea3ab4a 100644
--- a/README.md
+++ b/README.md
@@ -2035,6 +2035,7 @@
2784|[Check if Array is Good](./solutions/2784-check-if-array-is-good.js)|Easy|
2785|[Sort Vowels in a String](./solutions/2785-sort-vowels-in-a-string.js)|Medium|
2788|[Split Strings by Separator](./solutions/2788-split-strings-by-separator.js)|Easy|
+2789|[Largest Element in an Array after Merge Operations](./solutions/2789-largest-element-in-an-array-after-merge-operations.js)|Medium|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
diff --git a/solutions/2789-largest-element-in-an-array-after-merge-operations.js b/solutions/2789-largest-element-in-an-array-after-merge-operations.js
new file mode 100644
index 00000000..3de874a6
--- /dev/null
+++ b/solutions/2789-largest-element-in-an-array-after-merge-operations.js
@@ -0,0 +1,34 @@
+/**
+ * 2789. Largest Element in an Array after Merge Operations
+ * https://leetcode.com/problems/largest-element-in-an-array-after-merge-operations/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array nums consisting of positive integers.
+ *
+ * You can do the following operation on the array any number of times:
+ * - Choose an integer i such that 0 <= i < nums.length - 1 and nums[i] <= nums[i + 1].
+ * Replace the element nums[i + 1] with nums[i] + nums[i + 1] and delete the element
+ * nums[i] from the array.
+ *
+ * Return the value of the largest element that you can possibly obtain in the final array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maxArrayValue = function(nums) {
+ let result = nums[nums.length - 1];
+ let currentSum = result;
+
+ for (let i = nums.length - 2; i >= 0; i--) {
+ if (nums[i] <= currentSum) {
+ currentSum += nums[i];
+ } else {
+ currentSum = nums[i];
+ }
+ result = Math.max(result, currentSum);
+ }
+
+ return result;
+};
From 37b4c923a5eacfea1de58227a5f4041b1837dbf3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 1 Jun 2025 17:53:08 -0500
Subject: [PATCH 300/994] Add solution #2791
---
README.md | 1 +
...hs-that-can-form-a-palindrome-in-a-tree.js | 49 +++++++++++++++++++
2 files changed, 50 insertions(+)
create mode 100644 solutions/2791-count-paths-that-can-form-a-palindrome-in-a-tree.js
diff --git a/README.md b/README.md
index eea3ab4a..748f1003 100644
--- a/README.md
+++ b/README.md
@@ -2036,6 +2036,7 @@
2785|[Sort Vowels in a String](./solutions/2785-sort-vowels-in-a-string.js)|Medium|
2788|[Split Strings by Separator](./solutions/2788-split-strings-by-separator.js)|Easy|
2789|[Largest Element in an Array after Merge Operations](./solutions/2789-largest-element-in-an-array-after-merge-operations.js)|Medium|
+2791|[Count Paths That Can Form a Palindrome in a Tree](./solutions/2791-count-paths-that-can-form-a-palindrome-in-a-tree.js)|Hard|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
diff --git a/solutions/2791-count-paths-that-can-form-a-palindrome-in-a-tree.js b/solutions/2791-count-paths-that-can-form-a-palindrome-in-a-tree.js
new file mode 100644
index 00000000..195def8e
--- /dev/null
+++ b/solutions/2791-count-paths-that-can-form-a-palindrome-in-a-tree.js
@@ -0,0 +1,49 @@
+/**
+ * 2791. Count Paths That Can Form a Palindrome in a Tree
+ * https://leetcode.com/problems/count-paths-that-can-form-a-palindrome-in-a-tree/
+ * 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 the edge
+ * between i and parent[i]. s[0] can be ignored.
+ *
+ * Return the number of pairs of nodes (u, v) such that u < v and the characters assigned to edges
+ * on the path from u to v can be rearranged to form a palindrome.
+ *
+ * A string is a palindrome when it reads the same backwards as forwards.
+ */
+
+/**
+ * @param {number[]} parent
+ * @param {string} s
+ * @return {number}
+ */
+var countPalindromePaths = function(parent, s) {
+ const n = parent.length;
+ const graph = Array.from({ length: n }, () => []);
+ for (let i = 1; i < n; i++) {
+ graph[parent[i]].push(i);
+ }
+
+ const freq = new Map([[0, 1]]);
+ let result = 0;
+
+ dfs(0, 0);
+ return result;
+
+ function dfs(node, mask) {
+ for (const child of graph[node]) {
+ const newMask = mask ^ (1 << (s[child].charCodeAt(0) - 97));
+ result += freq.get(newMask) || 0;
+ for (let i = 0; i < 26; i++) {
+ result += freq.get(newMask ^ (1 << i)) || 0;
+ }
+ freq.set(newMask, (freq.get(newMask) || 0) + 1);
+ dfs(child, newMask);
+ }
+ }
+};
From 95dd22a1014fde0f445a2ab6353578582df0e076 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 1 Jun 2025 22:26:11 -0500
Subject: [PATCH 301/994] Add solution #2470
---
README.md | 1 +
...number-of-subarrays-with-lcm-equal-to-k.js | 45 +++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/2470-number-of-subarrays-with-lcm-equal-to-k.js
diff --git a/README.md b/README.md
index 748f1003..a779b8d6 100644
--- a/README.md
+++ b/README.md
@@ -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|
+2470|[Number of Subarrays With LCM Equal to K](./solutions/2470-number-of-subarrays-with-lcm-equal-to-k.js)|Medium|
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|
diff --git a/solutions/2470-number-of-subarrays-with-lcm-equal-to-k.js b/solutions/2470-number-of-subarrays-with-lcm-equal-to-k.js
new file mode 100644
index 00000000..41edda1d
--- /dev/null
+++ b/solutions/2470-number-of-subarrays-with-lcm-equal-to-k.js
@@ -0,0 +1,45 @@
+/**
+ * 2470. Number of Subarrays With LCM Equal to K
+ * https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/
+ * Difficulty: Medium
+ *
+ * Given an integer array nums and an integer k, return the number of subarrays of nums
+ * where the least common multiple of the subarray's elements is k.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ *
+ * The least common multiple of an array is the smallest positive integer that is divisible
+ * by all the array elements.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var subarrayLCM = function(nums, k) {
+ let count = 0;
+
+ for (let start = 0; start < nums.length; start++) {
+ let currentLCM = nums[start];
+ for (let end = start; end < nums.length; end++) {
+ currentLCM = lcm(currentLCM, nums[end]);
+ if (currentLCM > k) break;
+ if (currentLCM === k) count++;
+ }
+ }
+
+ return count;
+
+ function gcd(a, b) {
+ while (b) {
+ a %= b;
+ [a, b] = [b, a];
+ }
+ return a;
+ }
+
+ function lcm(a, b) {
+ return (a * b) / gcd(a, b);
+ }
+};
From 40d745a7c973848ce89841a00bac24aa0374406a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 1 Jun 2025 22:27:17 -0500
Subject: [PATCH 302/994] Add solution #2798
---
README.md | 1 +
...-number-of-employees-who-met-the-target.js | 30 +++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 solutions/2798-number-of-employees-who-met-the-target.js
diff --git a/README.md b/README.md
index a779b8d6..f452229e 100644
--- a/README.md
+++ b/README.md
@@ -2038,6 +2038,7 @@
2788|[Split Strings by Separator](./solutions/2788-split-strings-by-separator.js)|Easy|
2789|[Largest Element in an Array after Merge Operations](./solutions/2789-largest-element-in-an-array-after-merge-operations.js)|Medium|
2791|[Count Paths That Can Form a Palindrome in a Tree](./solutions/2791-count-paths-that-can-form-a-palindrome-in-a-tree.js)|Hard|
+2798|[Number of Employees Who Met the Target](./solutions/2798-number-of-employees-who-met-the-target.js)|Easy|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
diff --git a/solutions/2798-number-of-employees-who-met-the-target.js b/solutions/2798-number-of-employees-who-met-the-target.js
new file mode 100644
index 00000000..b3c1f4ac
--- /dev/null
+++ b/solutions/2798-number-of-employees-who-met-the-target.js
@@ -0,0 +1,30 @@
+/**
+ * 2798. Number of Employees Who Met the Target
+ * https://leetcode.com/problems/number-of-employees-who-met-the-target/
+ * Difficulty: Easy
+ *
+ * There are n employees in a company, numbered from 0 to n - 1. Each employee i has worked
+ * for hours[i] hours in the company.
+ *
+ * The company requires each employee to work for at least target hours.
+ *
+ * You are given a 0-indexed array of non-negative integers hours of length n and a non-negative
+ * integer target.
+ *
+ * Return the integer denoting the number of employees who worked at least target hours.
+ */
+
+/**
+ * @param {number[]} hours
+ * @param {number} target
+ * @return {number}
+ */
+var numberOfEmployeesWhoMetTarget = function(hours, target) {
+ let count = 0;
+
+ for (const hoursWorked of hours) {
+ if (hoursWorked >= target) count++;
+ }
+
+ return count;
+};
From 868f4d2c76d202d0bf29d2039735679938c828fc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 1 Jun 2025 22:28:28 -0500
Subject: [PATCH 303/994] Add solution #2806
---
README.md | 1 +
...-account-balance-after-rounded-purchase.js | 29 +++++++++++++++++++
2 files changed, 30 insertions(+)
create mode 100644 solutions/2806-account-balance-after-rounded-purchase.js
diff --git a/README.md b/README.md
index f452229e..cea362b0 100644
--- a/README.md
+++ b/README.md
@@ -2040,6 +2040,7 @@
2791|[Count Paths That Can Form a Palindrome in a Tree](./solutions/2791-count-paths-that-can-form-a-palindrome-in-a-tree.js)|Hard|
2798|[Number of Employees Who Met the Target](./solutions/2798-number-of-employees-who-met-the-target.js)|Easy|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
+2806|[Account Balance After Rounded Purchase](./solutions/2806-account-balance-after-rounded-purchase.js)|Easy|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
2845|[Count of Interesting Subarrays](./solutions/2845-count-of-interesting-subarrays.js)|Medium|
diff --git a/solutions/2806-account-balance-after-rounded-purchase.js b/solutions/2806-account-balance-after-rounded-purchase.js
new file mode 100644
index 00000000..0862ed28
--- /dev/null
+++ b/solutions/2806-account-balance-after-rounded-purchase.js
@@ -0,0 +1,29 @@
+/**
+ * 2806. Account Balance After Rounded Purchase
+ * https://leetcode.com/problems/account-balance-after-rounded-purchase/
+ * Difficulty: Easy
+ *
+ * Initially, you have a bank account balance of 100 dollars.
+ *
+ * You are given an integer purchaseAmount representing the amount you will spend on a purchase
+ * in dollars, in other words, its price.
+ *
+ * When making the purchase, first the purchaseAmount is rounded to the nearest multiple of 10.
+ * Let us call this value roundedAmount. Then, roundedAmount dollars are removed from your bank
+ * account.
+ *
+ * Return an integer denoting your final bank account balance after this purchase.
+ *
+ * Notes:
+ * - 0 is considered to be a multiple of 10 in this problem.
+ * - When rounding, 5 is rounded upward (5 is rounded to 10, 15 is rounded to 20, 25 to 30, and
+ * so on).
+ */
+
+/**
+ * @param {number} purchaseAmount
+ * @return {number}
+ */
+var accountBalanceAfterPurchase = function(purchaseAmount) {
+ return 100 - (Math.round(purchaseAmount / 10) * 10);
+};
From 839106c6c333a81b2060287c43f65a36c3897819 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 1 Jun 2025 22:29:37 -0500
Subject: [PATCH 304/994] Add solution #2807
---
README.md | 1 +
...greatest-common-divisors-in-linked-list.js | 45 +++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/2807-insert-greatest-common-divisors-in-linked-list.js
diff --git a/README.md b/README.md
index cea362b0..7244948d 100644
--- a/README.md
+++ b/README.md
@@ -2041,6 +2041,7 @@
2798|[Number of Employees Who Met the Target](./solutions/2798-number-of-employees-who-met-the-target.js)|Easy|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2806|[Account Balance After Rounded Purchase](./solutions/2806-account-balance-after-rounded-purchase.js)|Easy|
+2807|[Insert Greatest Common Divisors in Linked List](./solutions/2807-insert-greatest-common-divisors-in-linked-list.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
2845|[Count of Interesting Subarrays](./solutions/2845-count-of-interesting-subarrays.js)|Medium|
diff --git a/solutions/2807-insert-greatest-common-divisors-in-linked-list.js b/solutions/2807-insert-greatest-common-divisors-in-linked-list.js
new file mode 100644
index 00000000..ee1b2f8e
--- /dev/null
+++ b/solutions/2807-insert-greatest-common-divisors-in-linked-list.js
@@ -0,0 +1,45 @@
+/**
+ * 2807. Insert Greatest Common Divisors in Linked List
+ * https://leetcode.com/problems/insert-greatest-common-divisors-in-linked-list/
+ * Difficulty: Medium
+ *
+ * Given the head of a linked list head, in which each node contains an integer value.
+ *
+ * Between every pair of adjacent nodes, insert a new node with a value equal to the greatest
+ * common divisor of them.
+ *
+ * Return the linked list after insertion.
+ *
+ * The greatest common divisor of two numbers is the largest positive integer that evenly
+ * divides both numbers.
+ */
+
+/**
+ * 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 insertGreatestCommonDivisors = function(head) {
+ let current = head;
+ while (current && current.next) {
+ const nextNode = current.next;
+ const divisor = gcd(current.val, nextNode.val);
+ current.next = new ListNode(divisor, nextNode);
+ current = nextNode;
+ }
+ return head;
+
+ function gcd(a, b) {
+ while (b) {
+ a %= b;
+ [a, b] = [b, a];
+ }
+ return a;
+ }
+};
From 05c9c87efe1225935709f1f5843806435bfccbb6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 1 Jun 2025 22:30:44 -0500
Subject: [PATCH 305/994] Add solution #2810
---
README.md | 1 +
solutions/2810-faulty-keyboard.js | 30 ++++++++++++++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 solutions/2810-faulty-keyboard.js
diff --git a/README.md b/README.md
index 7244948d..86beb2cf 100644
--- a/README.md
+++ b/README.md
@@ -2042,6 +2042,7 @@
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2806|[Account Balance After Rounded Purchase](./solutions/2806-account-balance-after-rounded-purchase.js)|Easy|
2807|[Insert Greatest Common Divisors in Linked List](./solutions/2807-insert-greatest-common-divisors-in-linked-list.js)|Medium|
+2810|[Faulty Keyboard](./solutions/2810-faulty-keyboard.js)|Easy|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
2845|[Count of Interesting Subarrays](./solutions/2845-count-of-interesting-subarrays.js)|Medium|
diff --git a/solutions/2810-faulty-keyboard.js b/solutions/2810-faulty-keyboard.js
new file mode 100644
index 00000000..47cb30e8
--- /dev/null
+++ b/solutions/2810-faulty-keyboard.js
@@ -0,0 +1,30 @@
+/**
+ * 2810. Faulty Keyboard
+ * https://leetcode.com/problems/faulty-keyboard/
+ * Difficulty: Easy
+ *
+ * Your laptop keyboard is faulty, and whenever you type a character 'i' on it, it reverses the
+ * string that you have written. Typing other characters works as expected.
+ *
+ * You are given a 0-indexed string s, and you type each character of s using your faulty keyboard.
+ *
+ * Return the final string that will be present on your laptop screen.
+ */
+
+/**
+ * @param {string} s
+ * @return {string}
+ */
+var finalString = function(s) {
+ const result = [];
+
+ for (const char of s) {
+ if (char === 'i') {
+ result.reverse();
+ } else {
+ result.push(char);
+ }
+ }
+
+ return result.join('');
+};
From efd487b32f132886e89975d29709306f8e47a0ec Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 2 Jun 2025 22:57:37 -0500
Subject: [PATCH 306/994] Add solution #2815
---
README.md | 1 +
solutions/2815-max-pair-sum-in-an-array.js | 48 ++++++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/2815-max-pair-sum-in-an-array.js
diff --git a/README.md b/README.md
index 86beb2cf..997f5dad 100644
--- a/README.md
+++ b/README.md
@@ -2043,6 +2043,7 @@
2806|[Account Balance After Rounded Purchase](./solutions/2806-account-balance-after-rounded-purchase.js)|Easy|
2807|[Insert Greatest Common Divisors in Linked List](./solutions/2807-insert-greatest-common-divisors-in-linked-list.js)|Medium|
2810|[Faulty Keyboard](./solutions/2810-faulty-keyboard.js)|Easy|
+2815|[Max Pair Sum in an Array](./solutions/2815-max-pair-sum-in-an-array.js)|Easy|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
2845|[Count of Interesting Subarrays](./solutions/2845-count-of-interesting-subarrays.js)|Medium|
diff --git a/solutions/2815-max-pair-sum-in-an-array.js b/solutions/2815-max-pair-sum-in-an-array.js
new file mode 100644
index 00000000..d6a41368
--- /dev/null
+++ b/solutions/2815-max-pair-sum-in-an-array.js
@@ -0,0 +1,48 @@
+/**
+ * 2815. Max Pair Sum in an Array
+ * https://leetcode.com/problems/max-pair-sum-in-an-array/
+ * Difficulty: Easy
+ *
+ * You are given an integer array nums. You have to find the maximum sum of a pair of numbers from
+ * nums such that the largest digit in both numbers is equal.
+ *
+ * For example, 2373 is made up of three distinct digits: 2, 3, and 7, where 7 is the largest among
+ * them.
+ *
+ * Return the maximum sum or -1 if no such pair exists.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maxSum = function(nums) {
+ let result = -1;
+ const map = new Map();
+
+ for (const num of nums) {
+ const maxDigit = getMaxDigit(num);
+ if (!map.has(maxDigit)) {
+ map.set(maxDigit, []);
+ }
+ map.get(maxDigit).push(num);
+ }
+
+ for (const numbers of map.values()) {
+ if (numbers.length >= 2) {
+ numbers.sort((a, b) => b - a);
+ result = Math.max(result, numbers[0] + numbers[1]);
+ }
+ }
+
+ return result;
+
+ function getMaxDigit(num) {
+ let max = 0;
+ while (num > 0) {
+ max = Math.max(max, num % 10);
+ num = Math.floor(num / 10);
+ }
+ return max;
+ }
+};
From 17bff2dcc12ad5cf4d793015bb63224b18d66f2e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 2 Jun 2025 22:58:41 -0500
Subject: [PATCH 307/994] Add solution #2816
---
README.md | 1 +
...e-a-number-represented-as-a-linked-list.js | 54 +++++++++++++++++++
2 files changed, 55 insertions(+)
create mode 100644 solutions/2816-double-a-number-represented-as-a-linked-list.js
diff --git a/README.md b/README.md
index 997f5dad..592e14d3 100644
--- a/README.md
+++ b/README.md
@@ -2044,6 +2044,7 @@
2807|[Insert Greatest Common Divisors in Linked List](./solutions/2807-insert-greatest-common-divisors-in-linked-list.js)|Medium|
2810|[Faulty Keyboard](./solutions/2810-faulty-keyboard.js)|Easy|
2815|[Max Pair Sum in an Array](./solutions/2815-max-pair-sum-in-an-array.js)|Easy|
+2816|[Double a Number Represented as a Linked List](./solutions/2816-double-a-number-represented-as-a-linked-list.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
2845|[Count of Interesting Subarrays](./solutions/2845-count-of-interesting-subarrays.js)|Medium|
diff --git a/solutions/2816-double-a-number-represented-as-a-linked-list.js b/solutions/2816-double-a-number-represented-as-a-linked-list.js
new file mode 100644
index 00000000..d6ef8c24
--- /dev/null
+++ b/solutions/2816-double-a-number-represented-as-a-linked-list.js
@@ -0,0 +1,54 @@
+/**
+ * 2816. Double a Number Represented as a Linked List
+ * https://leetcode.com/problems/double-a-number-represented-as-a-linked-list/
+ * Difficulty: Medium
+ *
+ * You are given the head of a non-empty linked list representing a non-negative integer without
+ * leading zeroes.
+ *
+ * Return the head of the linked list after doubling it.
+ */
+
+/**
+ * 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 doubleIt = function(head) {
+ const reversed = reverseList(head);
+ let carry = 0;
+ let current = reversed;
+ let prev = null;
+
+ while (current) {
+ const doubled = current.val * 2 + carry;
+ current.val = doubled % 10;
+ carry = Math.floor(doubled / 10);
+ prev = current;
+ current = current.next;
+ }
+
+ if (carry) {
+ prev.next = new ListNode(carry);
+ }
+
+ return reverseList(reversed);
+
+ function reverseList(node) {
+ let prev = null;
+ let current = node;
+ while (current) {
+ const next = current.next;
+ current.next = prev;
+ prev = current;
+ current = next;
+ }
+ return prev;
+ }
+};
From b50edf07b922dc3c6780ccce0eaabf5a5e158054 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 2 Jun 2025 22:59:44 -0500
Subject: [PATCH 308/994] Add solution #2824
---
README.md | 1 +
...unt-pairs-whose-sum-is-less-than-target.js | 32 +++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/2824-count-pairs-whose-sum-is-less-than-target.js
diff --git a/README.md b/README.md
index 592e14d3..9c0edf51 100644
--- a/README.md
+++ b/README.md
@@ -2046,6 +2046,7 @@
2815|[Max Pair Sum in an Array](./solutions/2815-max-pair-sum-in-an-array.js)|Easy|
2816|[Double a Number Represented as a Linked List](./solutions/2816-double-a-number-represented-as-a-linked-list.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
+2824|[Count Pairs Whose Sum is Less than Target](./solutions/2824-count-pairs-whose-sum-is-less-than-target.js)|Easy|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
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|
diff --git a/solutions/2824-count-pairs-whose-sum-is-less-than-target.js b/solutions/2824-count-pairs-whose-sum-is-less-than-target.js
new file mode 100644
index 00000000..cdf97867
--- /dev/null
+++ b/solutions/2824-count-pairs-whose-sum-is-less-than-target.js
@@ -0,0 +1,32 @@
+/**
+ * 2824. Count Pairs Whose Sum is Less than Target
+ * https://leetcode.com/problems/count-pairs-whose-sum-is-less-than-target/
+ * Difficulty: Easy
+ *
+ * Given a 0-indexed integer array nums of length n and an integer target, return the number
+ * of pairs (i, j) where 0 <= i < j < n and nums[i] + nums[j] < target.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} target
+ * @return {number}
+ */
+var countPairs = function(nums, target) {
+ let result = 0;
+ let left = 0;
+ let right = nums.length - 1;
+
+ nums.sort((a, b) => a - b);
+
+ while (left < right) {
+ if (nums[left] + nums[right] < target) {
+ result += right - left;
+ left++;
+ } else {
+ right--;
+ }
+ }
+
+ return result;
+};
From eea7b0518c3ce571a67d9269da5e4691fa9683b1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 2 Jun 2025 23:00:45 -0500
Subject: [PATCH 309/994] Add solution #2825
---
README.md | 1 +
...g-a-subsequence-using-cyclic-increments.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/2825-make-string-a-subsequence-using-cyclic-increments.js
diff --git a/README.md b/README.md
index 9c0edf51..f6cf5380 100644
--- a/README.md
+++ b/README.md
@@ -2047,6 +2047,7 @@
2816|[Double a Number Represented as a Linked List](./solutions/2816-double-a-number-represented-as-a-linked-list.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
2824|[Count Pairs Whose Sum is Less than Target](./solutions/2824-count-pairs-whose-sum-is-less-than-target.js)|Easy|
+2825|[Make String a Subsequence Using Cyclic Increments](./solutions/2825-make-string-a-subsequence-using-cyclic-increments.js)|Medium|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
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|
diff --git a/solutions/2825-make-string-a-subsequence-using-cyclic-increments.js b/solutions/2825-make-string-a-subsequence-using-cyclic-increments.js
new file mode 100644
index 00000000..b6b96b8f
--- /dev/null
+++ b/solutions/2825-make-string-a-subsequence-using-cyclic-increments.js
@@ -0,0 +1,39 @@
+/**
+ * 2825. Make String a Subsequence Using Cyclic Increments
+ * https://leetcode.com/problems/make-string-a-subsequence-using-cyclic-increments/
+ * Difficulty: Medium
+ *
+ * You are given two 0-indexed strings str1 and str2.
+ *
+ * In an operation, you select a set of indices in str1, and for each index i in the set,
+ * increment str1[i] to the next character cyclically. That is 'a' becomes 'b', 'b' becomes
+ * 'c', and so on, and 'z' becomes 'a'.
+ *
+ * Return true if it is possible to make str2 a subsequence of str1 by performing the operation
+ * at most once, and false otherwise.
+ *
+ * Note: A subsequence of a string is a new string that is formed from the original string by
+ * deleting some (possibly none) of the characters without disturbing the relative positions
+ * of the remaining characters.
+ */
+
+/**
+ * @param {string} str1
+ * @param {string} str2
+ * @return {boolean}
+ */
+var canMakeSubsequence = function(str1, str2) {
+ let i = 0;
+ let j = 0;
+
+ while (i < str1.length && j < str2.length) {
+ const curr = str1[i].charCodeAt(0);
+ const next = curr === 122 ? 97 : curr + 1;
+ if (str1[i] === str2[j] || String.fromCharCode(next) === str2[j]) {
+ j++;
+ }
+ i++;
+ }
+
+ return j === str2.length;
+};
From 2182403a62c88f888765023b67fa94f9e2b50f09 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 2 Jun 2025 23:01:52 -0500
Subject: [PATCH 310/994] Add solution #2826
---
README.md | 1 +
solutions/2826-sorting-three-groups.js | 34 ++++++++++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/2826-sorting-three-groups.js
diff --git a/README.md b/README.md
index f6cf5380..380e4b77 100644
--- a/README.md
+++ b/README.md
@@ -2048,6 +2048,7 @@
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
2824|[Count Pairs Whose Sum is Less than Target](./solutions/2824-count-pairs-whose-sum-is-less-than-target.js)|Easy|
2825|[Make String a Subsequence Using Cyclic Increments](./solutions/2825-make-string-a-subsequence-using-cyclic-increments.js)|Medium|
+2826|[Sorting Three Groups](./solutions/2826-sorting-three-groups.js)|Medium|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
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|
diff --git a/solutions/2826-sorting-three-groups.js b/solutions/2826-sorting-three-groups.js
new file mode 100644
index 00000000..0153b199
--- /dev/null
+++ b/solutions/2826-sorting-three-groups.js
@@ -0,0 +1,34 @@
+/**
+ * 2826. Sorting Three Groups
+ * https://leetcode.com/problems/sorting-three-groups/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums. Each element in nums is 1, 2 or 3. In each operation,
+ * you can remove an element from nums. Return the minimum number of operations to make nums
+ * non-decreasing.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimumOperations = function(nums) {
+ const n = nums.length;
+ const dp = new Array(n + 1).fill(0).map(() => new Array(4).fill(Infinity));
+ dp[0][0] = 0;
+
+ for (let i = 0; i < n; i++) {
+ for (let prev = 0; prev <= 3; prev++) {
+ for (let curr = 1; curr <= 3; curr++) {
+ if (curr >= prev) {
+ dp[i + 1][curr] = Math.min(
+ dp[i + 1][curr],
+ dp[i][prev] + (nums[i] === curr ? 0 : 1)
+ );
+ }
+ }
+ }
+ }
+
+ return Math.min(...dp[n].slice(1));
+};
From 76477ff191df170d905b32bb917d7ed8d10df4cb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 22:27:32 -0500
Subject: [PATCH 311/994] Add solution #3403
---
README.md | 1 +
...aphically-largest-string-from-the-box-i.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/3403-find-the-lexicographically-largest-string-from-the-box-i.js
diff --git a/README.md b/README.md
index 380e4b77..61b2169a 100644
--- a/README.md
+++ b/README.md
@@ -2096,6 +2096,7 @@
3396|[Minimum Number of Operations to Make Elements in Array Distinct](./solutions/3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy|
3397|[Maximum Number of Distinct Elements After Operations](./solutions/3397-maximum-number-of-distinct-elements-after-operations.js)|Medium|
3402|[Minimum Operations to Make Columns Strictly Increasing](./solutions/3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy|
+3403|[Find the Lexicographically Largest String From the Box I](./solutions/3403-find-the-lexicographically-largest-string-from-the-box-i.js)|Medium|
3452|[Sum of Good Numbers](./solutions/3452-sum-of-good-numbers.js)|Easy|
3461|[Check If Digits Are Equal in String After Operations I](./solutions/3461-check-if-digits-are-equal-in-string-after-operations-i.js)|Easy|
3462|[Maximum Sum With at Most K Elements](./solutions/3462-maximum-sum-with-at-most-k-elements.js)|Medium|
diff --git a/solutions/3403-find-the-lexicographically-largest-string-from-the-box-i.js b/solutions/3403-find-the-lexicographically-largest-string-from-the-box-i.js
new file mode 100644
index 00000000..313bc4c7
--- /dev/null
+++ b/solutions/3403-find-the-lexicographically-largest-string-from-the-box-i.js
@@ -0,0 +1,39 @@
+/**
+ * 3403. Find the Lexicographically Largest String From the Box I
+ * https://leetcode.com/problems/find-the-lexicographically-largest-string-from-the-box-i/
+ * Difficulty: Medium
+ *
+ * You are given a string word, and an integer numFriends.
+ *
+ * Alice is organizing a game for her numFriends friends. There are multiple rounds in the game,
+ * where in each round:
+ * - word is split into numFriends non-empty strings, such that no previous round has had the
+ * exact same split.
+ * - All the split words are put into a box.
+ *
+ * Find the lexicographically largest string from the box after all the rounds are finished.
+ */
+
+/**
+ * @param {string} word
+ * @param {number} numFriends
+ * @return {string}
+ */
+var answerString = function(word, numFriends) {
+ if (numFriends === 1) return word;
+
+ let result = '';
+ const wordLength = word.length;
+
+ for (let startIndex = 0; startIndex < wordLength; startIndex++) {
+ const maxLength = wordLength - numFriends + 1;
+ const endIndex = Math.min(startIndex + maxLength, wordLength);
+ const substring = word.slice(startIndex, endIndex);
+
+ if (substring > result) {
+ result = substring;
+ }
+ }
+
+ return result;
+};
From 56525e804d5f3614c4b0ec4456c5d3ffe05f45e5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 22:29:08 -0500
Subject: [PATCH 312/994] Add solution #2828
---
README.md | 1 +
...heck-if-a-string-is-an-acronym-of-words.js | 23 +++++++++++++++++++
2 files changed, 24 insertions(+)
create mode 100644 solutions/2828-check-if-a-string-is-an-acronym-of-words.js
diff --git a/README.md b/README.md
index 61b2169a..bc76bd68 100644
--- a/README.md
+++ b/README.md
@@ -2049,6 +2049,7 @@
2824|[Count Pairs Whose Sum is Less than Target](./solutions/2824-count-pairs-whose-sum-is-less-than-target.js)|Easy|
2825|[Make String a Subsequence Using Cyclic Increments](./solutions/2825-make-string-a-subsequence-using-cyclic-increments.js)|Medium|
2826|[Sorting Three Groups](./solutions/2826-sorting-three-groups.js)|Medium|
+2828|[Check if a String Is an Acronym of Words](./solutions/2828-check-if-a-string-is-an-acronym-of-words.js)|Easy|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
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|
diff --git a/solutions/2828-check-if-a-string-is-an-acronym-of-words.js b/solutions/2828-check-if-a-string-is-an-acronym-of-words.js
new file mode 100644
index 00000000..c0b34517
--- /dev/null
+++ b/solutions/2828-check-if-a-string-is-an-acronym-of-words.js
@@ -0,0 +1,23 @@
+/**
+ * 2828. Check if a String Is an Acronym of Words
+ * https://leetcode.com/problems/check-if-a-string-is-an-acronym-of-words/
+ * Difficulty: Easy
+ *
+ * Given an array of strings words and a string s, determine if s is an acronym of words.
+ *
+ * The string s is considered an acronym of words if it can be formed by concatenating the
+ * first character of each string in words in order. For example, "ab" can be formed from
+ * ["apple", "banana"], but it can't be formed from ["bear", "aardvark"].
+ *
+ * Return true if s is an acronym of words, and false otherwise.
+ */
+
+/**
+ * @param {string[]} words
+ * @param {string} s
+ * @return {boolean}
+ */
+var isAcronym = function(words, s) {
+ if (words.length !== s.length) return false;
+ return words.every((word, index) => word[0] === s[index]);
+};
From fe97e998f15f83a05516fe1e113ff03123ae25fb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 22:30:37 -0500
Subject: [PATCH 313/994] Add solution #2829
---
README.md | 1 +
...e-the-minimum-sum-of-a-k-avoiding-array.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/2829-determine-the-minimum-sum-of-a-k-avoiding-array.js
diff --git a/README.md b/README.md
index bc76bd68..0cfbb2e9 100644
--- a/README.md
+++ b/README.md
@@ -2050,6 +2050,7 @@
2825|[Make String a Subsequence Using Cyclic Increments](./solutions/2825-make-string-a-subsequence-using-cyclic-increments.js)|Medium|
2826|[Sorting Three Groups](./solutions/2826-sorting-three-groups.js)|Medium|
2828|[Check if a String Is an Acronym of Words](./solutions/2828-check-if-a-string-is-an-acronym-of-words.js)|Easy|
+2829|[Determine the Minimum Sum of a k-avoiding Array](./solutions/2829-determine-the-minimum-sum-of-a-k-avoiding-array.js)|Medium|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
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|
diff --git a/solutions/2829-determine-the-minimum-sum-of-a-k-avoiding-array.js b/solutions/2829-determine-the-minimum-sum-of-a-k-avoiding-array.js
new file mode 100644
index 00000000..540df710
--- /dev/null
+++ b/solutions/2829-determine-the-minimum-sum-of-a-k-avoiding-array.js
@@ -0,0 +1,34 @@
+/**
+ * 2829. Determine the Minimum Sum of a k-avoiding Array
+ * https://leetcode.com/problems/determine-the-minimum-sum-of-a-k-avoiding-array/
+ * Difficulty: Medium
+ *
+ * You are given two integers, n and k.
+ *
+ * An array of distinct positive integers is called a k-avoiding array if there does not exist
+ * any pair of distinct elements that sum to k.
+ *
+ * Return the minimum possible sum of a k-avoiding array of length n.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} k
+ * @return {number}
+ */
+var minimumSum = function(n, k) {
+ const set = new Set();
+ let result = 0;
+ let num = 1;
+
+ for (let i = 0; i < n; i++) {
+ while (set.has(k - num)) {
+ num++;
+ }
+ result += num;
+ set.add(num);
+ num++;
+ }
+
+ return result;
+};
From 30ebd04632c332ceabe04ce5b5d7ef1d9fae3104 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 22:31:46 -0500
Subject: [PATCH 314/994] Add solution #2833
---
README.md | 1 +
solutions/2833-furthest-point-from-origin.js | 32 ++++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/2833-furthest-point-from-origin.js
diff --git a/README.md b/README.md
index 0cfbb2e9..7f17a029 100644
--- a/README.md
+++ b/README.md
@@ -2051,6 +2051,7 @@
2826|[Sorting Three Groups](./solutions/2826-sorting-three-groups.js)|Medium|
2828|[Check if a String Is an Acronym of Words](./solutions/2828-check-if-a-string-is-an-acronym-of-words.js)|Easy|
2829|[Determine the Minimum Sum of a k-avoiding Array](./solutions/2829-determine-the-minimum-sum-of-a-k-avoiding-array.js)|Medium|
+2833|[Furthest Point From Origin](./solutions/2833-furthest-point-from-origin.js)|Easy|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
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|
diff --git a/solutions/2833-furthest-point-from-origin.js b/solutions/2833-furthest-point-from-origin.js
new file mode 100644
index 00000000..0428216f
--- /dev/null
+++ b/solutions/2833-furthest-point-from-origin.js
@@ -0,0 +1,32 @@
+/**
+ * 2833. Furthest Point From Origin
+ * https://leetcode.com/problems/furthest-point-from-origin/
+ * Difficulty: Easy
+ *
+ * You are given a string moves of length n consisting only of characters 'L', 'R', and '_'.
+ * The string represents your movement on a number line starting from the origin 0.
+ *
+ * In the ith move, you can choose one of the following directions:
+ * - move to the left if moves[i] = 'L' or moves[i] = '_'
+ * - move to the right if moves[i] = 'R' or moves[i] = '_'
+ *
+ * Return the distance from the origin of the furthest point you can get to after n moves.
+ */
+
+/**
+ * @param {string} moves
+ * @return {number}
+ */
+var furthestDistanceFromOrigin = function(moves) {
+ let leftCount = 0;
+ let rightCount = 0;
+ let wildCount = 0;
+
+ for (const move of moves) {
+ if (move === 'L') leftCount++;
+ else if (move === 'R') rightCount++;
+ else wildCount++;
+ }
+
+ return Math.abs(leftCount - rightCount) + wildCount;
+};
From 8f31a0f5460ece01eae771730da7ef062564ef28 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 22:34:11 -0500
Subject: [PATCH 315/994] Add solution #2839
---
README.md | 1 +
...ngs-can-be-made-equal-with-operations-i.js | 25 +++++++++++++++++++
2 files changed, 26 insertions(+)
create mode 100644 solutions/2839-check-if-strings-can-be-made-equal-with-operations-i.js
diff --git a/README.md b/README.md
index 7f17a029..ea66a521 100644
--- a/README.md
+++ b/README.md
@@ -2052,6 +2052,7 @@
2828|[Check if a String Is an Acronym of Words](./solutions/2828-check-if-a-string-is-an-acronym-of-words.js)|Easy|
2829|[Determine the Minimum Sum of a k-avoiding Array](./solutions/2829-determine-the-minimum-sum-of-a-k-avoiding-array.js)|Medium|
2833|[Furthest Point From Origin](./solutions/2833-furthest-point-from-origin.js)|Easy|
+2839|[Check if Strings Can be Made Equal With Operations I](./solutions/2839-check-if-strings-can-be-made-equal-with-operations-i.js)|Easy|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
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|
diff --git a/solutions/2839-check-if-strings-can-be-made-equal-with-operations-i.js b/solutions/2839-check-if-strings-can-be-made-equal-with-operations-i.js
new file mode 100644
index 00000000..3eb6dfcb
--- /dev/null
+++ b/solutions/2839-check-if-strings-can-be-made-equal-with-operations-i.js
@@ -0,0 +1,25 @@
+/**
+ * 2839. Check if Strings Can be Made Equal With Operations I
+ * https://leetcode.com/problems/check-if-strings-can-be-made-equal-with-operations-i/
+ * Difficulty: Easy
+ *
+ * You are given two strings s1 and s2, both of length 4, consisting of lowercase English
+ * letters.
+ *
+ * You can apply the following operation on any of the two strings any number of times:
+ * - Choose any two indices i and j such that j - i = 2, then swap the two characters at those
+ * indices in the string.
+ *
+ * Return true if you can make the strings s1 and s2 equal, and false otherwise.
+ */
+
+/**
+ * @param {string} s1
+ * @param {string} s2
+ * @return {boolean}
+ */
+var canBeEqual = function(s1, s2) {
+ const firstPair = [s1[0], s1[2]].sort().join() === [s2[0], s2[2]].sort().join();
+ const secondPair = [s1[1], s1[3]].sort().join() === [s2[1], s2[3]].sort().join();
+ return firstPair && secondPair;
+};
From ba5f8ff3b9dc0f12b9e183007670118ba2eae7d3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 22:37:44 -0500
Subject: [PATCH 316/994] Add solution #2840
---
README.md | 1 +
...gs-can-be-made-equal-with-operations-ii.js | 38 +++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2840-check-if-strings-can-be-made-equal-with-operations-ii.js
diff --git a/README.md b/README.md
index ea66a521..a139cad0 100644
--- a/README.md
+++ b/README.md
@@ -2053,6 +2053,7 @@
2829|[Determine the Minimum Sum of a k-avoiding Array](./solutions/2829-determine-the-minimum-sum-of-a-k-avoiding-array.js)|Medium|
2833|[Furthest Point From Origin](./solutions/2833-furthest-point-from-origin.js)|Easy|
2839|[Check if Strings Can be Made Equal With Operations I](./solutions/2839-check-if-strings-can-be-made-equal-with-operations-i.js)|Easy|
+2840|[Check if Strings Can be Made Equal With Operations II](./solutions/2840-check-if-strings-can-be-made-equal-with-operations-ii.js)|Medium|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
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|
diff --git a/solutions/2840-check-if-strings-can-be-made-equal-with-operations-ii.js b/solutions/2840-check-if-strings-can-be-made-equal-with-operations-ii.js
new file mode 100644
index 00000000..28a8805e
--- /dev/null
+++ b/solutions/2840-check-if-strings-can-be-made-equal-with-operations-ii.js
@@ -0,0 +1,38 @@
+/**
+ * 2840. Check if Strings Can be Made Equal With Operations II
+ * https://leetcode.com/problems/check-if-strings-can-be-made-equal-with-operations-ii/
+ * Difficulty: Medium
+ *
+ * You are given two strings s1 and s2, both of length n, consisting of lowercase English letters.
+ *
+ * You can apply the following operation on any of the two strings any number of times:
+ * - Choose any two indices i and j such that i < j and the difference j - i is even, then swap the
+ * two characters at those indices in the string.
+ *
+ * Return true if you can make the strings s1 and s2 equal, and false otherwise.
+ */
+
+/**
+ * @param {string} s1
+ * @param {string} s2
+ * @return {boolean}
+ */
+var checkStrings = function(s1, s2) {
+ const evenChars1 = [];
+ const oddChars1 = [];
+ const evenChars2 = [];
+ const oddChars2 = [];
+
+ for (let i = 0; i < s1.length; i++) {
+ if (i % 2 === 0) {
+ evenChars1.push(s1[i]);
+ evenChars2.push(s2[i]);
+ } else {
+ oddChars1.push(s1[i]);
+ oddChars2.push(s2[i]);
+ }
+ }
+
+ return evenChars1.sort().join('') === evenChars2.sort().join('')
+ && oddChars1.sort().join('') === oddChars2.sort().join('');
+};
From f0060e7d874e30d06125474de3ffc18b8d5af05d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 22:40:31 -0500
Subject: [PATCH 317/994] Add solution #2846
---
README.md | 1 +
...ge-weight-equilibrium-queries-in-a-tree.js | 77 +++++++++++++++++++
2 files changed, 78 insertions(+)
create mode 100644 solutions/2846-minimum-edge-weight-equilibrium-queries-in-a-tree.js
diff --git a/README.md b/README.md
index a139cad0..3df9ef47 100644
--- a/README.md
+++ b/README.md
@@ -2056,6 +2056,7 @@
2840|[Check if Strings Can be Made Equal With Operations II](./solutions/2840-check-if-strings-can-be-made-equal-with-operations-ii.js)|Medium|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
2845|[Count of Interesting Subarrays](./solutions/2845-count-of-interesting-subarrays.js)|Medium|
+2846|[Minimum Edge Weight Equilibrium Queries in a Tree](./solutions/2846-minimum-edge-weight-equilibrium-queries-in-a-tree.js)|Hard|
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|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
diff --git a/solutions/2846-minimum-edge-weight-equilibrium-queries-in-a-tree.js b/solutions/2846-minimum-edge-weight-equilibrium-queries-in-a-tree.js
new file mode 100644
index 00000000..87c0f17c
--- /dev/null
+++ b/solutions/2846-minimum-edge-weight-equilibrium-queries-in-a-tree.js
@@ -0,0 +1,77 @@
+/**
+ * 2846. Minimum Edge Weight Equilibrium Queries in a Tree
+ * https://leetcode.com/problems/minimum-edge-weight-equilibrium-queries-in-a-tree/
+ * Difficulty: Hard
+ *
+ * There is an undirected tree with n nodes labeled from 0 to n - 1. You are given the integer n and
+ * a 2D integer array edges of length n - 1, where edges[i] = [ui, vi, wi] indicates that there is
+ * an edge between nodes ui and vi with weight wi in the tree.
+ *
+ * You are also given a 2D integer array queries of length m, where queries[i] = [ai, bi]. For each
+ * query, find the minimum number of operations required to make the weight of every edge on the
+ * path from ai to bi equal. In one operation, you can choose any edge of the tree and change its
+ * weight to any value.
+ *
+ * Note that:
+ * - Queries are independent of each other, meaning that the tree returns to its initial state on
+ * each new query.
+ * - The path from ai to bi is a sequence of distinct nodes starting with node ai and ending with
+ * node bi such that every two adjacent nodes in the sequence share an edge in the tree.
+ *
+ * Return an array answer of length m where answer[i] is the answer to the ith query.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @param {number[][]} queries
+ * @return {number[]}
+ */
+var minOperationsQueries = function(n, edges, queries) {
+ const graph = Array.from({ length: n }, () => []);
+ for (const [u, v, w] of edges) {
+ graph[u].push([v, w]);
+ graph[v].push([u, w]);
+ }
+
+ const parent = new Array(n).fill(-1);
+ const weightCount = new Array(n).fill().map(() => new Array(27).fill(0));
+ const depth = new Array(n).fill(0);
+
+ dfs(0, -1, 0);
+
+ const result = [];
+ for (const [u, v] of queries) {
+ const ancestor = lca(u, v);
+ const counts = Array(27).fill(0);
+ for (let i = 1; i <= 26; i++) {
+ counts[i] = weightCount[u][i] + weightCount[v][i] - 2 * weightCount[ancestor][i];
+ }
+ const total = depth[u] + depth[v] - 2 * depth[ancestor];
+ const maxCount = Math.max(...counts);
+ result.push(total - maxCount);
+ }
+
+ return result;
+
+ function dfs(node, par, dep) {
+ parent[node] = par;
+ depth[node] = dep;
+ for (const [next, w] of graph[node]) {
+ if (next !== par) {
+ weightCount[next] = [...weightCount[node]];
+ weightCount[next][w]++;
+ dfs(next, node, dep + 1);
+ }
+ }
+ }
+ function lca(u, v) {
+ if (depth[u] < depth[v]) [u, v] = [v, u];
+ while (depth[u] > depth[v]) u = parent[u];
+ while (u !== v) {
+ u = parent[u];
+ v = parent[v];
+ }
+ return u;
+ }
+};
From e771f7b9eb401ad00a2ccade4a178c2de0c4a7f0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 22:41:25 -0500
Subject: [PATCH 318/994] Add solution #2848
---
README.md | 1 +
.../2848-points-that-intersect-with-cars.js | 27 +++++++++++++++++++
2 files changed, 28 insertions(+)
create mode 100644 solutions/2848-points-that-intersect-with-cars.js
diff --git a/README.md b/README.md
index 3df9ef47..a42458bc 100644
--- a/README.md
+++ b/README.md
@@ -2057,6 +2057,7 @@
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
2845|[Count of Interesting Subarrays](./solutions/2845-count-of-interesting-subarrays.js)|Medium|
2846|[Minimum Edge Weight Equilibrium Queries in a Tree](./solutions/2846-minimum-edge-weight-equilibrium-queries-in-a-tree.js)|Hard|
+2848|[Points That Intersect With Cars](./solutions/2848-points-that-intersect-with-cars.js)|Easy|
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|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
diff --git a/solutions/2848-points-that-intersect-with-cars.js b/solutions/2848-points-that-intersect-with-cars.js
new file mode 100644
index 00000000..fc4f58de
--- /dev/null
+++ b/solutions/2848-points-that-intersect-with-cars.js
@@ -0,0 +1,27 @@
+/**
+ * 2848. Points That Intersect With Cars
+ * https://leetcode.com/problems/points-that-intersect-with-cars/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed 2D integer array nums representing the coordinates of the cars
+ * parking on a number line. For any index i, nums[i] = [starti, endi] where starti is the
+ * starting point of the ith car and endi is the ending point of the ith car.
+ *
+ * Return the number of integer points on the line that are covered with any part of a car.
+ */
+
+/**
+ * @param {number[][]} nums
+ * @return {number}
+ */
+var numberOfPoints = function(nums) {
+ const set = new Set();
+
+ for (const [start, end] of nums) {
+ for (let i = start; i <= end; i++) {
+ set.add(i);
+ }
+ }
+
+ return set.size;
+};
From 014542ebf7a0cda334dab65517187159cbe16704 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 22:43:18 -0500
Subject: [PATCH 319/994] Add solution #2850
---
README.md | 1 +
...inimum-moves-to-spread-stones-over-grid.js | 59 +++++++++++++++++++
2 files changed, 60 insertions(+)
create mode 100644 solutions/2850-minimum-moves-to-spread-stones-over-grid.js
diff --git a/README.md b/README.md
index a42458bc..97b24c98 100644
--- a/README.md
+++ b/README.md
@@ -2058,6 +2058,7 @@
2845|[Count of Interesting Subarrays](./solutions/2845-count-of-interesting-subarrays.js)|Medium|
2846|[Minimum Edge Weight Equilibrium Queries in a Tree](./solutions/2846-minimum-edge-weight-equilibrium-queries-in-a-tree.js)|Hard|
2848|[Points That Intersect With Cars](./solutions/2848-points-that-intersect-with-cars.js)|Easy|
+2850|[Minimum Moves to Spread Stones Over Grid](./solutions/2850-minimum-moves-to-spread-stones-over-grid.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|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
diff --git a/solutions/2850-minimum-moves-to-spread-stones-over-grid.js b/solutions/2850-minimum-moves-to-spread-stones-over-grid.js
new file mode 100644
index 00000000..b56e1393
--- /dev/null
+++ b/solutions/2850-minimum-moves-to-spread-stones-over-grid.js
@@ -0,0 +1,59 @@
+/**
+ * 2850. Minimum Moves to Spread Stones Over Grid
+ * https://leetcode.com/problems/minimum-moves-to-spread-stones-over-grid/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed 2D integer matrix grid of size 3 * 3, representing the number of
+ * stones in each cell. The grid contains exactly 9 stones, and there can be multiple stones
+ * in a single cell.
+ *
+ * In one move, you can move a single stone from its current cell to any other cell if the two
+ * cells share a side.
+ *
+ * Return the minimum number of moves required to place one stone in each cell.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var minimumMoves = function(grid) {
+ const sources = [];
+ const targets = [];
+
+ for (let i = 0; i < 3; i++) {
+ for (let j = 0; j < 3; j++) {
+ if (grid[i][j] > 1) {
+ for (let k = 1; k < grid[i][j]; k++) {
+ sources.push([i, j]);
+ }
+ } else if (grid[i][j] === 0) {
+ targets.push([i, j]);
+ }
+ }
+ }
+
+ let minMoves = Infinity;
+
+ permute(0, 0);
+ return minMoves;
+
+ function permute(index, moves) {
+ if (index === sources.length) {
+ minMoves = Math.min(minMoves, moves);
+ return;
+ }
+
+ for (let i = 0; i < targets.length; i++) {
+ if (targets[i]) {
+ const [si, sj] = sources[index];
+ const [ti, tj] = targets[i];
+ const dist = Math.abs(si - ti) + Math.abs(sj - tj);
+ const temp = targets[i];
+ targets[i] = null;
+ permute(index + 1, moves + dist);
+ targets[i] = temp;
+ }
+ }
+ }
+};
From dc63ca29ffd0410ce9b893bc6adf95e803be7c2a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 22:44:31 -0500
Subject: [PATCH 320/994] Add solution #2855
---
README.md | 1 +
...-minimum-right-shifts-to-sort-the-array.js | 33 +++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/2855-minimum-right-shifts-to-sort-the-array.js
diff --git a/README.md b/README.md
index 97b24c98..2bbf7f90 100644
--- a/README.md
+++ b/README.md
@@ -2059,6 +2059,7 @@
2846|[Minimum Edge Weight Equilibrium Queries in a Tree](./solutions/2846-minimum-edge-weight-equilibrium-queries-in-a-tree.js)|Hard|
2848|[Points That Intersect With Cars](./solutions/2848-points-that-intersect-with-cars.js)|Easy|
2850|[Minimum Moves to Spread Stones Over Grid](./solutions/2850-minimum-moves-to-spread-stones-over-grid.js)|Medium|
+2855|[Minimum Right Shifts to Sort the Array](./solutions/2855-minimum-right-shifts-to-sort-the-array.js)|Easy|
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|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
diff --git a/solutions/2855-minimum-right-shifts-to-sort-the-array.js b/solutions/2855-minimum-right-shifts-to-sort-the-array.js
new file mode 100644
index 00000000..9bf69806
--- /dev/null
+++ b/solutions/2855-minimum-right-shifts-to-sort-the-array.js
@@ -0,0 +1,33 @@
+/**
+ * 2855. Minimum Right Shifts to Sort the Array
+ * https://leetcode.com/problems/minimum-right-shifts-to-sort-the-array/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed array nums of length n containing distinct positive integers.
+ * Return the minimum number of right shifts required to sort nums and -1 if this is not
+ * possible.
+ *
+ * A right shift is defined as shifting the element at index i to index (i + 1) % n, for
+ * all indices.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimumRightShifts = function(nums) {
+ const n = nums.length;
+ let breakPoint = 0;
+
+ for (let i = 1; i < n; i++) {
+ if (nums[i] < nums[i - 1]) {
+ breakPoint++;
+ if (breakPoint > 1) return -1;
+ }
+ }
+
+ if (breakPoint === 0) return 0;
+ if (nums[n - 1] > nums[0]) return -1;
+
+ return n - (nums.indexOf(Math.min(...nums)));
+};
From 5c5c0c039fea0d14333afc99cc8fcf39e6362e9f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 23:02:48 -0500
Subject: [PATCH 321/994] Add solution #2858
---
README.md | 1 +
...ge-reversals-so-every-node-is-reachable.js | 62 +++++++++++++++++++
2 files changed, 63 insertions(+)
create mode 100644 solutions/2858-minimum-edge-reversals-so-every-node-is-reachable.js
diff --git a/README.md b/README.md
index 2bbf7f90..5a3b10ab 100644
--- a/README.md
+++ b/README.md
@@ -2060,6 +2060,7 @@
2848|[Points That Intersect With Cars](./solutions/2848-points-that-intersect-with-cars.js)|Easy|
2850|[Minimum Moves to Spread Stones Over Grid](./solutions/2850-minimum-moves-to-spread-stones-over-grid.js)|Medium|
2855|[Minimum Right Shifts to Sort the Array](./solutions/2855-minimum-right-shifts-to-sort-the-array.js)|Easy|
+2858|[Minimum Edge Reversals So Every Node Is Reachable](./solutions/2858-minimum-edge-reversals-so-every-node-is-reachable.js)|Hard|
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|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
diff --git a/solutions/2858-minimum-edge-reversals-so-every-node-is-reachable.js b/solutions/2858-minimum-edge-reversals-so-every-node-is-reachable.js
new file mode 100644
index 00000000..dc7b451a
--- /dev/null
+++ b/solutions/2858-minimum-edge-reversals-so-every-node-is-reachable.js
@@ -0,0 +1,62 @@
+/**
+ * 2858. Minimum Edge Reversals So Every Node Is Reachable
+ * https://leetcode.com/problems/minimum-edge-reversals-so-every-node-is-reachable/
+ * Difficulty: Hard
+ *
+ * There is a simple directed graph with n nodes labeled from 0 to n - 1. The graph would form
+ * a tree if its edges were bi-directional.
+ *
+ * You are given an integer n and a 2D integer array edges, where edges[i] = [ui, vi] represents
+ * a directed edge going from node ui to node vi.
+ *
+ * An edge reversal changes the direction of an edge, i.e., a directed edge going from node ui to
+ * node vi becomes a directed edge going from node vi to node ui.
+ *
+ * For every node i in the range [0, n - 1], your task is to independently calculate the minimum
+ * number of edge reversals required so it is possible to reach any other node starting from node
+ * i through a sequence of directed edges.
+ *
+ * Return an integer array answer, where answer[i] is the minimum number of edge reversals required
+ * so it is possible to reach any other node starting from node i through a sequence of directed
+ * edges.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @return {number[]}
+ */
+var minEdgeReversals = function(n, edges) {
+ const graph = Array.from({ length: n }, () => []);
+
+ for (const [u, v] of edges) {
+ graph[u].push([v, 0]);
+ graph[v].push([u, 1]);
+ }
+
+ const result = new Array(n);
+ const rootReversals = dfs(0, -1);
+
+ reroot(0, -1, rootReversals);
+
+ return result;
+ function dfs(node, parent) {
+ let reversals = 0;
+ for (const [neighbor, cost] of graph[node]) {
+ if (neighbor !== parent) {
+ reversals += cost + dfs(neighbor, node);
+ }
+ }
+ return reversals;
+ }
+
+ function reroot(node, parent, parentReversals) {
+ result[node] = parentReversals;
+ for (const [neighbor, cost] of graph[node]) {
+ if (neighbor !== parent) {
+ const childReversals = result[node] - cost + (1 - cost);
+ reroot(neighbor, node, childReversals);
+ }
+ }
+ }
+};
From 14de16569690e78238aeb72b867b08560b676376 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 23:04:02 -0500
Subject: [PATCH 322/994] Add solution #2859
---
README.md | 1 +
...um-of-values-at-indices-with-k-set-bits.js | 31 +++++++++++++++++++
2 files changed, 32 insertions(+)
create mode 100644 solutions/2859-sum-of-values-at-indices-with-k-set-bits.js
diff --git a/README.md b/README.md
index 5a3b10ab..24d4eeb3 100644
--- a/README.md
+++ b/README.md
@@ -2061,6 +2061,7 @@
2850|[Minimum Moves to Spread Stones Over Grid](./solutions/2850-minimum-moves-to-spread-stones-over-grid.js)|Medium|
2855|[Minimum Right Shifts to Sort the Array](./solutions/2855-minimum-right-shifts-to-sort-the-array.js)|Easy|
2858|[Minimum Edge Reversals So Every Node Is Reachable](./solutions/2858-minimum-edge-reversals-so-every-node-is-reachable.js)|Hard|
+2859|[Sum of Values at Indices With K Set Bits](./solutions/2859-sum-of-values-at-indices-with-k-set-bits.js)|Easy|
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|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
diff --git a/solutions/2859-sum-of-values-at-indices-with-k-set-bits.js b/solutions/2859-sum-of-values-at-indices-with-k-set-bits.js
new file mode 100644
index 00000000..c14b88d3
--- /dev/null
+++ b/solutions/2859-sum-of-values-at-indices-with-k-set-bits.js
@@ -0,0 +1,31 @@
+/**
+ * 2859. Sum of Values at Indices With K Set Bits
+ * https://leetcode.com/problems/sum-of-values-at-indices-with-k-set-bits/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums and an integer k.
+ *
+ * Return an integer that denotes the sum of elements in nums whose corresponding indices have
+ * exactly k set bits in their binary representation.
+ *
+ * The set bits in an integer are the 1's present when it is written in binary.
+ *
+ * For example, the binary representation of 21 is 10101, which has 3 set bits.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var sumIndicesWithKSetBits = function(nums, k) {
+ let result = 0;
+
+ for (let i = 0; i < nums.length; i++) {
+ if (i.toString(2).split('1').length - 1 === k) {
+ result += nums[i];
+ }
+ }
+
+ return result;
+};
From 1298166f30473b14c0aaa8ba85d3299440f2ded5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 23:05:27 -0500
Subject: [PATCH 323/994] Add solution #2860
---
README.md | 1 +
solutions/2860-happy-students.js | 38 ++++++++++++++++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2860-happy-students.js
diff --git a/README.md b/README.md
index 24d4eeb3..7822099b 100644
--- a/README.md
+++ b/README.md
@@ -2062,6 +2062,7 @@
2855|[Minimum Right Shifts to Sort the Array](./solutions/2855-minimum-right-shifts-to-sort-the-array.js)|Easy|
2858|[Minimum Edge Reversals So Every Node Is Reachable](./solutions/2858-minimum-edge-reversals-so-every-node-is-reachable.js)|Hard|
2859|[Sum of Values at Indices With K Set Bits](./solutions/2859-sum-of-values-at-indices-with-k-set-bits.js)|Easy|
+2860|[Happy Students](./solutions/2860-happy-students.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|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
diff --git a/solutions/2860-happy-students.js b/solutions/2860-happy-students.js
new file mode 100644
index 00000000..460015b2
--- /dev/null
+++ b/solutions/2860-happy-students.js
@@ -0,0 +1,38 @@
+/**
+ * 2860. Happy Students
+ * https://leetcode.com/problems/happy-students/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums of length n where n is the total number of
+ * students in the class. The class teacher tries to select a group of students so that
+ * all the students remain happy.
+ *
+ * The ith student will become happy if one of these two conditions is met:
+ * - The student is selected and the total number of selected students is strictly greater
+ * than nums[i].
+ * - The student is not selected and the total number of selected students is strictly less
+ * than nums[i].
+ *
+ * Return the number of ways to select a group of students so that everyone remains happy.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var countWays = function(nums) {
+ nums.sort((a, b) => a - b);
+ let result = 0;
+ let selected = 0;
+
+ if (0 < nums[0]) result++;
+
+ for (let i = 0; i < nums.length; i++) {
+ selected++;
+ if (selected > nums[i] && (i + 1 === nums.length || selected < nums[i + 1])) {
+ result++;
+ }
+ }
+
+ return result;
+};
From 6f1d2a364dfd66b073d9e5ea84a3d3d27c86b7f4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 23:06:38 -0500
Subject: [PATCH 324/994] Add solution #2862
---
README.md | 1 +
...ent-sum-of-a-complete-subset-of-indices.js | 46 +++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/2862-maximum-element-sum-of-a-complete-subset-of-indices.js
diff --git a/README.md b/README.md
index 7822099b..23f94888 100644
--- a/README.md
+++ b/README.md
@@ -2063,6 +2063,7 @@
2858|[Minimum Edge Reversals So Every Node Is Reachable](./solutions/2858-minimum-edge-reversals-so-every-node-is-reachable.js)|Hard|
2859|[Sum of Values at Indices With K Set Bits](./solutions/2859-sum-of-values-at-indices-with-k-set-bits.js)|Easy|
2860|[Happy Students](./solutions/2860-happy-students.js)|Medium|
+2862|[Maximum Element-Sum of a Complete Subset of Indices](./solutions/2862-maximum-element-sum-of-a-complete-subset-of-indices.js)|Hard|
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|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
diff --git a/solutions/2862-maximum-element-sum-of-a-complete-subset-of-indices.js b/solutions/2862-maximum-element-sum-of-a-complete-subset-of-indices.js
new file mode 100644
index 00000000..33a8aa2d
--- /dev/null
+++ b/solutions/2862-maximum-element-sum-of-a-complete-subset-of-indices.js
@@ -0,0 +1,46 @@
+/**
+ * 2862. Maximum Element-Sum of a Complete Subset of Indices
+ * https://leetcode.com/problems/maximum-element-sum-of-a-complete-subset-of-indices/
+ * Difficulty: Hard
+ *
+ * You are given a 1-indexed array nums. Your task is to select a complete subset from nums where
+ * every pair of selected indices multiplied is a perfect square,. i. e. if you select ai and aj,
+ * i * j must be a perfect square.
+ *
+ * Return the sum of the complete subset with the maximum sum.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maximumSum = function(nums) {
+ const n = nums.length;
+ const map = new Map();
+
+ for (let i = 1; i <= n; i++) {
+ let factors = 1;
+ let num = i;
+
+ for (let p = 2; p * p <= num; p++) {
+ let count = 0;
+ while (num % p === 0) {
+ count++;
+ num /= p;
+ }
+ if (count % 2 === 1) factors *= p;
+ }
+ if (num > 1) factors *= num;
+
+ if (!map.has(factors)) map.set(factors, []);
+ map.get(factors).push(nums[i - 1]);
+ }
+
+ let result = 0;
+ for (const group of map.values()) {
+ const sum = group.reduce((a, b) => a + b, 0);
+ result = Math.max(result, sum);
+ }
+
+ return result;
+};
From 1e3c8f6ac4aedec67efe3d6448e536460cd3e542 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 23:08:45 -0500
Subject: [PATCH 325/994] Add solution #2864
---
README.md | 1 +
solutions/2864-maximum-odd-binary-number.js | 27 +++++++++++++++++++++
2 files changed, 28 insertions(+)
create mode 100644 solutions/2864-maximum-odd-binary-number.js
diff --git a/README.md b/README.md
index 23f94888..fcb4a12d 100644
--- a/README.md
+++ b/README.md
@@ -2064,6 +2064,7 @@
2859|[Sum of Values at Indices With K Set Bits](./solutions/2859-sum-of-values-at-indices-with-k-set-bits.js)|Easy|
2860|[Happy Students](./solutions/2860-happy-students.js)|Medium|
2862|[Maximum Element-Sum of a Complete Subset of Indices](./solutions/2862-maximum-element-sum-of-a-complete-subset-of-indices.js)|Hard|
+2864|[Maximum Odd Binary Number](./solutions/2864-maximum-odd-binary-number.js)|Easy|
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|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
diff --git a/solutions/2864-maximum-odd-binary-number.js b/solutions/2864-maximum-odd-binary-number.js
new file mode 100644
index 00000000..82fd37bc
--- /dev/null
+++ b/solutions/2864-maximum-odd-binary-number.js
@@ -0,0 +1,27 @@
+/**
+ * 2864. Maximum Odd Binary Number
+ * https://leetcode.com/problems/maximum-odd-binary-number/
+ * Difficulty: Easy
+ *
+ * You are given a binary string s that contains at least one '1'.
+ *
+ * You have to rearrange the bits in such a way that the resulting binary number is the maximum
+ * odd binary number that can be created from this combination.
+ *
+ * Return a string representing the maximum odd binary number that can be created from the given
+ * combination.
+ *
+ * Note that the resulting string can have leading zeros.
+ */
+
+/**
+ * @param {string} s
+ * @return {string}
+ */
+var maximumOddBinaryNumber = function(s) {
+ let ones = 0;
+ for (const bit of s) {
+ if (bit === '1') ones++;
+ }
+ return '1'.padStart(ones, '1').padEnd(s.length, '0').slice(1) + '1';
+};
From c3d1534a119b12bd5cff56c822e4e1f8b2c780a2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 23:47:16 -0500
Subject: [PATCH 326/994] Add solution #2865
---
README.md | 1 +
solutions/2865-beautiful-towers-i.js | 44 ++++++++++++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/2865-beautiful-towers-i.js
diff --git a/README.md b/README.md
index fcb4a12d..e7305b1d 100644
--- a/README.md
+++ b/README.md
@@ -2065,6 +2065,7 @@
2860|[Happy Students](./solutions/2860-happy-students.js)|Medium|
2862|[Maximum Element-Sum of a Complete Subset of Indices](./solutions/2862-maximum-element-sum-of-a-complete-subset-of-indices.js)|Hard|
2864|[Maximum Odd Binary Number](./solutions/2864-maximum-odd-binary-number.js)|Easy|
+2865|[Beautiful Towers I](./solutions/2865-beautiful-towers-i.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|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
diff --git a/solutions/2865-beautiful-towers-i.js b/solutions/2865-beautiful-towers-i.js
new file mode 100644
index 00000000..f0fa8c07
--- /dev/null
+++ b/solutions/2865-beautiful-towers-i.js
@@ -0,0 +1,44 @@
+/**
+ * 2865. Beautiful Towers I
+ * https://leetcode.com/problems/beautiful-towers-i/
+ * Difficulty: Medium
+ *
+ * You are given an array heights of n integers representing the number of bricks in n
+ * consecutive towers. Your task is to remove some bricks to form a mountain-shaped tower
+ * arrangement. In this arrangement, the tower heights are non-decreasing, reaching a
+ * maximum peak value with one or multiple consecutive towers and then non-increasing.
+ *
+ * Return the maximum possible sum of heights of a mountain-shaped tower arrangement.
+ */
+
+/**
+ * @param {number[]} heights
+ * @return {number}
+ */
+var maximumSumOfHeights = function(heights) {
+ const n = heights.length;
+ let result = 0;
+
+ for (let peak = 0; peak < n; peak++) {
+ let currentSum = heights[peak];
+ let prevHeight = heights[peak];
+
+ for (let i = peak - 1; i >= 0; i--) {
+ const currentHeight = Math.min(heights[i], prevHeight);
+ currentSum += currentHeight;
+ prevHeight = currentHeight;
+ }
+
+ prevHeight = heights[peak];
+
+ for (let i = peak + 1; i < n; i++) {
+ const currentHeight = Math.min(heights[i], prevHeight);
+ currentSum += currentHeight;
+ prevHeight = currentHeight;
+ }
+
+ result = Math.max(result, currentSum);
+ }
+
+ return result;
+};
From c7188bb4998e386fdfd00b1081b030ba769008b6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 23:48:22 -0500
Subject: [PATCH 327/994] Add solution #2869
---
README.md | 1 +
...-minimum-operations-to-collect-elements.js | 29 +++++++++++++++++++
2 files changed, 30 insertions(+)
create mode 100644 solutions/2869-minimum-operations-to-collect-elements.js
diff --git a/README.md b/README.md
index e7305b1d..42d2bef8 100644
--- a/README.md
+++ b/README.md
@@ -2066,6 +2066,7 @@
2862|[Maximum Element-Sum of a Complete Subset of Indices](./solutions/2862-maximum-element-sum-of-a-complete-subset-of-indices.js)|Hard|
2864|[Maximum Odd Binary Number](./solutions/2864-maximum-odd-binary-number.js)|Easy|
2865|[Beautiful Towers I](./solutions/2865-beautiful-towers-i.js)|Medium|
+2869|[Minimum Operations to Collect Elements](./solutions/2869-minimum-operations-to-collect-elements.js)|Easy|
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|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
diff --git a/solutions/2869-minimum-operations-to-collect-elements.js b/solutions/2869-minimum-operations-to-collect-elements.js
new file mode 100644
index 00000000..4f52b704
--- /dev/null
+++ b/solutions/2869-minimum-operations-to-collect-elements.js
@@ -0,0 +1,29 @@
+/**
+ * 2869. Minimum Operations to Collect Elements
+ * https://leetcode.com/problems/minimum-operations-to-collect-elements/
+ * Difficulty: Easy
+ *
+ * You are given an array nums of positive integers and an integer k.
+ *
+ * In one operation, you can remove the last element of the array and add it to your collection.
+ *
+ * Return the minimum number of operations needed to collect elements 1, 2, ..., k.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var minOperations = function(nums, k) {
+ const set = new Set();
+ let result = 0;
+
+ for (let i = nums.length - 1; i >= 0; i--) {
+ result++;
+ if (nums[i] <= k) set.add(nums[i]);
+ if (set.size === k) return result;
+ }
+
+ return result;
+};
From edab83864c5ef7720b9302c12138eb48ab0f7ffb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 23:50:02 -0500
Subject: [PATCH 328/994] Add solution #2870
---
README.md | 1 +
...umber-of-operations-to-make-array-empty.js | 33 +++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/2870-minimum-number-of-operations-to-make-array-empty.js
diff --git a/README.md b/README.md
index 42d2bef8..ce513391 100644
--- a/README.md
+++ b/README.md
@@ -2067,6 +2067,7 @@
2864|[Maximum Odd Binary Number](./solutions/2864-maximum-odd-binary-number.js)|Easy|
2865|[Beautiful Towers I](./solutions/2865-beautiful-towers-i.js)|Medium|
2869|[Minimum Operations to Collect Elements](./solutions/2869-minimum-operations-to-collect-elements.js)|Easy|
+2870|[Minimum Number of Operations to Make Array Empty](./solutions/2870-minimum-number-of-operations-to-make-array-empty.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|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
diff --git a/solutions/2870-minimum-number-of-operations-to-make-array-empty.js b/solutions/2870-minimum-number-of-operations-to-make-array-empty.js
new file mode 100644
index 00000000..c6376c70
--- /dev/null
+++ b/solutions/2870-minimum-number-of-operations-to-make-array-empty.js
@@ -0,0 +1,33 @@
+/**
+ * 2870. Minimum Number of Operations to Make Array Empty
+ * https://leetcode.com/problems/minimum-number-of-operations-to-make-array-empty/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array nums consisting of positive integers.
+ *
+ * There are two types of operations that you can apply on the array any number of times:
+ * - Choose two elements with equal values and delete them from the array.
+ * - Choose three elements with equal values and delete them from the array.
+ *
+ * Return the minimum number of operations required to make the array empty, or -1 if it is
+ * not possible.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minOperations = function(nums) {
+ const map = new Map();
+ for (const num of nums) {
+ map.set(num, (map.get(num) || 0) + 1);
+ }
+
+ let result = 0;
+ for (const count of map.values()) {
+ if (count === 1) return -1;
+ result += Math.ceil(count / 3);
+ }
+
+ return result;
+};
From 25276ec6d5d4155a2151abf117f8e33b1a70a92b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 23:51:44 -0500
Subject: [PATCH 329/994] Add solution #2871
---
README.md | 1 +
...-array-into-maximum-number-of-subarrays.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/2871-split-array-into-maximum-number-of-subarrays.js
diff --git a/README.md b/README.md
index ce513391..387fcc63 100644
--- a/README.md
+++ b/README.md
@@ -2068,6 +2068,7 @@
2865|[Beautiful Towers I](./solutions/2865-beautiful-towers-i.js)|Medium|
2869|[Minimum Operations to Collect Elements](./solutions/2869-minimum-operations-to-collect-elements.js)|Easy|
2870|[Minimum Number of Operations to Make Array Empty](./solutions/2870-minimum-number-of-operations-to-make-array-empty.js)|Medium|
+2871|[Split Array Into Maximum Number of Subarrays](./solutions/2871-split-array-into-maximum-number-of-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|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
diff --git a/solutions/2871-split-array-into-maximum-number-of-subarrays.js b/solutions/2871-split-array-into-maximum-number-of-subarrays.js
new file mode 100644
index 00000000..ff3141ce
--- /dev/null
+++ b/solutions/2871-split-array-into-maximum-number-of-subarrays.js
@@ -0,0 +1,41 @@
+/**
+ * 2871. Split Array Into Maximum Number of Subarrays
+ * https://leetcode.com/problems/split-array-into-maximum-number-of-subarrays/
+ * Difficulty: Medium
+ *
+ * You are given an array nums consisting of non-negative integers.
+ *
+ * We define the score of subarray nums[l..r] such that l <= r as nums[l] AND nums[l + 1]
+ * AND ... AND nums[r] where AND is the bitwise AND operation.
+ *
+ * Consider splitting the array into one or more subarrays such that the following conditions
+ * are satisfied:
+ * - Each element of the array belongs to exactly one subarray.
+ * - The sum of scores of the subarrays is the minimum possible.
+ *
+ * Return the maximum number of subarrays in a split that satisfies the conditions above.
+ *
+ * A subarray is a contiguous part of an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maxSubarrays = function(nums) {
+ const total = nums.reduce((acc, num) => acc & num, nums[0]);
+ if (total !== 0) return 1;
+
+ let result = 0;
+ let current = -1;
+
+ for (const num of nums) {
+ current = current === -1 ? num : current & num;
+ if (current === 0) {
+ result++;
+ current = -1;
+ }
+ }
+
+ return result;
+};
From 7fd1c2294f8fd0a0d66942132c5aa6cfbf21db57 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 3 Jun 2025 23:53:40 -0500
Subject: [PATCH 330/994] Add solution #2872
---
README.md | 1 +
...aximum-number-of-k-divisible-components.js | 51 +++++++++++++++++++
2 files changed, 52 insertions(+)
create mode 100644 solutions/2872-maximum-number-of-k-divisible-components.js
diff --git a/README.md b/README.md
index 387fcc63..ffab6e42 100644
--- a/README.md
+++ b/README.md
@@ -2069,6 +2069,7 @@
2869|[Minimum Operations to Collect Elements](./solutions/2869-minimum-operations-to-collect-elements.js)|Easy|
2870|[Minimum Number of Operations to Make Array Empty](./solutions/2870-minimum-number-of-operations-to-make-array-empty.js)|Medium|
2871|[Split Array Into Maximum Number of Subarrays](./solutions/2871-split-array-into-maximum-number-of-subarrays.js)|Medium|
+2872|[Maximum Number of K-Divisible Components](./solutions/2872-maximum-number-of-k-divisible-components.js)|Hard|
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|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
diff --git a/solutions/2872-maximum-number-of-k-divisible-components.js b/solutions/2872-maximum-number-of-k-divisible-components.js
new file mode 100644
index 00000000..6ff1fdcd
--- /dev/null
+++ b/solutions/2872-maximum-number-of-k-divisible-components.js
@@ -0,0 +1,51 @@
+/**
+ * 2872. Maximum Number of K-Divisible Components
+ * https://leetcode.com/problems/maximum-number-of-k-divisible-components/
+ * Difficulty: Hard
+ *
+ * There is an undirected tree with n nodes labeled from 0 to n - 1. You are given the integer
+ * n and 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 a 0-indexed integer array values of length n, where values[i] is the value
+ * associated with the ith node, and an integer k.
+ *
+ * A valid split of the tree is obtained by removing any set of edges, possibly empty, from the
+ * tree such that the resulting components all have values that are divisible by k, where the
+ * value of a connected component is the sum of the values of its nodes.
+ *
+ * Return the maximum number of components in any valid split.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @param {number[]} values
+ * @param {number} k
+ * @return {number}
+ */
+var maxKDivisibleComponents = function(n, edges, values, k) {
+ const graph = Array.from({ length: n }, () => []);
+ for (const [u, v] of edges) {
+ graph[u].push(v);
+ graph[v].push(u);
+ }
+
+ let result = 0;
+ dfs(0, -1);
+ return result;
+
+ function dfs(node, parent) {
+ let total = values[node];
+ for (const neighbor of graph[node]) {
+ if (neighbor !== parent) {
+ total += dfs(neighbor, node);
+ }
+ }
+ if (total % k === 0) {
+ result++;
+ return 0;
+ }
+ return total;
+ }
+};
From 0e262d36ad22be90ec7bdcdc4df7b969ed75bc94 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 18:18:34 -0500
Subject: [PATCH 331/994] Add solution #2895
---
README.md | 1 +
solutions/2895-minimum-processing-time.js | 33 +++++++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/2895-minimum-processing-time.js
diff --git a/README.md b/README.md
index ffab6e42..0ec9f1fa 100644
--- a/README.md
+++ b/README.md
@@ -2073,6 +2073,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|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
+2895|[Minimum Processing Time](./solutions/2895-minimum-processing-time.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|
diff --git a/solutions/2895-minimum-processing-time.js b/solutions/2895-minimum-processing-time.js
new file mode 100644
index 00000000..c9ce8504
--- /dev/null
+++ b/solutions/2895-minimum-processing-time.js
@@ -0,0 +1,33 @@
+/**
+ * 2895. Minimum Processing Time
+ * https://leetcode.com/problems/minimum-processing-time/
+ * Difficulty: Medium
+ *
+ * You have a certain number of processors, each having 4 cores. The number of tasks to be executed
+ * is four times the number of processors. Each task must be assigned to a unique core, and each
+ * core can only be used once.
+ *
+ * You are given an array processorTime representing the time each processor becomes available and
+ * an array tasks representing how long each task takes to complete. Return the minimum time needed
+ * to complete all tasks.
+ */
+
+/**
+ * @param {number[]} processorTime
+ * @param {number[]} tasks
+ * @return {number}
+ */
+var minProcessingTime = function(processorTime, tasks) {
+ tasks.sort((a, b) => b - a);
+ processorTime.sort((a, b) => a - b);
+ let result = 0;
+
+ for (let i = 0; i < processorTime.length; i++) {
+ for (let j = 0; j < 4; j++) {
+ const taskIndex = i * 4 + j;
+ result = Math.max(result, processorTime[i] + tasks[taskIndex]);
+ }
+ }
+
+ return result;
+};
From 4a4bfbfebe824c4e92563f61ac67f030dda07485 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 18:21:28 -0500
Subject: [PATCH 332/994] Add solution #2897
---
README.md | 1 +
...ons-on-array-to-maximize-sum-of-squares.js | 48 +++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/2897-apply-operations-on-array-to-maximize-sum-of-squares.js
diff --git a/README.md b/README.md
index 0ec9f1fa..af557e07 100644
--- a/README.md
+++ b/README.md
@@ -2074,6 +2074,7 @@
2874|[Maximum Value of an Ordered Triplet II](./solutions/2874-maximum-value-of-an-ordered-triplet-ii.js)|Medium|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
2895|[Minimum Processing Time](./solutions/2895-minimum-processing-time.js)|Medium|
+2897|[Apply Operations on Array to Maximize Sum of Squares](./solutions/2897-apply-operations-on-array-to-maximize-sum-of-squares.js)|Hard|
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|
diff --git a/solutions/2897-apply-operations-on-array-to-maximize-sum-of-squares.js b/solutions/2897-apply-operations-on-array-to-maximize-sum-of-squares.js
new file mode 100644
index 00000000..eab93b10
--- /dev/null
+++ b/solutions/2897-apply-operations-on-array-to-maximize-sum-of-squares.js
@@ -0,0 +1,48 @@
+/**
+ * 2897. Apply Operations on Array to Maximize Sum of Squares
+ * https://leetcode.com/problems/apply-operations-on-array-to-maximize-sum-of-squares/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed integer array nums and a positive integer k.
+ *
+ * You can do the following operation on the array any number of times:
+ * - Choose any two distinct indices i and j and simultaneously update the values of nums[i]
+ * to (nums[i] AND nums[j]) and nums[j] to (nums[i] OR nums[j]). Here, OR denotes the bitwise
+ * OR operation, and AND denotes the bitwise AND operation.
+ *
+ * You have to choose k elements from the final array and calculate the sum of their squares.
+ *
+ * Return the maximum sum of squares you can achieve.
+ *
+ * Since the answer can be very large, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var maxSum = function(nums, k) {
+ const MOD = 1e9 + 7;
+ const bitCounts = new Array(30).fill(0);
+
+ for (const num of nums) {
+ for (let i = 0; i < 30; i++) {
+ if (num & (1 << i)) bitCounts[i]++;
+ }
+ }
+
+ let result = 0;
+ for (let i = 0; i < k; i++) {
+ let current = 0;
+ for (let j = 29; j >= 0; j--) {
+ if (bitCounts[j] > 0) {
+ current |= (1 << j);
+ bitCounts[j]--;
+ }
+ }
+ result = (result + Number((BigInt(current) * BigInt(current)) % BigInt(MOD))) % MOD;
+ }
+
+ return result;
+};
From 20efb1b8c86d03cfa5c6228d23b6f31b9e878bd2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 18:22:47 -0500
Subject: [PATCH 333/994] Add solution #2899
---
README.md | 1 +
solutions/2899-last-visited-integers.js | 41 +++++++++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/2899-last-visited-integers.js
diff --git a/README.md b/README.md
index af557e07..1e04967e 100644
--- a/README.md
+++ b/README.md
@@ -2075,6 +2075,7 @@
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
2895|[Minimum Processing Time](./solutions/2895-minimum-processing-time.js)|Medium|
2897|[Apply Operations on Array to Maximize Sum of Squares](./solutions/2897-apply-operations-on-array-to-maximize-sum-of-squares.js)|Hard|
+2899|[Last Visited Integers](./solutions/2899-last-visited-integers.js)|Easy|
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|
diff --git a/solutions/2899-last-visited-integers.js b/solutions/2899-last-visited-integers.js
new file mode 100644
index 00000000..0adcb661
--- /dev/null
+++ b/solutions/2899-last-visited-integers.js
@@ -0,0 +1,41 @@
+/**
+ * 2899. Last Visited Integers
+ * https://leetcode.com/problems/last-visited-integers/
+ * Difficulty: Easy
+ *
+ * Given an integer array nums where nums[i] is either a positive integer or -1. We need to find
+ * for each -1 the respective positive integer, which we call the last visited integer.
+ *
+ * To achieve this goal, let's define two empty arrays: seen and ans.
+ *
+ * Start iterating from the beginning of the array nums.
+ * - If a positive integer is encountered, prepend it to the front of seen.
+ * - If -1 is encountered, let k be the number of consecutive -1s seen so far (including the
+ * current -1),
+ * - If k is less than or equal to the length of seen, append the k-th element of seen to ans.
+ * - If k is strictly greater than the length of seen, append -1 to ans.
+ *
+ * Return the array ans.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var lastVisitedIntegers = function(nums) {
+ const seen = [];
+ const result = [];
+ let consecutiveNegatives = 0;
+
+ for (const num of nums) {
+ if (num > 0) {
+ seen.unshift(num);
+ consecutiveNegatives = 0;
+ } else {
+ consecutiveNegatives++;
+ result.push(consecutiveNegatives <= seen.length ? seen[consecutiveNegatives - 1] : -1);
+ }
+ }
+
+ return result;
+};
From 0fd595f0ba7762dca406a6b6eb66725339260c55 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 18:23:55 -0500
Subject: [PATCH 334/994] Add solution #2903
---
README.md | 1 +
...dices-with-index-and-value-difference-i.js | 36 +++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/2903-find-indices-with-index-and-value-difference-i.js
diff --git a/README.md b/README.md
index 1e04967e..8ee8a52e 100644
--- a/README.md
+++ b/README.md
@@ -2078,6 +2078,7 @@
2899|[Last Visited Integers](./solutions/2899-last-visited-integers.js)|Easy|
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|
+2903|[Find Indices With Index and Value Difference I](./solutions/2903-find-indices-with-index-and-value-difference-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|
2929|[Distribute Candies Among Children II](./solutions/2929-distribute-candies-among-children-ii.js)|Medium|
2942|[Find Words Containing Character](./solutions/2942-find-words-containing-character.js)|Easy|
diff --git a/solutions/2903-find-indices-with-index-and-value-difference-i.js b/solutions/2903-find-indices-with-index-and-value-difference-i.js
new file mode 100644
index 00000000..2ef70aeb
--- /dev/null
+++ b/solutions/2903-find-indices-with-index-and-value-difference-i.js
@@ -0,0 +1,36 @@
+/**
+ * 2903. Find Indices With Index and Value Difference I
+ * https://leetcode.com/problems/find-indices-with-index-and-value-difference-i/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums having length n, an integer indexDifference,
+ * and an integer valueDifference.
+ *
+ * Your task is to find two indices i and j, both in the range [0, n - 1], that satisfy the
+ * following conditions:
+ * - abs(i - j) >= indexDifference, and
+ * - abs(nums[i] - nums[j]) >= valueDifference
+ *
+ * Return an integer array answer, where answer = [i, j] if there are two such indices, and
+ * answer = [-1, -1] otherwise. If there are multiple choices for the two indices, return
+ * any of them.
+ *
+ * Note: i and j may be equal.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} indexDifference
+ * @param {number} valueDifference
+ * @return {number[]}
+ */
+var findIndices = function(nums, indexDifference, valueDifference) {
+ for (let i = 0; i < nums.length; i++) {
+ for (let j = i; j < nums.length; j++) {
+ if (Math.abs(i - j) >= indexDifference && Math.abs(nums[i] - nums[j]) >= valueDifference) {
+ return [i, j];
+ }
+ }
+ }
+ return [-1, -1];
+};
From e2ecf35dfb3e2ffafb9eef589a1eb04d5ce95b9c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 18:25:04 -0500
Subject: [PATCH 335/994] Add solution #2908
---
README.md | 1 +
...2908-minimum-sum-of-mountain-triplets-i.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/2908-minimum-sum-of-mountain-triplets-i.js
diff --git a/README.md b/README.md
index 8ee8a52e..e0e21bfe 100644
--- a/README.md
+++ b/README.md
@@ -2079,6 +2079,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|
2903|[Find Indices With Index and Value Difference I](./solutions/2903-find-indices-with-index-and-value-difference-i.js)|Easy|
+2908|[Minimum Sum of Mountain Triplets I](./solutions/2908-minimum-sum-of-mountain-triplets-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|
2929|[Distribute Candies Among Children II](./solutions/2929-distribute-candies-among-children-ii.js)|Medium|
2942|[Find Words Containing Character](./solutions/2942-find-words-containing-character.js)|Easy|
diff --git a/solutions/2908-minimum-sum-of-mountain-triplets-i.js b/solutions/2908-minimum-sum-of-mountain-triplets-i.js
new file mode 100644
index 00000000..31f04c6a
--- /dev/null
+++ b/solutions/2908-minimum-sum-of-mountain-triplets-i.js
@@ -0,0 +1,34 @@
+/**
+ * 2908. Minimum Sum of Mountain Triplets I
+ * https://leetcode.com/problems/minimum-sum-of-mountain-triplets-i/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed array nums of integers.
+ *
+ * A triplet of indices (i, j, k) is a mountain if:
+ * - i < j < k
+ * - nums[i] < nums[j] and nums[k] < nums[j]
+ *
+ * Return the minimum possible sum of a mountain triplet of nums. If no such triplet exists,
+ * return -1.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimumSum = function(nums) {
+ let minSum = Infinity;
+
+ for (let i = 0; i < nums.length - 2; i++) {
+ for (let j = i + 1; j < nums.length - 1; j++) {
+ for (let k = j + 1; k < nums.length; k++) {
+ if (nums[i] < nums[j] && nums[k] < nums[j]) {
+ minSum = Math.min(minSum, nums[i] + nums[j] + nums[k]);
+ }
+ }
+ }
+ }
+
+ return minSum === Infinity ? -1 : minSum;
+};
From f9dc17e7bf01dfcc9f9f804cbecd5f433c314499 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 21:34:45 -0500
Subject: [PATCH 336/994] Add solution #2909
---
README.md | 1 +
...909-minimum-sum-of-mountain-triplets-ii.js | 43 +++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/2909-minimum-sum-of-mountain-triplets-ii.js
diff --git a/README.md b/README.md
index e0e21bfe..b415e8f8 100644
--- a/README.md
+++ b/README.md
@@ -2080,6 +2080,7 @@
2901|[Longest Unequal Adjacent Groups Subsequence II](./solutions/2901-longest-unequal-adjacent-groups-subsequence-ii.js)|Medium|
2903|[Find Indices With Index and Value Difference I](./solutions/2903-find-indices-with-index-and-value-difference-i.js)|Easy|
2908|[Minimum Sum of Mountain Triplets I](./solutions/2908-minimum-sum-of-mountain-triplets-i.js)|Easy|
+2909|[Minimum Sum of Mountain Triplets II](./solutions/2909-minimum-sum-of-mountain-triplets-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|
2929|[Distribute Candies Among Children II](./solutions/2929-distribute-candies-among-children-ii.js)|Medium|
2942|[Find Words Containing Character](./solutions/2942-find-words-containing-character.js)|Easy|
diff --git a/solutions/2909-minimum-sum-of-mountain-triplets-ii.js b/solutions/2909-minimum-sum-of-mountain-triplets-ii.js
new file mode 100644
index 00000000..21e15bd7
--- /dev/null
+++ b/solutions/2909-minimum-sum-of-mountain-triplets-ii.js
@@ -0,0 +1,43 @@
+/**
+ * 2909. Minimum Sum of Mountain Triplets II
+ * https://leetcode.com/problems/minimum-sum-of-mountain-triplets-ii/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array nums of integers.
+ *
+ * A triplet of indices (i, j, k) is a mountain if:
+ * - i < j < k
+ * - nums[i] < nums[j] and nums[k] < nums[j]
+ *
+ * Return the minimum possible sum of a mountain triplet of nums. If no such triplet
+ * exists, return -1.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimumSum = function(nums) {
+ const n = nums.length;
+ const leftMin = new Array(n).fill(Infinity);
+ const rightMin = new Array(n).fill(Infinity);
+
+ leftMin[0] = nums[0];
+ for (let i = 1; i < n; i++) {
+ leftMin[i] = Math.min(leftMin[i - 1], nums[i]);
+ }
+
+ rightMin[n - 1] = nums[n - 1];
+ for (let i = n - 2; i >= 0; i--) {
+ rightMin[i] = Math.min(rightMin[i + 1], nums[i]);
+ }
+
+ let minSum = Infinity;
+ for (let j = 1; j < n - 1; j++) {
+ if (nums[j] > leftMin[j - 1] && nums[j] > rightMin[j + 1]) {
+ minSum = Math.min(minSum, leftMin[j - 1] + nums[j] + rightMin[j + 1]);
+ }
+ }
+
+ return minSum === Infinity ? -1 : minSum;
+};
From 94d3ad7dded5123770950797b2f39db18de346d6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 21:36:27 -0500
Subject: [PATCH 337/994] Add solution #2913
---
README.md | 1 +
...rrays-distinct-element-sum-of-squares-i.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/2913-subarrays-distinct-element-sum-of-squares-i.js
diff --git a/README.md b/README.md
index b415e8f8..487c2060 100644
--- a/README.md
+++ b/README.md
@@ -2081,6 +2081,7 @@
2903|[Find Indices With Index and Value Difference I](./solutions/2903-find-indices-with-index-and-value-difference-i.js)|Easy|
2908|[Minimum Sum of Mountain Triplets I](./solutions/2908-minimum-sum-of-mountain-triplets-i.js)|Easy|
2909|[Minimum Sum of Mountain Triplets II](./solutions/2909-minimum-sum-of-mountain-triplets-ii.js)|Medium|
+2913|[Subarrays Distinct Element Sum of Squares I](./solutions/2913-subarrays-distinct-element-sum-of-squares-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|
2929|[Distribute Candies Among Children II](./solutions/2929-distribute-candies-among-children-ii.js)|Medium|
2942|[Find Words Containing Character](./solutions/2942-find-words-containing-character.js)|Easy|
diff --git a/solutions/2913-subarrays-distinct-element-sum-of-squares-i.js b/solutions/2913-subarrays-distinct-element-sum-of-squares-i.js
new file mode 100644
index 00000000..ebb8fdfb
--- /dev/null
+++ b/solutions/2913-subarrays-distinct-element-sum-of-squares-i.js
@@ -0,0 +1,34 @@
+/**
+ * 2913. Subarrays Distinct Element Sum of Squares I
+ * https://leetcode.com/problems/subarrays-distinct-element-sum-of-squares-i/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums.
+ *
+ * The distinct count of a subarray of nums is defined as:
+ * - Let nums[i..j] be a subarray of nums consisting of all the indices from i to j such
+ * that 0 <= i <= j < nums.length. Then the number of distinct values in nums[i..j] is
+ * called the distinct count of nums[i..j].
+ *
+ * Return the sum of the squares of distinct counts of all subarrays of nums.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var sumCounts = function(nums) {
+ let result = 0;
+
+ for (let i = 0; i < nums.length; i++) {
+ const set = new Set();
+ for (let j = i; j < nums.length; j++) {
+ set.add(nums[j]);
+ result += set.size * set.size;
+ }
+ }
+
+ return result;
+};
From 076e09adcff4fb89295f495ceaae0b6d597ed55a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 21:38:19 -0500
Subject: [PATCH 338/994] Add solution #2914
---
README.md | 1 +
...changes-to-make-binary-string-beautiful.js | 29 +++++++++++++++++++
2 files changed, 30 insertions(+)
create mode 100644 solutions/2914-minimum-number-of-changes-to-make-binary-string-beautiful.js
diff --git a/README.md b/README.md
index 487c2060..a68f9335 100644
--- a/README.md
+++ b/README.md
@@ -2082,6 +2082,7 @@
2908|[Minimum Sum of Mountain Triplets I](./solutions/2908-minimum-sum-of-mountain-triplets-i.js)|Easy|
2909|[Minimum Sum of Mountain Triplets II](./solutions/2909-minimum-sum-of-mountain-triplets-ii.js)|Medium|
2913|[Subarrays Distinct Element Sum of Squares I](./solutions/2913-subarrays-distinct-element-sum-of-squares-i.js)|Easy|
+2914|[Minimum Number of Changes to Make Binary String Beautiful](./solutions/2914-minimum-number-of-changes-to-make-binary-string-beautiful.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|
2929|[Distribute Candies Among Children II](./solutions/2929-distribute-candies-among-children-ii.js)|Medium|
2942|[Find Words Containing Character](./solutions/2942-find-words-containing-character.js)|Easy|
diff --git a/solutions/2914-minimum-number-of-changes-to-make-binary-string-beautiful.js b/solutions/2914-minimum-number-of-changes-to-make-binary-string-beautiful.js
new file mode 100644
index 00000000..2c50bf70
--- /dev/null
+++ b/solutions/2914-minimum-number-of-changes-to-make-binary-string-beautiful.js
@@ -0,0 +1,29 @@
+/**
+ * 2914. Minimum Number of Changes to Make Binary String Beautiful
+ * https://leetcode.com/problems/minimum-number-of-changes-to-make-binary-string-beautiful/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed binary string s having an even length.
+ *
+ * A string is beautiful if it's possible to partition it into one or more substrings such that:
+ * - Each substring has an even length.
+ * - Each substring contains only 1's or only 0's.
+ *
+ * You can change any character in s to 0 or 1.
+ *
+ * Return the minimum number of changes required to make the string s beautiful.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var minChanges = function(s) {
+ let result = 0;
+
+ for (let i = 0; i < s.length; i += 2) {
+ if (s[i] !== s[i + 1]) result++;
+ }
+
+ return result;
+};
From 785ca3d81582540d3262071541a7aaf17d9e5c6a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 21:39:28 -0500
Subject: [PATCH 339/994] Add solution #2917
---
README.md | 1 +
solutions/2917-find-the-k-or-of-an-array.js | 30 +++++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 solutions/2917-find-the-k-or-of-an-array.js
diff --git a/README.md b/README.md
index a68f9335..ec7e3a8b 100644
--- a/README.md
+++ b/README.md
@@ -2083,6 +2083,7 @@
2909|[Minimum Sum of Mountain Triplets II](./solutions/2909-minimum-sum-of-mountain-triplets-ii.js)|Medium|
2913|[Subarrays Distinct Element Sum of Squares I](./solutions/2913-subarrays-distinct-element-sum-of-squares-i.js)|Easy|
2914|[Minimum Number of Changes to Make Binary String Beautiful](./solutions/2914-minimum-number-of-changes-to-make-binary-string-beautiful.js)|Medium|
+2917|[Find the K-or of an Array](./solutions/2917-find-the-k-or-of-an-array.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|
2929|[Distribute Candies Among Children II](./solutions/2929-distribute-candies-among-children-ii.js)|Medium|
2942|[Find Words Containing Character](./solutions/2942-find-words-containing-character.js)|Easy|
diff --git a/solutions/2917-find-the-k-or-of-an-array.js b/solutions/2917-find-the-k-or-of-an-array.js
new file mode 100644
index 00000000..d37773ad
--- /dev/null
+++ b/solutions/2917-find-the-k-or-of-an-array.js
@@ -0,0 +1,30 @@
+/**
+ * 2917. Find the K-or of an Array
+ * https://leetcode.com/problems/find-the-k-or-of-an-array/
+ * Difficulty: Easy
+ *
+ * You are given an integer array nums, and an integer k. Let's introduce K-or operation
+ * by extending the standard bitwise OR. In K-or, a bit position in the result is set to
+ * 1 if at least k numbers in nums have a 1 in that position.
+ *
+ * Return the K-or of nums.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var findKOr = function(nums, k) {
+ let result = 0;
+
+ for (let bit = 0; bit < 31; bit++) {
+ let count = 0;
+ for (const num of nums) {
+ if (num & (1 << bit)) count++;
+ }
+ if (count >= k) result |= (1 << bit);
+ }
+
+ return result;
+};
From 3c7061c2a2b0d6545bf7dbe12f32d514376eb3ff Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 21:40:52 -0500
Subject: [PATCH 340/994] Add solution #2923
---
README.md | 1 +
solutions/2923-find-champion-i.js | 37 +++++++++++++++++++++++++++++++
2 files changed, 38 insertions(+)
create mode 100644 solutions/2923-find-champion-i.js
diff --git a/README.md b/README.md
index ec7e3a8b..9ff13905 100644
--- a/README.md
+++ b/README.md
@@ -2085,6 +2085,7 @@
2914|[Minimum Number of Changes to Make Binary String Beautiful](./solutions/2914-minimum-number-of-changes-to-make-binary-string-beautiful.js)|Medium|
2917|[Find the K-or of an Array](./solutions/2917-find-the-k-or-of-an-array.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|
+2923|[Find Champion I](./solutions/2923-find-champion-i.js)|Easy|
2929|[Distribute Candies Among Children II](./solutions/2929-distribute-candies-among-children-ii.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|
diff --git a/solutions/2923-find-champion-i.js b/solutions/2923-find-champion-i.js
new file mode 100644
index 00000000..c641cd07
--- /dev/null
+++ b/solutions/2923-find-champion-i.js
@@ -0,0 +1,37 @@
+/**
+ * 2923. Find Champion I
+ * https://leetcode.com/problems/find-champion-i/
+ * Difficulty: Easy
+ *
+ * There are n teams numbered from 0 to n - 1 in a tournament.
+ *
+ * Given a 0-indexed 2D boolean matrix grid of size n * n. For all i, j that 0 <= i, j <= n - 1
+ * and i != j team i is stronger than team j if grid[i][j] == 1, otherwise, team j is stronger
+ * than team i.
+ *
+ * Team a will be the champion of the tournament if there is no team b that is stronger than
+ * team a.
+ *
+ * Return the team that will be the champion of the tournament.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var findChampion = function(grid) {
+ const n = grid.length;
+
+ for (let i = 0; i < n; i++) {
+ let isChampion = true;
+ for (let j = 0; j < n; j++) {
+ if (i !== j && grid[j][i] === 1) {
+ isChampion = false;
+ break;
+ }
+ }
+ if (isChampion) return i;
+ }
+
+ return -1;
+};
From a1040d25601c0bae735f94dde0b7df66b4a53493 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 22:03:49 -0500
Subject: [PATCH 341/994] Add solution #2924
---
README.md | 1 +
solutions/2924-find-champion-ii.js | 47 ++++++++++++++++++++++++++++++
2 files changed, 48 insertions(+)
create mode 100644 solutions/2924-find-champion-ii.js
diff --git a/README.md b/README.md
index 9ff13905..ebe62fea 100644
--- a/README.md
+++ b/README.md
@@ -2086,6 +2086,7 @@
2917|[Find the K-or of an Array](./solutions/2917-find-the-k-or-of-an-array.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|
2923|[Find Champion I](./solutions/2923-find-champion-i.js)|Easy|
+2924|[Find Champion II](./solutions/2924-find-champion-ii.js)|Medium|
2929|[Distribute Candies Among Children II](./solutions/2929-distribute-candies-among-children-ii.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|
diff --git a/solutions/2924-find-champion-ii.js b/solutions/2924-find-champion-ii.js
new file mode 100644
index 00000000..a475f55d
--- /dev/null
+++ b/solutions/2924-find-champion-ii.js
@@ -0,0 +1,47 @@
+/**
+ * 2924. Find Champion II
+ * https://leetcode.com/problems/find-champion-ii/
+ * Difficulty: Medium
+ *
+ * There are n teams numbered from 0 to n - 1 in a tournament; each team is also a node in a DAG.
+ *
+ * You are given the integer n and a 0-indexed 2D integer array edges of length m representing the
+ * DAG, where edges[i] = [ui, vi] indicates that there is a directed edge from team ui to team vi
+ * in the graph.
+ *
+ * A directed edge from a to b in the graph means that team a is stronger than team b and team b
+ * is weaker than team a.
+ *
+ * Team a will be the champion of the tournament if there is no team b that is stronger than team a.
+ *
+ * Return the team that will be the champion of the tournament if there is a unique champion,
+ * otherwise, return -1.
+ *
+ * Notes:
+ * - A cycle is a series of nodes a1, a2, ..., an, an+1 such that node a1 is the same node as node
+ * an+1, the nodes a1, a2, ..., an are distinct, and there is a directed edge from the node ai
+ * to node ai+1 for every i in the range [1, n].
+ * - A DAG is a directed graph that does not have any cycle.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @return {number}
+ */
+var findChampion = function(n, edges) {
+ const inDegree = new Array(n).fill(0);
+
+ for (const [, v] of edges) {
+ inDegree[v]++;
+ }
+ let champion = -1;
+ for (let i = 0; i < n; i++) {
+ if (inDegree[i] === 0) {
+ if (champion !== -1) return -1;
+ champion = i;
+ }
+ }
+
+ return champion;
+};
From a23ef9ea1cdd9afedfe15ed5e98b0c69d7accea9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 22:14:25 -0500
Subject: [PATCH 342/994] Add solution #2925
---
README.md | 1 +
...ore-after-applying-operations-on-a-tree.js | 58 +++++++++++++++++++
2 files changed, 59 insertions(+)
create mode 100644 solutions/2925-maximum-score-after-applying-operations-on-a-tree.js
diff --git a/README.md b/README.md
index ebe62fea..3ebde2b9 100644
--- a/README.md
+++ b/README.md
@@ -2087,6 +2087,7 @@
2918|[Minimum Equal Sum of Two Arrays After Replacing Zeros](./solutions/2918-minimum-equal-sum-of-two-arrays-after-replacing-zeros.js)|Medium|
2923|[Find Champion I](./solutions/2923-find-champion-i.js)|Easy|
2924|[Find Champion II](./solutions/2924-find-champion-ii.js)|Medium|
+2925|[Maximum Score After Applying Operations on a Tree](./solutions/2925-maximum-score-after-applying-operations-on-a-tree.js)|Medium|
2929|[Distribute Candies Among Children II](./solutions/2929-distribute-candies-among-children-ii.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|
diff --git a/solutions/2925-maximum-score-after-applying-operations-on-a-tree.js b/solutions/2925-maximum-score-after-applying-operations-on-a-tree.js
new file mode 100644
index 00000000..55cb4532
--- /dev/null
+++ b/solutions/2925-maximum-score-after-applying-operations-on-a-tree.js
@@ -0,0 +1,58 @@
+/**
+ * 2925. Maximum Score After Applying Operations on a Tree
+ * https://leetcode.com/problems/maximum-score-after-applying-operations-on-a-tree/
+ * Difficulty: Medium
+ *
+ * There is an undirected tree with n nodes labeled from 0 to n - 1, and rooted at node 0. You are
+ * given a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there
+ * is an edge between nodes ai and bi in the tree.
+ *
+ * You are also given a 0-indexed integer array values of length n, where values[i] is the value
+ * associated with the ith node.
+ *
+ * You start with a score of 0. In one operation, you can:
+ * - Pick any node i.
+ * - Add values[i] to your score.
+ * - Set values[i] to 0.
+ *
+ * A tree is healthy if the sum of values on the path from the root to any leaf node is different
+ * than zero.
+ *
+ * Return the maximum score you can obtain after performing these operations on the tree any
+ * number of times so that it remains healthy.
+ */
+
+/**
+ * @param {number[][]} edges
+ * @param {number[]} values
+ * @return {number}
+ */
+var maximumScoreAfterOperations = function(edges, values) {
+ const n = values.length;
+ const graph = new Array(n).fill().map(() => []);
+
+ for (const [u, v] of edges) {
+ graph[u].push(v);
+ graph[v].push(u);
+ }
+
+ const totalSum = values.reduce((sum, val) => sum + val, 0);
+ const minToKeep = dfs(0, -1);
+
+ return totalSum - minToKeep;
+
+ function dfs(node, parent) {
+ const children = graph[node].filter(child => child !== parent);
+
+ if (children.length === 0) {
+ return values[node];
+ }
+
+ let childrenSum = 0;
+ for (const child of children) {
+ childrenSum += dfs(child, node);
+ }
+
+ return Math.min(values[node], childrenSum);
+ }
+};
From b16149ddb0b4ad433e746ac8b984984903073e4b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 22:15:41 -0500
Subject: [PATCH 343/994] Add solution #2928
---
README.md | 1 +
...928-distribute-candies-among-children-i.js | 28 +++++++++++++++++++
2 files changed, 29 insertions(+)
create mode 100644 solutions/2928-distribute-candies-among-children-i.js
diff --git a/README.md b/README.md
index 3ebde2b9..1d736caf 100644
--- a/README.md
+++ b/README.md
@@ -2088,6 +2088,7 @@
2923|[Find Champion I](./solutions/2923-find-champion-i.js)|Easy|
2924|[Find Champion II](./solutions/2924-find-champion-ii.js)|Medium|
2925|[Maximum Score After Applying Operations on a Tree](./solutions/2925-maximum-score-after-applying-operations-on-a-tree.js)|Medium|
+2928|[Distribute Candies Among Children I](./solutions/2928-distribute-candies-among-children-i.js)|Easy|
2929|[Distribute Candies Among Children II](./solutions/2929-distribute-candies-among-children-ii.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|
diff --git a/solutions/2928-distribute-candies-among-children-i.js b/solutions/2928-distribute-candies-among-children-i.js
new file mode 100644
index 00000000..fe0c287d
--- /dev/null
+++ b/solutions/2928-distribute-candies-among-children-i.js
@@ -0,0 +1,28 @@
+/**
+ * 2928. Distribute Candies Among Children I
+ * https://leetcode.com/problems/distribute-candies-among-children-i/
+ * Difficulty: Easy
+ *
+ * You are given two positive integers n and limit.
+ *
+ * Return the total number of ways to distribute n candies among 3 children such that no child
+ * gets more than limit candies.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} limit
+ * @return {number}
+ */
+var distributeCandies = function(n, limit) {
+ let result = 0;
+
+ for (let i = 0; i <= Math.min(n, limit); i++) {
+ for (let j = 0; j <= Math.min(n - i, limit); j++) {
+ const k = n - i - j;
+ if (k >= 0 && k <= limit) result++;
+ }
+ }
+
+ return result;
+};
From 135555edbc4e9a12a2aebfc3f85fb3fd19f9886c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 22:38:33 -0500
Subject: [PATCH 344/994] Add solution #2932
---
README.md | 1 +
solutions/2932-maximum-strong-pair-xor-i.js | 37 +++++++++++++++++++++
2 files changed, 38 insertions(+)
create mode 100644 solutions/2932-maximum-strong-pair-xor-i.js
diff --git a/README.md b/README.md
index 1d736caf..ec5f205c 100644
--- a/README.md
+++ b/README.md
@@ -2090,6 +2090,7 @@
2925|[Maximum Score After Applying Operations on a Tree](./solutions/2925-maximum-score-after-applying-operations-on-a-tree.js)|Medium|
2928|[Distribute Candies Among Children I](./solutions/2928-distribute-candies-among-children-i.js)|Easy|
2929|[Distribute Candies Among Children II](./solutions/2929-distribute-candies-among-children-ii.js)|Medium|
+2932|[Maximum Strong Pair XOR I](./solutions/2932-maximum-strong-pair-xor-i.js)|Easy|
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|
diff --git a/solutions/2932-maximum-strong-pair-xor-i.js b/solutions/2932-maximum-strong-pair-xor-i.js
new file mode 100644
index 00000000..67477b17
--- /dev/null
+++ b/solutions/2932-maximum-strong-pair-xor-i.js
@@ -0,0 +1,37 @@
+/**
+ * 2932. Maximum Strong Pair XOR I
+ * https://leetcode.com/problems/maximum-strong-pair-xor-i/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums. A pair of integers x and y is called a strong pair
+ * if it satisfies the condition:
+ * - |x - y| <= min(x, y)
+ *
+ * You need to select two integers from nums such that they form a strong pair and their bitwise
+ * XOR is the maximum among all strong pairs in the array.
+ *
+ * Return the maximum XOR value out of all possible strong pairs in the array nums.
+ *
+ * Note that you can pick the same integer twice to form a pair.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maximumStrongPairXor = function(nums) {
+ let result = 0;
+ nums.sort((a, b) => a - b);
+
+ for (let i = 0; i < nums.length; i++) {
+ for (let j = i; j < nums.length; j++) {
+ if (nums[j] - nums[i] <= Math.min(nums[i], nums[j])) {
+ result = Math.max(result, nums[i] ^ nums[j]);
+ } else {
+ break;
+ }
+ }
+ }
+
+ return result;
+};
From 46b5b3ceb30c1949880a96f5222c75fa89cac5e9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 22:41:54 -0500
Subject: [PATCH 345/994] Add solution #2933
---
README.md | 1 +
solutions/2933-high-access-employees.js | 54 +++++++++++++++++++++++++
2 files changed, 55 insertions(+)
create mode 100644 solutions/2933-high-access-employees.js
diff --git a/README.md b/README.md
index ec5f205c..3a9cb8c5 100644
--- a/README.md
+++ b/README.md
@@ -2091,6 +2091,7 @@
2928|[Distribute Candies Among Children I](./solutions/2928-distribute-candies-among-children-i.js)|Easy|
2929|[Distribute Candies Among Children II](./solutions/2929-distribute-candies-among-children-ii.js)|Medium|
2932|[Maximum Strong Pair XOR I](./solutions/2932-maximum-strong-pair-xor-i.js)|Easy|
+2933|[High-Access Employees](./solutions/2933-high-access-employees.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|
diff --git a/solutions/2933-high-access-employees.js b/solutions/2933-high-access-employees.js
new file mode 100644
index 00000000..98c9a73f
--- /dev/null
+++ b/solutions/2933-high-access-employees.js
@@ -0,0 +1,54 @@
+/**
+ * 2933. High-Access Employees
+ * https://leetcode.com/problems/high-access-employees/
+ * Difficulty: Medium
+ *
+ * You are given a 2D 0-indexed array of strings, accessTimes, with size n. For each i where
+ * 0 <= i <= n - 1, accessTimes[i][0] represents the name of an employee, and accessTimes[i][1]
+ * represents the access time of that employee. All entries in accessTimes are within the same day.
+ *
+ * The access time is represented as four digits using a 24-hour time format, for example, "0800"
+ * or "2250".
+ *
+ * An employee is said to be high-access if he has accessed the system three or more times within
+ * a one-hour period.
+ *
+ * Times with exactly one hour of difference are not considered part of the same one-hour period.
+ * For example, "0815" and "0915" are not part of the same one-hour period.
+ *
+ * Access times at the start and end of the day are not counted within the same one-hour period.
+ * For example, "0005" and "2350" are not part of the same one-hour period.
+ *
+ * Return a list that contains the names of high-access employees with any order you want.
+ */
+
+/**
+ * @param {string[][]} accessTimes
+ * @return {string[]}
+ */
+var findHighAccessEmployees = function(accessTimes) {
+ const employeeAccess = new Map();
+
+ for (const [name, time] of accessTimes) {
+ const minutes = parseInt(time.slice(0, 2)) * 60 + parseInt(time.slice(2));
+ if (!employeeAccess.has(name)) {
+ employeeAccess.set(name, []);
+ }
+ employeeAccess.get(name).push(minutes);
+ }
+
+ const result = [];
+ for (const [name, times] of employeeAccess) {
+ times.sort((a, b) => a - b);
+ if (times.length >= 3) {
+ for (let i = 0; i <= times.length - 3; i++) {
+ if (times[i + 2] - times[i] < 60) {
+ result.push(name);
+ break;
+ }
+ }
+ }
+ }
+
+ return result;
+};
From e2d9e8baed1cbad586e2fd26760630c81b8889ae Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 23:43:29 -0500
Subject: [PATCH 346/994] Add solution #2934
---
README.md | 1 +
...ons-to-maximize-last-elements-in-arrays.js | 57 +++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/2934-minimum-operations-to-maximize-last-elements-in-arrays.js
diff --git a/README.md b/README.md
index 3a9cb8c5..cbe21d44 100644
--- a/README.md
+++ b/README.md
@@ -2092,6 +2092,7 @@
2929|[Distribute Candies Among Children II](./solutions/2929-distribute-candies-among-children-ii.js)|Medium|
2932|[Maximum Strong Pair XOR I](./solutions/2932-maximum-strong-pair-xor-i.js)|Easy|
2933|[High-Access Employees](./solutions/2933-high-access-employees.js)|Medium|
+2934|[Minimum Operations to Maximize Last Elements in Arrays](./solutions/2934-minimum-operations-to-maximize-last-elements-in-arrays.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|
diff --git a/solutions/2934-minimum-operations-to-maximize-last-elements-in-arrays.js b/solutions/2934-minimum-operations-to-maximize-last-elements-in-arrays.js
new file mode 100644
index 00000000..c2803a60
--- /dev/null
+++ b/solutions/2934-minimum-operations-to-maximize-last-elements-in-arrays.js
@@ -0,0 +1,57 @@
+/**
+ * 2934. Minimum Operations to Maximize Last Elements in Arrays
+ * https://leetcode.com/problems/minimum-operations-to-maximize-last-elements-in-arrays/
+ * Difficulty: Medium
+ *
+ * You are given two 0-indexed integer arrays, nums1 and nums2, both having length n.
+ *
+ * You are allowed to perform a series of operations (possibly none).
+ *
+ * In an operation, you select an index i in the range [0, n - 1] and swap the values of
+ * nums1[i] and nums2[i].
+ *
+ * Your task is to find the minimum number of operations required to satisfy the following
+ * conditions:
+ * - nums1[n - 1] is equal to the maximum value among all elements of nums1, i.e.,
+ * nums1[n - 1] = max(nums1[0], nums1[1], ..., nums1[n - 1]).
+ * - nums2[n - 1] is equal to the maximum value among all elements of nums2, i.e.,
+ * nums2[n - 1] = max(nums2[0], nums2[1], ..., nums2[n - 1]).
+ *
+ * Return an integer denoting the minimum number of operations needed to meet both conditions,
+ * or -1 if it is impossible to satisfy both conditions.
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @return {number}
+ */
+var minOperations = function(nums1, nums2) {
+ const n = nums1.length;
+ const last1 = nums1[n - 1];
+ const last2 = nums2[n - 1];
+
+ let swapsNoChange = 0;
+ let swapsChange = 0;
+
+ for (let i = 0; i < n - 1; i++) {
+ if (nums1[i] > last1 || nums2[i] > last2) {
+ if (nums2[i] > last1 || nums1[i] > last2) {
+ return -1;
+ }
+ swapsNoChange++;
+ }
+ if (nums1[i] > last2 || nums2[i] > last1) {
+ if (nums2[i] > last2 || nums1[i] > last1) {
+ return -1;
+ }
+ swapsChange++;
+ }
+ }
+
+ if (last1 !== last2) {
+ swapsChange++;
+ }
+
+ return Math.min(swapsNoChange, swapsChange);
+};
From a7a8ce14f2851b3e7cf73d59c1f3e65bf816013a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 23:44:27 -0500
Subject: [PATCH 347/994] Add solution #2937
---
README.md | 1 +
solutions/2937-make-three-strings-equal.js | 35 ++++++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/2937-make-three-strings-equal.js
diff --git a/README.md b/README.md
index cbe21d44..1b09c37c 100644
--- a/README.md
+++ b/README.md
@@ -2093,6 +2093,7 @@
2932|[Maximum Strong Pair XOR I](./solutions/2932-maximum-strong-pair-xor-i.js)|Easy|
2933|[High-Access Employees](./solutions/2933-high-access-employees.js)|Medium|
2934|[Minimum Operations to Maximize Last Elements in Arrays](./solutions/2934-minimum-operations-to-maximize-last-elements-in-arrays.js)|Medium|
+2937|[Make Three Strings Equal](./solutions/2937-make-three-strings-equal.js)|Easy|
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|
diff --git a/solutions/2937-make-three-strings-equal.js b/solutions/2937-make-three-strings-equal.js
new file mode 100644
index 00000000..c7dad334
--- /dev/null
+++ b/solutions/2937-make-three-strings-equal.js
@@ -0,0 +1,35 @@
+/**
+ * 2937. Make Three Strings Equal
+ * https://leetcode.com/problems/make-three-strings-equal/
+ * Difficulty: Easy
+ *
+ * You are given three strings: s1, s2, and s3. In one operation you can choose one of these
+ * strings and delete its rightmost character. Note that you cannot completely empty a string.
+ *
+ * Return the minimum number of operations required to make the strings equal. If it is
+ * impossible to make them equal, return -1.
+ */
+
+/**
+ * @param {string} s1
+ * @param {string} s2
+ * @param {string} s3
+ * @return {number}
+ */
+var findMinimumOperations = function(s1, s2, s3) {
+ const minLength = Math.min(s1.length, s2.length, s3.length);
+
+ let commonPrefixLength = 0;
+ for (let i = 0; i < minLength; i++) {
+ if (s1[i] !== s2[i] || s2[i] !== s3[i]) {
+ break;
+ }
+ commonPrefixLength++;
+ }
+
+ if (commonPrefixLength === 0) {
+ return -1;
+ }
+
+ return s1.length + s2.length + s3.length - 3 * commonPrefixLength;
+};
From fd57e606f75d48643c535fde44df856e853c4ad2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 23:47:40 -0500
Subject: [PATCH 348/994] Add solution #2938
---
README.md | 1 +
.../2938-separate-black-and-white-balls.js | 33 +++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/2938-separate-black-and-white-balls.js
diff --git a/README.md b/README.md
index 1b09c37c..0df8750c 100644
--- a/README.md
+++ b/README.md
@@ -2094,6 +2094,7 @@
2933|[High-Access Employees](./solutions/2933-high-access-employees.js)|Medium|
2934|[Minimum Operations to Maximize Last Elements in Arrays](./solutions/2934-minimum-operations-to-maximize-last-elements-in-arrays.js)|Medium|
2937|[Make Three Strings Equal](./solutions/2937-make-three-strings-equal.js)|Easy|
+2938|[Separate Black and White Balls](./solutions/2938-separate-black-and-white-balls.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|
diff --git a/solutions/2938-separate-black-and-white-balls.js b/solutions/2938-separate-black-and-white-balls.js
new file mode 100644
index 00000000..cd8d022d
--- /dev/null
+++ b/solutions/2938-separate-black-and-white-balls.js
@@ -0,0 +1,33 @@
+/**
+ * 2938. Separate Black and White Balls
+ * https://leetcode.com/problems/separate-black-and-white-balls/
+ * Difficulty: Medium
+ *
+ * There are n balls on a table, each ball has a color black or white.
+ *
+ * You are given a 0-indexed binary string s of length n, where 1 and 0 represent black and white
+ * balls, respectively.
+ *
+ * In each step, you can choose two adjacent balls and swap them.
+ *
+ * Return the minimum number of steps to group all the black balls to the right and all the white
+ * balls to the left.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var minimumSteps = function(s) {
+ let result = 0;
+ let whiteCount = 0;
+
+ for (let i = 0; i < s.length; i++) {
+ if (s[i] === '0') {
+ result += i - whiteCount;
+ whiteCount++;
+ }
+ }
+
+ return result;
+};
From fbb835747a462266fd58c471b672a4e1368019ae Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 23:48:39 -0500
Subject: [PATCH 349/994] Add solution #2946
---
README.md | 1 +
...6-matrix-similarity-after-cyclic-shifts.js | 35 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/2946-matrix-similarity-after-cyclic-shifts.js
diff --git a/README.md b/README.md
index 0df8750c..272aa5f7 100644
--- a/README.md
+++ b/README.md
@@ -2096,6 +2096,7 @@
2937|[Make Three Strings Equal](./solutions/2937-make-three-strings-equal.js)|Easy|
2938|[Separate Black and White Balls](./solutions/2938-separate-black-and-white-balls.js)|Medium|
2942|[Find Words Containing Character](./solutions/2942-find-words-containing-character.js)|Easy|
+2946|[Matrix Similarity After Cyclic Shifts](./solutions/2946-matrix-similarity-after-cyclic-shifts.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/2946-matrix-similarity-after-cyclic-shifts.js b/solutions/2946-matrix-similarity-after-cyclic-shifts.js
new file mode 100644
index 00000000..4d93251f
--- /dev/null
+++ b/solutions/2946-matrix-similarity-after-cyclic-shifts.js
@@ -0,0 +1,35 @@
+/**
+ * 2946. Matrix Similarity After Cyclic Shifts
+ * https://leetcode.com/problems/matrix-similarity-after-cyclic-shifts/
+ * Difficulty: Easy
+ *
+ * You are given an m x n integer matrix mat and an integer k. The matrix rows are 0-indexed.
+ *
+ * The following proccess happens k times:
+ * - Even-indexed rows (0, 2, 4, ...) are cyclically shifted to the left.
+ * - Odd-indexed rows (1, 3, 5, ...) are cyclically shifted to the right.
+ *
+ * Return true if the final modified matrix after k steps is identical to the original matrix,
+ * and false otherwise.
+ */
+
+/**
+ * @param {number[][]} mat
+ * @param {number} k
+ * @return {boolean}
+ */
+var areSimilar = function(mat, k) {
+ const m = mat.length;
+ const n = mat[0].length;
+
+ for (let i = 0; i < m; i++) {
+ for (let j = 0; j < n; j++) {
+ const shift = i % 2 === 0 ? (j - k % n + n) % n : (j + k % n) % n;
+ if (mat[i][j] !== mat[i][shift]) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+};
From 62eac7e6e59f44ae872922816c1c075e16294094 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 4 Jun 2025 23:49:55 -0500
Subject: [PATCH 350/994] Add solution #2947
---
README.md | 1 +
.../2947-count-beautiful-substrings-i.js | 51 +++++++++++++++++++
2 files changed, 52 insertions(+)
create mode 100644 solutions/2947-count-beautiful-substrings-i.js
diff --git a/README.md b/README.md
index 272aa5f7..78095fa2 100644
--- a/README.md
+++ b/README.md
@@ -2097,6 +2097,7 @@
2938|[Separate Black and White Balls](./solutions/2938-separate-black-and-white-balls.js)|Medium|
2942|[Find Words Containing Character](./solutions/2942-find-words-containing-character.js)|Easy|
2946|[Matrix Similarity After Cyclic Shifts](./solutions/2946-matrix-similarity-after-cyclic-shifts.js)|Easy|
+2947|[Count Beautiful Substrings I](./solutions/2947-count-beautiful-substrings-i.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/2947-count-beautiful-substrings-i.js b/solutions/2947-count-beautiful-substrings-i.js
new file mode 100644
index 00000000..0972a990
--- /dev/null
+++ b/solutions/2947-count-beautiful-substrings-i.js
@@ -0,0 +1,51 @@
+/**
+ * 2947. Count Beautiful Substrings I
+ * https://leetcode.com/problems/count-beautiful-substrings-i/
+ * Difficulty: Medium
+ *
+ * You are given a string s and a positive integer k.
+ *
+ * Let vowels and consonants be the number of vowels and consonants in a string.
+ *
+ * A string is beautiful if:
+ * - vowels == consonants.
+ * - (vowels * consonants) % k == 0, in other terms the multiplication of vowels and
+ * consonants is divisible by k.
+ *
+ * Return the number of non-empty beautiful substrings in the given string s.
+ *
+ * A substring is a contiguous sequence of characters in a string.
+ *
+ * Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.
+ *
+ * Consonant letters in English are every letter except vowels.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} k
+ * @return {number}
+ */
+var beautifulSubstrings = function(s, k) {
+ const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
+ let result = 0;
+
+ for (let start = 0; start < s.length; start++) {
+ let vowelCount = 0;
+ let consonantCount = 0;
+
+ for (let end = start; end < s.length; end++) {
+ if (vowels.has(s[end])) {
+ vowelCount++;
+ } else {
+ consonantCount++;
+ }
+
+ if (vowelCount === consonantCount && (vowelCount * consonantCount) % k === 0) {
+ result++;
+ }
+ }
+ }
+
+ return result;
+};
From 6077d6b590fdeaa812cd56c72247b4497adb6472 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 00:02:42 -0500
Subject: [PATCH 351/994] Add solution #2951
---
README.md | 1 +
solutions/2951-find-the-peaks.js | 30 ++++++++++++++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 solutions/2951-find-the-peaks.js
diff --git a/README.md b/README.md
index 78095fa2..89b0af4d 100644
--- a/README.md
+++ b/README.md
@@ -2099,6 +2099,7 @@
2946|[Matrix Similarity After Cyclic Shifts](./solutions/2946-matrix-similarity-after-cyclic-shifts.js)|Easy|
2947|[Count Beautiful Substrings I](./solutions/2947-count-beautiful-substrings-i.js)|Medium|
2948|[Make Lexicographically Smallest Array by Swapping Elements](./solutions/2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium|
+2951|[Find the Peaks](./solutions/2951-find-the-peaks.js)|Easy|
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|
diff --git a/solutions/2951-find-the-peaks.js b/solutions/2951-find-the-peaks.js
new file mode 100644
index 00000000..45e40576
--- /dev/null
+++ b/solutions/2951-find-the-peaks.js
@@ -0,0 +1,30 @@
+/**
+ * 2951. Find the Peaks
+ * https://leetcode.com/problems/find-the-peaks/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed array mountain. Your task is to find all the peaks in the
+ * mountain array.
+ *
+ * Return an array that consists of indices of peaks in the given array in any order.
+ *
+ * Notes:
+ * - A peak is defined as an element that is strictly greater than its neighboring elements.
+ * - The first and last elements of the array are not a peak.
+ */
+
+/**
+ * @param {number[]} mountain
+ * @return {number[]}
+ */
+var findPeaks = function(mountain) {
+ const result = [];
+
+ for (let i = 1; i < mountain.length - 1; i++) {
+ if (mountain[i] > mountain[i - 1] && mountain[i] > mountain[i + 1]) {
+ result.push(i);
+ }
+ }
+
+ return result;
+};
From b8f33a614859032a24630811c0e6305672b90d70 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 00:03:55 -0500
Subject: [PATCH 352/994] Add solution #2952
---
README.md | 1 +
...952-minimum-number-of-coins-to-be-added.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/2952-minimum-number-of-coins-to-be-added.js
diff --git a/README.md b/README.md
index 89b0af4d..3b3262ea 100644
--- a/README.md
+++ b/README.md
@@ -2100,6 +2100,7 @@
2947|[Count Beautiful Substrings I](./solutions/2947-count-beautiful-substrings-i.js)|Medium|
2948|[Make Lexicographically Smallest Array by Swapping Elements](./solutions/2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium|
2951|[Find the Peaks](./solutions/2951-find-the-peaks.js)|Easy|
+2952|[Minimum Number of Coins to be Added](./solutions/2952-minimum-number-of-coins-to-be-added.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|
diff --git a/solutions/2952-minimum-number-of-coins-to-be-added.js b/solutions/2952-minimum-number-of-coins-to-be-added.js
new file mode 100644
index 00000000..8290c3f1
--- /dev/null
+++ b/solutions/2952-minimum-number-of-coins-to-be-added.js
@@ -0,0 +1,41 @@
+/**
+ * 2952. Minimum Number of Coins to be Added
+ * https://leetcode.com/problems/minimum-number-of-coins-to-be-added/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array coins, representing the values of the coins available,
+ * and an integer target.
+ *
+ * An integer x is obtainable if there exists a subsequence of coins that sums to x.
+ *
+ * Return the minimum number of coins of any value that need to be added to the array so that every
+ * integer in the range [1, target] is obtainable.
+ *
+ * A subsequence of an array is a new non-empty array that is formed from the original array by
+ * deleting some (possibly none) of the elements without disturbing the relative positions of the
+ * remaining elements.
+ */
+
+/**
+ * @param {number[]} coins
+ * @param {number} target
+ * @return {number}
+ */
+var minimumAddedCoins = function(coins, target) {
+ coins.sort((a, b) => a - b);
+ let result = 0;
+ let currentMax = 0;
+ let index = 0;
+
+ while (currentMax < target) {
+ if (index < coins.length && coins[index] <= currentMax + 1) {
+ currentMax += coins[index];
+ index++;
+ } else {
+ currentMax += currentMax + 1;
+ result++;
+ }
+ }
+
+ return result;
+};
From 9dbe97dfe6b7df6a876acb96e7058bbf4f2a0d37 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 00:05:06 -0500
Subject: [PATCH 353/994] Add solution #2956
---
README.md | 1 +
...find-common-elements-between-two-arrays.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/2956-find-common-elements-between-two-arrays.js
diff --git a/README.md b/README.md
index 3b3262ea..2aefaf72 100644
--- a/README.md
+++ b/README.md
@@ -2101,6 +2101,7 @@
2948|[Make Lexicographically Smallest Array by Swapping Elements](./solutions/2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium|
2951|[Find the Peaks](./solutions/2951-find-the-peaks.js)|Easy|
2952|[Minimum Number of Coins to be Added](./solutions/2952-minimum-number-of-coins-to-be-added.js)|Medium|
+2956|[Find Common Elements Between Two Arrays](./solutions/2956-find-common-elements-between-two-arrays.js)|Easy|
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|
diff --git a/solutions/2956-find-common-elements-between-two-arrays.js b/solutions/2956-find-common-elements-between-two-arrays.js
new file mode 100644
index 00000000..8189c0e2
--- /dev/null
+++ b/solutions/2956-find-common-elements-between-two-arrays.js
@@ -0,0 +1,39 @@
+/**
+ * 2956. Find Common Elements Between Two Arrays
+ * https://leetcode.com/problems/find-common-elements-between-two-arrays/
+ * Difficulty: Easy
+ *
+ * You are given two integer arrays nums1 and nums2 of sizes n and m, respectively.
+ * Calculate the following values:
+ * - answer1 : the number of indices i such that nums1[i] exists in nums2.
+ * - answer2 : the number of indices i such that nums2[i] exists in nums1.
+ *
+ * Return [answer1,answer2].
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @return {number[]}
+ */
+var findIntersectionValues = function(nums1, nums2) {
+ const set1 = new Set(nums1);
+ const set2 = new Set(nums2);
+
+ let count1 = 0;
+ let count2 = 0;
+
+ for (const num of nums1) {
+ if (set2.has(num)) {
+ count1++;
+ }
+ }
+
+ for (const num of nums2) {
+ if (set1.has(num)) {
+ count2++;
+ }
+ }
+
+ return [count1, count2];
+};
From 70f15bc40282b0ad7d058c5675dcc41f2124c888 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 00:06:05 -0500
Subject: [PATCH 354/994] Add solution #2957
---
README.md | 1 +
...remove-adjacent-almost-equal-characters.js | 32 +++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/2957-remove-adjacent-almost-equal-characters.js
diff --git a/README.md b/README.md
index 2aefaf72..404fc1a0 100644
--- a/README.md
+++ b/README.md
@@ -2102,6 +2102,7 @@
2951|[Find the Peaks](./solutions/2951-find-the-peaks.js)|Easy|
2952|[Minimum Number of Coins to be Added](./solutions/2952-minimum-number-of-coins-to-be-added.js)|Medium|
2956|[Find Common Elements Between Two Arrays](./solutions/2956-find-common-elements-between-two-arrays.js)|Easy|
+2957|[Remove Adjacent Almost-Equal Characters](./solutions/2957-remove-adjacent-almost-equal-characters.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|
diff --git a/solutions/2957-remove-adjacent-almost-equal-characters.js b/solutions/2957-remove-adjacent-almost-equal-characters.js
new file mode 100644
index 00000000..c62070dc
--- /dev/null
+++ b/solutions/2957-remove-adjacent-almost-equal-characters.js
@@ -0,0 +1,32 @@
+/**
+ * 2957. Remove Adjacent Almost-Equal Characters
+ * https://leetcode.com/problems/remove-adjacent-almost-equal-characters/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed string word.
+ *
+ * In one operation, you can pick any index i of word and change word[i] to any lowercase
+ * English letter.
+ *
+ * Return the minimum number of operations needed to remove all adjacent almost-equal
+ * characters from word.
+ *
+ * Two characters a and b are almost-equal if a == b or a and b are adjacent in the alphabet.
+ */
+
+/**
+ * @param {string} word
+ * @return {number}
+ */
+var removeAlmostEqualCharacters = function(word) {
+ let result = 0;
+
+ for (let i = 1; i < word.length; i++) {
+ if (Math.abs(word.charCodeAt(i) - word.charCodeAt(i - 1)) <= 1) {
+ result++;
+ i++;
+ }
+ }
+
+ return result;
+};
From 40768a242d8499ffda5efab3081a037141aec583 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 00:07:23 -0500
Subject: [PATCH 355/994] Add solution #2958
---
README.md | 1 +
...ngest-subarray-with-at-most-k-frequency.js | 40 +++++++++++++++++++
2 files changed, 41 insertions(+)
create mode 100644 solutions/2958-length-of-longest-subarray-with-at-most-k-frequency.js
diff --git a/README.md b/README.md
index 404fc1a0..124100e6 100644
--- a/README.md
+++ b/README.md
@@ -2103,6 +2103,7 @@
2952|[Minimum Number of Coins to be Added](./solutions/2952-minimum-number-of-coins-to-be-added.js)|Medium|
2956|[Find Common Elements Between Two Arrays](./solutions/2956-find-common-elements-between-two-arrays.js)|Easy|
2957|[Remove Adjacent Almost-Equal Characters](./solutions/2957-remove-adjacent-almost-equal-characters.js)|Medium|
+2958|[Length of Longest Subarray With at Most K Frequency](./solutions/2958-length-of-longest-subarray-with-at-most-k-frequency.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|
diff --git a/solutions/2958-length-of-longest-subarray-with-at-most-k-frequency.js b/solutions/2958-length-of-longest-subarray-with-at-most-k-frequency.js
new file mode 100644
index 00000000..4efcb001
--- /dev/null
+++ b/solutions/2958-length-of-longest-subarray-with-at-most-k-frequency.js
@@ -0,0 +1,40 @@
+/**
+ * 2958. Length of Longest Subarray With at Most K Frequency
+ * https://leetcode.com/problems/length-of-longest-subarray-with-at-most-k-frequency/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums and an integer k.
+ *
+ * The frequency of an element x is the number of times it occurs in an array.
+ *
+ * An array is called good if the frequency of each element in this array is less than or
+ * equal to k.
+ *
+ * Return the length of the longest good subarray of nums.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var maxSubarrayLength = function(nums, k) {
+ const map = new Map();
+ let result = 0;
+ let left = 0;
+
+ for (let right = 0; right < nums.length; right++) {
+ map.set(nums[right], (map.get(nums[right]) || 0) + 1);
+
+ while (map.get(nums[right]) > k) {
+ map.set(nums[left], map.get(nums[left]) - 1);
+ left++;
+ }
+
+ result = Math.max(result, right - left + 1);
+ }
+
+ return result;
+};
From 12ba5ea261a8bf9422fe81264f82f05d69fced20 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 19:18:36 -0500
Subject: [PATCH 356/994] Add solution #2960
---
README.md | 1 +
...nt-tested-devices-after-test-operations.js | 40 +++++++++++++++++++
2 files changed, 41 insertions(+)
create mode 100644 solutions/2960-count-tested-devices-after-test-operations.js
diff --git a/README.md b/README.md
index 124100e6..8e9e4e07 100644
--- a/README.md
+++ b/README.md
@@ -2104,6 +2104,7 @@
2956|[Find Common Elements Between Two Arrays](./solutions/2956-find-common-elements-between-two-arrays.js)|Easy|
2957|[Remove Adjacent Almost-Equal Characters](./solutions/2957-remove-adjacent-almost-equal-characters.js)|Medium|
2958|[Length of Longest Subarray With at Most K Frequency](./solutions/2958-length-of-longest-subarray-with-at-most-k-frequency.js)|Medium|
+2960|[Count Tested Devices After Test Operations](./solutions/2960-count-tested-devices-after-test-operations.js)|Easy|
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|
diff --git a/solutions/2960-count-tested-devices-after-test-operations.js b/solutions/2960-count-tested-devices-after-test-operations.js
new file mode 100644
index 00000000..6c118fb3
--- /dev/null
+++ b/solutions/2960-count-tested-devices-after-test-operations.js
@@ -0,0 +1,40 @@
+/**
+ * 2960. Count Tested Devices After Test Operations
+ * https://leetcode.com/problems/count-tested-devices-after-test-operations/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array batteryPercentages having length n, denoting the
+ * battery percentages of n 0-indexed devices.
+ *
+ * Your task is to test each device i in order from 0 to n - 1, by performing the following
+ * test operations:
+ * - If batteryPercentages[i] is greater than 0:
+ * - Increment the count of tested devices.
+ * - Decrease the battery percentage of all devices with indices j in the range [i + 1, n - 1]
+ * by 1, ensuring their battery percentage never goes below 0, i.e,
+ * batteryPercentages[j] = max(0, batteryPercentages[j] - 1).
+ * - Move to the next device.
+ * - Otherwise, move to the next device without performing any test.
+ *
+ * Return an integer denoting the number of devices that will be tested after performing the test
+ * operations in order.
+ */
+
+/**
+ * @param {number[]} batteryPercentages
+ * @return {number}
+ */
+var countTestedDevices = function(batteryPercentages) {
+ let result = 0;
+
+ for (let i = 0; i < batteryPercentages.length; i++) {
+ if (batteryPercentages[i] > 0) {
+ result++;
+ for (let j = i + 1; j < batteryPercentages.length; j++) {
+ batteryPercentages[j] = Math.max(0, batteryPercentages[j] - 1);
+ }
+ }
+ }
+
+ return result;
+};
From 83667fb894fe97e80bd3eba3553f0488f7825dbb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 19:20:33 -0500
Subject: [PATCH 357/994] Add solution #2961
---
README.md | 1 +
.../2961-double-modular-exponentiation.js | 43 +++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/2961-double-modular-exponentiation.js
diff --git a/README.md b/README.md
index 8e9e4e07..c3d81976 100644
--- a/README.md
+++ b/README.md
@@ -2105,6 +2105,7 @@
2957|[Remove Adjacent Almost-Equal Characters](./solutions/2957-remove-adjacent-almost-equal-characters.js)|Medium|
2958|[Length of Longest Subarray With at Most K Frequency](./solutions/2958-length-of-longest-subarray-with-at-most-k-frequency.js)|Medium|
2960|[Count Tested Devices After Test Operations](./solutions/2960-count-tested-devices-after-test-operations.js)|Easy|
+2961|[Double Modular Exponentiation](./solutions/2961-double-modular-exponentiation.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|
diff --git a/solutions/2961-double-modular-exponentiation.js b/solutions/2961-double-modular-exponentiation.js
new file mode 100644
index 00000000..1a9f9162
--- /dev/null
+++ b/solutions/2961-double-modular-exponentiation.js
@@ -0,0 +1,43 @@
+/**
+ * 2961. Double Modular Exponentiation
+ * https://leetcode.com/problems/double-modular-exponentiation/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed 2D array variables where variables[i] = [ai, bi, ci, mi], and an
+ * integer target.
+ *
+ * An index i is good if the following formula holds:
+ * - 0 <= i < variables.length
+ * - ((aibi % 10)ci) % mi == target
+ *
+ * Return an array consisting of good indices in any order.
+ */
+
+/**
+ * @param {number[][]} variables
+ * @param {number} target
+ * @return {number[]}
+ */
+var getGoodIndices = function(variables, target) {
+ const result = [];
+
+ for (let i = 0; i < variables.length; i++) {
+ const [base, exp1, exp2, modulus] = variables[i];
+
+ let inner = 1;
+ for (let j = 0; j < exp1; j++) {
+ inner = (inner * base) % 10;
+ }
+
+ let count = 1;
+ for (let j = 0; j < exp2; j++) {
+ count = (count * inner) % modulus;
+ }
+
+ if (count === target) {
+ result.push(i);
+ }
+ }
+
+ return result;
+};
From b110ecc45393cb9821a085b241d22bc14e24b13d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 19:23:30 -0500
Subject: [PATCH 358/994] Add solution #2963
---
README.md | 1 +
...963-count-the-number-of-good-partitions.js | 43 +++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/2963-count-the-number-of-good-partitions.js
diff --git a/README.md b/README.md
index c3d81976..da1dbee2 100644
--- a/README.md
+++ b/README.md
@@ -2107,6 +2107,7 @@
2960|[Count Tested Devices After Test Operations](./solutions/2960-count-tested-devices-after-test-operations.js)|Easy|
2961|[Double Modular Exponentiation](./solutions/2961-double-modular-exponentiation.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|
+2963|[Count the Number of Good Partitions](./solutions/2963-count-the-number-of-good-partitions.js)|Hard|
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|
diff --git a/solutions/2963-count-the-number-of-good-partitions.js b/solutions/2963-count-the-number-of-good-partitions.js
new file mode 100644
index 00000000..9144b31e
--- /dev/null
+++ b/solutions/2963-count-the-number-of-good-partitions.js
@@ -0,0 +1,43 @@
+/**
+ * 2963. Count the Number of Good Partitions
+ * https://leetcode.com/problems/count-the-number-of-good-partitions/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed array nums consisting of positive integers.
+ *
+ * A partition of an array into one or more contiguous subarrays is called good if no two
+ * subarrays contain the same number.
+ *
+ * Return the total number of good partitions of nums.
+ *
+ * Since the answer may be large, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var numberOfGoodPartitions = function(nums) {
+ const mod = 1e9 + 7;
+ const map = new Map();
+ let segments = 0;
+ let end = -1;
+
+ for (let i = 0; i < nums.length; i++) {
+ map.set(nums[i], i);
+ }
+
+ for (let i = 0; i < nums.length; i++) {
+ if (i > end) {
+ segments++;
+ }
+ end = Math.max(end, map.get(nums[i]));
+ }
+
+ let result = 1;
+ for (let i = 1; i < segments; i++) {
+ result = (result * 2) % mod;
+ }
+
+ return result;
+};
From ff369b6694fff634a62ad332d92a7765a18248e8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 19:24:50 -0500
Subject: [PATCH 359/994] Add solution #2966
---
README.md | 1 +
...e-array-into-arrays-with-max-difference.js | 33 +++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/2966-divide-array-into-arrays-with-max-difference.js
diff --git a/README.md b/README.md
index da1dbee2..a5590086 100644
--- a/README.md
+++ b/README.md
@@ -2109,6 +2109,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|
2963|[Count the Number of Good Partitions](./solutions/2963-count-the-number-of-good-partitions.js)|Hard|
2965|[Find Missing and Repeated Values](./solutions/2965-find-missing-and-repeated-values.js)|Easy|
+2966|[Divide Array Into Arrays With Max Difference](./solutions/2966-divide-array-into-arrays-with-max-difference.js)|Medium|
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|
diff --git a/solutions/2966-divide-array-into-arrays-with-max-difference.js b/solutions/2966-divide-array-into-arrays-with-max-difference.js
new file mode 100644
index 00000000..3da39b41
--- /dev/null
+++ b/solutions/2966-divide-array-into-arrays-with-max-difference.js
@@ -0,0 +1,33 @@
+/**
+ * 2966. Divide Array Into Arrays With Max Difference
+ * https://leetcode.com/problems/divide-array-into-arrays-with-max-difference/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums of size n where n is a multiple of 3 and a positive
+ * integer k.
+ *
+ * Divide the array nums into n / 3 arrays of size 3 satisfying the following condition:
+ * - The difference between any two elements in one array is less than or equal to k.
+ *
+ * Return a 2D array containing the arrays. If it is impossible to satisfy the conditions, return
+ * an empty array. And if there are multiple answers, return any of them.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number[][]}
+ */
+var divideArray = function(nums, k) {
+ nums.sort((a, b) => a - b);
+ const result = [];
+
+ for (let i = 0; i < nums.length; i += 3) {
+ if (nums[i + 2] - nums[i] > k) {
+ return [];
+ }
+ result.push([nums[i], nums[i + 1], nums[i + 2]]);
+ }
+
+ return result;
+};
From 53177b8ddadab7cae848fdeae36389d8cabfe581 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 19:25:52 -0500
Subject: [PATCH 360/994] Add solution #2970
---
README.md | 1 +
...-the-number-of-incremovable-subarrays-i.js | 46 +++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/2970-count-the-number-of-incremovable-subarrays-i.js
diff --git a/README.md b/README.md
index a5590086..c37b5aa5 100644
--- a/README.md
+++ b/README.md
@@ -2110,6 +2110,7 @@
2963|[Count the Number of Good Partitions](./solutions/2963-count-the-number-of-good-partitions.js)|Hard|
2965|[Find Missing and Repeated Values](./solutions/2965-find-missing-and-repeated-values.js)|Easy|
2966|[Divide Array Into Arrays With Max Difference](./solutions/2966-divide-array-into-arrays-with-max-difference.js)|Medium|
+2970|[Count the Number of Incremovable Subarrays I](./solutions/2970-count-the-number-of-incremovable-subarrays-i.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|
diff --git a/solutions/2970-count-the-number-of-incremovable-subarrays-i.js b/solutions/2970-count-the-number-of-incremovable-subarrays-i.js
new file mode 100644
index 00000000..269065a7
--- /dev/null
+++ b/solutions/2970-count-the-number-of-incremovable-subarrays-i.js
@@ -0,0 +1,46 @@
+/**
+ * 2970. Count the Number of Incremovable Subarrays I
+ * https://leetcode.com/problems/count-the-number-of-incremovable-subarrays-i/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed array of positive integers nums.
+ *
+ * A subarray of nums is called incremovable if nums becomes strictly increasing on removing the
+ * subarray. For example, the subarray [3, 4] is an incremovable subarray of [5, 3, 4, 6, 7] because
+ * removing this subarray changes the array [5, 3, 4, 6, 7] to [5, 6, 7] which is strictly
+ * increasing.
+ *
+ * Return the total number of incremovable subarrays of nums.
+ *
+ * Note that an empty array is considered strictly increasing.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var incremovableSubarrayCount = function(nums) {
+ let result = 0;
+
+ for (let start = 0; start < nums.length; start++) {
+ for (let end = start; end < nums.length; end++) {
+ let isIncreasing = true;
+ let prev = -Infinity;
+
+ for (let i = 0; i < nums.length; i++) {
+ if (i >= start && i <= end) continue;
+ if (nums[i] <= prev) {
+ isIncreasing = false;
+ break;
+ }
+ prev = nums[i];
+ }
+
+ if (isIncreasing) result++;
+ }
+ }
+
+ return result;
+};
From 8029319c277f2145d71e05b364f27ebbe1d39d1c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 19:29:23 -0500
Subject: [PATCH 361/994] Add solution #2971
---
README.md | 1 +
...find-polygon-with-the-largest-perimeter.js | 33 +++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/2971-find-polygon-with-the-largest-perimeter.js
diff --git a/README.md b/README.md
index c37b5aa5..13ec7b4f 100644
--- a/README.md
+++ b/README.md
@@ -2111,6 +2111,7 @@
2965|[Find Missing and Repeated Values](./solutions/2965-find-missing-and-repeated-values.js)|Easy|
2966|[Divide Array Into Arrays With Max Difference](./solutions/2966-divide-array-into-arrays-with-max-difference.js)|Medium|
2970|[Count the Number of Incremovable Subarrays I](./solutions/2970-count-the-number-of-incremovable-subarrays-i.js)|Easy|
+2971|[Find Polygon With the Largest Perimeter](./solutions/2971-find-polygon-with-the-largest-perimeter.js)|Medium|
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|
diff --git a/solutions/2971-find-polygon-with-the-largest-perimeter.js b/solutions/2971-find-polygon-with-the-largest-perimeter.js
new file mode 100644
index 00000000..15d2e501
--- /dev/null
+++ b/solutions/2971-find-polygon-with-the-largest-perimeter.js
@@ -0,0 +1,33 @@
+/**
+ * 2971. Find Polygon With the Largest Perimeter
+ * https://leetcode.com/problems/find-polygon-with-the-largest-perimeter/
+ * Difficulty: Medium
+ *
+ * You are given an array of positive integers nums of length n.
+ *
+ * A polygon is a closed plane figure that has at least 3 sides. The longest side of a polygon is
+ * smaller than the sum of its other sides.
+ *
+ * Conversely, if you have k (k >= 3) positive real numbers a1, a2, a3, ..., ak where
+ * a1 <= a2 <= a3 <= ... <= ak and a1 + a2 + a3 + ... + ak-1 > ak, then there always exists
+ * a polygon with k sides whose lengths are a1, a2, a3, ..., ak.
+ *
+ * The perimeter of a polygon is the sum of lengths of its sides.
+ *
+ * Return the largest possible perimeter of a polygon whose sides can be formed from nums, or -1
+ * if it is not possible to create a polygon.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var largestPerimeter = function(nums) {
+ nums.sort((a, b) => b - a);
+ for (let i = 0; i < nums.length - 2; i++) {
+ if (nums[i] < nums.slice(i + 1).reduce((sum, num) => sum + num, 0)) {
+ return nums.slice(i).reduce((sum, num) => sum + num, 0);
+ }
+ }
+ return -1;
+};
From 6006d572901d2a8f4c61a7fe2e86706f227711de Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 19:30:59 -0500
Subject: [PATCH 362/994] Add solution #2976
---
README.md | 1 +
.../2976-minimum-cost-to-convert-string-i.js | 59 +++++++++++++++++++
2 files changed, 60 insertions(+)
create mode 100644 solutions/2976-minimum-cost-to-convert-string-i.js
diff --git a/README.md b/README.md
index 13ec7b4f..7d999055 100644
--- a/README.md
+++ b/README.md
@@ -2112,6 +2112,7 @@
2966|[Divide Array Into Arrays With Max Difference](./solutions/2966-divide-array-into-arrays-with-max-difference.js)|Medium|
2970|[Count the Number of Incremovable Subarrays I](./solutions/2970-count-the-number-of-incremovable-subarrays-i.js)|Easy|
2971|[Find Polygon With the Largest Perimeter](./solutions/2971-find-polygon-with-the-largest-perimeter.js)|Medium|
+2976|[Minimum Cost to Convert String I](./solutions/2976-minimum-cost-to-convert-string-i.js)|Medium|
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|
diff --git a/solutions/2976-minimum-cost-to-convert-string-i.js b/solutions/2976-minimum-cost-to-convert-string-i.js
new file mode 100644
index 00000000..9107955d
--- /dev/null
+++ b/solutions/2976-minimum-cost-to-convert-string-i.js
@@ -0,0 +1,59 @@
+/**
+ * 2976. Minimum Cost to Convert String I
+ * https://leetcode.com/problems/minimum-cost-to-convert-string-i/
+ * Difficulty: Medium
+ *
+ * You are given two 0-indexed strings source and target, both of length n and consisting of
+ * lowercase English letters. You are also given two 0-indexed character arrays original and
+ * changed, and an integer array cost, where cost[i] represents the cost of changing the character
+ * original[i] to the character changed[i].
+ *
+ * You start with the string source. In one operation, you can pick a character x from the string
+ * and change it to the character y at a cost of z if there exists any index j such that
+ * cost[j] == z, original[j] == x, and changed[j] == y.
+ *
+ * Return the minimum cost to convert the string source to the string target using any number of
+ * operations. If it is impossible to convert source to target, return -1.
+ *
+ * Note that there may exist indices i, j such that original[j] == original[i] and
+ * changed[j] == changed[i].
+ */
+
+/**
+ * @param {string} source
+ * @param {string} target
+ * @param {character[]} original
+ * @param {character[]} changed
+ * @param {number[]} cost
+ * @return {number}
+ */
+var minimumCost = function(source, target, original, changed, cost) {
+ const graph = new Array(26).fill().map(() => new Array(26).fill(Infinity));
+ for (let i = 0; i < 26; i++) graph[i][i] = 0;
+
+ for (let i = 0; i < original.length; i++) {
+ const from = original[i].charCodeAt(0) - 97;
+ const to = changed[i].charCodeAt(0) - 97;
+ graph[from][to] = Math.min(graph[from][to], cost[i]);
+ }
+
+ for (let k = 0; k < 26; k++) {
+ for (let i = 0; i < 26; i++) {
+ for (let j = 0; j < 26; j++) {
+ graph[i][j] = Math.min(graph[i][j], graph[i][k] + graph[k][j]);
+ }
+ }
+ }
+
+ let result = 0;
+ for (let i = 0; i < source.length; i++) {
+ if (source[i] !== target[i]) {
+ const from = source[i].charCodeAt(0) - 97;
+ const to = target[i].charCodeAt(0) - 97;
+ if (graph[from][to] === Infinity) return -1;
+ result += graph[from][to];
+ }
+ }
+
+ return result;
+};
From 64821b5d7288e911c6713971f8cbd4d71c76224a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 19:33:11 -0500
Subject: [PATCH 363/994] Add solution #2980
---
README.md | 1 +
...-check-if-bitwise-or-has-trailing-zeros.js | 36 +++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/2980-check-if-bitwise-or-has-trailing-zeros.js
diff --git a/README.md b/README.md
index 7d999055..5b3100ab 100644
--- a/README.md
+++ b/README.md
@@ -2113,6 +2113,7 @@
2970|[Count the Number of Incremovable Subarrays I](./solutions/2970-count-the-number-of-incremovable-subarrays-i.js)|Easy|
2971|[Find Polygon With the Largest Perimeter](./solutions/2971-find-polygon-with-the-largest-perimeter.js)|Medium|
2976|[Minimum Cost to Convert String I](./solutions/2976-minimum-cost-to-convert-string-i.js)|Medium|
+2980|[Check if Bitwise OR Has Trailing Zeros](./solutions/2980-check-if-bitwise-or-has-trailing-zeros.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|
diff --git a/solutions/2980-check-if-bitwise-or-has-trailing-zeros.js b/solutions/2980-check-if-bitwise-or-has-trailing-zeros.js
new file mode 100644
index 00000000..e3afe838
--- /dev/null
+++ b/solutions/2980-check-if-bitwise-or-has-trailing-zeros.js
@@ -0,0 +1,36 @@
+/**
+ * 2980. Check if Bitwise OR Has Trailing Zeros
+ * https://leetcode.com/problems/check-if-bitwise-or-has-trailing-zeros/
+ * Difficulty: Easy
+ *
+ * You are given an array of positive integers nums.
+ *
+ * You have to check if it is possible to select two or more elements in the array such
+ * that the bitwise OR of the selected elements has at least one trailing zero in its
+ * binary representation.
+ *
+ * For example, the binary representation of 5, which is "101", does not have any trailing
+ * zeros, whereas the binary representation of 4, which is "100", has two trailing zeros.
+ *
+ * Return true if it is possible to select two or more elements whose bitwise OR has trailing
+ * zeros, return false otherwise.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {boolean}
+ */
+var hasTrailingZeros = function(nums) {
+ let evenCount = 0;
+
+ for (const num of nums) {
+ if (num % 2 === 0) {
+ evenCount++;
+ if (evenCount >= 2) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+};
From 27782c850fdf90e272240d2b8c5bba3a4eb1fed4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 19:34:11 -0500
Subject: [PATCH 364/994] Add solution #2981
---
README.md | 1 +
...-special-substring-that-occurs-thrice-i.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/2981-find-longest-special-substring-that-occurs-thrice-i.js
diff --git a/README.md b/README.md
index 5b3100ab..366a2ca2 100644
--- a/README.md
+++ b/README.md
@@ -2114,6 +2114,7 @@
2971|[Find Polygon With the Largest Perimeter](./solutions/2971-find-polygon-with-the-largest-perimeter.js)|Medium|
2976|[Minimum Cost to Convert String I](./solutions/2976-minimum-cost-to-convert-string-i.js)|Medium|
2980|[Check if Bitwise OR Has Trailing Zeros](./solutions/2980-check-if-bitwise-or-has-trailing-zeros.js)|Easy|
+2981|[Find Longest Special Substring That Occurs Thrice I](./solutions/2981-find-longest-special-substring-that-occurs-thrice-i.js)|Medium|
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|
diff --git a/solutions/2981-find-longest-special-substring-that-occurs-thrice-i.js b/solutions/2981-find-longest-special-substring-that-occurs-thrice-i.js
new file mode 100644
index 00000000..ac12f932
--- /dev/null
+++ b/solutions/2981-find-longest-special-substring-that-occurs-thrice-i.js
@@ -0,0 +1,39 @@
+/**
+ * 2981. Find Longest Special Substring That Occurs Thrice I
+ * https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/
+ * Difficulty: Medium
+ *
+ * You are given a string s that consists of lowercase English letters.
+ *
+ * A string is called special if it is made up of only a single character. For example, the
+ * string "abc" is not special, whereas the strings "ddd", "zz", and "f" are special.
+ *
+ * Return the length of the longest special substring of s which occurs at least thrice,
+ * or -1 if no special substring occurs at least thrice.
+ *
+ * A substring is a contiguous non-empty sequence of characters within a string.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var maximumLength = function(s) {
+ const map = new Map();
+ let result = -1;
+
+ for (let i = 0; i < s.length; i++) {
+ for (let len = 1; len <= s.length - i; len++) {
+ const substr = s.slice(i, i + len);
+ if (substr.split('').every(c => c === substr[0])) {
+ const count = (map.get(substr) || 0) + 1;
+ map.set(substr, count);
+ if (count >= 3) {
+ result = Math.max(result, len);
+ }
+ }
+ }
+ }
+
+ return result;
+};
From 62f1c79ba1f60bf032cb520d5de7dd5be65b6313 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 19:35:21 -0500
Subject: [PATCH 365/994] Add solution #2997
---
README.md | 1 +
...operations-to-make-array-xor-equal-to-k.js | 38 +++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k.js
diff --git a/README.md b/README.md
index 366a2ca2..a4c4fac6 100644
--- a/README.md
+++ b/README.md
@@ -2115,6 +2115,7 @@
2976|[Minimum Cost to Convert String I](./solutions/2976-minimum-cost-to-convert-string-i.js)|Medium|
2980|[Check if Bitwise OR Has Trailing Zeros](./solutions/2980-check-if-bitwise-or-has-trailing-zeros.js)|Easy|
2981|[Find Longest Special Substring That Occurs Thrice I](./solutions/2981-find-longest-special-substring-that-occurs-thrice-i.js)|Medium|
+2997|[Minimum Number of Operations to Make Array XOR Equal to K](./solutions/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k.js)|Medium|
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|
diff --git a/solutions/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k.js b/solutions/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k.js
new file mode 100644
index 00000000..b1d492eb
--- /dev/null
+++ b/solutions/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k.js
@@ -0,0 +1,38 @@
+/**
+ * 2997. Minimum Number of Operations to Make Array XOR Equal to K
+ * https://leetcode.com/problems/minimum-number-of-operations-to-make-array-xor-equal-to-k/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums and a positive integer k.
+ *
+ * You can apply the following operation on the array any number of times:
+ * - Choose any element of the array and flip a bit in its binary representation. Flipping a bit
+ * means changing a 0 to 1 or vice versa.
+ *
+ * Return the minimum number of operations required to make the bitwise XOR of all elements of the
+ * final array equal to k.
+ *
+ * Note that you can flip leading zero bits in the binary representation of elements. For example,
+ * for the number (101)2 you can flip the fourth bit and obtain (1101)2.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var minOperations = function(nums, k) {
+ let xorResult = 0;
+ for (const num of nums) {
+ xorResult ^= num;
+ }
+
+ let result = 0;
+ let diff = xorResult ^ k;
+ while (diff > 0) {
+ result += diff & 1;
+ diff >>= 1;
+ }
+
+ return result;
+};
From 615e3fc09ec7a5e43a22798bd10e9aacb9183409 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 23:29:12 -0500
Subject: [PATCH 366/994] Add solution #2376
---
README.md | 1 +
solutions/2376-count-special-integers.js | 47 ++++++++++++++++++++++++
2 files changed, 48 insertions(+)
create mode 100644 solutions/2376-count-special-integers.js
diff --git a/README.md b/README.md
index a4c4fac6..aa1ebb9a 100644
--- a/README.md
+++ b/README.md
@@ -1801,6 +1801,7 @@
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|
+2376|[Count Special Integers](./solutions/2376-count-special-integers.js)|Hard|
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|
diff --git a/solutions/2376-count-special-integers.js b/solutions/2376-count-special-integers.js
new file mode 100644
index 00000000..977b5730
--- /dev/null
+++ b/solutions/2376-count-special-integers.js
@@ -0,0 +1,47 @@
+/**
+ * 2376. Count Special Integers
+ * https://leetcode.com/problems/count-special-integers/
+ * Difficulty: Hard
+ *
+ * We call a positive integer special if all of its digits are distinct.
+ *
+ * Given a positive integer n, return the number of special integers that belong to the
+ * interval [1, n].
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var countSpecialNumbers = function(n) {
+ const digits = String(n).split('').map(Number);
+ const len = digits.length;
+ let total = 0;
+
+ for (let i = 1; i < len; i++) {
+ let count = 9;
+ for (let j = 0; j < i - 1; j++) {
+ count *= (10 - j - 1);
+ }
+ total += count;
+ }
+
+ const used = new Set();
+ for (let i = 0; i < len; i++) {
+ for (let d = (i === 0 ? 1 : 0); d < digits[i]; d++) {
+ if (!used.has(d)) {
+ let count = 1;
+ for (let j = i + 1; j < len; j++) {
+ count *= (10 - used.size - (j - i));
+ }
+ total += count;
+ }
+ }
+ if (used.has(digits[i]) || digits[i] === 0 && i === 0) break;
+ used.add(digits[i]);
+ }
+
+ if (used.size === len) total++;
+
+ return total;
+};
From 1b2aa72fb7cd06e07fc693590197539474c7013f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 23:30:27 -0500
Subject: [PATCH 367/994] Add solution #2420
---
README.md | 1 +
solutions/2420-find-all-good-indices.js | 42 +++++++++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/2420-find-all-good-indices.js
diff --git a/README.md b/README.md
index aa1ebb9a..940b2e08 100644
--- a/README.md
+++ b/README.md
@@ -1829,6 +1829,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|
+2420|[Find All Good Indices](./solutions/2420-find-all-good-indices.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|
diff --git a/solutions/2420-find-all-good-indices.js b/solutions/2420-find-all-good-indices.js
new file mode 100644
index 00000000..e3216e6e
--- /dev/null
+++ b/solutions/2420-find-all-good-indices.js
@@ -0,0 +1,42 @@
+/**
+ * 2420. Find All Good Indices
+ * https://leetcode.com/problems/find-all-good-indices/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums of size n and a positive integer k.
+ *
+ * We call an index i in the range k <= i < n - k good if the following conditions are satisfied:
+ * - The k elements that are just before the index i are in non-increasing order.
+ * - The k elements that are just after the index i are in non-decreasing order.
+ *
+ * Return an array of all good indices sorted in increasing order.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number[]}
+ */
+var goodIndices = function(nums, k) {
+ const n = nums.length;
+ const nonIncreasing = new Array(n).fill(1);
+ const nonDecreasing = new Array(n).fill(1);
+ const result = [];
+
+ for (let i = 1; i < n; i++) {
+ if (nums[i - 1] >= nums[i]) {
+ nonIncreasing[i] = nonIncreasing[i - 1] + 1;
+ }
+ if (nums[n - i] >= nums[n - i - 1]) {
+ nonDecreasing[n - i - 1] = nonDecreasing[n - i] + 1;
+ }
+ }
+
+ for (let i = k; i < n - k; i++) {
+ if (nonIncreasing[i - 1] >= k && nonDecreasing[i + 1] >= k) {
+ result.push(i);
+ }
+ }
+
+ return result;
+};
From ad665db01368020b9bdf35b72763f75cbf0cf3ae Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 23:34:22 -0500
Subject: [PATCH 368/994] Add solution #2484
---
README.md | 1 +
.../2484-count-palindromic-subsequences.js | 59 +++++++++++++++++++
2 files changed, 60 insertions(+)
create mode 100644 solutions/2484-count-palindromic-subsequences.js
diff --git a/README.md b/README.md
index 940b2e08..c27f6816 100644
--- a/README.md
+++ b/README.md
@@ -1875,6 +1875,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|
+2484|[Count Palindromic Subsequences](./solutions/2484-count-palindromic-subsequences.js)|Hard|
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|
diff --git a/solutions/2484-count-palindromic-subsequences.js b/solutions/2484-count-palindromic-subsequences.js
new file mode 100644
index 00000000..a6c3851c
--- /dev/null
+++ b/solutions/2484-count-palindromic-subsequences.js
@@ -0,0 +1,59 @@
+/**
+ * 2484. Count Palindromic Subsequences
+ * https://leetcode.com/problems/count-palindromic-subsequences/
+ * Difficulty: Hard
+ *
+ * Given a string of digits s, return the number of palindromic subsequences of s having length 5.
+ * Since the answer may be very large, return it modulo 109 + 7.
+ *
+ * Note:
+ * - A string is palindromic if it reads the same forward and backward.
+ * - 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
+ * @return {number}
+ */
+var countPalindromes = function(s) {
+ const MOD = 1e9 + 7;
+ const n = s.length;
+
+ const prefixPairs = new Array(n).fill(0).map(() => new Array(100).fill(0));
+ const suffixPairs = new Array(n).fill(0).map(() => new Array(100).fill(0));
+
+ for (let i = 1; i < n; i++) {
+ for (let pair = 0; pair < 100; pair++) {
+ prefixPairs[i][pair] = prefixPairs[i - 1][pair];
+ }
+ for (let j = 0; j < i; j++) {
+ const pair = parseInt(s[j]) * 10 + parseInt(s[i]);
+ prefixPairs[i][pair]++;
+ }
+ }
+
+ for (let i = n - 2; i >= 0; i--) {
+ for (let pair = 0; pair < 100; pair++) {
+ suffixPairs[i][pair] = suffixPairs[i + 1][pair];
+ }
+ for (let j = i + 1; j < n; j++) {
+ const pair = parseInt(s[i]) * 10 + parseInt(s[j]);
+ suffixPairs[i][pair]++;
+ }
+ }
+
+ let result = 0;
+ for (let i = 2; i < n - 2; i++) {
+ for (let first = 0; first < 10; first++) {
+ for (let second = 0; second < 10; second++) {
+ const leftPair = first * 10 + second;
+ const rightPair = second * 10 + first;
+ result = (result + (prefixPairs[i - 1][leftPair]
+ * suffixPairs[i + 1][rightPair]) % MOD) % MOD;
+ }
+ }
+ }
+
+ return result;
+};
From e235c8bd45b3bef0b13567e977303c74fff2ddf6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 23:35:30 -0500
Subject: [PATCH 369/994] Add solution #2576
---
README.md | 1 +
...nd-the-maximum-number-of-marked-indices.js | 38 +++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2576-find-the-maximum-number-of-marked-indices.js
diff --git a/README.md b/README.md
index c27f6816..e18a2aac 100644
--- a/README.md
+++ b/README.md
@@ -1927,6 +1927,7 @@
2570|[Merge Two 2D Arrays by Summing Values](./solutions/2570-merge-two-2d-arrays-by-summing-values.js)|Easy|
2571|[Minimum Operations to Reduce an Integer to 0](./solutions/2571-minimum-operations-to-reduce-an-integer-to-0.js)|Medium|
2574|[Left and Right Sum Differences](./solutions/2574-left-and-right-sum-differences.js)|Easy|
+2576|[Find the Maximum Number of Marked Indices](./solutions/2576-find-the-maximum-number-of-marked-indices.js)|Medium|
2578|[Split With Minimum Sum](./solutions/2578-split-with-minimum-sum.js)|Easy|
2579|[Count Total Number of Colored Cells](./solutions/2579-count-total-number-of-colored-cells.js)|Medium|
2581|[Count Number of Possible Root Nodes](./solutions/2581-count-number-of-possible-root-nodes.js)|Hard|
diff --git a/solutions/2576-find-the-maximum-number-of-marked-indices.js b/solutions/2576-find-the-maximum-number-of-marked-indices.js
new file mode 100644
index 00000000..73f0f859
--- /dev/null
+++ b/solutions/2576-find-the-maximum-number-of-marked-indices.js
@@ -0,0 +1,38 @@
+/**
+ * 2576. Find the Maximum Number of Marked Indices
+ * https://leetcode.com/problems/find-the-maximum-number-of-marked-indices/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums.
+ *
+ * Initially, all of the indices are unmarked. You are allowed to make this operation any
+ * number of times:
+ * - Pick two different unmarked indices i and j such that 2 * nums[i] <= nums[j], then
+ * mark i and j.
+ *
+ * Return the maximum possible number of marked indices in nums using the above operation
+ * any number of times.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maxNumOfMarkedIndices = function(nums) {
+ nums.sort((a, b) => a - b);
+ let result = 0;
+ let left = 0;
+ let right = Math.floor(nums.length / 2);
+
+ while (left < Math.floor(nums.length / 2) && right < nums.length) {
+ if (2 * nums[left] <= nums[right]) {
+ result += 2;
+ left++;
+ right++;
+ } else {
+ right++;
+ }
+ }
+
+ return result;
+};
From 0000c47f5f854b3e8a8f01dea1285dd4e94eb20f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 23:36:49 -0500
Subject: [PATCH 370/994] Add solution #2598
---
README.md | 1 +
...g-non-negative-integer-after-operations.js | 40 +++++++++++++++++++
2 files changed, 41 insertions(+)
create mode 100644 solutions/2598-smallest-missing-non-negative-integer-after-operations.js
diff --git a/README.md b/README.md
index e18a2aac..0555738e 100644
--- a/README.md
+++ b/README.md
@@ -1942,6 +1942,7 @@
2595|[Number of Even and Odd Bits](./solutions/2595-number-of-even-and-odd-bits.js)|Easy|
2596|[Check Knight Tour Configuration](./solutions/2596-check-knight-tour-configuration.js)|Medium|
2597|[The Number of Beautiful Subsets](./solutions/2597-the-number-of-beautiful-subsets.js)|Medium|
+2598|[Smallest Missing Non-negative Integer After Operations](./solutions/2598-smallest-missing-non-negative-integer-after-operations.js)|Medium|
2600|[K Items With the Maximum Sum](./solutions/2600-k-items-with-the-maximum-sum.js)|Easy|
2601|[Prime Subtraction Operation](./solutions/2601-prime-subtraction-operation.js)|Medium|
2605|[Form Smallest Number From Two Digit Arrays](./solutions/2605-form-smallest-number-from-two-digit-arrays.js)|Easy|
diff --git a/solutions/2598-smallest-missing-non-negative-integer-after-operations.js b/solutions/2598-smallest-missing-non-negative-integer-after-operations.js
new file mode 100644
index 00000000..fe19438b
--- /dev/null
+++ b/solutions/2598-smallest-missing-non-negative-integer-after-operations.js
@@ -0,0 +1,40 @@
+/**
+ * 2598. Smallest Missing Non-negative Integer After Operations
+ * https://leetcode.com/problems/smallest-missing-non-negative-integer-after-operations/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums and an integer value.
+ *
+ * In one operation, you can add or subtract value from any element of nums.
+ * - For example, if nums = [1,2,3] and value = 2, you can choose to subtract value from nums[0]
+ * to make nums = [-1,2,3].
+ *
+ * The MEX (minimum excluded) of an array is the smallest missing non-negative integer in it.
+ * - For example, the MEX of [-1,2,3] is 0 while the MEX of [1,0,3] is 2.
+ *
+ * Return the maximum MEX of nums after applying the mentioned operation any number of times.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} value
+ * @return {number}
+ */
+var findSmallestInteger = function(nums, value) {
+ const remainderCount = new Map();
+
+ for (const num of nums) {
+ const remainder = ((num % value) + value) % value;
+ remainderCount.set(remainder, (remainderCount.get(remainder) || 0) + 1);
+ }
+
+ for (let mex = 0; mex <= nums.length; mex++) {
+ const remainder = mex % value;
+ if (!remainderCount.has(remainder) || remainderCount.get(remainder) === 0) {
+ return mex;
+ }
+ remainderCount.set(remainder, remainderCount.get(remainder) - 1);
+ }
+
+ return nums.length;
+};
From 8f96e3264da84e659cda370ca56942d3988b3763 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 23:39:45 -0500
Subject: [PATCH 371/994] Add solution #2841
---
README.md | 1 +
...1-maximum-sum-of-almost-unique-subarray.js | 51 +++++++++++++++++++
2 files changed, 52 insertions(+)
create mode 100644 solutions/2841-maximum-sum-of-almost-unique-subarray.js
diff --git a/README.md b/README.md
index 0555738e..19b1cfe2 100644
--- a/README.md
+++ b/README.md
@@ -2059,6 +2059,7 @@
2833|[Furthest Point From Origin](./solutions/2833-furthest-point-from-origin.js)|Easy|
2839|[Check if Strings Can be Made Equal With Operations I](./solutions/2839-check-if-strings-can-be-made-equal-with-operations-i.js)|Easy|
2840|[Check if Strings Can be Made Equal With Operations II](./solutions/2840-check-if-strings-can-be-made-equal-with-operations-ii.js)|Medium|
+2841|[Maximum Sum of Almost Unique Subarray](./solutions/2841-maximum-sum-of-almost-unique-subarray.js)|Medium|
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
2845|[Count of Interesting Subarrays](./solutions/2845-count-of-interesting-subarrays.js)|Medium|
2846|[Minimum Edge Weight Equilibrium Queries in a Tree](./solutions/2846-minimum-edge-weight-equilibrium-queries-in-a-tree.js)|Hard|
diff --git a/solutions/2841-maximum-sum-of-almost-unique-subarray.js b/solutions/2841-maximum-sum-of-almost-unique-subarray.js
new file mode 100644
index 00000000..e36e3b1a
--- /dev/null
+++ b/solutions/2841-maximum-sum-of-almost-unique-subarray.js
@@ -0,0 +1,51 @@
+/**
+ * 2841. Maximum Sum of Almost Unique Subarray
+ * https://leetcode.com/problems/maximum-sum-of-almost-unique-subarray/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums and two positive integers m and k.
+ *
+ * Return the maximum sum out of all almost unique subarrays of length k of nums. If no such
+ * subarray exists, return 0.
+ *
+ * A subarray of nums is almost unique if it contains at least m distinct elements.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} m
+ * @param {number} k
+ * @return {number}
+ */
+var maxSum = function(nums, m, k) {
+ const map = new Map();
+ let subarraySum = 0;
+ let result = 0;
+
+ for (let i = 0; i < k; i++) {
+ map.set(nums[i], (map.get(nums[i]) || 0) + 1);
+ subarraySum += nums[i];
+ }
+
+ if (map.size >= m) {
+ result = subarraySum;
+ }
+
+ for (let i = k; i < nums.length; i++) {
+ map.set(nums[i - k], map.get(nums[i - k]) - 1);
+ if (map.get(nums[i - k]) === 0) {
+ map.delete(nums[i - k]);
+ }
+
+ map.set(nums[i], (map.get(nums[i]) || 0) + 1);
+ subarraySum = subarraySum - nums[i - k] + nums[i];
+
+ if (map.size >= m) {
+ result = Math.max(result, subarraySum);
+ }
+ }
+
+ return result;
+};
From 4bdb205d690c0791e00306941b1c60ff47f2f570 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 23:41:08 -0500
Subject: [PATCH 372/994] Add solution #2904
---
README.md | 1 +
...cographically-smallest-beautiful-string.js | 48 +++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/2904-shortest-and-lexicographically-smallest-beautiful-string.js
diff --git a/README.md b/README.md
index 19b1cfe2..1c171deb 100644
--- a/README.md
+++ b/README.md
@@ -2085,6 +2085,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|
2903|[Find Indices With Index and Value Difference I](./solutions/2903-find-indices-with-index-and-value-difference-i.js)|Easy|
+2904|[Shortest and Lexicographically Smallest Beautiful String](./solutions/2904-shortest-and-lexicographically-smallest-beautiful-string.js)|Medium|
2908|[Minimum Sum of Mountain Triplets I](./solutions/2908-minimum-sum-of-mountain-triplets-i.js)|Easy|
2909|[Minimum Sum of Mountain Triplets II](./solutions/2909-minimum-sum-of-mountain-triplets-ii.js)|Medium|
2913|[Subarrays Distinct Element Sum of Squares I](./solutions/2913-subarrays-distinct-element-sum-of-squares-i.js)|Easy|
diff --git a/solutions/2904-shortest-and-lexicographically-smallest-beautiful-string.js b/solutions/2904-shortest-and-lexicographically-smallest-beautiful-string.js
new file mode 100644
index 00000000..d328f151
--- /dev/null
+++ b/solutions/2904-shortest-and-lexicographically-smallest-beautiful-string.js
@@ -0,0 +1,48 @@
+/**
+ * 2904. Shortest and Lexicographically Smallest Beautiful String
+ * https://leetcode.com/problems/shortest-and-lexicographically-smallest-beautiful-string/
+ * Difficulty: Medium
+ *
+ * You are given a binary string s and a positive integer k.
+ *
+ * A substring of s is beautiful if the number of 1's in it is exactly k.
+ *
+ * Let len be the length of the shortest beautiful substring.
+ *
+ * Return the lexicographically smallest beautiful substring of string s with length equal to
+ * len. If s doesn't contain a beautiful substring, return an empty string.
+ *
+ * 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} s
+ * @param {number} k
+ * @return {string}
+ */
+var shortestBeautifulSubstring = function(s, k) {
+ let minLength = Infinity;
+ let result = '';
+
+ for (let start = 0; start < s.length; start++) {
+ let onesCount = 0;
+ for (let end = start; end < s.length; end++) {
+ if (s[end] === '1') onesCount++;
+ if (onesCount === k) {
+ const currentLength = end - start + 1;
+ const currentSubstring = s.slice(start, end + 1);
+ if (currentLength < minLength
+ || (currentLength === minLength && currentSubstring < result)) {
+ minLength = currentLength;
+ result = currentSubstring;
+ }
+ }
+ }
+ }
+
+ return result;
+};
From d8248c38e1c52b1d4d725e6e058a421edcf949f9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 23:42:14 -0500
Subject: [PATCH 373/994] Add solution #2998
---
README.md | 1 +
...ber-of-operations-to-make-x-and-y-equal.js | 45 +++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/2998-minimum-number-of-operations-to-make-x-and-y-equal.js
diff --git a/README.md b/README.md
index 1c171deb..e87bd053 100644
--- a/README.md
+++ b/README.md
@@ -2123,6 +2123,7 @@
2980|[Check if Bitwise OR Has Trailing Zeros](./solutions/2980-check-if-bitwise-or-has-trailing-zeros.js)|Easy|
2981|[Find Longest Special Substring That Occurs Thrice I](./solutions/2981-find-longest-special-substring-that-occurs-thrice-i.js)|Medium|
2997|[Minimum Number of Operations to Make Array XOR Equal to K](./solutions/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k.js)|Medium|
+2998|[Minimum Number of Operations to Make X and Y Equal](./solutions/2998-minimum-number-of-operations-to-make-x-and-y-equal.js)|Medium|
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|
diff --git a/solutions/2998-minimum-number-of-operations-to-make-x-and-y-equal.js b/solutions/2998-minimum-number-of-operations-to-make-x-and-y-equal.js
new file mode 100644
index 00000000..cc18c133
--- /dev/null
+++ b/solutions/2998-minimum-number-of-operations-to-make-x-and-y-equal.js
@@ -0,0 +1,45 @@
+/**
+ * 2998. Minimum Number of Operations to Make X and Y Equal
+ * https://leetcode.com/problems/minimum-number-of-operations-to-make-x-and-y-equal/
+ * Difficulty: Medium
+ *
+ * You are given two positive integers x and y.
+ *
+ * In one operation, you can do one of the four following operations:
+ * 1. Divide x by 11 if x is a multiple of 11.
+ * 2. Divide x by 5 if x is a multiple of 5.
+ * 3. Decrement x by 1.
+ * 4. Increment x by 1.
+ *
+ * Return the minimum number of operations required to make x and y equal.
+ */
+
+/**
+ * @param {number} x
+ * @param {number} y
+ * @return {number}
+ */
+var minimumOperationsToMakeEqual = function(x, y) {
+ const queue = [[x, 0]];
+ const visited = new Set([x]);
+
+ while (queue.length) {
+ const [current, steps] = queue.shift();
+
+ if (current === y) return steps;
+
+ const nextStates = [];
+ if (current % 11 === 0) nextStates.push(current / 11);
+ if (current % 5 === 0) nextStates.push(current / 5);
+ nextStates.push(current - 1, current + 1);
+
+ for (const next of nextStates) {
+ if (next >= 0 && next <= 10000 && !visited.has(next)) {
+ visited.add(next);
+ queue.push([next, steps + 1]);
+ }
+ }
+ }
+
+ return -1;
+};
From 3f1b60254ef2ca1b45c1ac193f17907c6f843466 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 23:44:28 -0500
Subject: [PATCH 374/994] Add solution #3002
---
README.md | 1 +
...02-maximum-size-of-a-set-after-removals.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/3002-maximum-size-of-a-set-after-removals.js
diff --git a/README.md b/README.md
index e87bd053..357652eb 100644
--- a/README.md
+++ b/README.md
@@ -2125,6 +2125,7 @@
2997|[Minimum Number of Operations to Make Array XOR Equal to K](./solutions/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k.js)|Medium|
2998|[Minimum Number of Operations to Make X and Y Equal](./solutions/2998-minimum-number-of-operations-to-make-x-and-y-equal.js)|Medium|
2999|[Count the Number of Powerful Integers](./solutions/2999-count-the-number-of-powerful-integers.js)|Hard|
+3002|[Maximum Size of a Set After Removals](./solutions/3002-maximum-size-of-a-set-after-removals.js)|Medium|
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|
diff --git a/solutions/3002-maximum-size-of-a-set-after-removals.js b/solutions/3002-maximum-size-of-a-set-after-removals.js
new file mode 100644
index 00000000..66f30fd1
--- /dev/null
+++ b/solutions/3002-maximum-size-of-a-set-after-removals.js
@@ -0,0 +1,41 @@
+/**
+ * 3002. Maximum Size of a Set After Removals
+ * https://leetcode.com/problems/maximum-size-of-a-set-after-removals/
+ * Difficulty: Medium
+ *
+ * You are given two 0-indexed integer arrays nums1 and nums2 of even length n.
+ *
+ * You must remove n / 2 elements from nums1 and n / 2 elements from nums2. After the removals,
+ * you insert the remaining elements of nums1 and nums2 into a set s.
+ *
+ * Return the maximum possible size of the set s.
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @return {number}
+ */
+var maximumSetSize = function(nums1, nums2) {
+ const n = nums1.length;
+ const set1 = new Set(nums1);
+ const set2 = new Set(nums2);
+
+ let unique1 = set1.size;
+ let unique2 = set2.size;
+ let common = 0;
+
+ for (const num of set1) {
+ if (set2.has(num)) common++;
+ }
+
+ unique1 -= common;
+ unique2 -= common;
+
+ const max1 = Math.min(unique1, n / 2);
+ const max2 = Math.min(unique2, n / 2);
+ const remaining = n / 2 - max1 + n / 2 - max2;
+ const maxCommon = Math.min(common, remaining);
+
+ return max1 + max2 + maxCommon;
+};
From 7cca561752d43c089893e1f1d1174b8ddb1f3ed2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 23:45:32 -0500
Subject: [PATCH 375/994] Add solution #3005
---
README.md | 1 +
...5-count-elements-with-maximum-frequency.js | 35 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/3005-count-elements-with-maximum-frequency.js
diff --git a/README.md b/README.md
index 357652eb..f9b7fbaf 100644
--- a/README.md
+++ b/README.md
@@ -2126,6 +2126,7 @@
2998|[Minimum Number of Operations to Make X and Y Equal](./solutions/2998-minimum-number-of-operations-to-make-x-and-y-equal.js)|Medium|
2999|[Count the Number of Powerful Integers](./solutions/2999-count-the-number-of-powerful-integers.js)|Hard|
3002|[Maximum Size of a Set After Removals](./solutions/3002-maximum-size-of-a-set-after-removals.js)|Medium|
+3005|[Count Elements With Maximum Frequency](./solutions/3005-count-elements-with-maximum-frequency.js)|Easy|
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|
diff --git a/solutions/3005-count-elements-with-maximum-frequency.js b/solutions/3005-count-elements-with-maximum-frequency.js
new file mode 100644
index 00000000..cb89603e
--- /dev/null
+++ b/solutions/3005-count-elements-with-maximum-frequency.js
@@ -0,0 +1,35 @@
+/**
+ * 3005. Count Elements With Maximum Frequency
+ * https://leetcode.com/problems/count-elements-with-maximum-frequency/
+ * Difficulty: Easy
+ *
+ * You are given an array nums consisting of positive integers.
+ *
+ * Return the total frequencies of elements in nums such that those elements all have the
+ * maximum frequency.
+ *
+ * The frequency of an element is the number of occurrences of that element in the array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maxFrequencyElements = function(nums) {
+ const map = new Map();
+ let maxFreq = 0;
+ let result = 0;
+
+ for (const num of nums) {
+ const count = (map.get(num) || 0) + 1;
+ map.set(num, count);
+ if (count > maxFreq) {
+ maxFreq = count;
+ result = count;
+ } else if (count === maxFreq) {
+ result += count;
+ }
+ }
+
+ return result;
+};
From 9781a2cc5c277763abbf661d6750b0d2b30f7754 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 23:52:12 -0500
Subject: [PATCH 376/994] Add solution #3010
---
README.md | 1 +
...rray-into-subarrays-with-minimum-cost-i.js | 32 +++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/3010-divide-an-array-into-subarrays-with-minimum-cost-i.js
diff --git a/README.md b/README.md
index f9b7fbaf..5c3e6f26 100644
--- a/README.md
+++ b/README.md
@@ -2127,6 +2127,7 @@
2999|[Count the Number of Powerful Integers](./solutions/2999-count-the-number-of-powerful-integers.js)|Hard|
3002|[Maximum Size of a Set After Removals](./solutions/3002-maximum-size-of-a-set-after-removals.js)|Medium|
3005|[Count Elements With Maximum Frequency](./solutions/3005-count-elements-with-maximum-frequency.js)|Easy|
+3010|[Divide an Array Into Subarrays With Minimum Cost I](./solutions/3010-divide-an-array-into-subarrays-with-minimum-cost-i.js)|Easy|
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|
diff --git a/solutions/3010-divide-an-array-into-subarrays-with-minimum-cost-i.js b/solutions/3010-divide-an-array-into-subarrays-with-minimum-cost-i.js
new file mode 100644
index 00000000..26a184a5
--- /dev/null
+++ b/solutions/3010-divide-an-array-into-subarrays-with-minimum-cost-i.js
@@ -0,0 +1,32 @@
+/**
+ * 3010. Divide an Array Into Subarrays With Minimum Cost I
+ * https://leetcode.com/problems/divide-an-array-into-subarrays-with-minimum-cost-i/
+ * Difficulty: Easy
+ *
+ * You are given an array of integers nums of length n.
+ *
+ * The cost of an array is the value of its first element. For example, the cost of [1,2,3]
+ * is 1 while the cost of [3,4,1] is 3.
+ *
+ * You need to divide nums into 3 disjoint contiguous subarrays.
+ *
+ * Return the minimum possible sum of the cost of these subarrays.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimumCost = function(nums) {
+ const n = nums.length;
+ let result = Infinity;
+
+ for (let i = 1; i < n - 1; i++) {
+ for (let j = i + 1; j < n; j++) {
+ const cost = nums[0] + nums[i] + nums[j];
+ result = Math.min(result, cost);
+ }
+ }
+
+ return result;
+};
From 3e0b7849d652cc73fe4bfab37ee9065eb0101733 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 5 Jun 2025 23:53:37 -0500
Subject: [PATCH 377/994] Add solution #3011
---
README.md | 1 +
solutions/3011-find-if-array-can-be-sorted.js | 57 +++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/3011-find-if-array-can-be-sorted.js
diff --git a/README.md b/README.md
index 5c3e6f26..93f75535 100644
--- a/README.md
+++ b/README.md
@@ -2128,6 +2128,7 @@
3002|[Maximum Size of a Set After Removals](./solutions/3002-maximum-size-of-a-set-after-removals.js)|Medium|
3005|[Count Elements With Maximum Frequency](./solutions/3005-count-elements-with-maximum-frequency.js)|Easy|
3010|[Divide an Array Into Subarrays With Minimum Cost I](./solutions/3010-divide-an-array-into-subarrays-with-minimum-cost-i.js)|Easy|
+3011|[Find if Array Can Be Sorted](./solutions/3011-find-if-array-can-be-sorted.js)|Medium|
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|
diff --git a/solutions/3011-find-if-array-can-be-sorted.js b/solutions/3011-find-if-array-can-be-sorted.js
new file mode 100644
index 00000000..c395e89e
--- /dev/null
+++ b/solutions/3011-find-if-array-can-be-sorted.js
@@ -0,0 +1,57 @@
+/**
+ * 3011. Find if Array Can Be Sorted
+ * https://leetcode.com/problems/find-if-array-can-be-sorted/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array of positive integers nums.
+ *
+ * In one operation, you can swap any two adjacent elements if they have the same number of
+ * set bits. You are allowed to do this operation any number of times (including zero).
+ *
+ * Return true if you can sort the array in ascending order, else return false.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {boolean}
+ */
+var canSortArray = function(nums) {
+ const sorted = [...nums].sort((a, b) => a - b);
+ const bitGroups = [];
+ let currentBits = countSetBits(nums[0]);
+ let group = [nums[0]];
+
+ for (let i = 1; i < nums.length; i++) {
+ const bits = countSetBits(nums[i]);
+ if (bits === currentBits) {
+ group.push(nums[i]);
+ } else {
+ bitGroups.push(group);
+ group = [nums[i]];
+ currentBits = bits;
+ }
+ }
+ bitGroups.push(group);
+
+ let index = 0;
+ for (const group of bitGroups) {
+ const groupSorted = [...group].sort((a, b) => a - b);
+ for (const num of groupSorted) {
+ if (num !== sorted[index]) {
+ return false;
+ }
+ index++;
+ }
+ }
+
+ return true;
+
+ function countSetBits(num) {
+ let count = 0;
+ while (num) {
+ count += num & 1;
+ num >>= 1;
+ }
+ return count;
+ }
+};
From 77f8144db97be2a55a224408c29fd43c23ae8ea7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 00:02:41 -0500
Subject: [PATCH 378/994] Add solution #3014
---
README.md | 1 +
...minimum-number-of-pushes-to-type-word-i.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/3014-minimum-number-of-pushes-to-type-word-i.js
diff --git a/README.md b/README.md
index 93f75535..4aed3de7 100644
--- a/README.md
+++ b/README.md
@@ -2129,6 +2129,7 @@
3005|[Count Elements With Maximum Frequency](./solutions/3005-count-elements-with-maximum-frequency.js)|Easy|
3010|[Divide an Array Into Subarrays With Minimum Cost I](./solutions/3010-divide-an-array-into-subarrays-with-minimum-cost-i.js)|Easy|
3011|[Find if Array Can Be Sorted](./solutions/3011-find-if-array-can-be-sorted.js)|Medium|
+3014|[Minimum Number of Pushes to Type Word I](./solutions/3014-minimum-number-of-pushes-to-type-word-i.js)|Easy|
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|
diff --git a/solutions/3014-minimum-number-of-pushes-to-type-word-i.js b/solutions/3014-minimum-number-of-pushes-to-type-word-i.js
new file mode 100644
index 00000000..347e798e
--- /dev/null
+++ b/solutions/3014-minimum-number-of-pushes-to-type-word-i.js
@@ -0,0 +1,42 @@
+/**
+ * 3014. Minimum Number of Pushes to Type Word I
+ * https://leetcode.com/problems/minimum-number-of-pushes-to-type-word-i/
+ * Difficulty: Easy
+ *
+ * You are given a string word containing distinct lowercase English letters.
+ *
+ * Telephone keypads have keys mapped with distinct collections of lowercase English letters,
+ * which can be used to form words by pushing them. For example, the key 2 is mapped with
+ * ["a","b","c"], we need to push the key one time to type "a", two times to type "b", and
+ * three times to type "c".
+ *
+ * It is allowed to remap the keys numbered 2 to 9 to distinct collections of letters. The
+ * keys can be remapped to any amount of letters, but each letter must be mapped to exactly
+ * one key. You need to find the minimum number of times the keys will be pushed to type
+ * the string word.
+ *
+ * Return the minimum number of pushes needed to type word after remapping the keys.
+ *
+ * An example mapping of letters to keys on a telephone keypad is given below. Note that
+ * 1, *, #, and 0 do not map to any letters.
+ */
+
+/**
+ * @param {string} word
+ * @return {number}
+ */
+var minimumPushes = function(word) {
+ const frequency = new Array(26).fill(0);
+ for (const char of word) {
+ frequency[char.charCodeAt(0) - 97]++;
+ }
+ frequency.sort((a, b) => b - a);
+
+ let result = 0;
+ for (let i = 0; i < frequency.length; i++) {
+ if (frequency[i] === 0) break;
+ result += frequency[i] * (Math.floor(i / 8) + 1);
+ }
+
+ return result;
+};
From e88ca716b3afa194a51e0457b5ee35892c5f90e1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 00:04:06 -0500
Subject: [PATCH 379/994] Add solution #3015
---
README.md | 1 +
...umber-of-houses-at-a-certain-distance-i.js | 57 +++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/3015-count-the-number-of-houses-at-a-certain-distance-i.js
diff --git a/README.md b/README.md
index 4aed3de7..1482b713 100644
--- a/README.md
+++ b/README.md
@@ -2130,6 +2130,7 @@
3010|[Divide an Array Into Subarrays With Minimum Cost I](./solutions/3010-divide-an-array-into-subarrays-with-minimum-cost-i.js)|Easy|
3011|[Find if Array Can Be Sorted](./solutions/3011-find-if-array-can-be-sorted.js)|Medium|
3014|[Minimum Number of Pushes to Type Word I](./solutions/3014-minimum-number-of-pushes-to-type-word-i.js)|Easy|
+3015|[Count the Number of Houses at a Certain Distance I](./solutions/3015-count-the-number-of-houses-at-a-certain-distance-i.js)|Medium|
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|
diff --git a/solutions/3015-count-the-number-of-houses-at-a-certain-distance-i.js b/solutions/3015-count-the-number-of-houses-at-a-certain-distance-i.js
new file mode 100644
index 00000000..02801f91
--- /dev/null
+++ b/solutions/3015-count-the-number-of-houses-at-a-certain-distance-i.js
@@ -0,0 +1,57 @@
+/**
+ * 3015. Count the Number of Houses at a Certain Distance I
+ * https://leetcode.com/problems/count-the-number-of-houses-at-a-certain-distance-i/
+ * Difficulty: Medium
+ *
+ * You are given three positive integers n, x, and y.
+ *
+ * In a city, there exist houses numbered 1 to n connected by n streets. There is a street
+ * connecting the house numbered i with the house numbered i + 1 for all 1 <= i <= n - 1.
+ * An additional street connects the house numbered x with the house numbered y.
+ *
+ * For each k, such that 1 <= k <= n, you need to find the number of pairs of houses (house1,
+ * house2) such that the minimum number of streets that need to be traveled to reach house2
+ * from house1 is k.
+ *
+ * Return a 1-indexed array result of length n where result[k] represents the total number
+ * of pairs of houses such that the minimum streets required to reach one house from the
+ * other is k.
+ *
+ * Note that x and y can be equal.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} x
+ * @param {number} y
+ * @return {number[]}
+ */
+var countOfPairs = function(n, x, y) {
+ const distances = new Array(n + 1).fill().map(() => new Array(n + 1).fill(Infinity));
+
+ for (let i = 1; i <= n; i++) {
+ distances[i][i] = 0;
+ if (i < n) distances[i][i + 1] = distances[i + 1][i] = 1;
+ }
+
+ distances[x][y] = distances[y][x] = 1;
+
+ for (let k = 1; k <= n; k++) {
+ for (let i = 1; i <= n; i++) {
+ for (let j = 1; j <= n; j++) {
+ distances[i][j] = Math.min(distances[i][j], distances[i][k] + distances[k][j]);
+ }
+ }
+ }
+
+ const result = new Array(n + 1).fill(0);
+ for (let i = 1; i <= n; i++) {
+ for (let j = 1; j <= n; j++) {
+ if (i !== j && distances[i][j] !== Infinity) {
+ result[distances[i][j]]++;
+ }
+ }
+ }
+
+ return result.slice(1);
+};
From 003e11f2b3d065b7bc6b0b25892d36fdb6a610d7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 00:05:38 -0500
Subject: [PATCH 380/994] Add solution #3016
---
README.md | 1 +
...inimum-number-of-pushes-to-type-word-ii.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/3016-minimum-number-of-pushes-to-type-word-ii.js
diff --git a/README.md b/README.md
index 1482b713..3fcb1a49 100644
--- a/README.md
+++ b/README.md
@@ -2131,6 +2131,7 @@
3011|[Find if Array Can Be Sorted](./solutions/3011-find-if-array-can-be-sorted.js)|Medium|
3014|[Minimum Number of Pushes to Type Word I](./solutions/3014-minimum-number-of-pushes-to-type-word-i.js)|Easy|
3015|[Count the Number of Houses at a Certain Distance I](./solutions/3015-count-the-number-of-houses-at-a-certain-distance-i.js)|Medium|
+3016|[Minimum Number of Pushes to Type Word II](./solutions/3016-minimum-number-of-pushes-to-type-word-ii.js)|Medium|
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|
diff --git a/solutions/3016-minimum-number-of-pushes-to-type-word-ii.js b/solutions/3016-minimum-number-of-pushes-to-type-word-ii.js
new file mode 100644
index 00000000..5a54a46c
--- /dev/null
+++ b/solutions/3016-minimum-number-of-pushes-to-type-word-ii.js
@@ -0,0 +1,41 @@
+/**
+ * 3016. Minimum Number of Pushes to Type Word II
+ * https://leetcode.com/problems/minimum-number-of-pushes-to-type-word-ii/
+ * Difficulty: Medium
+ *
+ * You are given a string word containing lowercase English letters.
+ *
+ * Telephone keypads have keys mapped with distinct collections of lowercase English letters,
+ * which can be used to form words by pushing them. For example, the key 2 is mapped with
+ * ["a","b","c"], we need to push the key one time to type "a", two times to type "b", and
+ * three times to type "c".
+ *
+ * It is allowed to remap the keys numbered 2 to 9 to distinct collections of letters. The
+ * keys can be remapped to any amount of letters, but each letter must be mapped to exactly
+ * one key. You need to find the minimum number of times the keys will be pushed to type the
+ * string word.
+ *
+ * Return the minimum number of pushes needed to type word after remapping the keys.
+ *
+ * An example mapping of letters to keys on a telephone keypad is given below. Note that
+ * 1, *, #, and 0 do not map to any letters.
+ */
+
+/**
+ * @param {string} word
+ * @return {number}
+ */
+var minimumPushes = function(word) {
+ const frequency = new Array(26).fill(0);
+ for (const char of word) {
+ frequency[char.charCodeAt(0) - 97]++;
+ }
+ frequency.sort((a, b) => b - a);
+
+ let result = 0;
+ for (let i = 0; i < frequency.length && frequency[i] > 0; i++) {
+ result += frequency[i] * (Math.floor(i / 8) + 1);
+ }
+
+ return result;
+};
From 860a9ce17b3fedd972ce791064b301e1220c4d1b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 22:38:05 -0500
Subject: [PATCH 381/994] Add solution #3170
---
README.md | 1 +
...lly-minimum-string-after-removing-stars.js | 40 +++++++++++++++++++
2 files changed, 41 insertions(+)
create mode 100644 solutions/3170-lexicographically-minimum-string-after-removing-stars.js
diff --git a/README.md b/README.md
index 3fcb1a49..9dcc163a 100644
--- a/README.md
+++ b/README.md
@@ -2142,6 +2142,7 @@
3151|[Special Array I](./solutions/3151-special-array-i.js)|Easy|
3160|[Find the Number of Distinct Colors Among the Balls](./solutions/3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium|
3169|[Count Days Without Meetings](./solutions/3169-count-days-without-meetings.js)|Medium|
+3170|[Lexicographically Minimum String After Removing Stars](./solutions/3170-lexicographically-minimum-string-after-removing-stars.js)|Medium|
3174|[Clear Digits](./solutions/3174-clear-digits.js)|Easy|
3178|[Find the Child Who Has the Ball After K Seconds](./solutions/3178-find-the-child-who-has-the-ball-after-k-seconds.js)|Easy|
3191|[Minimum Operations to Make Binary Array Elements Equal to One I](./solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js)|Medium|
diff --git a/solutions/3170-lexicographically-minimum-string-after-removing-stars.js b/solutions/3170-lexicographically-minimum-string-after-removing-stars.js
new file mode 100644
index 00000000..c0efec6b
--- /dev/null
+++ b/solutions/3170-lexicographically-minimum-string-after-removing-stars.js
@@ -0,0 +1,40 @@
+/**
+ * 3170. Lexicographically Minimum String After Removing Stars
+ * https://leetcode.com/problems/lexicographically-minimum-string-after-removing-stars/
+ * Difficulty: Medium
+ *
+ * You are given a string s. It may contain any number of '*' characters. Your task is to
+ * remove all '*' characters.
+ *
+ * While there is a '*', do the following operation:
+ * - Delete the leftmost '*' and the smallest non-'*' character to its left. If there are several
+ * smallest characters, you can delete any of them.
+ *
+ * Return the lexicographically smallest resulting string after removing all '*' characters.
+ */
+
+/**
+ * @param {string} s
+ * @return {string}
+ */
+var clearStars = function(s) {
+ const chars = s.split('');
+ const deleted = new Set();
+ const stacks = new Array(26).fill().map(() => []);
+
+ for (let i = 0; i < s.length; i++) {
+ if (s[i] === '*') {
+ for (let j = 0; j < 26; j++) {
+ if (stacks[j].length) {
+ deleted.add(stacks[j].pop());
+ deleted.add(i);
+ break;
+ }
+ }
+ } else {
+ stacks[s[i].charCodeAt(0) - 97].push(i);
+ }
+ }
+
+ return chars.filter((_, i) => !deleted.has(i)).join('');
+};
From 2fd61650d5528ddcd1fd4af43865629fc167df9b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 22:41:48 -0500
Subject: [PATCH 382/994] Add solution #3019
---
README.md | 1 +
solutions/3019-number-of-changing-keys.js | 30 +++++++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 solutions/3019-number-of-changing-keys.js
diff --git a/README.md b/README.md
index 9dcc163a..91036696 100644
--- a/README.md
+++ b/README.md
@@ -2132,6 +2132,7 @@
3014|[Minimum Number of Pushes to Type Word I](./solutions/3014-minimum-number-of-pushes-to-type-word-i.js)|Easy|
3015|[Count the Number of Houses at a Certain Distance I](./solutions/3015-count-the-number-of-houses-at-a-certain-distance-i.js)|Medium|
3016|[Minimum Number of Pushes to Type Word II](./solutions/3016-minimum-number-of-pushes-to-type-word-ii.js)|Medium|
+3019|[Number of Changing Keys](./solutions/3019-number-of-changing-keys.js)|Easy|
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|
diff --git a/solutions/3019-number-of-changing-keys.js b/solutions/3019-number-of-changing-keys.js
new file mode 100644
index 00000000..f48c69f0
--- /dev/null
+++ b/solutions/3019-number-of-changing-keys.js
@@ -0,0 +1,30 @@
+/**
+ * 3019. Number of Changing Keys
+ * https://leetcode.com/problems/number-of-changing-keys/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed string s typed by a user. Changing a key is defined as using a key
+ * different from the last used key. For example, s = "ab" has a change of a key while s = "bBBb"
+ * does not have any.
+ *
+ * Return the number of times the user had to change the key.
+ *
+ * Note: Modifiers like shift or caps lock won't be counted in changing the key that is if a user
+ * typed the letter 'a' and then the letter 'A' then it will not be considered as a changing of key.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var countKeyChanges = function(s) {
+ let result = 0;
+
+ for (let i = 1; i < s.length; i++) {
+ if (s[i].toLowerCase() !== s[i - 1].toLowerCase()) {
+ result++;
+ }
+ }
+
+ return result;
+};
From 510da6865bd40a2f7c5215781668762b2503a8a7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 22:48:12 -0500
Subject: [PATCH 383/994] Add solution #3021
---
README.md | 1 +
.../3021-alice-and-bob-playing-flower-game.js | 37 +++++++++++++++++++
2 files changed, 38 insertions(+)
create mode 100644 solutions/3021-alice-and-bob-playing-flower-game.js
diff --git a/README.md b/README.md
index 91036696..ba2bbff4 100644
--- a/README.md
+++ b/README.md
@@ -2133,6 +2133,7 @@
3015|[Count the Number of Houses at a Certain Distance I](./solutions/3015-count-the-number-of-houses-at-a-certain-distance-i.js)|Medium|
3016|[Minimum Number of Pushes to Type Word II](./solutions/3016-minimum-number-of-pushes-to-type-word-ii.js)|Medium|
3019|[Number of Changing Keys](./solutions/3019-number-of-changing-keys.js)|Easy|
+3021|[Alice and Bob Playing Flower Game](./solutions/3021-alice-and-bob-playing-flower-game.js)|Medium|
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|
diff --git a/solutions/3021-alice-and-bob-playing-flower-game.js b/solutions/3021-alice-and-bob-playing-flower-game.js
new file mode 100644
index 00000000..4335643c
--- /dev/null
+++ b/solutions/3021-alice-and-bob-playing-flower-game.js
@@ -0,0 +1,37 @@
+/**
+ * 3021. Alice and Bob Playing Flower Game
+ * https://leetcode.com/problems/alice-and-bob-playing-flower-game/
+ * Difficulty: Medium
+ *
+ * Alice and Bob are playing a turn-based game on a circular field surrounded by flowers.
+ * The circle represents the field, and there are x flowers in the clockwise direction
+ * between Alice and Bob, and y flowers in the anti-clockwise direction between them.
+ *
+ * The game proceeds as follows:
+ * 1. Alice takes the first turn.
+ * 2. In each turn, a player must choose either the clockwise or anti-clockwise direction
+ * and pick one flower from that side.
+ * 3. At the end of the turn, if there are no flowers left at all, the current player
+ * captures their opponent and wins the game.
+ *
+ * Given two integers, n and m, the task is to compute the number of possible pairs (x, y)
+ * that satisfy the conditions:
+ * - Alice must win the game according to the described rules.
+ * - The number of flowers x in the clockwise direction must be in the range [1,n].
+ * - The number of flowers y in the anti-clockwise direction must be in the range [1,m].
+ *
+ * Return the number of possible pairs (x, y) that satisfy the conditions mentioned in the
+ * statement.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} m
+ * @return {number}
+ */
+var flowerGame = function(n, m) {
+ const evenN = Math.floor(n / 2);
+ const evenM = Math.floor(m / 2);
+
+ return evenN * (m - evenM) + (n - evenN) * evenM;
+};
From b290eacee8bdc4390978caea5addaf2a766ba084 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 22:49:28 -0500
Subject: [PATCH 384/994] Add solution #3025
---
README.md | 1 +
...nd-the-number-of-ways-to-place-people-i.js | 43 +++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/3025-find-the-number-of-ways-to-place-people-i.js
diff --git a/README.md b/README.md
index ba2bbff4..85e644ea 100644
--- a/README.md
+++ b/README.md
@@ -2135,6 +2135,7 @@
3019|[Number of Changing Keys](./solutions/3019-number-of-changing-keys.js)|Easy|
3021|[Alice and Bob Playing Flower Game](./solutions/3021-alice-and-bob-playing-flower-game.js)|Medium|
3024|[Type of Triangle](./solutions/3024-type-of-triangle.js)|Easy|
+3025|[Find the Number of Ways to Place People I](./solutions/3025-find-the-number-of-ways-to-place-people-i.js)|Medium|
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|
diff --git a/solutions/3025-find-the-number-of-ways-to-place-people-i.js b/solutions/3025-find-the-number-of-ways-to-place-people-i.js
new file mode 100644
index 00000000..d0b579c1
--- /dev/null
+++ b/solutions/3025-find-the-number-of-ways-to-place-people-i.js
@@ -0,0 +1,43 @@
+/**
+ * 3025. Find the Number of Ways to Place People I
+ * https://leetcode.com/problems/find-the-number-of-ways-to-place-people-i/
+ * Difficulty: Medium
+ *
+ * You are given a 2D array points of size n x 2 representing integer coordinates of some points
+ * on a 2D plane, where points[i] = [xi, yi].
+ *
+ * Count the number of pairs of points (A, B), where
+ * - A is on the upper left side of B, and
+ * - there are no other points in the rectangle (or line) they make (including the border).
+ *
+ * Return the count.
+ */
+
+/**
+ * @param {number[][]} points
+ * @return {number}
+ */
+var numberOfPairs = function(points) {
+ points.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]);
+ let result = 0;
+
+ for (let i = 0; i < points.length; i++) {
+ for (let j = i + 1; j < points.length; j++) {
+ if (points[i][1] >= points[j][1]) {
+ let isValid = true;
+ for (let k = 0; k < points.length; k++) {
+ if (k !== i && k !== j) {
+ if (points[k][0] >= points[i][0] && points[k][0] <= points[j][0]
+ && points[k][1] <= points[i][1] && points[k][1] >= points[j][1]) {
+ isValid = false;
+ break;
+ }
+ }
+ }
+ if (isValid) result++;
+ }
+ }
+ }
+
+ return result;
+};
From f57d6169a016738cb770aae86ce001e34c6874e8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 22:53:25 -0500
Subject: [PATCH 385/994] Add solution #3027
---
README.md | 1 +
...d-the-number-of-ways-to-place-people-ii.js | 68 +++++++++++++++++++
2 files changed, 69 insertions(+)
create mode 100644 solutions/3027-find-the-number-of-ways-to-place-people-ii.js
diff --git a/README.md b/README.md
index 85e644ea..8530698d 100644
--- a/README.md
+++ b/README.md
@@ -2136,6 +2136,7 @@
3021|[Alice and Bob Playing Flower Game](./solutions/3021-alice-and-bob-playing-flower-game.js)|Medium|
3024|[Type of Triangle](./solutions/3024-type-of-triangle.js)|Easy|
3025|[Find the Number of Ways to Place People I](./solutions/3025-find-the-number-of-ways-to-place-people-i.js)|Medium|
+3027|[Find the Number of Ways to Place People II](./solutions/3027-find-the-number-of-ways-to-place-people-ii.js)|Hard|
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|
diff --git a/solutions/3027-find-the-number-of-ways-to-place-people-ii.js b/solutions/3027-find-the-number-of-ways-to-place-people-ii.js
new file mode 100644
index 00000000..6077d142
--- /dev/null
+++ b/solutions/3027-find-the-number-of-ways-to-place-people-ii.js
@@ -0,0 +1,68 @@
+/**
+ * 3027. Find the Number of Ways to Place People II
+ * https://leetcode.com/problems/find-the-number-of-ways-to-place-people-ii/
+ * Difficulty: Hard
+ *
+ * You are given a 2D array points of size n x 2 representing integer coordinates of some points
+ * on a 2D-plane, where points[i] = [xi, yi].
+ *
+ * We define the right direction as positive x-axis (increasing x-coordinate) and the left
+ * direction as negative x-axis (decreasing x-coordinate). Similarly, we define the up direction
+ * as positive y-axis (increasing y-coordinate) and the down direction as negative y-axis
+ * (decreasing y-coordinate)
+ *
+ * You have to place n people, including Alice and Bob, at these points such that there is exactly
+ * one person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular
+ * fence with Alice's position as the upper left corner and Bob's position as the lower right
+ * corner of the fence (Note that the fence might not enclose any area, i.e. it can be a line).
+ * If any person other than Alice and Bob is either inside the fence or on the fence, Alice will
+ * be sad.
+ *
+ * Return the number of pairs of points where you can place Alice and Bob, such that Alice does not
+ * become sad on building the fence.
+ *
+ * Note that Alice can only build a fence with Alice's position as the upper left corner, and Bob's
+ * position as the lower right corner. For example, Alice cannot build either of the fences in the
+ * picture below with four corners (1, 1), (1, 3), (3, 1), and (3, 3), because:
+ * - With Alice at (3, 3) and Bob at (1, 1), Alice's position is not the upper left corner and Bob's
+ * position is not the lower right corner of the fence.
+ * - With Alice at (1, 3) and Bob at (1, 1), Bob's position is not the lower right corner of the
+ * fence.
+ */
+
+/**
+ * @param {number[][]} points
+ * @return {number}
+ */
+var numberOfPairs = function(points) {
+ points.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]);
+ let result = 0;
+
+ for (let i = 0; i < points.length; i++) {
+ const [, maxY] = points[i];
+ let minY = -Infinity;
+
+ for (let j = i + 1; j < points.length; j++) {
+ const [, y] = points[j];
+ if (y <= maxY && y > minY) {
+ let isValid = true;
+ for (let k = 0; k < points.length; k++) {
+ if (k !== i && k !== j) {
+ const [x, ky] = points[k];
+ if (x >= points[i][0] && x <= points[j][0]
+ && ky <= points[i][1] && ky >= points[j][1]) {
+ isValid = false;
+ break;
+ }
+ }
+ }
+ if (isValid) {
+ result++;
+ minY = y;
+ }
+ }
+ }
+ }
+
+ return result;
+};
From e81783a8dc1bb79756221bbe4334a5961ee9a9af Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 22:57:58 -0500
Subject: [PATCH 386/994] Add solution #3028
---
README.md | 1 +
solutions/3028-ant-on-the-boundary.js | 38 +++++++++++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/3028-ant-on-the-boundary.js
diff --git a/README.md b/README.md
index 8530698d..8b032a67 100644
--- a/README.md
+++ b/README.md
@@ -2137,6 +2137,7 @@
3024|[Type of Triangle](./solutions/3024-type-of-triangle.js)|Easy|
3025|[Find the Number of Ways to Place People I](./solutions/3025-find-the-number-of-ways-to-place-people-i.js)|Medium|
3027|[Find the Number of Ways to Place People II](./solutions/3027-find-the-number-of-ways-to-place-people-ii.js)|Hard|
+3028|[Ant on the Boundary](./solutions/3028-ant-on-the-boundary.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|
diff --git a/solutions/3028-ant-on-the-boundary.js b/solutions/3028-ant-on-the-boundary.js
new file mode 100644
index 00000000..fab768da
--- /dev/null
+++ b/solutions/3028-ant-on-the-boundary.js
@@ -0,0 +1,38 @@
+/**
+ * 3028. Ant on the Boundary
+ * https://leetcode.com/problems/ant-on-the-boundary/
+ * Difficulty: Easy
+ *
+ * An ant is on a boundary. It sometimes goes left and sometimes right.
+ *
+ * You are given an array of non-zero integers nums. The ant starts reading nums from the
+ * first element of it to its end. At each step, it moves according to the value of the
+ * current element:
+ * - If nums[i] < 0, it moves left by -nums[i] units.
+ * - If nums[i] > 0, it moves right by nums[i] units.
+ *
+ * Return the number of times the ant returns to the boundary.
+ *
+ * Notes:
+ * - There is an infinite space on both sides of the boundary.
+ * - We check whether the ant is on the boundary only after it has moved |nums[i]| units.
+ * In other words, if the ant crosses the boundary during its movement, it does not count.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var returnToBoundaryCount = function(nums) {
+ let position = 0;
+ let result = 0;
+
+ for (const step of nums) {
+ position += step;
+ if (position === 0) {
+ result++;
+ }
+ }
+
+ return result;
+};
From e64a4159d399badaa8024e26ce8303c1c27cf2ce Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 22:59:13 -0500
Subject: [PATCH 387/994] Add solution #3029
---
README.md | 1 +
...-time-to-revert-word-to-initial-state-i.js | 33 +++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/3029-minimum-time-to-revert-word-to-initial-state-i.js
diff --git a/README.md b/README.md
index 8b032a67..f4133126 100644
--- a/README.md
+++ b/README.md
@@ -2138,6 +2138,7 @@
3025|[Find the Number of Ways to Place People I](./solutions/3025-find-the-number-of-ways-to-place-people-i.js)|Medium|
3027|[Find the Number of Ways to Place People II](./solutions/3027-find-the-number-of-ways-to-place-people-ii.js)|Hard|
3028|[Ant on the Boundary](./solutions/3028-ant-on-the-boundary.js)|Easy|
+3029|[Minimum Time to Revert Word to Initial State I](./solutions/3029-minimum-time-to-revert-word-to-initial-state-i.js)|Medium|
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|
diff --git a/solutions/3029-minimum-time-to-revert-word-to-initial-state-i.js b/solutions/3029-minimum-time-to-revert-word-to-initial-state-i.js
new file mode 100644
index 00000000..07d7e492
--- /dev/null
+++ b/solutions/3029-minimum-time-to-revert-word-to-initial-state-i.js
@@ -0,0 +1,33 @@
+/**
+ * 3029. Minimum Time to Revert Word to Initial State I
+ * https://leetcode.com/problems/minimum-time-to-revert-word-to-initial-state-i/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed string word and an integer k.
+ *
+ * At every second, you must perform the following operations:
+ * - Remove the first k characters of word.
+ * - Add any k characters to the end of word.
+ *
+ * Note that you do not necessarily need to add the same characters that you removed.
+ * However, you must perform both operations at every second.
+ *
+ * Return the minimum time greater than zero required for word to revert to its initial state.
+ */
+
+/**
+ * @param {string} word
+ * @param {number} k
+ * @return {number}
+ */
+var minimumTimeToInitialState = function(word, k) {
+ const n = word.length;
+
+ for (let i = 1; i * k <= n; i++) {
+ if (word.slice(i * k) === word.slice(0, n - i * k)) {
+ return i;
+ }
+ }
+
+ return Math.ceil(n / k);
+};
From b916175568720fdf0d3fe35b157c91cc329ba50c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 23:08:50 -0500
Subject: [PATCH 388/994] Add solution #3030
---
README.md | 1 +
.../3030-find-the-grid-of-region-average.js | 94 +++++++++++++++++++
2 files changed, 95 insertions(+)
create mode 100644 solutions/3030-find-the-grid-of-region-average.js
diff --git a/README.md b/README.md
index f4133126..1b22f69a 100644
--- a/README.md
+++ b/README.md
@@ -2139,6 +2139,7 @@
3027|[Find the Number of Ways to Place People II](./solutions/3027-find-the-number-of-ways-to-place-people-ii.js)|Hard|
3028|[Ant on the Boundary](./solutions/3028-ant-on-the-boundary.js)|Easy|
3029|[Minimum Time to Revert Word to Initial State I](./solutions/3029-minimum-time-to-revert-word-to-initial-state-i.js)|Medium|
+3030|[Find the Grid of Region Average](./solutions/3030-find-the-grid-of-region-average.js)|Medium|
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|
diff --git a/solutions/3030-find-the-grid-of-region-average.js b/solutions/3030-find-the-grid-of-region-average.js
new file mode 100644
index 00000000..d15b7ada
--- /dev/null
+++ b/solutions/3030-find-the-grid-of-region-average.js
@@ -0,0 +1,94 @@
+/**
+ * 3030. Find the Grid of Region Average
+ * https://leetcode.com/problems/find-the-grid-of-region-average/
+ * Difficulty: Medium
+ *
+ * You are given m x n grid image which represents a grayscale image, where image[i][j]
+ * represents a pixel with intensity in the range [0..255]. You are also given a non-negative
+ * integer threshold.
+ *
+ * Two pixels are adjacent if they share an edge.
+ *
+ * A region is a 3 x 3 subgrid where the absolute difference in intensity between any two
+ * adjacent pixels is less than or equal to threshold.
+ *
+ * All pixels in a region belong to that region, note that a pixel can belong to multiple regions.
+ *
+ * You need to calculate a m x n grid result, where result[i][j] is the average intensity of the
+ * regions to which image[i][j] belongs, rounded down to the nearest integer. If image[i][j]
+ * belongs to multiple regions, result[i][j] is the average of the rounded-down average intensities
+ * of these regions, rounded down to the nearest integer. If image[i][j] does not belong to any
+ * region, result[i][j] is equal to image[i][j].
+ *
+ * Return the grid result.
+ */
+
+/**
+ * @param {number[][]} image
+ * @param {number} threshold
+ * @return {number[][]}
+ */
+var resultGrid = function(image, threshold) {
+ const rows = image.length;
+ const cols = image[0].length;
+ const result = Array.from({ length: rows }, () => new Array(cols).fill(0));
+ const regionCount = Array.from({ length: rows }, () => new Array(cols).fill(0));
+
+ for (let i = 0; i <= rows - 3; i++) {
+ for (let j = 0; j <= cols - 3; j++) {
+ if (isValidRegion(i, j)) {
+ const regionAvg = calculateRegionAverage(i, j);
+
+ for (let r = i; r < i + 3; r++) {
+ for (let c = j; c < j + 3; c++) {
+ result[r][c] += regionAvg;
+ regionCount[r][c]++;
+ }
+ }
+ }
+ }
+ }
+
+ for (let i = 0; i < rows; i++) {
+ for (let j = 0; j < cols; j++) {
+ if (regionCount[i][j] === 0) {
+ result[i][j] = image[i][j];
+ } else {
+ result[i][j] = Math.floor(result[i][j] / regionCount[i][j]);
+ }
+ }
+ }
+
+ return result;
+
+ function calculateRegionAverage(startRow, startCol) {
+ let sum = 0;
+ for (let i = startRow; i < startRow + 3; i++) {
+ for (let j = startCol; j < startCol + 3; j++) {
+ sum += image[i][j];
+ }
+ }
+ return Math.floor(sum / 9);
+ }
+
+ function isValidRegion(startRow, startCol) {
+ const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
+
+ for (let i = startRow; i < startRow + 3; i++) {
+ for (let j = startCol; j < startCol + 3; j++) {
+ for (const [dr, dc] of directions) {
+ const newRow = i + dr;
+ const newCol = j + dc;
+
+ if (newRow >= startRow && newRow < startRow + 3
+ && newCol >= startCol && newCol < startCol + 3) {
+ if (Math.abs(image[i][j] - image[newRow][newCol]) > threshold) {
+ return false;
+ }
+ }
+ }
+ }
+ }
+ return true;
+ }
+};
From 193e5382e211eaa392fc467298ddc95e46f4c050 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 23:09:55 -0500
Subject: [PATCH 389/994] Add solution #3033
---
README.md | 1 +
solutions/3033-modify-the-matrix.js | 38 +++++++++++++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/3033-modify-the-matrix.js
diff --git a/README.md b/README.md
index 1b22f69a..5813ec55 100644
--- a/README.md
+++ b/README.md
@@ -2140,6 +2140,7 @@
3028|[Ant on the Boundary](./solutions/3028-ant-on-the-boundary.js)|Easy|
3029|[Minimum Time to Revert Word to Initial State I](./solutions/3029-minimum-time-to-revert-word-to-initial-state-i.js)|Medium|
3030|[Find the Grid of Region Average](./solutions/3030-find-the-grid-of-region-average.js)|Medium|
+3033|[Modify the Matrix](./solutions/3033-modify-the-matrix.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|
diff --git a/solutions/3033-modify-the-matrix.js b/solutions/3033-modify-the-matrix.js
new file mode 100644
index 00000000..6d8b09ab
--- /dev/null
+++ b/solutions/3033-modify-the-matrix.js
@@ -0,0 +1,38 @@
+/**
+ * 3033. Modify the Matrix
+ * https://leetcode.com/problems/modify-the-matrix/
+ * Difficulty: Easy
+ *
+ * Given a 0-indexed m x n integer matrix matrix, create a new 0-indexed matrix called answer.
+ * Make answer equal to matrix, then replace each element with the value -1 with the maximum
+ * element in its respective column.
+ *
+ * Return the matrix answer.
+ */
+
+/**
+ * @param {number[][]} matrix
+ * @return {number[][]}
+ */
+var modifiedMatrix = function(matrix) {
+ const m = matrix.length;
+ const n = matrix[0].length;
+ const result = matrix.map(row => [...row]);
+ const colMaxes = new Array(n).fill(-Infinity);
+
+ for (let j = 0; j < n; j++) {
+ for (let i = 0; i < m; i++) {
+ colMaxes[j] = Math.max(colMaxes[j], matrix[i][j]);
+ }
+ }
+
+ for (let i = 0; i < m; i++) {
+ for (let j = 0; j < n; j++) {
+ if (result[i][j] === -1) {
+ result[i][j] = colMaxes[j];
+ }
+ }
+ }
+
+ return result;
+};
From 9f5c2a6feea84705f50bb59ae6513df99380519b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 23:13:06 -0500
Subject: [PATCH 390/994] Add solution #3034
---
README.md | 1 +
...ber-of-subarrays-that-match-a-pattern-i.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/3034-number-of-subarrays-that-match-a-pattern-i.js
diff --git a/README.md b/README.md
index 5813ec55..8156f858 100644
--- a/README.md
+++ b/README.md
@@ -2141,6 +2141,7 @@
3029|[Minimum Time to Revert Word to Initial State I](./solutions/3029-minimum-time-to-revert-word-to-initial-state-i.js)|Medium|
3030|[Find the Grid of Region Average](./solutions/3030-find-the-grid-of-region-average.js)|Medium|
3033|[Modify the Matrix](./solutions/3033-modify-the-matrix.js)|Easy|
+3034|[Number of Subarrays That Match a Pattern I](./solutions/3034-number-of-subarrays-that-match-a-pattern-i.js)|Medium|
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|
diff --git a/solutions/3034-number-of-subarrays-that-match-a-pattern-i.js b/solutions/3034-number-of-subarrays-that-match-a-pattern-i.js
new file mode 100644
index 00000000..d95a2c36
--- /dev/null
+++ b/solutions/3034-number-of-subarrays-that-match-a-pattern-i.js
@@ -0,0 +1,41 @@
+/**
+ * 3034. Number of Subarrays That Match a Pattern I
+ * https://leetcode.com/problems/number-of-subarrays-that-match-a-pattern-i/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums of size n, and a 0-indexed integer array pattern
+ * of size m consisting of integers -1, 0, and 1.
+ *
+ * A subarray nums[i..j] of size m + 1 is said to match the pattern if the following conditions
+ * hold for each element pattern[k]:
+ * - nums[i + k + 1] > nums[i + k] if pattern[k] == 1.
+ * - nums[i + k + 1] == nums[i + k] if pattern[k] == 0.
+ * - nums[i + k + 1] < nums[i + k] if pattern[k] == -1.
+ *
+ * Return the count of subarrays in nums that match the pattern.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[]} pattern
+ * @return {number}
+ */
+var countMatchingSubarrays = function(nums, pattern) {
+ let result = 0;
+ const m = pattern.length;
+
+ for (let i = 0; i <= nums.length - m - 1; i++) {
+ let isMatch = true;
+ for (let j = 0; j < m; j++) {
+ const diff = nums[i + j + 1] - nums[i + j];
+ if ((pattern[j] === 1 && diff <= 0) || (pattern[j] === 0 && diff !== 0)
+ || (pattern[j] === -1 && diff >= 0)) {
+ isMatch = false;
+ break;
+ }
+ }
+ if (isMatch) result++;
+ }
+
+ return result;
+};
From eb7252f6dea5fd4c8f636b4d0bdbca4baad342aa Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 23:17:41 -0500
Subject: [PATCH 391/994] Add solution #3035
---
README.md | 1 +
...35-maximum-palindromes-after-operations.js | 46 +++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/3035-maximum-palindromes-after-operations.js
diff --git a/README.md b/README.md
index 8156f858..0564b6f9 100644
--- a/README.md
+++ b/README.md
@@ -2142,6 +2142,7 @@
3030|[Find the Grid of Region Average](./solutions/3030-find-the-grid-of-region-average.js)|Medium|
3033|[Modify the Matrix](./solutions/3033-modify-the-matrix.js)|Easy|
3034|[Number of Subarrays That Match a Pattern I](./solutions/3034-number-of-subarrays-that-match-a-pattern-i.js)|Medium|
+3035|[Maximum Palindromes After Operations](./solutions/3035-maximum-palindromes-after-operations.js)|Medium|
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|
diff --git a/solutions/3035-maximum-palindromes-after-operations.js b/solutions/3035-maximum-palindromes-after-operations.js
new file mode 100644
index 00000000..8897c387
--- /dev/null
+++ b/solutions/3035-maximum-palindromes-after-operations.js
@@ -0,0 +1,46 @@
+/**
+ * 3035. Maximum Palindromes After Operations
+ * https://leetcode.com/problems/maximum-palindromes-after-operations/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed string array words having length n and containing 0-indexed strings.
+ *
+ * You are allowed to perform the following operation any number of times (including zero):
+ * - Choose integers i, j, x, and y such that 0 <= i, j < n, 0 <= x < words[i].length,
+ * 0 <= y < words[j].length, and swap the characters words[i][x] and words[j][y].
+ *
+ * Return an integer denoting the maximum number of palindromes words can contain, after performing
+ * some operations.
+ *
+ * Note: i and j may be equal during an operation.
+ */
+
+/**
+ * @param {string[]} words
+ * @return {number}
+ */
+var maxPalindromesAfterOperations = function(words) {
+ const charCount = new Array(26).fill(0);
+ let pairCount = 0;
+ let result = 0;
+
+ for (const word of words) {
+ for (const char of word) {
+ charCount[char.charCodeAt(0) - 97]++;
+ }
+ }
+
+ for (const count of charCount) {
+ pairCount += Math.floor(count / 2);
+ }
+
+ const lengths = words.map(word => word.length).sort((a, b) => a - b);
+ for (const length of lengths) {
+ if (pairCount >= Math.floor(length / 2)) {
+ pairCount -= Math.floor(length / 2);
+ result++;
+ }
+ }
+
+ return result;
+};
From 63bb953726f8d4d43f6e137e7df5da6ad588b727 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 23:18:39 -0500
Subject: [PATCH 392/994] Add solution #3038
---
README.md | 1 +
...ber-of-operations-with-the-same-score-i.js | 33 +++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/3038-maximum-number-of-operations-with-the-same-score-i.js
diff --git a/README.md b/README.md
index 0564b6f9..c3883230 100644
--- a/README.md
+++ b/README.md
@@ -2143,6 +2143,7 @@
3033|[Modify the Matrix](./solutions/3033-modify-the-matrix.js)|Easy|
3034|[Number of Subarrays That Match a Pattern I](./solutions/3034-number-of-subarrays-that-match-a-pattern-i.js)|Medium|
3035|[Maximum Palindromes After Operations](./solutions/3035-maximum-palindromes-after-operations.js)|Medium|
+3038|[Maximum Number of Operations With the Same Score I](./solutions/3038-maximum-number-of-operations-with-the-same-score-i.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|
diff --git a/solutions/3038-maximum-number-of-operations-with-the-same-score-i.js b/solutions/3038-maximum-number-of-operations-with-the-same-score-i.js
new file mode 100644
index 00000000..d1e825cb
--- /dev/null
+++ b/solutions/3038-maximum-number-of-operations-with-the-same-score-i.js
@@ -0,0 +1,33 @@
+/**
+ * 3038. Maximum Number of Operations With the Same Score I
+ * https://leetcode.com/problems/maximum-number-of-operations-with-the-same-score-i/
+ * Difficulty: Easy
+ *
+ * You are given an array of integers nums. Consider the following operation:
+ * - Delete the first two elements nums and define the score of the operation as the sum of
+ * these two elements.
+ *
+ * You can perform this operation until nums contains fewer than two elements. Additionally,
+ * the same score must be achieved in all operations.
+ *
+ * Return the maximum number of operations you can perform.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maxOperations = function(nums) {
+ let result = 0;
+ const targetScore = nums[0] + nums[1];
+
+ for (let i = 0; i < nums.length - 1; i += 2) {
+ if (nums[i] + nums[i + 1] === targetScore) {
+ result++;
+ } else {
+ break;
+ }
+ }
+
+ return result;
+};
From 9c7788b880aa3d8ed355bc0a6b4a86fa7cf935ab Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 23:19:52 -0500
Subject: [PATCH 393/994] Add solution #3039
---
README.md | 1 +
...9-apply-operations-to-make-string-empty.js | 45 +++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/3039-apply-operations-to-make-string-empty.js
diff --git a/README.md b/README.md
index c3883230..d5744f10 100644
--- a/README.md
+++ b/README.md
@@ -2144,6 +2144,7 @@
3034|[Number of Subarrays That Match a Pattern I](./solutions/3034-number-of-subarrays-that-match-a-pattern-i.js)|Medium|
3035|[Maximum Palindromes After Operations](./solutions/3035-maximum-palindromes-after-operations.js)|Medium|
3038|[Maximum Number of Operations With the Same Score I](./solutions/3038-maximum-number-of-operations-with-the-same-score-i.js)|Easy|
+3039|[Apply Operations to Make String Empty](./solutions/3039-apply-operations-to-make-string-empty.js)|Medium|
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|
diff --git a/solutions/3039-apply-operations-to-make-string-empty.js b/solutions/3039-apply-operations-to-make-string-empty.js
new file mode 100644
index 00000000..82cc2e56
--- /dev/null
+++ b/solutions/3039-apply-operations-to-make-string-empty.js
@@ -0,0 +1,45 @@
+/**
+ * 3039. Apply Operations to Make String Empty
+ * https://leetcode.com/problems/apply-operations-to-make-string-empty/
+ * Difficulty: Medium
+ *
+ * You are given a string s.
+ *
+ * Consider performing the following operation until s becomes empty:
+ * - For every alphabet character from 'a' to 'z', remove the first occurrence of that
+ * character in s (if it exists).
+ *
+ * For example, let initially s = "aabcbbca". We do the following operations:
+ * - Remove the underlined characters s = "aabcbbca". The resulting string is s = "abbca".
+ * - Remove the underlined characters s = "abbca". The resulting string is s = "ba".
+ * - Remove the underlined characters s = "ba". The resulting string is s = "".
+ *
+ * Return the value of the string s right before applying the last operation. In the
+ * example above, answer is "ba".
+ */
+
+/**
+ * @param {string} s
+ * @return {string}
+ */
+var lastNonEmptyString = function(s) {
+ const charCount = new Array(26).fill(0);
+ let maxFrequency = 0;
+
+ for (const char of s) {
+ const index = char.charCodeAt(0) - 97;
+ charCount[index]++;
+ maxFrequency = Math.max(maxFrequency, charCount[index]);
+ }
+
+ let result = '';
+ for (let i = s.length - 1; i >= 0; i--) {
+ const index = s.charCodeAt(i) - 97;
+ if (charCount[index] === maxFrequency) {
+ result = s[i] + result;
+ charCount[index]--;
+ }
+ }
+
+ return result;
+};
From f1f4f70b52340a97becf997430adddec83ce1b4e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 23:21:02 -0500
Subject: [PATCH 394/994] Add solution #3043
---
README.md | 1 +
...the-length-of-the-longest-common-prefix.js | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/3043-find-the-length-of-the-longest-common-prefix.js
diff --git a/README.md b/README.md
index d5744f10..e638c748 100644
--- a/README.md
+++ b/README.md
@@ -2146,6 +2146,7 @@
3038|[Maximum Number of Operations With the Same Score I](./solutions/3038-maximum-number-of-operations-with-the-same-score-i.js)|Easy|
3039|[Apply Operations to Make String Empty](./solutions/3039-apply-operations-to-make-string-empty.js)|Medium|
3042|[Count Prefix and Suffix Pairs I](./solutions/3042-count-prefix-and-suffix-pairs-i.js)|Easy|
+3043|[Find the Length of the Longest Common Prefix](./solutions/3043-find-the-length-of-the-longest-common-prefix.js)|Medium|
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|
diff --git a/solutions/3043-find-the-length-of-the-longest-common-prefix.js b/solutions/3043-find-the-length-of-the-longest-common-prefix.js
new file mode 100644
index 00000000..13ad3b97
--- /dev/null
+++ b/solutions/3043-find-the-length-of-the-longest-common-prefix.js
@@ -0,0 +1,50 @@
+/**
+ * 3043. Find the Length of the Longest Common Prefix
+ * https://leetcode.com/problems/find-the-length-of-the-longest-common-prefix/
+ * Difficulty: Medium
+ *
+ * You are given two arrays with positive integers arr1 and arr2.
+ *
+ * A prefix of a positive integer is an integer formed by one or more of its digits, starting
+ * from its leftmost digit. For example, 123 is a prefix of the integer 12345, while 234 is not.
+ *
+ * A common prefix of two integers a and b is an integer c, such that c is a prefix of both a
+ * and b. For example, 5655359 and 56554 have common prefixes 565 and 5655 while 1223 and 43456
+ * do not have a common prefix.
+ *
+ * You need to find the length of the longest common prefix between all pairs of integers (x, y)
+ * such that x belongs to arr1 and y belongs to arr2.
+ *
+ * Return the length of the longest common prefix among all pairs. If no common prefix exists
+ * among them, return 0.
+ */
+
+/**
+ * @param {number[]} arr1
+ * @param {number[]} arr2
+ * @return {number}
+ */
+var longestCommonPrefix = function(arr1, arr2) {
+ const prefixSet = new Set();
+ let result = 0;
+
+ for (const num of arr1) {
+ let prefix = num;
+ while (prefix > 0) {
+ prefixSet.add(prefix);
+ prefix = Math.floor(prefix / 10);
+ }
+ }
+
+ for (const num of arr2) {
+ let prefix = num;
+ while (prefix > 0) {
+ if (prefixSet.has(prefix)) {
+ result = Math.max(result, String(prefix).length);
+ }
+ prefix = Math.floor(prefix / 10);
+ }
+ }
+
+ return result;
+};
From 98717e60f120f4490a8806a2daa1885d6552cbb9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 6 Jun 2025 23:22:21 -0500
Subject: [PATCH 395/994] Add solution #3044
---
README.md | 1 +
solutions/3044-most-frequent-prime.js | 68 +++++++++++++++++++++++++++
2 files changed, 69 insertions(+)
create mode 100644 solutions/3044-most-frequent-prime.js
diff --git a/README.md b/README.md
index e638c748..b02dc685 100644
--- a/README.md
+++ b/README.md
@@ -2147,6 +2147,7 @@
3039|[Apply Operations to Make String Empty](./solutions/3039-apply-operations-to-make-string-empty.js)|Medium|
3042|[Count Prefix and Suffix Pairs I](./solutions/3042-count-prefix-and-suffix-pairs-i.js)|Easy|
3043|[Find the Length of the Longest Common Prefix](./solutions/3043-find-the-length-of-the-longest-common-prefix.js)|Medium|
+3044|[Most Frequent Prime](./solutions/3044-most-frequent-prime.js)|Medium|
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|
diff --git a/solutions/3044-most-frequent-prime.js b/solutions/3044-most-frequent-prime.js
new file mode 100644
index 00000000..cde4f2e9
--- /dev/null
+++ b/solutions/3044-most-frequent-prime.js
@@ -0,0 +1,68 @@
+/**
+ * 3044. Most Frequent Prime
+ * https://leetcode.com/problems/most-frequent-prime/
+ * Difficulty: Medium
+ *
+ * You are given a m x n 0-indexed 2D matrix mat. From every cell, you can create numbers
+ * in the following way:
+ * - There could be at most 8 paths from the cells namely: east, south-east, south, south-west,
+ * west, north-west, north, and north-east.
+ * - Select a path from them and append digits in this path to the number being formed by
+ * traveling in this direction.
+ * - Note that numbers are generated at every step, for example, if the digits along the path
+ * are 1, 9, 1, then there will be three numbers generated along the way: 1, 19, 191.
+ *
+ * Return the most frequent prime number greater than 10 out of all the numbers created by
+ * traversing the matrix or -1 if no such prime number exists. If there are multiple prime
+ * numbers with the highest frequency, then return the largest among them.
+ *
+ * Note: It is invalid to change the direction during the move.
+ */
+
+/**
+ * @param {number[][]} mat
+ * @return {number}
+ */
+var mostFrequentPrime = function(mat) {
+ const m = mat.length;
+ const n = mat[0].length;
+ const frequency = new Map();
+ const directions = [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]];
+
+ const isPrime = num => {
+ if (num <= 1) return false;
+ for (let i = 2; i * i <= num; i++) {
+ if (num % i === 0) return false;
+ }
+ return true;
+ };
+
+ for (let i = 0; i < m; i++) {
+ for (let j = 0; j < n; j++) {
+ for (const [dx, dy] of directions) {
+ let x = i;
+ let y = j;
+ let num = 0;
+ while (x >= 0 && x < m && y >= 0 && y < n) {
+ num = num * 10 + mat[x][y];
+ if (num > 10 && isPrime(num)) {
+ frequency.set(num, (frequency.get(num) || 0) + 1);
+ }
+ x += dx;
+ y += dy;
+ }
+ }
+ }
+ }
+
+ let maxFreq = 0;
+ let result = -1;
+ for (const [num, freq] of frequency) {
+ if (freq > maxFreq || (freq === maxFreq && num > result)) {
+ maxFreq = freq;
+ result = num;
+ }
+ }
+
+ return result;
+};
From 8a0613b6c20bca61b40d45f491ea59ce35583f5a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 7 Jun 2025 23:44:17 -0500
Subject: [PATCH 396/994] Add solution #3046
---
README.md | 1 +
solutions/3046-split-the-array.js | 28 ++++++++++++++++++++++++++++
2 files changed, 29 insertions(+)
create mode 100644 solutions/3046-split-the-array.js
diff --git a/README.md b/README.md
index b02dc685..2a09b6a0 100644
--- a/README.md
+++ b/README.md
@@ -2148,6 +2148,7 @@
3042|[Count Prefix and Suffix Pairs I](./solutions/3042-count-prefix-and-suffix-pairs-i.js)|Easy|
3043|[Find the Length of the Longest Common Prefix](./solutions/3043-find-the-length-of-the-longest-common-prefix.js)|Medium|
3044|[Most Frequent Prime](./solutions/3044-most-frequent-prime.js)|Medium|
+3046|[Split the Array](./solutions/3046-split-the-array.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|
diff --git a/solutions/3046-split-the-array.js b/solutions/3046-split-the-array.js
new file mode 100644
index 00000000..14f28868
--- /dev/null
+++ b/solutions/3046-split-the-array.js
@@ -0,0 +1,28 @@
+/**
+ * 3046. Split the Array
+ * https://leetcode.com/problems/split-the-array/
+ * Difficulty: Easy
+ *
+ * You are given an integer array nums of even length. You have to split the array into two
+ * parts nums1 and nums2 such that:
+ * - nums1.length == nums2.length == nums.length / 2.
+ * - nums1 should contain distinct elements.
+ * - nums2 should also contain distinct elements.
+ *
+ * Return true if it is possible to split the array, and false otherwise.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {boolean}
+ */
+var isPossibleToSplit = function(nums) {
+ const map = new Map();
+
+ for (const num of nums) {
+ map.set(num, (map.get(num) || 0) + 1);
+ if (map.get(num) > 2) return false;
+ }
+
+ return true;
+};
From 6c1c55a62911bf84186e231ae154ed6fd88cbb81 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 7 Jun 2025 23:45:25 -0500
Subject: [PATCH 397/994] Add solution #3047
---
README.md | 1 +
...st-area-of-square-inside-two-rectangles.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/3047-find-the-largest-area-of-square-inside-two-rectangles.js
diff --git a/README.md b/README.md
index 2a09b6a0..83285a3b 100644
--- a/README.md
+++ b/README.md
@@ -2149,6 +2149,7 @@
3043|[Find the Length of the Longest Common Prefix](./solutions/3043-find-the-length-of-the-longest-common-prefix.js)|Medium|
3044|[Most Frequent Prime](./solutions/3044-most-frequent-prime.js)|Medium|
3046|[Split the Array](./solutions/3046-split-the-array.js)|Easy|
+3047|[Find the Largest Area of Square Inside Two Rectangles](./solutions/3047-find-the-largest-area-of-square-inside-two-rectangles.js)|Medium|
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|
diff --git a/solutions/3047-find-the-largest-area-of-square-inside-two-rectangles.js b/solutions/3047-find-the-largest-area-of-square-inside-two-rectangles.js
new file mode 100644
index 00000000..7075570e
--- /dev/null
+++ b/solutions/3047-find-the-largest-area-of-square-inside-two-rectangles.js
@@ -0,0 +1,39 @@
+/**
+ * 3047. Find the Largest Area of Square Inside Two Rectangles
+ * https://leetcode.com/problems/find-the-largest-area-of-square-inside-two-rectangles/
+ * Difficulty: Medium
+ *
+ * There exist n rectangles in a 2D plane with edges parallel to the x and y axis. You
+ * are given two 2D integer arrays bottomLeft and topRight where bottomLeft[i] = [a_i, b_i]
+ * and topRight[i] = [c_i, d_i] represent the bottom-left and top-right coordinates of the
+ * ith rectangle, respectively.
+ *
+ * You need to find the maximum area of a square that can fit inside the intersecting
+ * region of at least two rectangles. Return 0 if such a square does not exist.
+ */
+
+/**
+ * @param {number[][]} bottomLeft
+ * @param {number[][]} topRight
+ * @return {number}
+ */
+var largestSquareArea = function(bottomLeft, topRight) {
+ const n = bottomLeft.length;
+ let maxSide = 0;
+
+ for (let i = 0; i < n; i++) {
+ for (let j = i + 1; j < n; j++) {
+ const xLeft = Math.max(bottomLeft[i][0], bottomLeft[j][0]);
+ const yBottom = Math.max(bottomLeft[i][1], bottomLeft[j][1]);
+ const xRight = Math.min(topRight[i][0], topRight[j][0]);
+ const yTop = Math.min(topRight[i][1], topRight[j][1]);
+
+ if (xLeft < xRight && yBottom < yTop) {
+ const side = Math.min(xRight - xLeft, yTop - yBottom);
+ maxSide = Math.max(maxSide, side);
+ }
+ }
+ }
+
+ return maxSide * maxSide;
+};
From dbf84e18974fb03cc1f3caa01dbdb6a615f5e5e9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 7 Jun 2025 23:46:21 -0500
Subject: [PATCH 398/994] Add solution #3065
---
README.md | 1 +
...-operations-to-exceed-threshold-value-i.js | 27 +++++++++++++++++++
2 files changed, 28 insertions(+)
create mode 100644 solutions/3065-minimum-operations-to-exceed-threshold-value-i.js
diff --git a/README.md b/README.md
index 83285a3b..c53843e5 100644
--- a/README.md
+++ b/README.md
@@ -2150,6 +2150,7 @@
3044|[Most Frequent Prime](./solutions/3044-most-frequent-prime.js)|Medium|
3046|[Split the Array](./solutions/3046-split-the-array.js)|Easy|
3047|[Find the Largest Area of Square Inside Two Rectangles](./solutions/3047-find-the-largest-area-of-square-inside-two-rectangles.js)|Medium|
+3065|[Minimum Operations to Exceed Threshold Value I](./solutions/3065-minimum-operations-to-exceed-threshold-value-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|
diff --git a/solutions/3065-minimum-operations-to-exceed-threshold-value-i.js b/solutions/3065-minimum-operations-to-exceed-threshold-value-i.js
new file mode 100644
index 00000000..53ae27ae
--- /dev/null
+++ b/solutions/3065-minimum-operations-to-exceed-threshold-value-i.js
@@ -0,0 +1,27 @@
+/**
+ * 3065. Minimum Operations to Exceed Threshold Value I
+ * https://leetcode.com/problems/minimum-operations-to-exceed-threshold-value-i/
+ * Difficulty: Easy
+ *
+ * You are given a 0-indexed integer array nums, and an integer k.
+ *
+ * In one operation, you can remove one occurrence of the smallest element of nums.
+ *
+ * Return the minimum number of operations needed so that all elements of the array are greater
+ * than or equal to k.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var minOperations = function(nums, k) {
+ let operations = 0;
+
+ for (const num of nums) {
+ if (num < k) operations++;
+ }
+
+ return operations;
+};
From e3b44e8cd63ecba74384add4189a944facea1134 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 7 Jun 2025 23:48:15 -0500
Subject: [PATCH 399/994] Add solution #3067
---
README.md | 1 +
...able-servers-in-a-weighted-tree-network.js | 64 +++++++++++++++++++
2 files changed, 65 insertions(+)
create mode 100644 solutions/3067-count-pairs-of-connectable-servers-in-a-weighted-tree-network.js
diff --git a/README.md b/README.md
index c53843e5..81a1bfc5 100644
--- a/README.md
+++ b/README.md
@@ -2152,6 +2152,7 @@
3047|[Find the Largest Area of Square Inside Two Rectangles](./solutions/3047-find-the-largest-area-of-square-inside-two-rectangles.js)|Medium|
3065|[Minimum Operations to Exceed Threshold Value I](./solutions/3065-minimum-operations-to-exceed-threshold-value-i.js)|Easy|
3066|[Minimum Operations to Exceed Threshold Value II](./solutions/3066-minimum-operations-to-exceed-threshold-value-ii.js)|Medium|
+3067|[Count Pairs of Connectable Servers in a Weighted Tree Network](./solutions/3067-count-pairs-of-connectable-servers-in-a-weighted-tree-network.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|
diff --git a/solutions/3067-count-pairs-of-connectable-servers-in-a-weighted-tree-network.js b/solutions/3067-count-pairs-of-connectable-servers-in-a-weighted-tree-network.js
new file mode 100644
index 00000000..cfcb71ff
--- /dev/null
+++ b/solutions/3067-count-pairs-of-connectable-servers-in-a-weighted-tree-network.js
@@ -0,0 +1,64 @@
+/**
+ * 3067. Count Pairs of Connectable Servers in a Weighted Tree Network
+ * https://leetcode.com/problems/count-pairs-of-connectable-servers-in-a-weighted-tree-network/
+ * Difficulty: Medium
+ *
+ * You are given an unrooted weighted tree with n vertices representing servers numbered from 0
+ * to n - 1, an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional edge
+ * between vertices ai and bi of weight weighti. You are also given an integer signalSpeed.
+ *
+ * Two servers a and b are connectable through a server c if:
+ * - a < b, a != c and b != c.
+ * - The distance from c to a is divisible by signalSpeed.
+ * - The distance from c to b is divisible by signalSpeed.
+ * - The path from c to b and the path from c to a do not share any edges.
+ *
+ * Return an integer array count of length n where count[i] is the number of server pairs that are
+ * connectable through the server i.
+ */
+
+/**
+ * @param {number[][]} edges
+ * @param {number} signalSpeed
+ * @return {number[]}
+ */
+var countPairsOfConnectableServers = function(edges, signalSpeed) {
+ const n = edges.length + 1;
+ const graph = Array.from({ length: n }, () => []);
+ for (const [u, v, w] of edges) {
+ graph[u].push([v, w]);
+ graph[v].push([u, w]);
+ }
+
+ const result = new Array(n).fill(0);
+ for (let i = 0; i < n; i++) {
+ result[i] = countValidPairs(i);
+ }
+ return result;
+
+ function countValidPairs(root) {
+ function dfs(node, parent, distance) {
+ let count = distance % signalSpeed === 0 ? 1 : 0;
+ for (const [next, weight] of graph[node]) {
+ if (next !== parent) {
+ count += dfs(next, node, distance + weight);
+ }
+ }
+ return count;
+ }
+
+ let totalPairs = 0;
+ const counts = [];
+ for (const [child, weight] of graph[root]) {
+ const count = dfs(child, root, weight);
+ counts.push(count);
+ }
+
+ let sum = 0;
+ for (const count of counts) {
+ totalPairs += sum * count;
+ sum += count;
+ }
+ return totalPairs;
+ }
+};
From 7cd6a7b5e3f4f7934f8f94e5414c1f5cbee917d0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 7 Jun 2025 23:49:27 -0500
Subject: [PATCH 400/994] Add solution #3069
---
README.md | 1 +
...9-distribute-elements-into-two-arrays-i.js | 37 +++++++++++++++++++
2 files changed, 38 insertions(+)
create mode 100644 solutions/3069-distribute-elements-into-two-arrays-i.js
diff --git a/README.md b/README.md
index 81a1bfc5..74290fb7 100644
--- a/README.md
+++ b/README.md
@@ -2154,6 +2154,7 @@
3066|[Minimum Operations to Exceed Threshold Value II](./solutions/3066-minimum-operations-to-exceed-threshold-value-ii.js)|Medium|
3067|[Count Pairs of Connectable Servers in a Weighted Tree Network](./solutions/3067-count-pairs-of-connectable-servers-in-a-weighted-tree-network.js)|Medium|
3068|[Find the Maximum Sum of Node Values](./solutions/3068-find-the-maximum-sum-of-node-values.js)|Hard|
+3069|[Distribute Elements Into Two Arrays I](./solutions/3069-distribute-elements-into-two-arrays-i.js)|Easy|
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/3069-distribute-elements-into-two-arrays-i.js b/solutions/3069-distribute-elements-into-two-arrays-i.js
new file mode 100644
index 00000000..ed2f0d96
--- /dev/null
+++ b/solutions/3069-distribute-elements-into-two-arrays-i.js
@@ -0,0 +1,37 @@
+/**
+ * 3069. Distribute Elements Into Two Arrays I
+ * https://leetcode.com/problems/distribute-elements-into-two-arrays-i/
+ * Difficulty: Easy
+ *
+ * You are given a 1-indexed array of distinct integers nums of length n.
+ *
+ * You need to distribute all the elements of nums between two arrays arr1 and arr2 using n
+ * operations. In the first operation, append nums[1] to arr1. In the second operation,
+ * append nums[2] to arr2. Afterwards, in the ith operation:
+ * - If the last element of arr1 is greater than the last element of arr2, append nums[i] to arr1.
+ * Otherwise, append nums[i] to arr2.
+ *
+ * The array result is formed by concatenating the arrays arr1 and arr2. For example, if
+ * arr1 == [1,2,3] and arr2 == [4,5,6], then result = [1,2,3,4,5,6].
+ *
+ * Return the array result.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var resultArray = function(nums) {
+ const arr1 = [nums[0]];
+ const arr2 = [nums[1]];
+
+ for (let i = 2; i < nums.length; i++) {
+ if (arr1[arr1.length - 1] > arr2[arr2.length - 1]) {
+ arr1.push(nums[i]);
+ } else {
+ arr2.push(nums[i]);
+ }
+ }
+
+ return [...arr1, ...arr2];
+};
From 955db95e1a93a55ca6cf10781cfde167d2e1e90a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 7 Jun 2025 23:51:39 -0500
Subject: [PATCH 401/994] Add solution #3070
---
README.md | 1 +
...th-top-left-element-and-sum-less-than-k.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/3070-count-submatrices-with-top-left-element-and-sum-less-than-k.js
diff --git a/README.md b/README.md
index 74290fb7..a0366757 100644
--- a/README.md
+++ b/README.md
@@ -2155,6 +2155,7 @@
3067|[Count Pairs of Connectable Servers in a Weighted Tree Network](./solutions/3067-count-pairs-of-connectable-servers-in-a-weighted-tree-network.js)|Medium|
3068|[Find the Maximum Sum of Node Values](./solutions/3068-find-the-maximum-sum-of-node-values.js)|Hard|
3069|[Distribute Elements Into Two Arrays I](./solutions/3069-distribute-elements-into-two-arrays-i.js)|Easy|
+3070|[Count Submatrices with Top-Left Element and Sum Less Than k](./solutions/3070-count-submatrices-with-top-left-element-and-sum-less-than-k.js)|Medium|
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/3070-count-submatrices-with-top-left-element-and-sum-less-than-k.js b/solutions/3070-count-submatrices-with-top-left-element-and-sum-less-than-k.js
new file mode 100644
index 00000000..93cd1cb1
--- /dev/null
+++ b/solutions/3070-count-submatrices-with-top-left-element-and-sum-less-than-k.js
@@ -0,0 +1,39 @@
+/**
+ * 3070. Count Submatrices with Top-Left Element and Sum Less Than k
+ * https://leetcode.com/problems/count-submatrices-with-top-left-element-and-sum-less-than-k/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer matrix grid and an integer k.
+ *
+ * Return the number of submatrices that contain the top-left element of the grid, and have a sum
+ * less than or equal to k.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @param {number} k
+ * @return {number}
+ */
+var countSubmatrices = function(grid, k) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const prefixSum = 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++) {
+ prefixSum[i][j] = grid[i-1][j-1] + prefixSum[i-1][j]
+ + prefixSum[i][j-1] - prefixSum[i-1][j-1];
+ }
+ }
+
+ let result = 0;
+ for (let i = 1; i <= rows; i++) {
+ for (let j = 1; j <= cols; j++) {
+ if (prefixSum[i][j] <= k) {
+ result++;
+ }
+ }
+ }
+
+ return result;
+};
From e4ebac16fe2b7353556bf4a7af5a0757ca7a5b9f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 7 Jun 2025 23:53:20 -0500
Subject: [PATCH 402/994] Add solution #3071
---
README.md | 1 +
...rations-to-write-the-letter-y-on-a-grid.js | 63 +++++++++++++++++++
2 files changed, 64 insertions(+)
create mode 100644 solutions/3071-minimum-operations-to-write-the-letter-y-on-a-grid.js
diff --git a/README.md b/README.md
index a0366757..b2b929bf 100644
--- a/README.md
+++ b/README.md
@@ -2156,6 +2156,7 @@
3068|[Find the Maximum Sum of Node Values](./solutions/3068-find-the-maximum-sum-of-node-values.js)|Hard|
3069|[Distribute Elements Into Two Arrays I](./solutions/3069-distribute-elements-into-two-arrays-i.js)|Easy|
3070|[Count Submatrices with Top-Left Element and Sum Less Than k](./solutions/3070-count-submatrices-with-top-left-element-and-sum-less-than-k.js)|Medium|
+3071|[Minimum Operations to Write the Letter Y on a Grid](./solutions/3071-minimum-operations-to-write-the-letter-y-on-a-grid.js)|Medium|
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/3071-minimum-operations-to-write-the-letter-y-on-a-grid.js b/solutions/3071-minimum-operations-to-write-the-letter-y-on-a-grid.js
new file mode 100644
index 00000000..15ad3700
--- /dev/null
+++ b/solutions/3071-minimum-operations-to-write-the-letter-y-on-a-grid.js
@@ -0,0 +1,63 @@
+/**
+ * 3071. Minimum Operations to Write the Letter Y on a Grid
+ * https://leetcode.com/problems/minimum-operations-to-write-the-letter-y-on-a-grid/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed n x n grid where n is odd, and grid[r][c] is 0, 1, or 2.
+ *
+ * We say that a cell belongs to the Letter Y if it belongs to one of the following:
+ * - The diagonal starting at the top-left cell and ending at the center cell of the grid.
+ * - The diagonal starting at the top-right cell and ending at the center cell of the grid.
+ * - The vertical line starting at the center cell and ending at the bottom border of the grid.
+ *
+ * The Letter Y is written on the grid if and only if:
+ * - All values at cells belonging to the Y are equal.
+ * - All values at cells not belonging to the Y are equal.
+ * - The values at cells belonging to the Y are different from the values at cells not belonging
+ * to the Y.
+ *
+ * Return the minimum number of operations needed to write the letter Y on the grid given that
+ * in one operation you can change the value at any cell to 0, 1, or 2.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var minimumOperationsToWriteY = function(grid) {
+ const n = grid.length;
+ const center = Math.floor(n / 2);
+ const yCells = [];
+ const nonYCells = [];
+
+ for (let i = 0; i < n; i++) {
+ for (let j = 0; j < n; j++) {
+ if ((i === j && i <= center) || (i === n - 1 - j && i <= center)
+ || (j === center && i >= center)) {
+ yCells.push(grid[i][j]);
+ } else {
+ nonYCells.push(grid[i][j]);
+ }
+ }
+ }
+
+ const yCounts = [0, 0, 0];
+ const nonYCounts = [0, 0, 0];
+
+ for (const val of yCells) yCounts[val]++;
+ for (const val of nonYCells) nonYCounts[val]++;
+
+ let minOperations = Infinity;
+
+ for (let yVal = 0; yVal <= 2; yVal++) {
+ for (let nonYVal = 0; nonYVal <= 2; nonYVal++) {
+ if (yVal !== nonYVal) {
+ const yOps = yCells.length - yCounts[yVal];
+ const nonYOps = nonYCells.length - nonYCounts[nonYVal];
+ minOperations = Math.min(minOperations, yOps + nonYOps);
+ }
+ }
+ }
+
+ return minOperations;
+};
From 62d047bdf2175c01901df2862841cdd4657a3f6f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 7 Jun 2025 23:54:20 -0500
Subject: [PATCH 403/994] Add solution #3074
---
README.md | 1 +
.../3074-apple-redistribution-into-boxes.js | 38 +++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/3074-apple-redistribution-into-boxes.js
diff --git a/README.md b/README.md
index b2b929bf..0293af67 100644
--- a/README.md
+++ b/README.md
@@ -2157,6 +2157,7 @@
3069|[Distribute Elements Into Two Arrays I](./solutions/3069-distribute-elements-into-two-arrays-i.js)|Easy|
3070|[Count Submatrices with Top-Left Element and Sum Less Than k](./solutions/3070-count-submatrices-with-top-left-element-and-sum-less-than-k.js)|Medium|
3071|[Minimum Operations to Write the Letter Y on a Grid](./solutions/3071-minimum-operations-to-write-the-letter-y-on-a-grid.js)|Medium|
+3074|[Apple Redistribution into Boxes](./solutions/3074-apple-redistribution-into-boxes.js)|Easy|
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/3074-apple-redistribution-into-boxes.js b/solutions/3074-apple-redistribution-into-boxes.js
new file mode 100644
index 00000000..27e3f17a
--- /dev/null
+++ b/solutions/3074-apple-redistribution-into-boxes.js
@@ -0,0 +1,38 @@
+/**
+ * 3074. Apple Redistribution into Boxes
+ * https://leetcode.com/problems/apple-redistribution-into-boxes/
+ * Difficulty: Easy
+ *
+ * You are given an array apple of size n and an array capacity of size m.
+ *
+ * There are n packs where the ith pack contains apple[i] apples. There are m boxes as well,
+ * and the ith box has a capacity of capacity[i] apples.
+ *
+ * Return the minimum number of boxes you need to select to redistribute these n packs of
+ * apples into boxes.
+ *
+ * Note that, apples from the same pack can be distributed into different boxes.
+ */
+
+/**
+ * @param {number[]} apple
+ * @param {number[]} capacity
+ * @return {number}
+ */
+var minimumBoxes = function(apple, capacity) {
+ const totalApples = apple.reduce((sum, num) => sum + num, 0);
+ const sortedCapacities = capacity.sort((a, b) => b - a);
+ let currentCapacity = 0;
+ let result = 0;
+
+ for (const box of sortedCapacities) {
+ if (currentCapacity < totalApples) {
+ currentCapacity += box;
+ result++;
+ } else {
+ break;
+ }
+ }
+
+ return result;
+};
From 2811dde9b6a5d99904920f01b6f89c41d32dc0cc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 7 Jun 2025 23:55:31 -0500
Subject: [PATCH 404/994] Add solution #3075
---
README.md | 1 +
...maximize-happiness-of-selected-children.js | 35 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/3075-maximize-happiness-of-selected-children.js
diff --git a/README.md b/README.md
index 0293af67..e9152641 100644
--- a/README.md
+++ b/README.md
@@ -2158,6 +2158,7 @@
3070|[Count Submatrices with Top-Left Element and Sum Less Than k](./solutions/3070-count-submatrices-with-top-left-element-and-sum-less-than-k.js)|Medium|
3071|[Minimum Operations to Write the Letter Y on a Grid](./solutions/3071-minimum-operations-to-write-the-letter-y-on-a-grid.js)|Medium|
3074|[Apple Redistribution into Boxes](./solutions/3074-apple-redistribution-into-boxes.js)|Easy|
+3075|[Maximize Happiness of Selected Children](./solutions/3075-maximize-happiness-of-selected-children.js)|Medium|
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/3075-maximize-happiness-of-selected-children.js b/solutions/3075-maximize-happiness-of-selected-children.js
new file mode 100644
index 00000000..853a0851
--- /dev/null
+++ b/solutions/3075-maximize-happiness-of-selected-children.js
@@ -0,0 +1,35 @@
+/**
+ * 3075. Maximize Happiness of Selected Children
+ * https://leetcode.com/problems/maximize-happiness-of-selected-children/
+ * Difficulty: Medium
+ *
+ * You are given an array happiness of length n, and a positive integer k.
+ *
+ * There are n children standing in a queue, where the ith child has happiness value
+ * happiness[i]. You want to select k children from these n children in k turns.
+ *
+ * In each turn, when you select a child, the happiness value of all the children that
+ * have not been selected till now decreases by 1. Note that the happiness value cannot
+ * become negative and gets decremented only if it is positive.
+ *
+ * Return the maximum sum of the happiness values of the selected children you can
+ * achieve by selecting k children.
+ */
+
+/**
+ * @param {number[]} happiness
+ * @param {number} k
+ * @return {number}
+ */
+var maximumHappinessSum = function(happiness, k) {
+ const sortedHappiness = happiness.sort((a, b) => b - a);
+ let result = 0;
+
+ for (let i = 0; i < k; i++) {
+ const currentHappiness = sortedHappiness[i] - i;
+ if (currentHappiness <= 0) break;
+ result += currentHappiness;
+ }
+
+ return result;
+};
From a74449370b48a41cf1baa758b994a5127aa25833 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 7 Jun 2025 23:57:02 -0500
Subject: [PATCH 405/994] Add solution #3076
---
README.md | 1 +
...shortest-uncommon-substring-in-an-array.js | 56 +++++++++++++++++++
2 files changed, 57 insertions(+)
create mode 100644 solutions/3076-shortest-uncommon-substring-in-an-array.js
diff --git a/README.md b/README.md
index e9152641..72e021ec 100644
--- a/README.md
+++ b/README.md
@@ -2159,6 +2159,7 @@
3071|[Minimum Operations to Write the Letter Y on a Grid](./solutions/3071-minimum-operations-to-write-the-letter-y-on-a-grid.js)|Medium|
3074|[Apple Redistribution into Boxes](./solutions/3074-apple-redistribution-into-boxes.js)|Easy|
3075|[Maximize Happiness of Selected Children](./solutions/3075-maximize-happiness-of-selected-children.js)|Medium|
+3076|[Shortest Uncommon Substring in an Array](./solutions/3076-shortest-uncommon-substring-in-an-array.js)|Medium|
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/3076-shortest-uncommon-substring-in-an-array.js b/solutions/3076-shortest-uncommon-substring-in-an-array.js
new file mode 100644
index 00000000..60559014
--- /dev/null
+++ b/solutions/3076-shortest-uncommon-substring-in-an-array.js
@@ -0,0 +1,56 @@
+/**
+ * 3076. Shortest Uncommon Substring in an Array
+ * https://leetcode.com/problems/shortest-uncommon-substring-in-an-array/
+ * Difficulty: Medium
+ *
+ * You are given an array arr of size n consisting of non-empty strings.
+ *
+ * Find a string array answer of size n such that:
+ * - answer[i] is the shortest substring of arr[i] that does not occur as a substring in any
+ * other string in arr. If multiple such substrings exist, answer[i] should be the
+ * lexicographically smallest. And if no such substring exists, answer[i] should be an
+ * empty string.
+ *
+ * Return the array answer.
+ */
+
+/**
+ * @param {string[]} arr
+ * @return {string[]}
+ */
+var shortestSubstrings = function(arr) {
+ const n = arr.length;
+ const result = new Array(n).fill('');
+
+ for (let i = 0; i < n; i++) {
+ const str = arr[i];
+ let minLen = Infinity;
+ let minSubstr = '';
+
+ for (let len = 1; len <= str.length; len++) {
+ for (let start = 0; start <= str.length - len; start++) {
+ const substr = str.slice(start, start + len);
+ if (isUnique(substr, i)) {
+ if (len < minLen || (len === minLen && substr < minSubstr)) {
+ minLen = len;
+ minSubstr = substr;
+ }
+ }
+ }
+ if (minSubstr) break;
+ }
+
+ result[i] = minSubstr;
+ }
+
+ return result;
+
+ function isUnique(substr, strIdx) {
+ for (let i = 0; i < n; i++) {
+ if (i !== strIdx && arr[i].includes(substr)) {
+ return false;
+ }
+ }
+ return true;
+ }
+};
From 4e64eea1e676bc856ff125a9438cd20c280bee16 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 00:30:29 -0500
Subject: [PATCH 406/994] Add solution #3079
---
README.md | 1 +
...3079-find-the-sum-of-encrypted-integers.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/3079-find-the-sum-of-encrypted-integers.js
diff --git a/README.md b/README.md
index 72e021ec..47af3b8a 100644
--- a/README.md
+++ b/README.md
@@ -2160,6 +2160,7 @@
3074|[Apple Redistribution into Boxes](./solutions/3074-apple-redistribution-into-boxes.js)|Easy|
3075|[Maximize Happiness of Selected Children](./solutions/3075-maximize-happiness-of-selected-children.js)|Medium|
3076|[Shortest Uncommon Substring in an Array](./solutions/3076-shortest-uncommon-substring-in-an-array.js)|Medium|
+3079|[Find the Sum of Encrypted Integers](./solutions/3079-find-the-sum-of-encrypted-integers.js)|Easy|
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/3079-find-the-sum-of-encrypted-integers.js b/solutions/3079-find-the-sum-of-encrypted-integers.js
new file mode 100644
index 00000000..8bdaf881
--- /dev/null
+++ b/solutions/3079-find-the-sum-of-encrypted-integers.js
@@ -0,0 +1,41 @@
+/**
+ * 3079. Find the Sum of Encrypted Integers
+ * https://leetcode.com/problems/find-the-sum-of-encrypted-integers/
+ * Difficulty: Easy
+ *
+ * You are given an integer array nums containing positive integers. We define a function
+ * encrypt such that encrypt(x) replaces every digit in x with the largest digit in x.
+ * For example, encrypt(523) = 555 and encrypt(213) = 333.
+ *
+ * Return the sum of encrypted elements.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var sumOfEncryptedInt = function(nums) {
+ let result = 0;
+
+ for (const num of nums) {
+ let maxDigit = 0;
+ let temp = num;
+ let digitCount = 0;
+
+ while (temp > 0) {
+ maxDigit = Math.max(maxDigit, temp % 10);
+ temp = Math.floor(temp / 10);
+ digitCount++;
+ }
+
+ let encrypted = 0;
+ while (digitCount > 0) {
+ encrypted = encrypted * 10 + maxDigit;
+ digitCount--;
+ }
+
+ result += encrypted;
+ }
+
+ return result;
+};
From 268db1b632067c7c0fc10eba55f54a77f3596ce1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 00:31:22 -0500
Subject: [PATCH 407/994] Add solution #3083
---
README.md | 1 +
...a-substring-in-a-string-and-its-reverse.js | 26 +++++++++++++++++++
2 files changed, 27 insertions(+)
create mode 100644 solutions/3083-existence-of-a-substring-in-a-string-and-its-reverse.js
diff --git a/README.md b/README.md
index 47af3b8a..7b7dcf53 100644
--- a/README.md
+++ b/README.md
@@ -2161,6 +2161,7 @@
3075|[Maximize Happiness of Selected Children](./solutions/3075-maximize-happiness-of-selected-children.js)|Medium|
3076|[Shortest Uncommon Substring in an Array](./solutions/3076-shortest-uncommon-substring-in-an-array.js)|Medium|
3079|[Find the Sum of Encrypted Integers](./solutions/3079-find-the-sum-of-encrypted-integers.js)|Easy|
+3083|[Existence of a Substring in a String and Its Reverse](./solutions/3083-existence-of-a-substring-in-a-string-and-its-reverse.js)|Easy|
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/3083-existence-of-a-substring-in-a-string-and-its-reverse.js b/solutions/3083-existence-of-a-substring-in-a-string-and-its-reverse.js
new file mode 100644
index 00000000..8af3eb50
--- /dev/null
+++ b/solutions/3083-existence-of-a-substring-in-a-string-and-its-reverse.js
@@ -0,0 +1,26 @@
+/**
+ * 3083. Existence of a Substring in a String and Its Reverse
+ * https://leetcode.com/problems/existence-of-a-substring-in-a-string-and-its-reverse/
+ * Difficulty: Easy
+ *
+ * Given a string s, find any substring of length 2 which is also present in the reverse of s.
+ *
+ * Return true if such a substring exists, and false otherwise.
+ */
+
+/**
+ * @param {string} s
+ * @return {boolean}
+ */
+var isSubstringPresent = function(s) {
+ const reversed = s.split('').reverse().join('');
+
+ for (let i = 0; i < s.length - 1; i++) {
+ const substr = s.slice(i, i + 2);
+ if (reversed.includes(substr)) {
+ return true;
+ }
+ }
+
+ return false;
+};
From ccddc4126af9e72410514a763dcece27f52a3182 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 00:32:39 -0500
Subject: [PATCH 408/994] Add solution #3084
---
README.md | 1 +
...tarting-and-ending-with-given-character.js | 21 +++++++++++++++++++
2 files changed, 22 insertions(+)
create mode 100644 solutions/3084-count-substrings-starting-and-ending-with-given-character.js
diff --git a/README.md b/README.md
index 7b7dcf53..32715922 100644
--- a/README.md
+++ b/README.md
@@ -2162,6 +2162,7 @@
3076|[Shortest Uncommon Substring in an Array](./solutions/3076-shortest-uncommon-substring-in-an-array.js)|Medium|
3079|[Find the Sum of Encrypted Integers](./solutions/3079-find-the-sum-of-encrypted-integers.js)|Easy|
3083|[Existence of a Substring in a String and Its Reverse](./solutions/3083-existence-of-a-substring-in-a-string-and-its-reverse.js)|Easy|
+3084|[Count Substrings Starting and Ending with Given Character](./solutions/3084-count-substrings-starting-and-ending-with-given-character.js)|Medium|
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/3084-count-substrings-starting-and-ending-with-given-character.js b/solutions/3084-count-substrings-starting-and-ending-with-given-character.js
new file mode 100644
index 00000000..be6b8bc2
--- /dev/null
+++ b/solutions/3084-count-substrings-starting-and-ending-with-given-character.js
@@ -0,0 +1,21 @@
+/**
+ * 3084. Count Substrings Starting and Ending with Given Character
+ * https://leetcode.com/problems/count-substrings-starting-and-ending-with-given-character/
+ * Difficulty: Medium
+ *
+ * You are given a string s and a character c. Return the total number of substrings of s
+ * that start and end with c.
+ */
+
+/**
+ * @param {string} s
+ * @param {character} c
+ * @return {number}
+ */
+var countSubstrings = function(s, c) {
+ let count = 0;
+ for (const char of s) {
+ if (char === c) count++;
+ }
+ return (count * (count + 1)) / 2;
+};
From c51cab88dfbe49798cc17b85133ef941a6454ca3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 00:35:26 -0500
Subject: [PATCH 409/994] Add solution #3085
---
README.md | 1 +
...imum-deletions-to-make-string-k-special.js | 45 +++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/3085-minimum-deletions-to-make-string-k-special.js
diff --git a/README.md b/README.md
index 32715922..5815b93a 100644
--- a/README.md
+++ b/README.md
@@ -2163,6 +2163,7 @@
3079|[Find the Sum of Encrypted Integers](./solutions/3079-find-the-sum-of-encrypted-integers.js)|Easy|
3083|[Existence of a Substring in a String and Its Reverse](./solutions/3083-existence-of-a-substring-in-a-string-and-its-reverse.js)|Easy|
3084|[Count Substrings Starting and Ending with Given Character](./solutions/3084-count-substrings-starting-and-ending-with-given-character.js)|Medium|
+3085|[Minimum Deletions to Make String K-Special](./solutions/3085-minimum-deletions-to-make-string-k-special.js)|Medium|
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/3085-minimum-deletions-to-make-string-k-special.js b/solutions/3085-minimum-deletions-to-make-string-k-special.js
new file mode 100644
index 00000000..98db902e
--- /dev/null
+++ b/solutions/3085-minimum-deletions-to-make-string-k-special.js
@@ -0,0 +1,45 @@
+/**
+ * 3085. Minimum Deletions to Make String K-Special
+ * https://leetcode.com/problems/minimum-deletions-to-make-string-k-special/
+ * Difficulty: Medium
+ *
+ * You are given a string word and an integer k.
+ *
+ * We consider word to be k-special if |freq(word[i]) - freq(word[j])| <= k for all indices i
+ * and j in the string.
+ *
+ * Here, freq(x) denotes the frequency of the character x in word, and |y| denotes the absolute
+ * value of y.
+ *
+ * Return the minimum number of characters you need to delete to make word k-special.
+ */
+
+/**
+ * @param {string} word
+ * @param {number} k
+ * @return {number}
+ */
+var minimumDeletions = function(word, k) {
+ const freq = new Array(26).fill(0);
+
+ for (const char of word) {
+ freq[char.charCodeAt(0) - 97]++;
+ }
+
+ const counts = freq.filter(x => x > 0).sort((a, b) => a - b);
+ let minDeletions = Infinity;
+ for (let i = 0; i < counts.length; i++) {
+ let deletions = 0;
+ for (let j = 0; j < i; j++) {
+ deletions += counts[j];
+ }
+ for (let j = i; j < counts.length; j++) {
+ if (counts[j] - counts[i] > k) {
+ deletions += counts[j] - (counts[i] + k);
+ }
+ }
+ minDeletions = Math.min(minDeletions, deletions);
+ }
+
+ return minDeletions;
+};
From 26f419f85867486a8ff90b6930fd70876fd03e92 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 00:37:09 -0500
Subject: [PATCH 410/994] Add solution #3090
---
README.md | 1 +
...m-length-substring-with-two-occurrences.js | 31 +++++++++++++++++++
2 files changed, 32 insertions(+)
create mode 100644 solutions/3090-maximum-length-substring-with-two-occurrences.js
diff --git a/README.md b/README.md
index 5815b93a..79079f1f 100644
--- a/README.md
+++ b/README.md
@@ -2164,6 +2164,7 @@
3083|[Existence of a Substring in a String and Its Reverse](./solutions/3083-existence-of-a-substring-in-a-string-and-its-reverse.js)|Easy|
3084|[Count Substrings Starting and Ending with Given Character](./solutions/3084-count-substrings-starting-and-ending-with-given-character.js)|Medium|
3085|[Minimum Deletions to Make String K-Special](./solutions/3085-minimum-deletions-to-make-string-k-special.js)|Medium|
+3090|[Maximum Length Substring With Two Occurrences](./solutions/3090-maximum-length-substring-with-two-occurrences.js)|Easy|
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/3090-maximum-length-substring-with-two-occurrences.js b/solutions/3090-maximum-length-substring-with-two-occurrences.js
new file mode 100644
index 00000000..84003cd8
--- /dev/null
+++ b/solutions/3090-maximum-length-substring-with-two-occurrences.js
@@ -0,0 +1,31 @@
+/**
+ * 3090. Maximum Length Substring With Two Occurrences
+ * https://leetcode.com/problems/maximum-length-substring-with-two-occurrences/
+ * Difficulty: Easy
+ *
+ * Given a string s, return the maximum length of a substring such that it contains at most
+ * two occurrences of each character.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var maximumLengthSubstring = function(s) {
+ let result = 0;
+ const map = new Map();
+
+ for (let left = 0, right = 0; right < s.length; right++) {
+ map.set(s[right], (map.get(s[right]) || 0) + 1);
+
+ while (map.get(s[right]) > 2) {
+ map.set(s[left], map.get(s[left]) - 1);
+ if (map.get(s[left]) === 0) map.delete(s[left]);
+ left++;
+ }
+
+ result = Math.max(result, right - left + 1);
+ }
+
+ return result;
+};
From 4263c309164aa4d4475c47673a3cbb114d35f76d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 00:41:57 -0500
Subject: [PATCH 411/994] Add solution #3091
---
README.md | 1 +
...sum-of-array-greater-than-or-equal-to-k.js | 33 +++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/3091-apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k.js
diff --git a/README.md b/README.md
index 79079f1f..0c888523 100644
--- a/README.md
+++ b/README.md
@@ -2165,6 +2165,7 @@
3084|[Count Substrings Starting and Ending with Given Character](./solutions/3084-count-substrings-starting-and-ending-with-given-character.js)|Medium|
3085|[Minimum Deletions to Make String K-Special](./solutions/3085-minimum-deletions-to-make-string-k-special.js)|Medium|
3090|[Maximum Length Substring With Two Occurrences](./solutions/3090-maximum-length-substring-with-two-occurrences.js)|Easy|
+3091|[Apply Operations to Make Sum of Array Greater Than or Equal to k](./solutions/3091-apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k.js)|Medium|
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/3091-apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k.js b/solutions/3091-apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k.js
new file mode 100644
index 00000000..a1c50bd6
--- /dev/null
+++ b/solutions/3091-apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k.js
@@ -0,0 +1,33 @@
+/**
+ * 3091. Apply Operations to Make Sum of Array Greater Than or Equal to k
+ * https://leetcode.com/problems/apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k/
+ * Difficulty: Medium
+ *
+ * You are given a positive integer k. Initially, you have an array nums = [1].
+ *
+ * You can perform any of the following operations on the array any number of times (possibly zero):
+ * - Choose any element in the array and increase its value by 1.
+ * - Duplicate any element in the array and add it to the end of the array.
+ *
+ * Return the minimum number of operations required to make the sum of elements of the final array
+ * greater than or equal to k.
+ */
+
+/**
+ * @param {number} k
+ * @return {number}
+ */
+var minOperations = function(k) {
+ if (k === 1) return 0;
+
+ let result = Infinity;
+ for (let increments = 0; increments <= Math.ceil(Math.sqrt(k)); increments++) {
+ const value = 1 + increments;
+ const duplicates = Math.ceil(k / value) - 1;
+ if (duplicates >= 0) {
+ result = Math.min(result, increments + duplicates);
+ }
+ }
+
+ return result;
+};
From 62a53f151a46ac48955994739c19e07469a375ab Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 00:42:47 -0500
Subject: [PATCH 412/994] Add solution #3095
---
README.md | 1 +
...-shortest-subarray-with-or-at-least-k-i.js | 35 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/3095-shortest-subarray-with-or-at-least-k-i.js
diff --git a/README.md b/README.md
index 0c888523..8b62326e 100644
--- a/README.md
+++ b/README.md
@@ -2166,6 +2166,7 @@
3085|[Minimum Deletions to Make String K-Special](./solutions/3085-minimum-deletions-to-make-string-k-special.js)|Medium|
3090|[Maximum Length Substring With Two Occurrences](./solutions/3090-maximum-length-substring-with-two-occurrences.js)|Easy|
3091|[Apply Operations to Make Sum of Array Greater Than or Equal to k](./solutions/3091-apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k.js)|Medium|
+3095|[Shortest Subarray With OR at Least K I](./solutions/3095-shortest-subarray-with-or-at-least-k-i.js)|Easy|
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/3095-shortest-subarray-with-or-at-least-k-i.js b/solutions/3095-shortest-subarray-with-or-at-least-k-i.js
new file mode 100644
index 00000000..0f03aa97
--- /dev/null
+++ b/solutions/3095-shortest-subarray-with-or-at-least-k-i.js
@@ -0,0 +1,35 @@
+/**
+ * 3095. Shortest Subarray With OR at Least K I
+ * https://leetcode.com/problems/shortest-subarray-with-or-at-least-k-i/
+ * Difficulty: Easy
+ *
+ * You are given an array nums of non-negative integers and an integer k.
+ *
+ * An array is called special if the bitwise OR of all of its elements is at least k.
+ *
+ * Return the length of the shortest special non-empty subarray of nums, or return -1 if
+ * no special subarray exists.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var minimumSubarrayLength = function(nums, k) {
+ if (k === 0) return 1;
+
+ let minLength = Infinity;
+ for (let start = 0; start < nums.length; start++) {
+ let orResult = 0;
+ for (let end = start; end < nums.length; end++) {
+ orResult |= nums[end];
+ if (orResult >= k) {
+ minLength = Math.min(minLength, end - start + 1);
+ break;
+ }
+ }
+ }
+
+ return minLength === Infinity ? -1 : minLength;
+};
From f094b28dfaa56fbe52714cb1c81cdcf4e4a64a64 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 00:44:06 -0500
Subject: [PATCH 413/994] Add solution #3097
---
README.md | 1 +
...shortest-subarray-with-or-at-least-k-ii.js | 48 +++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/3097-shortest-subarray-with-or-at-least-k-ii.js
diff --git a/README.md b/README.md
index 8b62326e..9c303f81 100644
--- a/README.md
+++ b/README.md
@@ -2167,6 +2167,7 @@
3090|[Maximum Length Substring With Two Occurrences](./solutions/3090-maximum-length-substring-with-two-occurrences.js)|Easy|
3091|[Apply Operations to Make Sum of Array Greater Than or Equal to k](./solutions/3091-apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k.js)|Medium|
3095|[Shortest Subarray With OR at Least K I](./solutions/3095-shortest-subarray-with-or-at-least-k-i.js)|Easy|
+3097|[Shortest Subarray With OR at Least K II](./solutions/3097-shortest-subarray-with-or-at-least-k-ii.js)|Medium|
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/3097-shortest-subarray-with-or-at-least-k-ii.js b/solutions/3097-shortest-subarray-with-or-at-least-k-ii.js
new file mode 100644
index 00000000..f85c9879
--- /dev/null
+++ b/solutions/3097-shortest-subarray-with-or-at-least-k-ii.js
@@ -0,0 +1,48 @@
+/**
+ * 3097. Shortest Subarray With OR at Least K II
+ * https://leetcode.com/problems/shortest-subarray-with-or-at-least-k-ii/
+ * Difficulty: Medium
+ *
+ * You are given an array nums of non-negative integers and an integer k.
+ *
+ * An array is called special if the bitwise OR of all of its elements is at least k.
+ *
+ * Return the length of the shortest special non-empty subarray of nums, or return -1 if no
+ * special subarray exists.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var minimumSubarrayLength = function(nums, k) {
+ if (k === 0) return 1;
+
+ const bitCounts = new Array(32).fill(0);
+ let minLength = Infinity;
+ let orValue = 0;
+ let left = 0;
+
+ for (let right = 0; right < nums.length; right++) {
+ const num = nums[right];
+ for (let bit = 0; bit < 32; bit++) {
+ if (num & (1 << bit)) bitCounts[bit]++;
+ if (bitCounts[bit] > 0) orValue |= 1 << bit;
+ }
+
+ while (orValue >= k && left <= right) {
+ minLength = Math.min(minLength, right - left + 1);
+ const leftNum = nums[left];
+ for (let bit = 0; bit < 32; bit++) {
+ if (leftNum & (1 << bit)) {
+ bitCounts[bit]--;
+ if (bitCounts[bit] === 0) orValue &= ~(1 << bit);
+ }
+ }
+ left++;
+ }
+ }
+
+ return minLength === Infinity ? -1 : minLength;
+};
From bd03519917a620e1006ef514c64a9f9f61260f7e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 00:44:53 -0500
Subject: [PATCH 414/994] Add solution #3099
---
README.md | 1 +
solutions/3099-harshad-number.js | 22 ++++++++++++++++++++++
2 files changed, 23 insertions(+)
create mode 100644 solutions/3099-harshad-number.js
diff --git a/README.md b/README.md
index 9c303f81..d1dcd732 100644
--- a/README.md
+++ b/README.md
@@ -2168,6 +2168,7 @@
3091|[Apply Operations to Make Sum of Array Greater Than or Equal to k](./solutions/3091-apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k.js)|Medium|
3095|[Shortest Subarray With OR at Least K I](./solutions/3095-shortest-subarray-with-or-at-least-k-i.js)|Easy|
3097|[Shortest Subarray With OR at Least K II](./solutions/3097-shortest-subarray-with-or-at-least-k-ii.js)|Medium|
+3099|[Harshad Number](./solutions/3099-harshad-number.js)|Easy|
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/3099-harshad-number.js b/solutions/3099-harshad-number.js
new file mode 100644
index 00000000..f096f4c8
--- /dev/null
+++ b/solutions/3099-harshad-number.js
@@ -0,0 +1,22 @@
+/**
+ * 3099. Harshad Number
+ * https://leetcode.com/problems/harshad-number/
+ * Difficulty: Easy
+ *
+ * An integer divisible by the sum of its digits is said to be a Harshad number. You are given
+ * an integer x. Return the sum of the digits of x if x is a Harshad number, otherwise, return -1.
+ */
+
+/**
+ * @param {number} x
+ * @return {number}
+ */
+var sumOfTheDigitsOfHarshadNumber = function(x) {
+ let digitSum = 0;
+ let num = x;
+ while (num > 0) {
+ digitSum += num % 10;
+ num = Math.floor(num / 10);
+ }
+ return x % digitSum === 0 ? digitSum : -1;
+};
From ac4268814dbf772f44d89b0105eae043e2af2f3a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 00:46:39 -0500
Subject: [PATCH 415/994] Add solution #3100
---
README.md | 1 +
solutions/3100-water-bottles-ii.js | 43 ++++++++++++++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/3100-water-bottles-ii.js
diff --git a/README.md b/README.md
index d1dcd732..0fa62b03 100644
--- a/README.md
+++ b/README.md
@@ -2169,6 +2169,7 @@
3095|[Shortest Subarray With OR at Least K I](./solutions/3095-shortest-subarray-with-or-at-least-k-i.js)|Easy|
3097|[Shortest Subarray With OR at Least K II](./solutions/3097-shortest-subarray-with-or-at-least-k-ii.js)|Medium|
3099|[Harshad Number](./solutions/3099-harshad-number.js)|Easy|
+3100|[Water Bottles II](./solutions/3100-water-bottles-ii.js)|Medium|
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/3100-water-bottles-ii.js b/solutions/3100-water-bottles-ii.js
new file mode 100644
index 00000000..a251d5d6
--- /dev/null
+++ b/solutions/3100-water-bottles-ii.js
@@ -0,0 +1,43 @@
+/**
+ * 3100. Water Bottles II
+ * https://leetcode.com/problems/water-bottles-ii/
+ * Difficulty: Medium
+ *
+ * You are given two integers numBottles and numExchange.
+ *
+ * numBottles represents the number of full water bottles that you initially have. In one
+ * operation, you can perform one of the following operations:
+ * - Drink any number of full water bottles turning them into empty bottles.
+ * - Exchange numExchange empty bottles with one full water bottle. Then, increase
+ * numExchange by one.
+ *
+ * Note that you cannot exchange multiple batches of empty bottles for the same value of
+ * numExchange. For example, if numBottles == 3 and numExchange == 1, you cannot exchange
+ * 3 empty water bottles for 3 full bottles.
+ *
+ * Return the maximum number of water bottles you can drink.
+ */
+
+/**
+ * @param {number} numBottles
+ * @param {number} numExchange
+ * @return {number}
+ */
+var maxBottlesDrunk = function(numBottles, numExchange) {
+ let result = 0;
+ let full = numBottles;
+ let empty = 0;
+
+ while (full > 0) {
+ result += full;
+ empty += full;
+ full = 0;
+ if (empty >= numExchange) {
+ full = 1;
+ empty -= numExchange;
+ numExchange++;
+ }
+ }
+
+ return result;
+};
From a0f002d29b1a26803d1b451f53e11ed24bedf9a6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 18:32:01 -0500
Subject: [PATCH 416/994] Add solution #156
---
README.md | 1 +
solutions/0156-binary-tree-upside-down.js | 39 +++++++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/0156-binary-tree-upside-down.js
diff --git a/README.md b/README.md
index 0fa62b03..b58ed613 100644
--- a/README.md
+++ b/README.md
@@ -161,6 +161,7 @@
153|[Find Minimum in Rotated Sorted Array](./solutions/0153-find-minimum-in-rotated-sorted-array.js)|Medium|
154|[Find Minimum in Rotated Sorted Array II](./solutions/0154-find-minimum-in-rotated-sorted-array-ii.js)|Hard|
155|[Min Stack](./solutions/0155-min-stack.js)|Medium|
+156|[Binary Tree Upside Down](./solutions/0156-binary-tree-upside-down.js)|Medium|
160|[Intersection of Two Linked Lists](./solutions/0160-intersection-of-two-linked-lists.js)|Medium|
162|[Find Peak Element](./solutions/0162-find-peak-element.js)|Medium|
164|[Maximum Gap](./solutions/0164-maximum-gap.js)|Medium|
diff --git a/solutions/0156-binary-tree-upside-down.js b/solutions/0156-binary-tree-upside-down.js
new file mode 100644
index 00000000..77bfd8ce
--- /dev/null
+++ b/solutions/0156-binary-tree-upside-down.js
@@ -0,0 +1,39 @@
+/**
+ * 156. Binary Tree Upside Down
+ * https://leetcode.com/problems/binary-tree-upside-down/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree, turn the tree upside down and return the new root.
+ *
+ * You can turn a binary tree upside down with the following steps:
+ * - The original left child becomes the new root.
+ * - The original root becomes the new right child.
+ * - The original right child becomes the new left child.
+ *
+ * The mentioned steps are done level by level. It is guaranteed that every right node has
+ * a sibling (a left node with the same parent) and 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} root
+ * @return {TreeNode}
+ */
+var upsideDownBinaryTree = function(root) {
+ if (!root || !root.left) return root;
+
+ const newRoot = upsideDownBinaryTree(root.left);
+ root.left.left = root.right;
+ root.left.right = root;
+ root.left = null;
+ root.right = null;
+
+ return newRoot;
+};
From 271a933af5d3479dc65c3c5887a875d073460006 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 18:33:47 -0500
Subject: [PATCH 417/994] Add solution #157
---
README.md | 1 +
.../0157-read-n-characters-given-read4.js | 48 +++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/0157-read-n-characters-given-read4.js
diff --git a/README.md b/README.md
index b58ed613..1fad1130 100644
--- a/README.md
+++ b/README.md
@@ -162,6 +162,7 @@
154|[Find Minimum in Rotated Sorted Array II](./solutions/0154-find-minimum-in-rotated-sorted-array-ii.js)|Hard|
155|[Min Stack](./solutions/0155-min-stack.js)|Medium|
156|[Binary Tree Upside Down](./solutions/0156-binary-tree-upside-down.js)|Medium|
+157|[Read N Characters Given Read4](./solutions/0157-read-n-characters-given-read4.js)|Easy|
160|[Intersection of Two Linked Lists](./solutions/0160-intersection-of-two-linked-lists.js)|Medium|
162|[Find Peak Element](./solutions/0162-find-peak-element.js)|Medium|
164|[Maximum Gap](./solutions/0164-maximum-gap.js)|Medium|
diff --git a/solutions/0157-read-n-characters-given-read4.js b/solutions/0157-read-n-characters-given-read4.js
new file mode 100644
index 00000000..0074fec8
--- /dev/null
+++ b/solutions/0157-read-n-characters-given-read4.js
@@ -0,0 +1,48 @@
+/**
+ * 157. Read N Characters Given Read4
+ * https://leetcode.com/problems/read-n-characters-given-read4/
+ * Difficulty: Easy
+ *
+ * Given a file and assume that you can only read the file using a given method read4, implement
+ * a method to read n characters.
+ *
+ * Method read4:
+ * - The API read4 reads four consecutive characters from file, then writes those characters into
+ * the buffer array buf4.
+ *
+ * The return value is the number of actual characters read.
+ *
+ * Note that read4() has its own file pointer, much like FILE *fp in C.
+ */
+
+/**
+ * @param {function} read4()
+ * @return {function}
+ */
+var solution = function(read4) {
+ let cache = [];
+ let cacheIndex = 0;
+ let cacheSize = 0;
+
+ /**
+ * @param {character[]} buf Destination buffer
+ * @param {number} n Number of characters to read
+ * @return {number} The number of actual characters read
+ */
+ return function(buf, n) {
+ let charsRead = 0;
+
+ while (charsRead < n) {
+ if (cacheIndex >= cacheSize) {
+ cache = new Array(4);
+ cacheSize = read4(cache);
+ cacheIndex = 0;
+ if (cacheSize === 0) break;
+ }
+
+ buf[charsRead++] = cache[cacheIndex++];
+ }
+
+ return charsRead;
+ };
+};
From d46baa0a9aa3e2d3896f1c9d74ffefe9e1511442 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 18:43:10 -0500
Subject: [PATCH 418/994] Add solution #158
---
README.md | 1 +
...ters-given-read4-ii-call-multiple-times.js | 48 +++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/0158-read-n-characters-given-read4-ii-call-multiple-times.js
diff --git a/README.md b/README.md
index 1fad1130..521ee4bd 100644
--- a/README.md
+++ b/README.md
@@ -163,6 +163,7 @@
155|[Min Stack](./solutions/0155-min-stack.js)|Medium|
156|[Binary Tree Upside Down](./solutions/0156-binary-tree-upside-down.js)|Medium|
157|[Read N Characters Given Read4](./solutions/0157-read-n-characters-given-read4.js)|Easy|
+158|[Read N Characters Given read4 II - Call Multiple Times](./solutions/0158-read-n-characters-given-read4-ii-call-multiple-times.js)|Hard|
160|[Intersection of Two Linked Lists](./solutions/0160-intersection-of-two-linked-lists.js)|Medium|
162|[Find Peak Element](./solutions/0162-find-peak-element.js)|Medium|
164|[Maximum Gap](./solutions/0164-maximum-gap.js)|Medium|
diff --git a/solutions/0158-read-n-characters-given-read4-ii-call-multiple-times.js b/solutions/0158-read-n-characters-given-read4-ii-call-multiple-times.js
new file mode 100644
index 00000000..9fdd7b54
--- /dev/null
+++ b/solutions/0158-read-n-characters-given-read4-ii-call-multiple-times.js
@@ -0,0 +1,48 @@
+/**
+ * 158. Read N Characters Given read4 II - Call Multiple Times
+ * https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/
+ * Difficulty: Hard
+ *
+ * Given a file and assume that you can only read the file using a given method read4, implement
+ * a method read to read n characters. Your method read may be called multiple times.
+ *
+ * Method read4:
+ * - The API read4 reads four consecutive characters from file, then writes those characters into
+ * the buffer array buf4.
+ *
+ * The return value is the number of actual characters read.
+ *
+ * Note that read4() has its own file pointer, much like FILE *fp in C.
+ */
+
+/**
+ * @param {function} read4()
+ * @return {function}
+ */
+var solution = function(read4) {
+ let cache = [];
+ let cacheIndex = 0;
+ let cacheSize = 0;
+
+ /**
+ * @param {character[]} buf Destination buffer
+ * @param {number} n Number of characters to read
+ * @return {number} The number of actual characters read
+ */
+ return function(buf, n) {
+ let charsRead = 0;
+
+ while (charsRead < n) {
+ if (cacheIndex >= cacheSize) {
+ cache = new Array(4);
+ cacheSize = read4(cache);
+ cacheIndex = 0;
+ if (cacheSize === 0) break;
+ }
+
+ buf[charsRead++] = cache[cacheIndex++];
+ }
+
+ return charsRead;
+ };
+};
From 58deb62546b78c4ca383bb6051b7c7de8865de07 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 18:44:08 -0500
Subject: [PATCH 419/994] Add solution #159
---
README.md | 1 +
...ng-with-at-most-two-distinct-characters.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/0159-longest-substring-with-at-most-two-distinct-characters.js
diff --git a/README.md b/README.md
index 521ee4bd..37806dff 100644
--- a/README.md
+++ b/README.md
@@ -164,6 +164,7 @@
156|[Binary Tree Upside Down](./solutions/0156-binary-tree-upside-down.js)|Medium|
157|[Read N Characters Given Read4](./solutions/0157-read-n-characters-given-read4.js)|Easy|
158|[Read N Characters Given read4 II - Call Multiple Times](./solutions/0158-read-n-characters-given-read4-ii-call-multiple-times.js)|Hard|
+159|[Longest Substring with At Most Two Distinct Characters](./solutions/0159-longest-substring-with-at-most-two-distinct-characters.js)|Medium|
160|[Intersection of Two Linked Lists](./solutions/0160-intersection-of-two-linked-lists.js)|Medium|
162|[Find Peak Element](./solutions/0162-find-peak-element.js)|Medium|
164|[Maximum Gap](./solutions/0164-maximum-gap.js)|Medium|
diff --git a/solutions/0159-longest-substring-with-at-most-two-distinct-characters.js b/solutions/0159-longest-substring-with-at-most-two-distinct-characters.js
new file mode 100644
index 00000000..8e023114
--- /dev/null
+++ b/solutions/0159-longest-substring-with-at-most-two-distinct-characters.js
@@ -0,0 +1,34 @@
+/**
+ * 159. Longest Substring with At Most Two Distinct Characters
+ * https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/
+ * Difficulty: Medium
+ *
+ * Given a string s, return the length of the longest substring that contains at most two
+ * distinct characters.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var lengthOfLongestSubstringTwoDistinct = function(s) {
+ const map = new Map();
+ let maxLength = 0;
+ let start = 0;
+
+ for (let end = 0; end < s.length; end++) {
+ map.set(s[end], (map.get(s[end]) || 0) + 1);
+
+ while (map.size > 2) {
+ map.set(s[start], map.get(s[start]) - 1);
+ if (map.get(s[start]) === 0) {
+ map.delete(s[start]);
+ }
+ start++;
+ }
+
+ maxLength = Math.max(maxLength, end - start + 1);
+ }
+
+ return maxLength;
+};
From dfd2d68c8537cd5e66be0825b61eb7ece99eb057 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 18:49:29 -0500
Subject: [PATCH 420/994] Add solution #161
---
README.md | 1 +
solutions/0161-one-edit-distance.js | 36 +++++++++++++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/0161-one-edit-distance.js
diff --git a/README.md b/README.md
index 37806dff..be959ba1 100644
--- a/README.md
+++ b/README.md
@@ -166,6 +166,7 @@
158|[Read N Characters Given read4 II - Call Multiple Times](./solutions/0158-read-n-characters-given-read4-ii-call-multiple-times.js)|Hard|
159|[Longest Substring with At Most Two Distinct Characters](./solutions/0159-longest-substring-with-at-most-two-distinct-characters.js)|Medium|
160|[Intersection of Two Linked Lists](./solutions/0160-intersection-of-two-linked-lists.js)|Medium|
+161|[One Edit Distance](./solutions/0161-one-edit-distance.js)|Medium|
162|[Find Peak Element](./solutions/0162-find-peak-element.js)|Medium|
164|[Maximum Gap](./solutions/0164-maximum-gap.js)|Medium|
165|[Compare Version Numbers](./solutions/0165-compare-version-numbers.js)|Medium|
diff --git a/solutions/0161-one-edit-distance.js b/solutions/0161-one-edit-distance.js
new file mode 100644
index 00000000..cb69f9ec
--- /dev/null
+++ b/solutions/0161-one-edit-distance.js
@@ -0,0 +1,36 @@
+/**
+ * 161. One Edit Distance
+ * https://leetcode.com/problems/one-edit-distance/
+ * Difficulty: Medium
+ *
+ * Given two strings s and t, return true if they are both one edit distance apart, otherwise
+ * return false.
+ *
+ * A string s is said to be one distance apart from a string t if you can:
+ * - Insert exactly one character into s to get t.
+ * - Delete exactly one character from s to get t.
+ * - Replace exactly one character of s with a different character to get t.
+ */
+
+/**
+ * @param {string} s
+ * @param {string} t
+ * @return {boolean}
+ */
+var isOneEditDistance = function(s, t) {
+ if (s === t) return false;
+ const sLength = s.length;
+ const tLength = t.length;
+ if (Math.abs(sLength - tLength) > 1) return false;
+
+ if (sLength > tLength) return isOneEditDistance(t, s);
+
+ let i = 0;
+ while (i < sLength && s[i] === t[i]) i++;
+
+ if (sLength === tLength) {
+ return i < sLength && s.slice(i + 1) === t.slice(i + 1);
+ }
+
+ return s.slice(i) === t.slice(i + 1);
+};
From c58201ea69b03b0527234f9677aff158651b54fe Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 18:51:15 -0500
Subject: [PATCH 421/994] Add solution #163
---
README.md | 1 +
solutions/0163-missing-ranges.js | 35 ++++++++++++++++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/0163-missing-ranges.js
diff --git a/README.md b/README.md
index be959ba1..f9f4c4ea 100644
--- a/README.md
+++ b/README.md
@@ -168,6 +168,7 @@
160|[Intersection of Two Linked Lists](./solutions/0160-intersection-of-two-linked-lists.js)|Medium|
161|[One Edit Distance](./solutions/0161-one-edit-distance.js)|Medium|
162|[Find Peak Element](./solutions/0162-find-peak-element.js)|Medium|
+163|[Missing Ranges](./solutions/0163-missing-ranges.js)|Easy|
164|[Maximum Gap](./solutions/0164-maximum-gap.js)|Medium|
165|[Compare Version Numbers](./solutions/0165-compare-version-numbers.js)|Medium|
166|[Fraction to Recurring Decimal](./solutions/0166-fraction-to-recurring-decimal.js)|Medium|
diff --git a/solutions/0163-missing-ranges.js b/solutions/0163-missing-ranges.js
new file mode 100644
index 00000000..717b6edb
--- /dev/null
+++ b/solutions/0163-missing-ranges.js
@@ -0,0 +1,35 @@
+/**
+ * 163. Missing Ranges
+ * https://leetcode.com/problems/missing-ranges/
+ * Difficulty: Easy
+ *
+ * You are given an inclusive range [lower, upper] and a sorted unique integer array nums,
+ * where all elements are within the inclusive range.
+ *
+ * A number x is considered missing if x is in the range [lower, upper] and x is not in nums.
+ *
+ * Return the shortest sorted list of ranges that exactly covers all the missing numbers.
+ * That is, no element of nums is included in any of the ranges, and each missing number
+ * is covered by one of the ranges.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} lower
+ * @param {number} upper
+ * @return {number[][]}
+ */
+var findMissingRanges = function(nums, lower, upper) {
+ const result = [];
+ let prev = lower - 1;
+
+ for (let i = 0; i <= nums.length; i++) {
+ const curr = i < nums.length ? nums[i] : upper + 1;
+ if (curr - prev > 1) {
+ result.push([prev + 1, curr - 1]);
+ }
+ prev = curr;
+ }
+
+ return result;
+};
From 80e2eb6dd3f929098f26c1572b5fe8d944a4a473 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 18:53:41 -0500
Subject: [PATCH 422/994] Add solution #170
---
README.md | 1 +
.../0170-two-sum-iii-data-structure-design.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/0170-two-sum-iii-data-structure-design.js
diff --git a/README.md b/README.md
index f9f4c4ea..076d25c9 100644
--- a/README.md
+++ b/README.md
@@ -175,6 +175,7 @@
167|[Two Sum II - Input Array Is Sorted](./solutions/0167-two-sum-ii-input-array-is-sorted.js)|Easy|
168|[Excel Sheet Column Title](./solutions/0168-excel-sheet-column-title.js)|Easy|
169|[Majority Element](./solutions/0169-majority-element.js)|Easy|
+170|[Two Sum III - Data structure design](./solutions/0170-two-sum-iii-data-structure-design.js)|Easy|
171|[Excel Sheet Column Number](./solutions/0171-excel-sheet-column-number.js)|Easy|
172|[Factorial Trailing Zeroes](./solutions/0172-factorial-trailing-zeroes.js)|Medium|
173|[Binary Search Tree Iterator](./solutions/0173-binary-search-tree-iterator.js)|Medium|
diff --git a/solutions/0170-two-sum-iii-data-structure-design.js b/solutions/0170-two-sum-iii-data-structure-design.js
new file mode 100644
index 00000000..f0cd8777
--- /dev/null
+++ b/solutions/0170-two-sum-iii-data-structure-design.js
@@ -0,0 +1,42 @@
+/**
+ * 170. Two Sum III - Data structure design
+ * https://leetcode.com/problems/two-sum-iii-data-structure-design/
+ * Difficulty: Easy
+ *
+ * Design a data structure that accepts a stream of integers and checks if it has a pair of
+ * integers that sum up to a particular value.
+ *
+ * Implement the TwoSum class:
+ * - TwoSum() Initializes the TwoSum object, with an empty array initially.
+ * - void add(int number) Adds number to the data structure.
+ * - boolean find(int value) Returns true if there exists any pair of numbers whose sum is equal
+ * to value, otherwise, it returns false.
+ */
+
+var TwoSum = function() {
+ this.numCount = new Map();
+};
+
+/**
+ * @param {number} number
+ * @return {void}
+ */
+TwoSum.prototype.add = function(number) {
+ this.numCount.set(number, (this.numCount.get(number) || 0) + 1);
+};
+
+/**
+ * @param {number} value
+ * @return {boolean}
+ */
+TwoSum.prototype.find = function(value) {
+ for (const num of this.numCount.keys()) {
+ const complement = value - num;
+ if (complement === num) {
+ if (this.numCount.get(num) > 1) return true;
+ } else if (this.numCount.has(complement)) {
+ return true;
+ }
+ }
+ return false;
+};
From 1295bfa53221ed57c921531896ca1a5b55e30cf3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 18:54:37 -0500
Subject: [PATCH 423/994] Add solution #186
---
README.md | 1 +
.../0186-reverse-words-in-a-string-ii.js | 40 +++++++++++++++++++
2 files changed, 41 insertions(+)
create mode 100644 solutions/0186-reverse-words-in-a-string-ii.js
diff --git a/README.md b/README.md
index 076d25c9..a178ce3e 100644
--- a/README.md
+++ b/README.md
@@ -181,6 +181,7 @@
173|[Binary Search Tree Iterator](./solutions/0173-binary-search-tree-iterator.js)|Medium|
174|[Dungeon Game](./solutions/0174-dungeon-game.js)|Hard|
179|[Largest Number](./solutions/0179-largest-number.js)|Medium|
+186|[Reverse Words in a String II](./solutions/0186-reverse-words-in-a-string-ii.js)|Medium|
187|[Repeated DNA Sequences](./solutions/0187-repeated-dna-sequences.js)|Medium|
188|[Best Time to Buy and Sell Stock IV](./solutions/0188-best-time-to-buy-and-sell-stock-iv.js)|Hard|
189|[Rotate Array](./solutions/0189-rotate-array.js)|Medium|
diff --git a/solutions/0186-reverse-words-in-a-string-ii.js b/solutions/0186-reverse-words-in-a-string-ii.js
new file mode 100644
index 00000000..ebc713fa
--- /dev/null
+++ b/solutions/0186-reverse-words-in-a-string-ii.js
@@ -0,0 +1,40 @@
+/**
+ * 186. Reverse Words in a String II
+ * https://leetcode.com/problems/reverse-words-in-a-string-ii/
+ * Difficulty: Medium
+ *
+ * Given a character array s, reverse the order of the words.
+ *
+ * A word is defined as a sequence of non-space characters. The words in s will be separated
+ * by a single space.
+ *
+ * Your code must solve the problem in-place, i.e. without allocating extra space.
+ */
+
+/**
+ * @param {character[]} s
+ * @return {void} Do not return anything, modify s in-place instead.
+ */
+var reverseWords = function(s) {
+ let left = 0;
+ let right = s.length - 1;
+
+ while (left < right) {
+ [s[left], s[right]] = [s[right], s[left]];
+ left++;
+ right--;
+ }
+
+ left = 0;
+ for (let i = 0; i <= s.length; i++) {
+ if (i === s.length || s[i] === ' ') {
+ right = i - 1;
+ while (left < right) {
+ [s[left], s[right]] = [s[right], s[left]];
+ left++;
+ right--;
+ }
+ left = i + 1;
+ }
+ }
+};
From 1989e556c4c5e8a5aa30dac82e703106b5345359 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 18:55:32 -0500
Subject: [PATCH 424/994] Add solution #243
---
README.md | 1 +
solutions/0243-shortest-word-distance.js | 36 ++++++++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/0243-shortest-word-distance.js
diff --git a/README.md b/README.md
index a178ce3e..74934875 100644
--- a/README.md
+++ b/README.md
@@ -232,6 +232,7 @@
240|[Search a 2D Matrix II](./solutions/0240-search-a-2d-matrix-ii.js)|Medium|
241|[Different Ways to Add Parentheses](./solutions/0241-different-ways-to-add-parentheses.js)|Medium|
242|[Valid Anagram](./solutions/0242-valid-anagram.js)|Easy|
+243|[Shortest Word Distance](./solutions/0243-shortest-word-distance.js)|Easy|
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
diff --git a/solutions/0243-shortest-word-distance.js b/solutions/0243-shortest-word-distance.js
new file mode 100644
index 00000000..d05ac820
--- /dev/null
+++ b/solutions/0243-shortest-word-distance.js
@@ -0,0 +1,36 @@
+/**
+ * 243. Shortest Word Distance
+ * https://leetcode.com/problems/shortest-word-distance/
+ * Difficulty: Easy
+ *
+ * Given an array of strings wordsDict and two different strings that already exist in the array
+ * word1 and word2, return the shortest distance between these two words in the list.
+ */
+
+/**
+ * @param {string[]} wordsDict
+ * @param {string} word1
+ * @param {string} word2
+ * @return {number}
+ */
+var shortestDistance = function(wordsDict, word1, word2) {
+ let result = Infinity;
+ let index1 = -1;
+ let index2 = -1;
+
+ for (let i = 0; i < wordsDict.length; i++) {
+ if (wordsDict[i] === word1) {
+ index1 = i;
+ if (index2 !== -1) {
+ result = Math.min(result, index1 - index2);
+ }
+ } else if (wordsDict[i] === word2) {
+ index2 = i;
+ if (index1 !== -1) {
+ result = Math.min(result, index2 - index1);
+ }
+ }
+ }
+
+ return result;
+};
From ea7c0cde4e285e76ec9e1f38dcde9df5ba1aa701 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 18:56:54 -0500
Subject: [PATCH 425/994] Add solution #244
---
README.md | 1 +
solutions/0244-shortest-word-distance-ii.js | 50 +++++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/0244-shortest-word-distance-ii.js
diff --git a/README.md b/README.md
index 74934875..717769ed 100644
--- a/README.md
+++ b/README.md
@@ -233,6 +233,7 @@
241|[Different Ways to Add Parentheses](./solutions/0241-different-ways-to-add-parentheses.js)|Medium|
242|[Valid Anagram](./solutions/0242-valid-anagram.js)|Easy|
243|[Shortest Word Distance](./solutions/0243-shortest-word-distance.js)|Easy|
+244|[Shortest Word Distance II](./solutions/0244-shortest-word-distance-ii.js)|Medium|
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
diff --git a/solutions/0244-shortest-word-distance-ii.js b/solutions/0244-shortest-word-distance-ii.js
new file mode 100644
index 00000000..3d66d604
--- /dev/null
+++ b/solutions/0244-shortest-word-distance-ii.js
@@ -0,0 +1,50 @@
+/**
+ * 244. Shortest Word Distance II
+ * https://leetcode.com/problems/shortest-word-distance-ii/
+ * Difficulty: Medium
+ *
+ * Design a data structure that will be initialized with a string array, and then it should
+ * answer queries of the shortest distance between two different strings from the array.
+ *
+ * Implement the WordDistance class:
+ * - WordDistance(String[] wordsDict) initializes the object with the strings array wordsDict.
+ * - int shortest(String word1, String word2) returns the shortest distance between word1 and
+ * word2 in the array wordsDict.
+ */
+
+/**
+ * @param {string[]} wordsDict
+ */
+var WordDistance = function(wordsDict) {
+ this.wordIndices = new Map();
+ for (let i = 0; i < wordsDict.length; i++) {
+ if (!this.wordIndices.has(wordsDict[i])) {
+ this.wordIndices.set(wordsDict[i], []);
+ }
+ this.wordIndices.get(wordsDict[i]).push(i);
+ }
+};
+
+/**
+ * @param {string} word1
+ * @param {string} word2
+ * @return {number}
+ */
+WordDistance.prototype.shortest = function(word1, word2) {
+ const indices1 = this.wordIndices.get(word1);
+ const indices2 = this.wordIndices.get(word2);
+ let minDistance = Infinity;
+ let i = 0;
+ let j = 0;
+
+ while (i < indices1.length && j < indices2.length) {
+ minDistance = Math.min(minDistance, Math.abs(indices1[i] - indices2[j]));
+ if (indices1[i] < indices2[j]) {
+ i++;
+ } else {
+ j++;
+ }
+ }
+
+ return minDistance;
+};
From 51091d3b92e9beba6325a1388767f9831717509b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 20:29:15 -0500
Subject: [PATCH 426/994] Add solution #2636
---
README.md | 1 +
solutions/2636-promise-pool.js | 32 ++++++++++++++++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/2636-promise-pool.js
diff --git a/README.md b/README.md
index 717769ed..c55a5172 100644
--- a/README.md
+++ b/README.md
@@ -1976,6 +1976,7 @@
2631|[Group By](./solutions/2631-group-by.js)|Medium|
2634|[Filter Elements from Array](./solutions/2634-filter-elements-from-array.js)|Easy|
2635|[Apply Transform Over Each Element in Array](./solutions/2635-apply-transform-over-each-element-in-array.js)|Easy|
+2636|[Promise Pool](./solutions/2636-promise-pool.js)|Medium|
2637|[Promise Time Limit](./solutions/2637-promise-time-limit.js)|Medium|
2639|[Find the Width of Columns of a Grid](./solutions/2639-find-the-width-of-columns-of-a-grid.js)|Easy|
2640|[Find the Score of All Prefixes of an Array](./solutions/2640-find-the-score-of-all-prefixes-of-an-array.js)|Medium|
diff --git a/solutions/2636-promise-pool.js b/solutions/2636-promise-pool.js
new file mode 100644
index 00000000..c2bde850
--- /dev/null
+++ b/solutions/2636-promise-pool.js
@@ -0,0 +1,32 @@
+/**
+ * 2636. Promise Pool
+ * https://leetcode.com/problems/promise-pool/
+ * Difficulty: Medium
+ *
+ * Given an array of asynchronous functions functions and a pool limit n, return an asynchronous
+ * function promisePool. It should return a promise that resolves when all the input functions
+ * resolve.
+ *
+ * Pool limit is defined as the maximum number promises that can be pending at once. promisePool
+ * should begin execution of as many functions as possible and continue executing new functions
+ * when old promises resolve. promisePool should execute functions[i] then functions[i + 1] then
+ * functions[i + 2], etc. When the last promise resolves, promisePool should also resolve.
+ *
+ * For example, if n = 1, promisePool will execute one function at a time in series. However,
+ * if n = 2, it first executes two functions. When either of the two functions resolve, a 3rd
+ * function should be executed (if available), and so on until there are no functions left to
+ * execute.
+ *
+ * You can assume all functions never reject. It is acceptable for promisePool to return a promise
+ * that resolves any value.
+ */
+
+/**
+ * @param {Function[]} functions
+ * @param {number} n
+ * @return {Promise}
+ */
+var promisePool = async function(functions, n) {
+ const next = () => functions[n++]?.().then(next);
+ return Promise.all(functions.slice(0, n).map(f => f().then(next)));
+};
From b1d45cf0c9a6390a73dfce34d1ea025947061217 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 20:31:03 -0500
Subject: [PATCH 427/994] Add solution #2676
---
README.md | 1 +
solutions/2676-throttle.js | 55 ++++++++++++++++++++++++++++++++++++++
2 files changed, 56 insertions(+)
create mode 100644 solutions/2676-throttle.js
diff --git a/README.md b/README.md
index c55a5172..bd988ca4 100644
--- a/README.md
+++ b/README.md
@@ -2000,6 +2000,7 @@
2670|[Find the Distinct Difference Array](./solutions/2670-find-the-distinct-difference-array.js)|Easy|
2672|[Number of Adjacent Elements With the Same Color](./solutions/2672-number-of-adjacent-elements-with-the-same-color.js)|Medium|
2673|[Make Costs of Paths Equal in a Binary Tree](./solutions/2673-make-costs-of-paths-equal-in-a-binary-tree.js)|Medium|
+2676|[Throttle](./solutions/2676-throttle.js)|Medium|
2677|[Chunk Array](./solutions/2677-chunk-array.js)|Easy|
2678|[Number of Senior Citizens](./solutions/2678-number-of-senior-citizens.js)|Easy|
2680|[Maximum OR](./solutions/2680-maximum-or.js)|Medium|
diff --git a/solutions/2676-throttle.js b/solutions/2676-throttle.js
new file mode 100644
index 00000000..a17f27b2
--- /dev/null
+++ b/solutions/2676-throttle.js
@@ -0,0 +1,55 @@
+/**
+ * 2676. Throttle
+ * https://leetcode.com/problems/throttle/
+ * Difficulty: Medium
+ *
+ * Given a function fn and a time in milliseconds t, return a throttled version of that
+ * function.
+ *
+ * A throttled function is first called without delay and then, for a time interval of
+ * t milliseconds, can't be executed but should store the latest function arguments provided
+ * to call fn with them after the end of the delay.
+ *
+ * For instance, t = 50ms, and the function was called at 30ms, 40ms, and 60ms.
+ *
+ * At 30ms, without delay, the throttled function fn should be called with the arguments,
+ * and calling the throttled function fn should be blocked for the following t milliseconds.
+ *
+ * At 40ms, the function should just save arguments.
+ *
+ * At 60ms, arguments should overwrite currently stored arguments from the second call because
+ * the second and third calls are made before 80ms. Once the delay has passed, the throttled
+ * function fn should be called with the latest arguments provided during the delay period,
+ * and it should also create another delay period of 80ms + t.
+ */
+
+/**
+ * @param {Function} fn
+ * @param {number} t
+ * @return {Function}
+ */
+var throttle = function(fn, t) {
+ let isThrottled = false;
+ let nextArgs = null;
+
+ function invoke() {
+ if (nextArgs) {
+ fn(...nextArgs);
+ nextArgs = null;
+ setTimeout(invoke, t);
+ } else {
+ isThrottled = false;
+ }
+ }
+
+ return function(...args) {
+ if (isThrottled) {
+ nextArgs = args;
+ return;
+ }
+
+ fn(...args);
+ isThrottled = true;
+ setTimeout(invoke, t);
+ };
+};
From e486edb97e0872a2e45376b92204e01aab03a487 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 20:32:21 -0500
Subject: [PATCH 428/994] Add solution #2632
---
README.md | 1 +
solutions/2632-curry.js | 28 ++++++++++++++++++++++++++++
2 files changed, 29 insertions(+)
create mode 100644 solutions/2632-curry.js
diff --git a/README.md b/README.md
index bd988ca4..d606e3e9 100644
--- a/README.md
+++ b/README.md
@@ -1974,6 +1974,7 @@
2629|[Function Composition](./solutions/2629-function-composition.js)|Easy|
2630|[Memoize II](./solutions/2630-memoize-ii.js)|Hard|
2631|[Group By](./solutions/2631-group-by.js)|Medium|
+2632|[Curry](./solutions/2632-curry.js)|Medium|
2634|[Filter Elements from Array](./solutions/2634-filter-elements-from-array.js)|Easy|
2635|[Apply Transform Over Each Element in Array](./solutions/2635-apply-transform-over-each-element-in-array.js)|Easy|
2636|[Promise Pool](./solutions/2636-promise-pool.js)|Medium|
diff --git a/solutions/2632-curry.js b/solutions/2632-curry.js
new file mode 100644
index 00000000..23b54c9f
--- /dev/null
+++ b/solutions/2632-curry.js
@@ -0,0 +1,28 @@
+/**
+ * 2632. Curry
+ * https://leetcode.com/problems/curry/
+ * Difficulty: Medium
+ *
+ * Given a function fn, return a curried version of that function.
+ *
+ * A curried function is a function that accepts fewer or an equal number of parameters as the
+ * original function and returns either another curried function or the same value the original
+ * function would have returned.
+ *
+ * In practical terms, if you called the original function like sum(1,2,3), you would call the
+ * curried version like csum(1)(2)(3), csum(1)(2,3), csum(1,2)(3), or csum(1,2,3). All these
+ * methods of calling the curried function should return the same value as the original.
+ */
+
+/**
+ * @param {Function} fn
+ * @return {Function}
+ */
+var curry = function(fn) {
+ return function curried(...args) {
+ if (args.length >= fn.length) {
+ return fn(...args);
+ }
+ return (...nextArgs) => curried(...args, ...nextArgs);
+ };
+};
From 6f25e2430fb752b4ce251422b9ab163a7616a119 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 20:34:14 -0500
Subject: [PATCH 429/994] Add solution #2628
---
README.md | 1 +
solutions/2628-json-deep-equal.js | 43 +++++++++++++++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/2628-json-deep-equal.js
diff --git a/README.md b/README.md
index d606e3e9..1b6a992f 100644
--- a/README.md
+++ b/README.md
@@ -1971,6 +1971,7 @@
2625|[Flatten Deeply Nested Array](./solutions/2625-flatten-deeply-nested-array.js)|Medium|
2626|[Array Reduce Transformation](./solutions/2626-array-reduce-transformation.js)|Easy|
2627|[Debounce](./solutions/2627-debounce.js)|Medium|
+2628|[JSON Deep Equal](./solutions/2628-json-deep-equal.js)|Medium|
2629|[Function Composition](./solutions/2629-function-composition.js)|Easy|
2630|[Memoize II](./solutions/2630-memoize-ii.js)|Hard|
2631|[Group By](./solutions/2631-group-by.js)|Medium|
diff --git a/solutions/2628-json-deep-equal.js b/solutions/2628-json-deep-equal.js
new file mode 100644
index 00000000..2f0cf372
--- /dev/null
+++ b/solutions/2628-json-deep-equal.js
@@ -0,0 +1,43 @@
+/**
+ * 2628. JSON Deep Equal
+ * https://leetcode.com/problems/json-deep-equal/
+ * Difficulty: Medium
+ *
+ * Given two values o1 and o2, return a boolean value indicating whether two values, o1 and o2,
+ * are deeply equal.
+ *
+ * For two values to be deeply equal, the following conditions must be met:
+ * - If both values are primitive types, they are deeply equal if they pass the === equality check.
+ * - If both values are arrays, they are deeply equal if they have the same elements in the same
+ * order, and each element is also deeply equal according to these conditions.
+ * - If both values are objects, they are deeply equal if they have the same keys, and the
+ * associated values for each key are also deeply equal according to these conditions.
+ *
+ * You may assume both values are the output of JSON.parse. In other words, they are valid JSON.
+ *
+ * Please solve it without using lodash's _.isEqual() function
+ */
+
+/**
+ * @param {null|boolean|number|string|Array|Object} o1
+ * @param {null|boolean|number|string|Array|Object} o2
+ * @return {boolean}
+ */
+var areDeeplyEqual = function(o1, o2) {
+ if (o1 === o2) return true;
+ if (o1 == null || o2 == null) return false;
+ if (typeof o1 !== 'object' || typeof o2 !== 'object') return false;
+
+ if (Array.isArray(o1) !== Array.isArray(o2)) return false;
+
+ if (Array.isArray(o1)) {
+ if (o1.length !== o2.length) return false;
+ return o1.every((item, index) => areDeeplyEqual(item, o2[index]));
+ }
+
+ const keys1 = Object.keys(o1);
+ const keys2 = Object.keys(o2);
+ if (keys1.length !== keys2.length) return false;
+
+ return keys1.every(key => keys2.includes(key) && areDeeplyEqual(o1[key], o2[key]));
+};
From 8c3c2f77cefb288e4b31b717dfd1b7d7f1e4c3ae Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 20:37:39 -0500
Subject: [PATCH 430/994] Add solution #2633
---
README.md | 1 +
.../2633-convert-object-to-json-string.js | 29 +++++++++++++++++++
2 files changed, 30 insertions(+)
create mode 100644 solutions/2633-convert-object-to-json-string.js
diff --git a/README.md b/README.md
index 1b6a992f..6af6cc1f 100644
--- a/README.md
+++ b/README.md
@@ -1976,6 +1976,7 @@
2630|[Memoize II](./solutions/2630-memoize-ii.js)|Hard|
2631|[Group By](./solutions/2631-group-by.js)|Medium|
2632|[Curry](./solutions/2632-curry.js)|Medium|
+2633|[Convert Object to JSON String](./solutions/2633-convert-object-to-json-string.js)|Medium|
2634|[Filter Elements from Array](./solutions/2634-filter-elements-from-array.js)|Easy|
2635|[Apply Transform Over Each Element in Array](./solutions/2635-apply-transform-over-each-element-in-array.js)|Easy|
2636|[Promise Pool](./solutions/2636-promise-pool.js)|Medium|
diff --git a/solutions/2633-convert-object-to-json-string.js b/solutions/2633-convert-object-to-json-string.js
new file mode 100644
index 00000000..90fd0f2e
--- /dev/null
+++ b/solutions/2633-convert-object-to-json-string.js
@@ -0,0 +1,29 @@
+/**
+ * 2633. Convert Object to JSON String
+ * https://leetcode.com/problems/convert-object-to-json-string/
+ * Difficulty: Medium
+ *
+ * Given a value, return a valid JSON string of that value. The value can be a string, number,
+ * array, object, boolean, or null. The returned string should not include extra spaces. The
+ * order of keys should be the same as the order returned by Object.keys().
+ *
+ * Please solve it without using the built-in JSON.stringify method.
+ */
+
+/**
+ * @param {null|boolean|number|string|Array|Object} object
+ * @return {string}
+ */
+var jsonStringify = function(object) {
+ if (object === null) return 'null';
+ if (typeof object === 'boolean' || typeof object === 'number') return String(object);
+ if (typeof object === 'string') return `"${object}"`;
+
+ if (Array.isArray(object)) {
+ const elements = object.map(item => jsonStringify(item));
+ return `[${elements.join(',')}]`;
+ }
+
+ const pairs = Object.keys(object).map(key => `"${key}":${jsonStringify(object[key])}`);
+ return `{${pairs.join(',')}}`;
+};
From 1be86642961b2026762f67aff930769f764d5312 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 22:54:56 -0500
Subject: [PATCH 431/994] Add solution #245
---
README.md | 1 +
solutions/0245-shortest-word-distance-iii.js | 46 ++++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/0245-shortest-word-distance-iii.js
diff --git a/README.md b/README.md
index 6af6cc1f..ce1d26be 100644
--- a/README.md
+++ b/README.md
@@ -234,6 +234,7 @@
242|[Valid Anagram](./solutions/0242-valid-anagram.js)|Easy|
243|[Shortest Word Distance](./solutions/0243-shortest-word-distance.js)|Easy|
244|[Shortest Word Distance II](./solutions/0244-shortest-word-distance-ii.js)|Medium|
+245|[Shortest Word Distance III](./solutions/0245-shortest-word-distance-iii.js)|Medium|
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
diff --git a/solutions/0245-shortest-word-distance-iii.js b/solutions/0245-shortest-word-distance-iii.js
new file mode 100644
index 00000000..0e1c24f5
--- /dev/null
+++ b/solutions/0245-shortest-word-distance-iii.js
@@ -0,0 +1,46 @@
+/**
+ * 245. Shortest Word Distance III
+ * https://leetcode.com/problems/shortest-word-distance-iii/
+ * Difficulty: Medium
+ *
+ * Given an array of strings wordsDict and two strings that already exist in the array word1
+ * and word2, return the shortest distance between the occurrence of these two words in the list.
+ *
+ * Note that word1 and word2 may be the same. It is guaranteed that they represent two individual
+ * words in the list.
+ */
+
+/**
+ * @param {string[]} wordsDict
+ * @param {string} word1
+ * @param {string} word2
+ * @return {number}
+ */
+var shortestWordDistance = function(wordsDict, word1, word2) {
+ let result = Infinity;
+ let lastWord1Index = -1;
+ let lastWord2Index = -1;
+ const areSameWords = word1 === word2;
+
+ for (let index = 0; index < wordsDict.length; index++) {
+ const currentWord = wordsDict[index];
+
+ if (currentWord === word1) {
+ if (areSameWords) {
+ if (lastWord1Index !== -1) {
+ result = Math.min(result, index - lastWord1Index);
+ }
+ } else if (lastWord2Index !== -1) {
+ result = Math.min(result, index - lastWord2Index);
+ }
+ lastWord1Index = index;
+ } else if (!areSameWords && currentWord === word2) {
+ if (lastWord1Index !== -1) {
+ result = Math.min(result, index - lastWord1Index);
+ }
+ lastWord2Index = index;
+ }
+ }
+
+ return result;
+};
From d185181a712677f80e9603fc069f131e42c5d8a0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 22:55:56 -0500
Subject: [PATCH 432/994] Add solution #246
---
README.md | 1 +
solutions/0246-strobogrammatic-number.js | 40 ++++++++++++++++++++++++
2 files changed, 41 insertions(+)
create mode 100644 solutions/0246-strobogrammatic-number.js
diff --git a/README.md b/README.md
index ce1d26be..05e7c420 100644
--- a/README.md
+++ b/README.md
@@ -235,6 +235,7 @@
243|[Shortest Word Distance](./solutions/0243-shortest-word-distance.js)|Easy|
244|[Shortest Word Distance II](./solutions/0244-shortest-word-distance-ii.js)|Medium|
245|[Shortest Word Distance III](./solutions/0245-shortest-word-distance-iii.js)|Medium|
+246|[Strobogrammatic Number](./solutions/0246-strobogrammatic-number.js)|Easy|
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
diff --git a/solutions/0246-strobogrammatic-number.js b/solutions/0246-strobogrammatic-number.js
new file mode 100644
index 00000000..19c3ab46
--- /dev/null
+++ b/solutions/0246-strobogrammatic-number.js
@@ -0,0 +1,40 @@
+/**
+ * 246. Strobogrammatic Number
+ * https://leetcode.com/problems/strobogrammatic-number/
+ * Difficulty: Easy
+ *
+ * Given a string num which represents an integer, return true if num is a strobogrammatic number.
+ *
+ * A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at
+ * upside down).
+ */
+
+/**
+ * @param {string} num
+ * @return {boolean}
+ */
+var isStrobogrammatic = function(num) {
+ const validPairs = new Map([
+ ['0', '0'],
+ ['1', '1'],
+ ['6', '9'],
+ ['8', '8'],
+ ['9', '6']
+ ]);
+ let left = 0;
+ let right = num.length - 1;
+
+ while (left <= right) {
+ const leftDigit = num[left];
+ const rightDigit = num[right];
+
+ if (!validPairs.has(leftDigit) || validPairs.get(leftDigit) !== rightDigit) {
+ return false;
+ }
+
+ left++;
+ right--;
+ }
+
+ return true;
+};
From 5a3caf19b4d2e279f385a20f36a953945fd0129d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 22:56:56 -0500
Subject: [PATCH 433/994] Add solution #247
---
README.md | 1 +
solutions/0247-strobogrammatic-number-ii.js | 43 +++++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/0247-strobogrammatic-number-ii.js
diff --git a/README.md b/README.md
index 05e7c420..5c8b989e 100644
--- a/README.md
+++ b/README.md
@@ -236,6 +236,7 @@
244|[Shortest Word Distance II](./solutions/0244-shortest-word-distance-ii.js)|Medium|
245|[Shortest Word Distance III](./solutions/0245-shortest-word-distance-iii.js)|Medium|
246|[Strobogrammatic Number](./solutions/0246-strobogrammatic-number.js)|Easy|
+247|[Strobogrammatic Number II](./solutions/0247-strobogrammatic-number-ii.js)|Medium|
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
diff --git a/solutions/0247-strobogrammatic-number-ii.js b/solutions/0247-strobogrammatic-number-ii.js
new file mode 100644
index 00000000..d8ebf09a
--- /dev/null
+++ b/solutions/0247-strobogrammatic-number-ii.js
@@ -0,0 +1,43 @@
+/**
+ * 247. Strobogrammatic Number II
+ * https://leetcode.com/problems/strobogrammatic-number-ii/
+ * Difficulty: Medium
+ *
+ * Given an integer n, return all the strobogrammatic numbers that are of length n. You may
+ * return the answer in any order.
+ *
+ * A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked
+ * at upside down).
+ */
+
+/**
+ * @param {number} n
+ * @return {string[]}
+ */
+var findStrobogrammatic = function(n) {
+ const pairs = [
+ ['0', '0'],
+ ['1', '1'],
+ ['6', '9'],
+ ['8', '8'],
+ ['9', '6']
+ ];
+
+ return generateStrobogrammatic(n, n);
+
+ function generateStrobogrammatic(length, finalLength) {
+ if (length === 0) return [''];
+ if (length === 1) return ['0', '1', '8'];
+
+ const result = [];
+ const subNumbers = generateStrobogrammatic(length - 2, finalLength);
+ for (const [left, right] of pairs) {
+ for (const sub of subNumbers) {
+ if (length === finalLength && left === '0') continue;
+ result.push(left + sub + right);
+ }
+ }
+
+ return result;
+ }
+};
From c67cbf0263f057db819e31375cd95f0491e90a15 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 22:58:27 -0500
Subject: [PATCH 434/994] Add solution #248
---
README.md | 1 +
solutions/0248-strobogrammatic-number-iii.js | 65 ++++++++++++++++++++
2 files changed, 66 insertions(+)
create mode 100644 solutions/0248-strobogrammatic-number-iii.js
diff --git a/README.md b/README.md
index 5c8b989e..f0f56a9e 100644
--- a/README.md
+++ b/README.md
@@ -237,6 +237,7 @@
245|[Shortest Word Distance III](./solutions/0245-shortest-word-distance-iii.js)|Medium|
246|[Strobogrammatic Number](./solutions/0246-strobogrammatic-number.js)|Easy|
247|[Strobogrammatic Number II](./solutions/0247-strobogrammatic-number-ii.js)|Medium|
+248|[Strobogrammatic Number III](./solutions/0248-strobogrammatic-number-iii.js)|Hard|
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
diff --git a/solutions/0248-strobogrammatic-number-iii.js b/solutions/0248-strobogrammatic-number-iii.js
new file mode 100644
index 00000000..d20b8dda
--- /dev/null
+++ b/solutions/0248-strobogrammatic-number-iii.js
@@ -0,0 +1,65 @@
+/**
+ * 248. Strobogrammatic Number III
+ * https://leetcode.com/problems/strobogrammatic-number-iii/
+ * Difficulty: Hard
+ *
+ * Given two strings low and high that represent two integers low and high where low <= high,
+ * return the number of strobogrammatic numbers in the range [low, high].
+ *
+ * A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked
+ * at upside down).
+ */
+
+/**
+ * @param {string} low
+ * @param {string} high
+ * @return {number}
+ */
+var strobogrammaticInRange = function(low, high) {
+ const pairs = [
+ ['0', '0'],
+ ['1', '1'],
+ ['6', '9'],
+ ['8', '8'],
+ ['9', '6']
+ ];
+
+ function generateStrobogrammatic(length, isOuter) {
+ if (length === 0) return [''];
+ if (length === 1) return ['0', '1', '8'];
+
+ const result = [];
+ const subNumbers = generateStrobogrammatic(length - 2, false);
+
+ for (const [left, right] of pairs) {
+ for (const sub of subNumbers) {
+ if (isOuter && left === '0') continue;
+ result.push(left + sub + right);
+ }
+ }
+
+ return result;
+ }
+
+ function countInRange(num, lowVal, highVal) {
+ if (num.length < lowVal.length || num.length > highVal.length) return false;
+ if (num.length === lowVal.length && num < lowVal) return false;
+ if (num.length === highVal.length && num > highVal) return false;
+ return true;
+ }
+
+ let count = 0;
+ const lowLength = low.length;
+ const highLength = high.length;
+
+ for (let len = lowLength; len <= highLength; len++) {
+ const numbers = generateStrobogrammatic(len, true);
+ for (const num of numbers) {
+ if (countInRange(num, low, high)) {
+ count++;
+ }
+ }
+ }
+
+ return count;
+};
From 07784bdbec8550f51340cc33a3b4cce749820aad Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 8 Jun 2025 23:00:17 -0500
Subject: [PATCH 435/994] Add solution #249
---
README.md | 1 +
solutions/0249-group-shifted-strings.js | 49 +++++++++++++++++++++++++
2 files changed, 50 insertions(+)
create mode 100644 solutions/0249-group-shifted-strings.js
diff --git a/README.md b/README.md
index f0f56a9e..fcad0802 100644
--- a/README.md
+++ b/README.md
@@ -238,6 +238,7 @@
246|[Strobogrammatic Number](./solutions/0246-strobogrammatic-number.js)|Easy|
247|[Strobogrammatic Number II](./solutions/0247-strobogrammatic-number-ii.js)|Medium|
248|[Strobogrammatic Number III](./solutions/0248-strobogrammatic-number-iii.js)|Hard|
+249|[Group Shifted Strings](./solutions/0249-group-shifted-strings.js)|Medium|
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
diff --git a/solutions/0249-group-shifted-strings.js b/solutions/0249-group-shifted-strings.js
new file mode 100644
index 00000000..cbcfaf26
--- /dev/null
+++ b/solutions/0249-group-shifted-strings.js
@@ -0,0 +1,49 @@
+/**
+ * 249. Group Shifted Strings
+ * https://leetcode.com/problems/group-shifted-strings/
+ * Difficulty: Medium
+ *
+ * Perform the following shift operations on a string:
+ * - Right shift: Replace every letter with the successive letter of the English alphabet, where
+ * 'z' is replaced by 'a'. For example, "abc" can be right-shifted to "bcd" or "xyz" can be
+ * right-shifted to "yza".
+ * - Left shift: Replace every letter with the preceding letter of the English alphabet, where
+ * 'a' is replaced by 'z'. For example, "bcd" can be left-shifted to "abc" or "yza" can be
+ * left-shifted to "xyz".
+ *
+ * We can keep shifting the string in both directions to form an endless shifting sequence.
+ * - For example, shift "abc" to form the sequence: ... <-> "abc" <-> "bcd" <-> ... <-> "xyz"
+ * <-> "yza" <-> .... <-> "zab" <-> "abc" <-> ...
+ *
+ * You are given an array of strings strings, group together all strings[i] that belong to the same
+ * shifting sequence. You may return the answer in any order.
+ */
+
+/**
+ * @param {string[]} strings
+ * @return {string[][]}
+ */
+var groupStrings = function(strings) {
+ const groups = new Map();
+
+ for (const str of strings) {
+ const key = getShiftKey(str);
+ if (!groups.has(key)) {
+ groups.set(key, []);
+ }
+ groups.get(key).push(str);
+ }
+
+ return Array.from(groups.values());
+
+ function getShiftKey(str) {
+ if (str.length === 1) return 'single';
+ const key = [];
+ for (let i = 1; i < str.length; i++) {
+ let diff = str.charCodeAt(i) - str.charCodeAt(i - 1);
+ if (diff < 0) diff += 26;
+ key.push(diff);
+ }
+ return key.join(',');
+ }
+};
From 78226951755d3737afcfd2cff95ab7cc87c30023 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 9 Jun 2025 23:38:10 -0500
Subject: [PATCH 436/994] Add solution #250
---
README.md | 1 +
solutions/0250-count-univalue-subtrees.js | 44 +++++++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/0250-count-univalue-subtrees.js
diff --git a/README.md b/README.md
index fcad0802..0c92dcf0 100644
--- a/README.md
+++ b/README.md
@@ -239,6 +239,7 @@
247|[Strobogrammatic Number II](./solutions/0247-strobogrammatic-number-ii.js)|Medium|
248|[Strobogrammatic Number III](./solutions/0248-strobogrammatic-number-iii.js)|Hard|
249|[Group Shifted Strings](./solutions/0249-group-shifted-strings.js)|Medium|
+250|[Count Univalue Subtrees](./solutions/0250-count-univalue-subtrees.js)|Medium|
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
diff --git a/solutions/0250-count-univalue-subtrees.js b/solutions/0250-count-univalue-subtrees.js
new file mode 100644
index 00000000..8a8e14ff
--- /dev/null
+++ b/solutions/0250-count-univalue-subtrees.js
@@ -0,0 +1,44 @@
+/**
+ * 250. Count Univalue Subtrees
+ * https://leetcode.com/problems/count-univalue-subtrees/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree, return the number of uni-value subtrees.
+ *
+ * A uni-value subtree means all nodes of the subtree have the same value.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @return {number}
+ */
+var countUnivalSubtrees = function(root) {
+ let count = 0;
+ traverse(root);
+ return count;
+
+ function isUnival(node, value) {
+ if (!node) return true;
+
+ if (node.val !== value) return false;
+
+ return isUnival(node.left, value) && isUnival(node.right, value);
+ }
+
+ function traverse(node) {
+ if (!node) return;
+
+ if (isUnival(node, node.val)) count++;
+
+ traverse(node.left);
+ traverse(node.right);
+ }
+};
From e2a514394a2ca4aee648b7067f5b64a2a2c9290d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 10 Jun 2025 21:49:19 -0500
Subject: [PATCH 437/994] Add solution #3442
---
README.md | 1 +
...erence-between-even-and-odd-frequency-i.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/3442-maximum-difference-between-even-and-odd-frequency-i.js
diff --git a/README.md b/README.md
index 0c92dcf0..c0a41c70 100644
--- a/README.md
+++ b/README.md
@@ -2222,6 +2222,7 @@
3397|[Maximum Number of Distinct Elements After Operations](./solutions/3397-maximum-number-of-distinct-elements-after-operations.js)|Medium|
3402|[Minimum Operations to Make Columns Strictly Increasing](./solutions/3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy|
3403|[Find the Lexicographically Largest String From the Box I](./solutions/3403-find-the-lexicographically-largest-string-from-the-box-i.js)|Medium|
+3442|[Maximum Difference Between Even and Odd Frequency I](./solutions/3442-maximum-difference-between-even-and-odd-frequency-i.js)|Easy|
3452|[Sum of Good Numbers](./solutions/3452-sum-of-good-numbers.js)|Easy|
3461|[Check If Digits Are Equal in String After Operations I](./solutions/3461-check-if-digits-are-equal-in-string-after-operations-i.js)|Easy|
3462|[Maximum Sum With at Most K Elements](./solutions/3462-maximum-sum-with-at-most-k-elements.js)|Medium|
diff --git a/solutions/3442-maximum-difference-between-even-and-odd-frequency-i.js b/solutions/3442-maximum-difference-between-even-and-odd-frequency-i.js
new file mode 100644
index 00000000..313d3fb5
--- /dev/null
+++ b/solutions/3442-maximum-difference-between-even-and-odd-frequency-i.js
@@ -0,0 +1,39 @@
+/**
+ * 3442. Maximum Difference Between Even and Odd Frequency I
+ * https://leetcode.com/problems/maximum-difference-between-even-and-odd-frequency-i/
+ * Difficulty: Easy
+ *
+ * You are given a string s consisting of lowercase English letters.
+ *
+ * Your task is to find the maximum difference diff = freq(a1) - freq(a2) between the frequency
+ * of characters a1 and a2 in the string such that:
+ * - a1 has an odd frequency in the string.
+ * - a2 has an even frequency in the string.
+ *
+ * Return this maximum difference.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var maxDifference = function(s) {
+ const map = new Map();
+
+ for (const char of s) {
+ map.set(char, (map.get(char) || 0) + 1);
+ }
+
+ let maxOdd = 0;
+ let minEven = Infinity;
+
+ for (const freq of map.values()) {
+ if (freq % 2 === 1) {
+ maxOdd = Math.max(maxOdd, freq);
+ } else {
+ minEven = Math.min(minEven, freq);
+ }
+ }
+
+ return maxOdd - minEven;
+};
From 64ed1dbdf57c5421d6b13d2e86aab9413296a962 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 10 Jun 2025 21:50:48 -0500
Subject: [PATCH 438/994] Add solution #251
---
README.md | 1 +
solutions/0251-flatten-2d-vector.js | 44 +++++++++++++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/0251-flatten-2d-vector.js
diff --git a/README.md b/README.md
index c0a41c70..d66153bb 100644
--- a/README.md
+++ b/README.md
@@ -240,6 +240,7 @@
248|[Strobogrammatic Number III](./solutions/0248-strobogrammatic-number-iii.js)|Hard|
249|[Group Shifted Strings](./solutions/0249-group-shifted-strings.js)|Medium|
250|[Count Univalue Subtrees](./solutions/0250-count-univalue-subtrees.js)|Medium|
+251|[Flatten 2D Vector](./solutions/0251-flatten-2d-vector.js)|Medium|
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
diff --git a/solutions/0251-flatten-2d-vector.js b/solutions/0251-flatten-2d-vector.js
new file mode 100644
index 00000000..612cc921
--- /dev/null
+++ b/solutions/0251-flatten-2d-vector.js
@@ -0,0 +1,44 @@
+/**
+ * 251. Flatten 2D Vector
+ * https://leetcode.com/problems/flatten-2d-vector/
+ * Difficulty: Medium
+ *
+ * Design an iterator to flatten a 2D vector. It should support the next and hasNext operations.
+ *
+ * Implement the Vector2D class:
+ * - Vector2D(int[][] vec) initializes the object with the 2D vector vec.
+ * - next() returns the next element from the 2D vector and moves the pointer one step forward.
+ * You may assume that all the calls to next are valid.
+ * - hasNext() returns true if there are still some elements in the vector, and false otherwise.
+ */
+
+/**
+ * @param {number[][]} vec
+ */
+var Vector2D = function(vec) {
+ this.vector = vec;
+ this.row = 0;
+ this.col = 0;
+};
+
+/**
+ * @return {number}
+ */
+Vector2D.prototype.next = function() {
+ while (this.row < this.vector.length && this.col >= this.vector[this.row].length) {
+ this.row++;
+ this.col = 0;
+ }
+ return this.vector[this.row][this.col++];
+};
+
+/**
+ * @return {boolean}
+ */
+Vector2D.prototype.hasNext = function() {
+ while (this.row < this.vector.length && this.col >= this.vector[this.row].length) {
+ this.row++;
+ this.col = 0;
+ }
+ return this.row < this.vector.length;
+};
From 281d6bd6776644b6d571b731e91dab6b9c9c082d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 10 Jun 2025 21:52:03 -0500
Subject: [PATCH 439/994] Add solution #252
---
README.md | 1 +
solutions/0252-meeting-rooms.js | 24 ++++++++++++++++++++++++
2 files changed, 25 insertions(+)
create mode 100644 solutions/0252-meeting-rooms.js
diff --git a/README.md b/README.md
index d66153bb..1129452e 100644
--- a/README.md
+++ b/README.md
@@ -241,6 +241,7 @@
249|[Group Shifted Strings](./solutions/0249-group-shifted-strings.js)|Medium|
250|[Count Univalue Subtrees](./solutions/0250-count-univalue-subtrees.js)|Medium|
251|[Flatten 2D Vector](./solutions/0251-flatten-2d-vector.js)|Medium|
+252|[Meeting Rooms](./solutions/0252-meeting-rooms.js)|Easy|
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
diff --git a/solutions/0252-meeting-rooms.js b/solutions/0252-meeting-rooms.js
new file mode 100644
index 00000000..09045654
--- /dev/null
+++ b/solutions/0252-meeting-rooms.js
@@ -0,0 +1,24 @@
+/**
+ * 252. Meeting Rooms
+ * https://leetcode.com/problems/meeting-rooms/
+ * Difficulty: Easy
+ *
+ * Given an array of meeting time intervals where intervals[i] = [starti, endi], determine
+ * if a person could attend all meetings.
+ */
+
+/**
+ * @param {number[][]} intervals
+ * @return {boolean}
+ */
+var canAttendMeetings = function(intervals) {
+ intervals.sort((a, b) => a[0] - b[0]);
+
+ for (let i = 1; i < intervals.length; i++) {
+ if (intervals[i][0] < intervals[i - 1][1]) {
+ return false;
+ }
+ }
+
+ return true;
+};
From dd567cc40756eddd0a419d3322358e5ee71886ad Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 10 Jun 2025 21:53:02 -0500
Subject: [PATCH 440/994] Add solution #253
---
README.md | 1 +
solutions/0253-meeting-rooms-ii.js | 34 ++++++++++++++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/0253-meeting-rooms-ii.js
diff --git a/README.md b/README.md
index 1129452e..00485098 100644
--- a/README.md
+++ b/README.md
@@ -242,6 +242,7 @@
250|[Count Univalue Subtrees](./solutions/0250-count-univalue-subtrees.js)|Medium|
251|[Flatten 2D Vector](./solutions/0251-flatten-2d-vector.js)|Medium|
252|[Meeting Rooms](./solutions/0252-meeting-rooms.js)|Easy|
+253|[Meeting Rooms II](./solutions/0253-meeting-rooms-ii.js)|Medium|
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
diff --git a/solutions/0253-meeting-rooms-ii.js b/solutions/0253-meeting-rooms-ii.js
new file mode 100644
index 00000000..2c08e7e3
--- /dev/null
+++ b/solutions/0253-meeting-rooms-ii.js
@@ -0,0 +1,34 @@
+/**
+ * 253. Meeting Rooms II
+ * https://leetcode.com/problems/meeting-rooms-ii/
+ * Difficulty: Medium
+ *
+ * Given an array of meeting time intervals intervals where intervals[i] = [starti, endi],
+ * return the minimum number of conference rooms required.
+ */
+
+/**
+ * @param {number[][]} intervals
+ * @return {number}
+ */
+var minMeetingRooms = function(intervals) {
+ const starts = intervals.map(([start]) => start).sort((a, b) => a - b);
+ const ends = intervals.map(([, end]) => end).sort((a, b) => a - b);
+ let rooms = 0;
+ let startIndex = 0;
+ let endIndex = 0;
+ let result = 0;
+
+ while (startIndex < intervals.length) {
+ if (starts[startIndex] < ends[endIndex]) {
+ rooms++;
+ result = Math.max(result, rooms);
+ startIndex++;
+ } else {
+ rooms--;
+ endIndex++;
+ }
+ }
+
+ return result;
+};
From 1781b76797d1649ca9617b2eb80df8fa7a64f146 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 10 Jun 2025 22:03:02 -0500
Subject: [PATCH 441/994] Add solution #3445
---
README.md | 1 +
...rence-between-even-and-odd-frequency-ii.js | 70 +++++++++++++++++++
2 files changed, 71 insertions(+)
create mode 100644 solutions/3445-maximum-difference-between-even-and-odd-frequency-ii.js
diff --git a/README.md b/README.md
index 00485098..c2bca6de 100644
--- a/README.md
+++ b/README.md
@@ -2226,6 +2226,7 @@
3402|[Minimum Operations to Make Columns Strictly Increasing](./solutions/3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy|
3403|[Find the Lexicographically Largest String From the Box I](./solutions/3403-find-the-lexicographically-largest-string-from-the-box-i.js)|Medium|
3442|[Maximum Difference Between Even and Odd Frequency I](./solutions/3442-maximum-difference-between-even-and-odd-frequency-i.js)|Easy|
+3445|[Maximum Difference Between Even and Odd Frequency II](./solutions/3445-maximum-difference-between-even-and-odd-frequency-ii.js)|Hard|
3452|[Sum of Good Numbers](./solutions/3452-sum-of-good-numbers.js)|Easy|
3461|[Check If Digits Are Equal in String After Operations I](./solutions/3461-check-if-digits-are-equal-in-string-after-operations-i.js)|Easy|
3462|[Maximum Sum With at Most K Elements](./solutions/3462-maximum-sum-with-at-most-k-elements.js)|Medium|
diff --git a/solutions/3445-maximum-difference-between-even-and-odd-frequency-ii.js b/solutions/3445-maximum-difference-between-even-and-odd-frequency-ii.js
new file mode 100644
index 00000000..3648091e
--- /dev/null
+++ b/solutions/3445-maximum-difference-between-even-and-odd-frequency-ii.js
@@ -0,0 +1,70 @@
+/**
+ * 3445. Maximum Difference Between Even and Odd Frequency II
+ * https://leetcode.com/problems/maximum-difference-between-even-and-odd-frequency-ii/
+ * Difficulty: Hard
+ *
+ * You are given a string s and an integer k. Your task is to find the maximum difference between
+ * the frequency of two characters, freq[a] - freq[b], in a substring subs of s, such that:
+ * - subs has a size of at least k.
+ * - Character a has an odd frequency in subs.
+ * - Character b has an even frequency in subs.
+ *
+ * Return the maximum difference.
+ *
+ * Note that subs can contain more than 2 distinct characters.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} k
+ * @return {number}
+ */
+var maxDifference = function(s, k) {
+ const n = s.length;
+ let result = -Infinity;
+
+ const calculateParityStatus = (freqA, freqB) => {
+ return ((freqA & 1) << 1) | (freqB & 1);
+ };
+
+ for (const charA of ['0', '1', '2', '3', '4']) {
+ for (const charB of ['0', '1', '2', '3', '4']) {
+ if (charA === charB) continue;
+
+ const minDifferences = [Infinity, Infinity, Infinity, Infinity];
+ let currentFreqA = 0;
+ let currentFreqB = 0;
+ let prefixFreqA = 0;
+ let prefixFreqB = 0;
+ let leftBoundary = -1;
+
+ for (let rightIndex = 0; rightIndex < n; rightIndex++) {
+ currentFreqA += s[rightIndex] === charA ? 1 : 0;
+ currentFreqB += s[rightIndex] === charB ? 1 : 0;
+
+ while (rightIndex - leftBoundary >= k && currentFreqB - prefixFreqB >= 2) {
+ const prefixStatus = calculateParityStatus(prefixFreqA, prefixFreqB);
+ minDifferences[prefixStatus] = Math.min(
+ minDifferences[prefixStatus],
+ prefixFreqA - prefixFreqB
+ );
+ leftBoundary++;
+ prefixFreqA += s[leftBoundary] === charA ? 1 : 0;
+ prefixFreqB += s[leftBoundary] === charB ? 1 : 0;
+ }
+
+ const currentStatus = calculateParityStatus(currentFreqA, currentFreqB);
+ const targetStatus = currentStatus ^ 0b10;
+
+ if (minDifferences[targetStatus] !== Infinity) {
+ result = Math.max(
+ result,
+ currentFreqA - currentFreqB - minDifferences[targetStatus]
+ );
+ }
+ }
+ }
+ }
+
+ return result;
+};
From b6b62b7af6bdce7a89b62f14c1f047c65e886d24 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 10 Jun 2025 22:29:20 -0500
Subject: [PATCH 442/994] Add solution #254
---
README.md | 1 +
solutions/0254-factor-combinations.js | 36 +++++++++++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/0254-factor-combinations.js
diff --git a/README.md b/README.md
index c2bca6de..7e653c64 100644
--- a/README.md
+++ b/README.md
@@ -243,6 +243,7 @@
251|[Flatten 2D Vector](./solutions/0251-flatten-2d-vector.js)|Medium|
252|[Meeting Rooms](./solutions/0252-meeting-rooms.js)|Easy|
253|[Meeting Rooms II](./solutions/0253-meeting-rooms-ii.js)|Medium|
+254|[Factor Combinations](./solutions/0254-factor-combinations.js)|Medium|
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
diff --git a/solutions/0254-factor-combinations.js b/solutions/0254-factor-combinations.js
new file mode 100644
index 00000000..ab66abba
--- /dev/null
+++ b/solutions/0254-factor-combinations.js
@@ -0,0 +1,36 @@
+/**
+ * 254. Factor Combinations
+ * https://leetcode.com/problems/factor-combinations/
+ * Difficulty: Medium
+ *
+ * Numbers can be regarded as the product of their factors.
+ *
+ * For example, 8 = 2 x 2 x 2 = 2 x 4.
+ *
+ * Given an integer n, return all possible combinations of its factors. You may return the
+ * answer in any order.
+ *
+ * Note that the factors should be in the range [2, n - 1].
+ */
+
+/**
+ * @param {number} n
+ * @return {number[][]}
+ */
+var getFactors = function(n) {
+ const result = [];
+ findFactors(n, 2, []);
+ return result;
+
+ function findFactors(currentNum, start, combination) {
+ for (let i = start; i * i <= currentNum; i++) {
+ if (currentNum % i === 0) {
+ const nextNum = currentNum / i;
+ if (nextNum >= i && nextNum < currentNum) {
+ result.push([...combination, i, nextNum]);
+ findFactors(nextNum, i, [...combination, i]);
+ }
+ }
+ }
+ }
+};
From c28a804ed5fc33607bd9910e9002a8a961538059 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 10 Jun 2025 22:30:17 -0500
Subject: [PATCH 443/994] Add solution #255
---
README.md | 1 +
...preorder-sequence-in-binary-search-tree.js | 27 +++++++++++++++++++
2 files changed, 28 insertions(+)
create mode 100644 solutions/0255-verify-preorder-sequence-in-binary-search-tree.js
diff --git a/README.md b/README.md
index 7e653c64..7c5c7d9a 100644
--- a/README.md
+++ b/README.md
@@ -244,6 +244,7 @@
252|[Meeting Rooms](./solutions/0252-meeting-rooms.js)|Easy|
253|[Meeting Rooms II](./solutions/0253-meeting-rooms-ii.js)|Medium|
254|[Factor Combinations](./solutions/0254-factor-combinations.js)|Medium|
+255|[Verify Preorder Sequence in Binary Search Tree](./solutions/0255-verify-preorder-sequence-in-binary-search-tree.js)|Medium|
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
diff --git a/solutions/0255-verify-preorder-sequence-in-binary-search-tree.js b/solutions/0255-verify-preorder-sequence-in-binary-search-tree.js
new file mode 100644
index 00000000..2e502211
--- /dev/null
+++ b/solutions/0255-verify-preorder-sequence-in-binary-search-tree.js
@@ -0,0 +1,27 @@
+/**
+ * 255. Verify Preorder Sequence in Binary Search Tree
+ * https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/
+ * Difficulty: Medium
+ *
+ * Given an array of unique integers preorder, return true if it is the correct preorder
+ * traversal sequence of a binary search tree.
+ */
+
+/**
+ * @param {number[]} preorder
+ * @return {boolean}
+ */
+var verifyPreorder = function(preorder) {
+ let minLimit = -Infinity;
+ const stack = [];
+
+ for (const value of preorder) {
+ while (stack.length && stack[stack.length - 1] < value) {
+ minLimit = stack.pop();
+ }
+ if (value <= minLimit) return false;
+ stack.push(value);
+ }
+
+ return true;
+};
From 8514d2214466e223b3466c413ac4cbc43d897407 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 10 Jun 2025 22:32:06 -0500
Subject: [PATCH 444/994] Add solution #256
---
README.md | 1 +
solutions/0256-paint-house.js | 34 ++++++++++++++++++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/0256-paint-house.js
diff --git a/README.md b/README.md
index 7c5c7d9a..f46e3c67 100644
--- a/README.md
+++ b/README.md
@@ -245,6 +245,7 @@
253|[Meeting Rooms II](./solutions/0253-meeting-rooms-ii.js)|Medium|
254|[Factor Combinations](./solutions/0254-factor-combinations.js)|Medium|
255|[Verify Preorder Sequence in Binary Search Tree](./solutions/0255-verify-preorder-sequence-in-binary-search-tree.js)|Medium|
+256|[Paint House](./solutions/0256-paint-house.js)|Medium|
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
diff --git a/solutions/0256-paint-house.js b/solutions/0256-paint-house.js
new file mode 100644
index 00000000..c37cc991
--- /dev/null
+++ b/solutions/0256-paint-house.js
@@ -0,0 +1,34 @@
+/**
+ * 256. Paint House
+ * https://leetcode.com/problems/paint-house/
+ * Difficulty: Medium
+ *
+ * There is a row of n houses, where each house can be painted one of three colors: red, blue,
+ * or green. The cost of painting each house with a certain color is different. You have to
+ * paint all the houses such that no two adjacent houses have the same color.
+ *
+ * The cost of painting each house with a certain color is represented by an n x 3 cost matrix
+ * costs.
+ * - For example, costs[0][0] is the cost of painting house 0 with the color red; costs[1][2]
+ * is the cost of painting house 1 with color green, and so on...
+ *
+ * Return the minimum cost to paint all houses.
+ */
+
+/**
+ * @param {number[][]} costs
+ * @return {number}
+ */
+var minCost = function(costs) {
+ let prev = [...costs[0]];
+
+ for (let i = 1; i < costs.length; i++) {
+ prev = [
+ costs[i][0] + Math.min(prev[1], prev[2]),
+ costs[i][1] + Math.min(prev[0], prev[2]),
+ costs[i][2] + Math.min(prev[0], prev[1])
+ ];
+ }
+
+ return Math.min(...prev);
+};
From 34bce6d304df5bfc3b7fc6430f19cac95d531b46 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 10 Jun 2025 22:33:01 -0500
Subject: [PATCH 445/994] Add solution #259
---
README.md | 1 +
solutions/0259-3sum-smaller.js | 36 ++++++++++++++++++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/0259-3sum-smaller.js
diff --git a/README.md b/README.md
index f46e3c67..8868f4a2 100644
--- a/README.md
+++ b/README.md
@@ -248,6 +248,7 @@
256|[Paint House](./solutions/0256-paint-house.js)|Medium|
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
+259|[3Sum Smaller](./solutions/0259-3sum-smaller.js)|Medium|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
263|[Ugly Number](./solutions/0263-ugly-number.js)|Easy|
264|[Ugly Number II](./solutions/0264-ugly-number-ii.js)|Medium|
diff --git a/solutions/0259-3sum-smaller.js b/solutions/0259-3sum-smaller.js
new file mode 100644
index 00000000..89e0d4b5
--- /dev/null
+++ b/solutions/0259-3sum-smaller.js
@@ -0,0 +1,36 @@
+/**
+ * 259. 3Sum Smaller
+ * https://leetcode.com/problems/3sum-smaller/
+ * Difficulty: Medium
+ *
+ * Given an array of n integers nums and an integer target, find the number of index triplets
+ * i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} target
+ * @return {number}
+ */
+var threeSumSmaller = function(nums, target) {
+ nums.sort((a, b) => a - b);
+ const n = nums.length;
+ let result = 0;
+
+ for (let i = 0; i < n - 2; i++) {
+ let left = i + 1;
+ let right = n - 1;
+
+ while (left < right) {
+ const sum = nums[i] + nums[left] + nums[right];
+ if (sum < target) {
+ result += right - left;
+ left++;
+ } else {
+ right--;
+ }
+ }
+ }
+
+ return result;
+};
From 204f1e04339fb3bbeb4863d837bbb96ea764486b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 10 Jun 2025 22:45:03 -0500
Subject: [PATCH 446/994] Add solution #261
---
README.md | 1 +
solutions/0261-graph-valid-tree.js | 45 ++++++++++++++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/0261-graph-valid-tree.js
diff --git a/README.md b/README.md
index 8868f4a2..d6211ff7 100644
--- a/README.md
+++ b/README.md
@@ -250,6 +250,7 @@
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
259|[3Sum Smaller](./solutions/0259-3sum-smaller.js)|Medium|
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
+261|[Graph Valid Tree](./solutions/0261-graph-valid-tree.js)|Medium|
263|[Ugly Number](./solutions/0263-ugly-number.js)|Easy|
264|[Ugly Number II](./solutions/0264-ugly-number-ii.js)|Medium|
268|[Missing Number](./solutions/0268-missing-number.js)|Easy|
diff --git a/solutions/0261-graph-valid-tree.js b/solutions/0261-graph-valid-tree.js
new file mode 100644
index 00000000..483b2345
--- /dev/null
+++ b/solutions/0261-graph-valid-tree.js
@@ -0,0 +1,45 @@
+/**
+ * 261. Graph Valid Tree
+ * https://leetcode.com/problems/graph-valid-tree/
+ * Difficulty: Medium
+ *
+ * You have a graph of n nodes labeled from 0 to n - 1. You are given an integer n and a list of
+ * edges where edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai
+ * and bi in the graph.
+ *
+ * Return true if the edges of the given graph make up a valid tree, and false otherwise.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @return {boolean}
+ */
+var validTree = function(n, edges) {
+ const parent = new Array(n).fill(-1);
+
+ for (const [u, v] of edges) {
+ if (!union(u, v)) return false;
+ }
+
+ let components = 0;
+ for (let i = 0; i < n; i++) {
+ if (parent[i] === -1) components++;
+ if (components > 1) return false;
+ }
+
+ return edges.length === n - 1;
+
+ function find(x) {
+ if (parent[x] === -1) return x;
+ return parent[x] = find(parent[x]);
+ }
+
+ function union(x, y) {
+ const rootX = find(x);
+ const rootY = find(y);
+ if (rootX === rootY) return false;
+ parent[rootX] = rootY;
+ return true;
+ }
+};
From 4b4ed1c5202bcfbae1aff86ad0afb92ea7b5cef0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 10 Jun 2025 22:46:39 -0500
Subject: [PATCH 447/994] Add solution #265
---
README.md | 1 +
solutions/0265-paint-house-ii.js | 51 ++++++++++++++++++++++++++++++++
2 files changed, 52 insertions(+)
create mode 100644 solutions/0265-paint-house-ii.js
diff --git a/README.md b/README.md
index d6211ff7..7d565dbd 100644
--- a/README.md
+++ b/README.md
@@ -253,6 +253,7 @@
261|[Graph Valid Tree](./solutions/0261-graph-valid-tree.js)|Medium|
263|[Ugly Number](./solutions/0263-ugly-number.js)|Easy|
264|[Ugly Number II](./solutions/0264-ugly-number-ii.js)|Medium|
+265|[Paint House II](./solutions/0265-paint-house-ii.js)|Hard|
268|[Missing Number](./solutions/0268-missing-number.js)|Easy|
273|[Integer to English Words](./solutions/0273-integer-to-english-words.js)|Hard|
274|[H-Index](./solutions/0274-h-index.js)|Medium|
diff --git a/solutions/0265-paint-house-ii.js b/solutions/0265-paint-house-ii.js
new file mode 100644
index 00000000..6a883f10
--- /dev/null
+++ b/solutions/0265-paint-house-ii.js
@@ -0,0 +1,51 @@
+/**
+ * 265. Paint House II
+ * https://leetcode.com/problems/paint-house-ii/
+ * Difficulty: Hard
+ *
+ * There are a row of n houses, each house can be painted with one of the k colors. The cost of
+ * painting each house with a certain color is different. You have to paint all the houses such
+ * that no two adjacent houses have the same color.
+ *
+ * The cost of painting each house with a certain color is represented by an n x k cost matrix
+ * costs.
+ * - For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the
+ * cost of painting house 1 with color 2, and so on...
+ *
+ * Return the minimum cost to paint all houses.
+ */
+
+/**
+ * @param {number[][]} costs
+ * @return {number}
+ */
+var minCostII = function(costs) {
+ const n = costs.length;
+ const k = costs[0].length;
+ let prev = [...costs[0]];
+
+ for (let i = 1; i < n; i++) {
+ const curr = new Array(k);
+ let min1 = Infinity;
+ let min2 = Infinity;
+ let index = -1;
+
+ for (let j = 0; j < k; j++) {
+ if (prev[j] < min1) {
+ min2 = min1;
+ min1 = prev[j];
+ index = j;
+ } else if (prev[j] < min2) {
+ min2 = prev[j];
+ }
+ }
+
+ for (let j = 0; j < k; j++) {
+ curr[j] = costs[i][j] + (j === index ? min2 : min1);
+ }
+
+ prev = curr;
+ }
+
+ return Math.min(...prev);
+};
From 109acf98bfb64977061cc7cb56b64742ebe85888 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 10 Jun 2025 22:47:52 -0500
Subject: [PATCH 448/994] Add solution #266
---
README.md | 1 +
solutions/0266-palindrome-permutation.js | 28 ++++++++++++++++++++++++
2 files changed, 29 insertions(+)
create mode 100644 solutions/0266-palindrome-permutation.js
diff --git a/README.md b/README.md
index 7d565dbd..435bbd25 100644
--- a/README.md
+++ b/README.md
@@ -254,6 +254,7 @@
263|[Ugly Number](./solutions/0263-ugly-number.js)|Easy|
264|[Ugly Number II](./solutions/0264-ugly-number-ii.js)|Medium|
265|[Paint House II](./solutions/0265-paint-house-ii.js)|Hard|
+266|[Palindrome Permutation](./solutions/0266-palindrome-permutation.js)|Easy|
268|[Missing Number](./solutions/0268-missing-number.js)|Easy|
273|[Integer to English Words](./solutions/0273-integer-to-english-words.js)|Hard|
274|[H-Index](./solutions/0274-h-index.js)|Medium|
diff --git a/solutions/0266-palindrome-permutation.js b/solutions/0266-palindrome-permutation.js
new file mode 100644
index 00000000..9f710d28
--- /dev/null
+++ b/solutions/0266-palindrome-permutation.js
@@ -0,0 +1,28 @@
+/**
+ * 266. Palindrome Permutation
+ * https://leetcode.com/problems/palindrome-permutation/
+ * Difficulty: Easy
+ *
+ * Given a string s, return true if a permutation of the string could form a palindrome
+ * and false otherwise.
+ */
+
+/**
+ * @param {string} s
+ * @return {boolean}
+ */
+var canPermutePalindrome = function(s) {
+ const map = new Map();
+
+ for (const char of s) {
+ map.set(char, (map.get(char) || 0) + 1);
+ }
+
+ let oddCount = 0;
+ for (const count of map.values()) {
+ if (count % 2 !== 0) oddCount++;
+ if (oddCount > 1) return false;
+ }
+
+ return true;
+};
From 83b8a8385bf6e5589f4befeeff428310fbfe0e0a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 10 Jun 2025 22:49:49 -0500
Subject: [PATCH 449/994] Add solution #267
---
README.md | 1 +
solutions/0267-palindrome-permutation-ii.js | 62 +++++++++++++++++++++
2 files changed, 63 insertions(+)
create mode 100644 solutions/0267-palindrome-permutation-ii.js
diff --git a/README.md b/README.md
index 435bbd25..e7053d3f 100644
--- a/README.md
+++ b/README.md
@@ -255,6 +255,7 @@
264|[Ugly Number II](./solutions/0264-ugly-number-ii.js)|Medium|
265|[Paint House II](./solutions/0265-paint-house-ii.js)|Hard|
266|[Palindrome Permutation](./solutions/0266-palindrome-permutation.js)|Easy|
+267|[Palindrome Permutation II](./solutions/0267-palindrome-permutation-ii.js)|Medium|
268|[Missing Number](./solutions/0268-missing-number.js)|Easy|
273|[Integer to English Words](./solutions/0273-integer-to-english-words.js)|Hard|
274|[H-Index](./solutions/0274-h-index.js)|Medium|
diff --git a/solutions/0267-palindrome-permutation-ii.js b/solutions/0267-palindrome-permutation-ii.js
new file mode 100644
index 00000000..6f1127c0
--- /dev/null
+++ b/solutions/0267-palindrome-permutation-ii.js
@@ -0,0 +1,62 @@
+/**
+ * 267. Palindrome Permutation II
+ * https://leetcode.com/problems/palindrome-permutation-ii/
+ * Difficulty: Medium
+ *
+ * Given a string s, return all the palindromic permutations (without duplicates) of it.
+ *
+ * You may return the answer in any order. If s has no palindromic permutation, return an
+ * empty list.
+ */
+
+/**
+ * @param {string} s
+ * @return {string[]}
+ */
+var generatePalindromes = function(s) {
+ const map = new Map();
+ for (const char of s) {
+ map.set(char, (map.get(char) || 0) + 1);
+ }
+
+ let oddChar = '';
+ const half = [];
+ let oddCount = 0;
+
+ for (const [char, count] of map) {
+ if (count % 2) {
+ oddCount++;
+ oddChar = char;
+ }
+ for (let i = 0; i < Math.floor(count / 2); i++) {
+ half.push(char);
+ }
+ }
+
+ if (oddCount > 1) return [];
+
+ const result = new Set();
+
+ half.sort();
+ permute(half, [], new Array(half.length).fill(false));
+ return Array.from(result);
+
+ function permute(chars, current, used) {
+ if (current.length === chars.length) {
+ const palindrome = current.join('') + oddChar + current.reverse().join('');
+ result.add(palindrome);
+ current.reverse();
+ return;
+ }
+
+ for (let i = 0; i < chars.length; i++) {
+ if (!used[i] && (i === 0 || chars[i] !== chars[i - 1] || used[i - 1])) {
+ used[i] = true;
+ current.push(chars[i]);
+ permute(chars, current, used);
+ current.pop();
+ used[i] = false;
+ }
+ }
+ }
+};
From 5b3ba9844209f81e1f0e190173fbd63c656ae66d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 10 Jun 2025 22:55:46 -0500
Subject: [PATCH 450/994] Add solution #269
---
README.md | 1 +
solutions/0269-alien-dictionary.js | 73 ++++++++++++++++++++++++++++++
2 files changed, 74 insertions(+)
create mode 100644 solutions/0269-alien-dictionary.js
diff --git a/README.md b/README.md
index e7053d3f..80fb4078 100644
--- a/README.md
+++ b/README.md
@@ -257,6 +257,7 @@
266|[Palindrome Permutation](./solutions/0266-palindrome-permutation.js)|Easy|
267|[Palindrome Permutation II](./solutions/0267-palindrome-permutation-ii.js)|Medium|
268|[Missing Number](./solutions/0268-missing-number.js)|Easy|
+269|[Alien Dictionary](./solutions/0269-alien-dictionary.js)|Hard|
273|[Integer to English Words](./solutions/0273-integer-to-english-words.js)|Hard|
274|[H-Index](./solutions/0274-h-index.js)|Medium|
275|[H-Index II](./solutions/0275-h-index-ii.js)|Medium|
diff --git a/solutions/0269-alien-dictionary.js b/solutions/0269-alien-dictionary.js
new file mode 100644
index 00000000..00e19ca3
--- /dev/null
+++ b/solutions/0269-alien-dictionary.js
@@ -0,0 +1,73 @@
+/**
+ * 269. Alien Dictionary
+ * https://leetcode.com/problems/alien-dictionary/
+ * Difficulty: Hard
+ *
+ * There is a new alien language that uses the English alphabet. However, the order of the
+ * letters is unknown to you.
+ *
+ * You are given a list of strings words from the alien language's dictionary. Now it is
+ * claimed that the strings in words are sorted lexicographically by the rules of this new
+ * language.
+ *
+ * If this claim is incorrect, and the given arrangement of string in words cannot correspond
+ * to any order of letters, return "".
+ *
+ * Otherwise, return a string of the unique letters in the new alien language sorted in
+ * lexicographically increasing order by the new language's rules. If there are multiple
+ * solutions, return any of them.
+ */
+
+/**
+ * @param {string[]} words
+ * @return {string}
+ */
+var alienOrder = function(words) {
+ const graph = new Map();
+ const inDegree = new Map();
+
+ for (const word of words) {
+ for (const char of word) {
+ if (!graph.has(char)) {
+ graph.set(char, new Set());
+ inDegree.set(char, 0);
+ }
+ }
+ }
+
+ for (let i = 1; i < words.length; i++) {
+ const prev = words[i - 1];
+ const curr = words[i];
+ const minLen = Math.min(prev.length, curr.length);
+
+ if (prev.length > curr.length && prev.startsWith(curr)) return '';
+
+ for (let j = 0; j < minLen; j++) {
+ if (prev[j] !== curr[j]) {
+ if (!graph.get(prev[j]).has(curr[j])) {
+ graph.get(prev[j]).add(curr[j]);
+ inDegree.set(curr[j], inDegree.get(curr[j]) + 1);
+ }
+ break;
+ }
+ }
+ }
+
+ const queue = [];
+ for (const [char, degree] of inDegree) {
+ if (degree === 0) queue.push(char);
+ }
+
+ let result = '';
+ while (queue.length) {
+ const char = queue.shift();
+ result += char;
+
+ for (const next of graph.get(char)) {
+ inDegree.set(next, inDegree.get(next) - 1);
+ if (inDegree.get(next) === 0) queue.push(next);
+ }
+ }
+
+ return result.length === graph.size ? result : '';
+};
From 154f2745b71e8b71270f5adab993da88316206ce Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 11 Jun 2025 22:52:58 -0500
Subject: [PATCH 451/994] Add solution #3423
---
README.md | 1 +
...n-adjacent-elements-in-a-circular-array.js | 25 +++++++++++++++++++
2 files changed, 26 insertions(+)
create mode 100644 solutions/3423-maximum-difference-between-adjacent-elements-in-a-circular-array.js
diff --git a/README.md b/README.md
index 80fb4078..874bc8d7 100644
--- a/README.md
+++ b/README.md
@@ -2234,6 +2234,7 @@
3397|[Maximum Number of Distinct Elements After Operations](./solutions/3397-maximum-number-of-distinct-elements-after-operations.js)|Medium|
3402|[Minimum Operations to Make Columns Strictly Increasing](./solutions/3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy|
3403|[Find the Lexicographically Largest String From the Box I](./solutions/3403-find-the-lexicographically-largest-string-from-the-box-i.js)|Medium|
+3423|[Maximum Difference Between Adjacent Elements in a Circular Array](./solutions/3423-maximum-difference-between-adjacent-elements-in-a-circular-array.js)|Easy|
3442|[Maximum Difference Between Even and Odd Frequency I](./solutions/3442-maximum-difference-between-even-and-odd-frequency-i.js)|Easy|
3445|[Maximum Difference Between Even and Odd Frequency II](./solutions/3445-maximum-difference-between-even-and-odd-frequency-ii.js)|Hard|
3452|[Sum of Good Numbers](./solutions/3452-sum-of-good-numbers.js)|Easy|
diff --git a/solutions/3423-maximum-difference-between-adjacent-elements-in-a-circular-array.js b/solutions/3423-maximum-difference-between-adjacent-elements-in-a-circular-array.js
new file mode 100644
index 00000000..dae3e36c
--- /dev/null
+++ b/solutions/3423-maximum-difference-between-adjacent-elements-in-a-circular-array.js
@@ -0,0 +1,25 @@
+/**
+ * 3423. Maximum Difference Between Adjacent Elements in a Circular Array
+ * https://leetcode.com/problems/maximum-difference-between-adjacent-elements-in-a-circular-array/
+ * Difficulty: Easy
+ *
+ * Given a circular array nums, find the maximum absolute difference between adjacent elements.
+ *
+ * Note: In a circular array, the first and last elements are adjacent.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maxAdjacentDistance = function(nums) {
+ let result = 0;
+
+ for (let i = 0; i < nums.length; i++) {
+ const next = (i + 1) % nums.length;
+ const diff = Math.abs(nums[i] - nums[next]);
+ result = Math.max(result, diff);
+ }
+
+ return result;
+};
From e25fe3ddd8bbc65d5fe52b0489c5fa9e4bb31392 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 11 Jun 2025 22:58:41 -0500
Subject: [PATCH 452/994] Add solution #270
---
README.md | 1 +
.../0270-closest-binary-search-tree-value.js | 36 +++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/0270-closest-binary-search-tree-value.js
diff --git a/README.md b/README.md
index 874bc8d7..003c38e7 100644
--- a/README.md
+++ b/README.md
@@ -258,6 +258,7 @@
267|[Palindrome Permutation II](./solutions/0267-palindrome-permutation-ii.js)|Medium|
268|[Missing Number](./solutions/0268-missing-number.js)|Easy|
269|[Alien Dictionary](./solutions/0269-alien-dictionary.js)|Hard|
+270|[Closest Binary Search Tree Value](./solutions/0270-closest-binary-search-tree-value.js)|Easy|
273|[Integer to English Words](./solutions/0273-integer-to-english-words.js)|Hard|
274|[H-Index](./solutions/0274-h-index.js)|Medium|
275|[H-Index II](./solutions/0275-h-index-ii.js)|Medium|
diff --git a/solutions/0270-closest-binary-search-tree-value.js b/solutions/0270-closest-binary-search-tree-value.js
new file mode 100644
index 00000000..b0e78a8e
--- /dev/null
+++ b/solutions/0270-closest-binary-search-tree-value.js
@@ -0,0 +1,36 @@
+/**
+ * 270. Closest Binary Search Tree Value
+ * https://leetcode.com/problems/closest-binary-search-tree-value/
+ * Difficulty: Easy
+ *
+ * Given the root of a binary search tree and a target value, return the value in the BST that
+ * is closest to the target. If there are multiple answers, print the smallest.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @param {number} target
+ * @return {number}
+ */
+var closestValue = function(root, target) {
+ let closest = root.val;
+
+ while (root) {
+ closest = Math.abs(root.val - target) < Math.abs(closest - target)
+ || (Math.abs(root.val - target) === Math.abs(closest - target) && root.val < closest)
+ ? root.val
+ : closest;
+
+ root = target < root.val ? root.left : root.right;
+ }
+
+ return closest;
+};
From b8924677cce0f5294934778e5d7d8c9d0febdcaa Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 11 Jun 2025 23:00:40 -0500
Subject: [PATCH 453/994] Add solution #271
---
README.md | 1 +
solutions/0271-encode-and-decode-strings.js | 58 +++++++++++++++++++++
2 files changed, 59 insertions(+)
create mode 100644 solutions/0271-encode-and-decode-strings.js
diff --git a/README.md b/README.md
index 003c38e7..ac585788 100644
--- a/README.md
+++ b/README.md
@@ -259,6 +259,7 @@
268|[Missing Number](./solutions/0268-missing-number.js)|Easy|
269|[Alien Dictionary](./solutions/0269-alien-dictionary.js)|Hard|
270|[Closest Binary Search Tree Value](./solutions/0270-closest-binary-search-tree-value.js)|Easy|
+271|[Encode and Decode Strings](./solutions/0271-encode-and-decode-strings.js)|Medium|
273|[Integer to English Words](./solutions/0273-integer-to-english-words.js)|Hard|
274|[H-Index](./solutions/0274-h-index.js)|Medium|
275|[H-Index II](./solutions/0275-h-index-ii.js)|Medium|
diff --git a/solutions/0271-encode-and-decode-strings.js b/solutions/0271-encode-and-decode-strings.js
new file mode 100644
index 00000000..e32296b3
--- /dev/null
+++ b/solutions/0271-encode-and-decode-strings.js
@@ -0,0 +1,58 @@
+/**
+ * 271. Encode and Decode Strings
+ * https://leetcode.com/problems/encode-and-decode-strings/
+ * Difficulty: Medium
+ *
+ * Design an algorithm to encode a list of strings to a string. The encoded string is then sent over
+ * the network and is decoded back to the original list of strings.
+ *
+ * Machine 1 (sender) has the function:
+ * string encode(vector strs) {
+ * // ... your code
+ * return encoded_string;
+ * }
+ * Machine 2 (receiver) has the function:
+ * vector decode(string s) {
+ * //... your code
+ * return strs;
+ * }
+ * So Machine 1 does:
+ * string encoded_string = encode(strs);
+ * and Machine 2 does:
+ * vector strs2 = decode(encoded_string);
+ * strs2 in Machine 2 should be the same as strs in Machine 1.
+ *
+ * Implement the encode and decode methods.
+ *
+ * You are not allowed to solve the problem using any serialize methods (such as eval).
+ */
+
+/**
+ * Encodes a list of strings to a single string.
+ *
+ * @param {string[]} strs
+ * @return {string}
+ */
+var encode = function(strs) {
+ return strs.map(str => `${str.length}:${str}`).join('');
+};
+
+/**
+ * Decodes a single string to a list of strings.
+ *
+ * @param {string} s
+ * @return {string[]}
+ */
+var decode = function(s) {
+ const result = [];
+ let i = 0;
+
+ while (i < s.length) {
+ const colon = s.indexOf(':', i);
+ const len = parseInt(s.slice(i, colon));
+ result.push(s.slice(colon + 1, colon + 1 + len));
+ i = colon + 1 + len;
+ }
+
+ return result;
+};
From d8bc15dfc5fb7b87b63fdbeda3fc96a78da4f917 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 11 Jun 2025 23:01:52 -0500
Subject: [PATCH 454/994] Add solution #272
---
README.md | 1 +
...272-closest-binary-search-tree-value-ii.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/0272-closest-binary-search-tree-value-ii.js
diff --git a/README.md b/README.md
index ac585788..b0e85585 100644
--- a/README.md
+++ b/README.md
@@ -260,6 +260,7 @@
269|[Alien Dictionary](./solutions/0269-alien-dictionary.js)|Hard|
270|[Closest Binary Search Tree Value](./solutions/0270-closest-binary-search-tree-value.js)|Easy|
271|[Encode and Decode Strings](./solutions/0271-encode-and-decode-strings.js)|Medium|
+272|[Closest Binary Search Tree Value II](./solutions/0272-closest-binary-search-tree-value-ii.js)|Hard|
273|[Integer to English Words](./solutions/0273-integer-to-english-words.js)|Hard|
274|[H-Index](./solutions/0274-h-index.js)|Medium|
275|[H-Index II](./solutions/0275-h-index-ii.js)|Medium|
diff --git a/solutions/0272-closest-binary-search-tree-value-ii.js b/solutions/0272-closest-binary-search-tree-value-ii.js
new file mode 100644
index 00000000..b3a6b27b
--- /dev/null
+++ b/solutions/0272-closest-binary-search-tree-value-ii.js
@@ -0,0 +1,41 @@
+/**
+ * 272. Closest Binary Search Tree Value II
+ * https://leetcode.com/problems/closest-binary-search-tree-value-ii/
+ * Difficulty: Hard
+ *
+ * Given the root of a binary search tree, a target value, and an integer k, return the k values
+ * in the BST that are closest to the target. You may return the answer in any order.
+ *
+ * You are guaranteed to have only one unique set of k values in the BST that are closest to the
+ * target.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @param {number} target
+ * @param {number} k
+ * @return {number[]}
+ */
+var closestKValues = function(root, target, k) {
+ const values = [];
+
+ inOrder(root);
+
+ values.sort((a, b) => Math.abs(a - target) - Math.abs(b - target));
+ return values.slice(0, k);
+
+ function inOrder(node) {
+ if (!node) return;
+ inOrder(node.left);
+ values.push(node.val);
+ inOrder(node.right);
+ }
+};
From 4e00bead7edd9ff2d416769a92b0978d49b6f185 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 11 Jun 2025 23:03:12 -0500
Subject: [PATCH 455/994] Add solution #276
---
README.md | 1 +
solutions/0276-paint-fence.js | 33 +++++++++++++++++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/0276-paint-fence.js
diff --git a/README.md b/README.md
index b0e85585..e390381f 100644
--- a/README.md
+++ b/README.md
@@ -264,6 +264,7 @@
273|[Integer to English Words](./solutions/0273-integer-to-english-words.js)|Hard|
274|[H-Index](./solutions/0274-h-index.js)|Medium|
275|[H-Index II](./solutions/0275-h-index-ii.js)|Medium|
+276|[Paint Fence](./solutions/0276-paint-fence.js)|Medium|
278|[First Bad Version](./solutions/0278-first-bad-version.js)|Medium|
279|[Perfect Squares](./solutions/0279-perfect-squares.js)|Medium|
282|[Expression Add Operators](./solutions/0282-expression-add-operators.js)|Hard|
diff --git a/solutions/0276-paint-fence.js b/solutions/0276-paint-fence.js
new file mode 100644
index 00000000..c19bb08a
--- /dev/null
+++ b/solutions/0276-paint-fence.js
@@ -0,0 +1,33 @@
+/**
+ * 276. Paint Fence
+ * https://leetcode.com/problems/paint-fence/
+ * Difficulty: Medium
+ *
+ * You are painting a fence of n posts with k different colors. You must paint the posts following
+ * these rules:
+ * - Every post must be painted exactly one color.
+ * - There cannot be three or more consecutive posts with the same color.
+ *
+ * Given the two integers n and k, return the number of ways you can paint the fence.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} k
+ * @return {number}
+ */
+var numWays = function(n, k) {
+ if (n === 1) return k;
+ if (n === 2) return k * k;
+
+ let same = k;
+ let diff = k * (k - 1);
+
+ for (let i = 3; i <= n; i++) {
+ const prevSame = same;
+ same = diff;
+ diff = (prevSame + diff) * (k - 1);
+ }
+
+ return same + diff;
+};
From e72809206acbc640a9ff5d66986d3730cd71831d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 11 Jun 2025 23:06:17 -0500
Subject: [PATCH 456/994] Add solution #277
---
README.md | 1 +
solutions/0277-find-the-celebrity.js | 53 ++++++++++++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/0277-find-the-celebrity.js
diff --git a/README.md b/README.md
index e390381f..561fcfb3 100644
--- a/README.md
+++ b/README.md
@@ -265,6 +265,7 @@
274|[H-Index](./solutions/0274-h-index.js)|Medium|
275|[H-Index II](./solutions/0275-h-index-ii.js)|Medium|
276|[Paint Fence](./solutions/0276-paint-fence.js)|Medium|
+277|[Find the Celebrity](./solutions/0277-find-the-celebrity.js)|Medium|
278|[First Bad Version](./solutions/0278-first-bad-version.js)|Medium|
279|[Perfect Squares](./solutions/0279-perfect-squares.js)|Medium|
282|[Expression Add Operators](./solutions/0282-expression-add-operators.js)|Hard|
diff --git a/solutions/0277-find-the-celebrity.js b/solutions/0277-find-the-celebrity.js
new file mode 100644
index 00000000..ad6f71a4
--- /dev/null
+++ b/solutions/0277-find-the-celebrity.js
@@ -0,0 +1,53 @@
+/**
+ * 277. Find the Celebrity
+ * https://leetcode.com/problems/find-the-celebrity/
+ * Difficulty: Medium
+ *
+ * Suppose you are at a party with n people labeled from 0 to n - 1 and among them, there may
+ * exist one celebrity. The definition of a celebrity is that all the other n - 1 people know
+ * the celebrity, but the celebrity does not know any of them.
+ *
+ * Now you want to find out who the celebrity is or verify that there is not one. You are only
+ * allowed to ask questions like: "Hi, A. Do you know B?" to get information about whether A
+ * knows B. You need to find out the celebrity (or verify there is not one) by asking as few
+ * questions as possible (in the asymptotic sense).
+ *
+ * You are given an integer n and a helper function bool knows(a, b) that tells you whether a
+ * knows b. Implement a function int findCelebrity(n). There will be exactly one celebrity if
+ * they are at the party.
+ *
+ * Return the celebrity's label if there is a celebrity at the party. If there is no celebrity,
+ * return -1.
+ *
+ * Note that the n x n 2D array graph given as input is not directly available to you, and
+ * instead only accessible through the helper function knows. graph[i][j] == 1 represents
+ * person i knows person j, wherease graph[i][j] == 0 represents person j does not know person i.
+ */
+
+/**
+ * @param {function} knows()
+ * @return {function}
+ */
+var solution = function(knows) {
+ /**
+ * @param {integer} n Total people
+ * @return {integer} The celebrity
+ */
+ return function(n) {
+ let candidate = 0;
+
+ for (let i = 1; i < n; i++) {
+ if (knows(candidate, i)) {
+ candidate = i;
+ }
+ }
+
+ for (let i = 0; i < n; i++) {
+ if (i !== candidate && (knows(candidate, i) || !knows(i, candidate))) {
+ return -1;
+ }
+ }
+
+ return candidate;
+ };
+};
From f7fbf71d8335a7fbc8ae8897bdb475308247482a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 11 Jun 2025 23:07:03 -0500
Subject: [PATCH 457/994] Add solution #280
---
README.md | 1 +
solutions/0280-wiggle-sort.js | 25 +++++++++++++++++++++++++
2 files changed, 26 insertions(+)
create mode 100644 solutions/0280-wiggle-sort.js
diff --git a/README.md b/README.md
index 561fcfb3..4e73effc 100644
--- a/README.md
+++ b/README.md
@@ -268,6 +268,7 @@
277|[Find the Celebrity](./solutions/0277-find-the-celebrity.js)|Medium|
278|[First Bad Version](./solutions/0278-first-bad-version.js)|Medium|
279|[Perfect Squares](./solutions/0279-perfect-squares.js)|Medium|
+280|[Wiggle Sort](./solutions/0280-wiggle-sort.js)|Medium|
282|[Expression Add Operators](./solutions/0282-expression-add-operators.js)|Hard|
283|[Move Zeroes](./solutions/0283-move-zeroes.js)|Easy|
284|[Peeking Iterator](./solutions/0284-peeking-iterator.js)|Medium|
diff --git a/solutions/0280-wiggle-sort.js b/solutions/0280-wiggle-sort.js
new file mode 100644
index 00000000..2f2aee91
--- /dev/null
+++ b/solutions/0280-wiggle-sort.js
@@ -0,0 +1,25 @@
+/**
+ * 280. Wiggle Sort
+ * https://leetcode.com/problems/wiggle-sort/
+ * Difficulty: Medium
+ *
+ * Given an integer array nums, reorder it such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
+ *
+ * You may assume the input array always has a valid answer.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {void} Do not return anything, modify nums in-place instead.
+ */
+var wiggleSort = function(nums) {
+ const n = nums.length;
+
+ for (let i = 0; i < n - 1; i++) {
+ if (i % 2 === 0 && nums[i] > nums[i + 1]) {
+ [nums[i], nums[i + 1]] = [nums[i + 1], nums[i]];
+ } else if (i % 2 === 1 && nums[i] < nums[i + 1]) {
+ [nums[i], nums[i + 1]] = [nums[i + 1], nums[i]];
+ }
+ }
+};
From a51bbdb6b2a9bb95f9a2bca25f1412a89d8bc62d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 11 Jun 2025 23:08:41 -0500
Subject: [PATCH 458/994] Add solution #281
---
README.md | 1 +
solutions/0281-zigzag-iterator.js | 49 +++++++++++++++++++++++++++++++
2 files changed, 50 insertions(+)
create mode 100644 solutions/0281-zigzag-iterator.js
diff --git a/README.md b/README.md
index 4e73effc..9bc63b4b 100644
--- a/README.md
+++ b/README.md
@@ -269,6 +269,7 @@
278|[First Bad Version](./solutions/0278-first-bad-version.js)|Medium|
279|[Perfect Squares](./solutions/0279-perfect-squares.js)|Medium|
280|[Wiggle Sort](./solutions/0280-wiggle-sort.js)|Medium|
+281|[Zigzag Iterator](./solutions/0281-zigzag-iterator.js)|Medium|
282|[Expression Add Operators](./solutions/0282-expression-add-operators.js)|Hard|
283|[Move Zeroes](./solutions/0283-move-zeroes.js)|Easy|
284|[Peeking Iterator](./solutions/0284-peeking-iterator.js)|Medium|
diff --git a/solutions/0281-zigzag-iterator.js b/solutions/0281-zigzag-iterator.js
new file mode 100644
index 00000000..ce71c1d5
--- /dev/null
+++ b/solutions/0281-zigzag-iterator.js
@@ -0,0 +1,49 @@
+/**
+ * 281. Zigzag Iterator
+ * https://leetcode.com/problems/zigzag-iterator/
+ * Difficulty: Medium
+ *
+ * Given two vectors of integers v1 and v2, implement an iterator to return their elements
+ * alternately.
+ *
+ * Implement the ZigzagIterator class:
+ * - ZigzagIterator(List v1, List v2) initializes the object with the two vectors
+ * v1 and v2.
+ * - boolean hasNext() returns true if the iterator still has elements, and false otherwise.
+ * - int next() returns the current element of the iterator and moves the iterator to the
+ * next element.
+ */
+
+/**
+ * @constructor
+ * @param {Integer[]} v1
+ * @param {Integer[]} v2
+ */
+var ZigzagIterator = function ZigzagIterator(v1, v2) {
+ this.queue = [];
+ if (v1.length) this.queue.push([v1, 0]);
+ if (v2.length) this.queue.push([v2, 0]);
+};
+
+/**
+ * @this ZigzagIterator
+ * @returns {boolean}
+ */
+ZigzagIterator.prototype.hasNext = function hasNext() {
+ return this.queue.length > 0;
+};
+
+/**
+ * @this ZigzagIterator
+ * @returns {integer}
+ */
+ZigzagIterator.prototype.next = function next() {
+ const [vector, index] = this.queue.shift();
+ const value = vector[index];
+
+ if (index + 1 < vector.length) {
+ this.queue.push([vector, index + 1]);
+ }
+
+ return value;
+};
From 34ffe1866abc7b7b22e981f6dab04f5431ff9792 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 11 Jun 2025 23:09:38 -0500
Subject: [PATCH 459/994] Add solution #285
---
README.md | 1 +
solutions/0285-inorder-successor-in-bst.js | 35 ++++++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/0285-inorder-successor-in-bst.js
diff --git a/README.md b/README.md
index 9bc63b4b..d7c0da0d 100644
--- a/README.md
+++ b/README.md
@@ -273,6 +273,7 @@
282|[Expression Add Operators](./solutions/0282-expression-add-operators.js)|Hard|
283|[Move Zeroes](./solutions/0283-move-zeroes.js)|Easy|
284|[Peeking Iterator](./solutions/0284-peeking-iterator.js)|Medium|
+285|[Inorder Successor in BST](./solutions/0285-inorder-successor-in-bst.js)|Medium|
287|[Find the Duplicate Number](./solutions/0287-find-the-duplicate-number.js)|Medium|
289|[Game of Life](./solutions/0289-game-of-life.js)|Medium|
290|[Word Pattern](./solutions/0290-word-pattern.js)|Easy|
diff --git a/solutions/0285-inorder-successor-in-bst.js b/solutions/0285-inorder-successor-in-bst.js
new file mode 100644
index 00000000..d589f0e4
--- /dev/null
+++ b/solutions/0285-inorder-successor-in-bst.js
@@ -0,0 +1,35 @@
+/**
+ * 285. Inorder Successor in BST
+ * https://leetcode.com/problems/inorder-successor-in-bst/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary search tree and a node p in it, return the in-order successor of
+ * that node in the BST. If the given node has no in-order successor in the tree, return null.
+ *
+ * The successor of a node p is the node with the smallest key greater than p.val.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val) {
+ * this.val = val;
+ * this.left = this.right = null;
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @param {TreeNode} p
+ * @return {TreeNode}
+ */
+var inorderSuccessor = function(root, p) {
+ let successor = null;
+ while (root) {
+ if (p.val < root.val) {
+ successor = root;
+ root = root.left;
+ } else {
+ root = root.right;
+ }
+ }
+ return successor;
+};
From 08324bf1c2d4da410809e23b1fe680fd4bafa16b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 11 Jun 2025 23:10:58 -0500
Subject: [PATCH 460/994] Add solution #286
---
README.md | 1 +
solutions/0286-walls-and-gates.js | 49 +++++++++++++++++++++++++++++++
2 files changed, 50 insertions(+)
create mode 100644 solutions/0286-walls-and-gates.js
diff --git a/README.md b/README.md
index d7c0da0d..24e55714 100644
--- a/README.md
+++ b/README.md
@@ -274,6 +274,7 @@
283|[Move Zeroes](./solutions/0283-move-zeroes.js)|Easy|
284|[Peeking Iterator](./solutions/0284-peeking-iterator.js)|Medium|
285|[Inorder Successor in BST](./solutions/0285-inorder-successor-in-bst.js)|Medium|
+286|[Walls and Gates](./solutions/0286-walls-and-gates.js)|Medium|
287|[Find the Duplicate Number](./solutions/0287-find-the-duplicate-number.js)|Medium|
289|[Game of Life](./solutions/0289-game-of-life.js)|Medium|
290|[Word Pattern](./solutions/0290-word-pattern.js)|Easy|
diff --git a/solutions/0286-walls-and-gates.js b/solutions/0286-walls-and-gates.js
new file mode 100644
index 00000000..13440941
--- /dev/null
+++ b/solutions/0286-walls-and-gates.js
@@ -0,0 +1,49 @@
+/**
+ * 286. Walls and Gates
+ * https://leetcode.com/problems/walls-and-gates/
+ * Difficulty: Medium
+ *
+ * You are given an m x n grid rooms initialized with these three possible values.
+ * - -1 A wall or an obstacle.
+ * - 0 A gate.
+ * - INF Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF
+ * as you may assume that the distance to a gate is less than 2147483647.
+ *
+ * Fill each empty room with the distance to its nearest gate. If it is impossible to reach
+ * a gate, it should be filled with INF.
+ */
+
+/**
+ * @param {number[][]} rooms
+ * @return {void} Do not return anything, modify rooms in-place instead.
+ */
+var wallsAndGates = function(rooms) {
+ const rows = rooms.length;
+ const cols = rooms[0].length;
+ const queue = [];
+ const INF = 2147483647;
+
+ for (let i = 0; i < rows; i++) {
+ for (let j = 0; j < cols; j++) {
+ if (rooms[i][j] === 0) {
+ queue.push([i, j]);
+ }
+ }
+ }
+
+ const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
+ while (queue.length) {
+ const [row, col] = queue.shift();
+
+ for (const [dr, dc] of directions) {
+ const newRow = row + dr;
+ const newCol = col + dc;
+
+ if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols
+ && rooms[newRow][newCol] === INF) {
+ rooms[newRow][newCol] = rooms[row][col] + 1;
+ queue.push([newRow, newCol]);
+ }
+ }
+ }
+};
From 74c38195d589c710c46fb796b139ff56be1d24ed Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 11 Jun 2025 23:23:56 -0500
Subject: [PATCH 461/994] Add solution #288
---
README.md | 1 +
solutions/0288-unique-word-abbreviation.js | 57 ++++++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/0288-unique-word-abbreviation.js
diff --git a/README.md b/README.md
index 24e55714..4ae8e33d 100644
--- a/README.md
+++ b/README.md
@@ -276,6 +276,7 @@
285|[Inorder Successor in BST](./solutions/0285-inorder-successor-in-bst.js)|Medium|
286|[Walls and Gates](./solutions/0286-walls-and-gates.js)|Medium|
287|[Find the Duplicate Number](./solutions/0287-find-the-duplicate-number.js)|Medium|
+288|[Unique Word Abbreviation](./solutions/0288-unique-word-abbreviation.js)|Medium|
289|[Game of Life](./solutions/0289-game-of-life.js)|Medium|
290|[Word Pattern](./solutions/0290-word-pattern.js)|Easy|
292|[Nim Game](./solutions/0292-nim-game.js)|Easy|
diff --git a/solutions/0288-unique-word-abbreviation.js b/solutions/0288-unique-word-abbreviation.js
new file mode 100644
index 00000000..886f3b29
--- /dev/null
+++ b/solutions/0288-unique-word-abbreviation.js
@@ -0,0 +1,57 @@
+/**
+ * 288. Unique Word Abbreviation
+ * https://leetcode.com/problems/unique-word-abbreviation/
+ * Difficulty: Medium
+ *
+ * The abbreviation of a word is a concatenation of its first letter, the number of characters
+ * between the first and last letter, and its last letter. If a word has only two characters,
+ * then it is an abbreviation of itself.
+ *
+ * For example:
+ * - dog --> d1g because there is one letter between the first letter 'd' and the last letter 'g'.
+ * - internationalization --> i18n because there are 18 letters between the first letter 'i' and
+ * the last letter 'n'.
+ * - it --> it because any word with only two characters is an abbreviation of itself.
+ *
+ * Implement the ValidWordAbbr class:
+ * - ValidWordAbbr(String[] dictionary) Initializes the object with a dictionary of words.
+ * - boolean isUnique(string word) Returns true if either of the following conditions are met
+ * (otherwise returns false):
+ * - There is no word in dictionary whose abbreviation is equal to word's abbreviation.
+ * - For any word in dictionary whose abbreviation is equal to word's abbreviation, that word
+ * and word are the same.
+ */
+
+/**
+ * @param {string[]} dictionary
+ */
+var ValidWordAbbr = function(dictionary) {
+ this.abbrMap = new Map();
+
+ for (const word of dictionary) {
+ const abbr = this.getAbbreviation(word);
+ if (!this.abbrMap.has(abbr)) {
+ this.abbrMap.set(abbr, new Set());
+ }
+ this.abbrMap.get(abbr).add(word);
+ }
+};
+
+/**
+ * @param {string} word
+ * @return {string}
+ */
+ValidWordAbbr.prototype.getAbbreviation = function(word) {
+ if (word.length <= 2) return word;
+ return word[0] + (word.length - 2) + word[word.length - 1];
+};
+
+/**
+ * @param {string} word
+ * @return {boolean}
+ */
+ValidWordAbbr.prototype.isUnique = function(word) {
+ const abbr = this.getAbbreviation(word);
+ const words = this.abbrMap.get(abbr);
+ return !words || (words.size === 1 && words.has(word));
+};
From da456a357706381acb70da6589f541ea30484485 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 11 Jun 2025 23:32:39 -0500
Subject: [PATCH 462/994] Add solution #291
---
README.md | 1 +
solutions/0291-word-pattern-ii.js | 51 +++++++++++++++++++++++++++++++
2 files changed, 52 insertions(+)
create mode 100644 solutions/0291-word-pattern-ii.js
diff --git a/README.md b/README.md
index 4ae8e33d..c2040aa6 100644
--- a/README.md
+++ b/README.md
@@ -279,6 +279,7 @@
288|[Unique Word Abbreviation](./solutions/0288-unique-word-abbreviation.js)|Medium|
289|[Game of Life](./solutions/0289-game-of-life.js)|Medium|
290|[Word Pattern](./solutions/0290-word-pattern.js)|Easy|
+291|[Word Pattern II](./solutions/0291-word-pattern-ii.js)|Medium|
292|[Nim Game](./solutions/0292-nim-game.js)|Easy|
295|[Find Median from Data Stream](./solutions/0295-find-median-from-data-stream.js)|Hard|
297|[Serialize and Deserialize Binary Tree](./solutions/0297-serialize-and-deserialize-binary-tree.js)|Hard|
diff --git a/solutions/0291-word-pattern-ii.js b/solutions/0291-word-pattern-ii.js
new file mode 100644
index 00000000..83e7eca5
--- /dev/null
+++ b/solutions/0291-word-pattern-ii.js
@@ -0,0 +1,51 @@
+/**
+ * 291. Word Pattern II
+ * https://leetcode.com/problems/word-pattern-ii/
+ * Difficulty: Medium
+ *
+ * Given a pattern and a string s, return true if s matches the pattern.
+ *
+ * A string s matches a pattern if there is some bijective mapping of single characters to
+ * non-empty strings such that if each character in pattern is replaced by the string it
+ * maps to, then the resulting string is s. A bijective mapping means that no two characters
+ * map to the same string, and no character maps to two different strings.
+ */
+
+/**
+ * @param {string} pattern
+ * @param {string} s
+ * @return {boolean}
+ */
+var wordPatternMatch = function(pattern, s) {
+ const charToWord = new Map();
+ const usedWords = new Set();
+
+ return backtrack(0, 0);
+
+ function backtrack(patIndex, strIndex) {
+ if (patIndex === pattern.length && strIndex === s.length) return true;
+ if (patIndex >= pattern.length || strIndex >= s.length) return false;
+
+ const char = pattern[patIndex];
+ if (charToWord.has(char)) {
+ const word = charToWord.get(char);
+ if (!s.startsWith(word, strIndex)) return false;
+ return backtrack(patIndex + 1, strIndex + word.length);
+ }
+
+ for (let i = strIndex + 1; i <= s.length; i++) {
+ const word = s.slice(strIndex, i);
+ if (usedWords.has(word)) continue;
+
+ charToWord.set(char, word);
+ usedWords.add(word);
+
+ if (backtrack(patIndex + 1, strIndex + word.length)) return true;
+
+ charToWord.delete(char);
+ usedWords.delete(word);
+ }
+
+ return false;
+ }
+};
From 218a9b7bbd0f516842e2d413bc97536e38ca359f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 11 Jun 2025 23:33:34 -0500
Subject: [PATCH 463/994] Add solution #293
---
README.md | 1 +
solutions/0293-flip-game.js | 32 ++++++++++++++++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/0293-flip-game.js
diff --git a/README.md b/README.md
index c2040aa6..7a374230 100644
--- a/README.md
+++ b/README.md
@@ -281,6 +281,7 @@
290|[Word Pattern](./solutions/0290-word-pattern.js)|Easy|
291|[Word Pattern II](./solutions/0291-word-pattern-ii.js)|Medium|
292|[Nim Game](./solutions/0292-nim-game.js)|Easy|
+293|[Flip Game](./solutions/0293-flip-game.js)|Easy|
295|[Find Median from Data Stream](./solutions/0295-find-median-from-data-stream.js)|Hard|
297|[Serialize and Deserialize Binary Tree](./solutions/0297-serialize-and-deserialize-binary-tree.js)|Hard|
299|[Bulls and Cows](./solutions/0299-bulls-and-cows.js)|Medium|
diff --git a/solutions/0293-flip-game.js b/solutions/0293-flip-game.js
new file mode 100644
index 00000000..8fe0485a
--- /dev/null
+++ b/solutions/0293-flip-game.js
@@ -0,0 +1,32 @@
+/**
+ * 293. Flip Game
+ * https://leetcode.com/problems/flip-game/
+ * Difficulty: Easy
+ *
+ * You are playing a Flip Game with your friend.
+ *
+ * You are given a string currentState that contains only '+' and '-'. You and your friend take
+ * turns to flip two consecutive "++" into "--". The game ends when a person can no longer make
+ * a move, and therefore the other person will be the winner.
+ *
+ * Return all possible states of the string currentState after one valid move. You may return
+ * the answer in any order. If there is no valid move, return an empty list [].
+ */
+
+/**
+ * @param {string} currentState
+ * @return {string[]}
+ */
+var generatePossibleNextMoves = function(currentState) {
+ const results = [];
+
+ for (let i = 0; i < currentState.length - 1; i++) {
+ if (currentState[i] === '+' && currentState[i + 1] === '+') {
+ results.push(
+ currentState.slice(0, i) + '--' + currentState.slice(i + 2)
+ );
+ }
+ }
+
+ return results;
+};
From 23129b164f933a04725437fc69325b47b5bf262b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 11 Jun 2025 23:34:41 -0500
Subject: [PATCH 464/994] Add solution #294
---
README.md | 1 +
solutions/0294-flip-game-ii.js | 40 ++++++++++++++++++++++++++++++++++
2 files changed, 41 insertions(+)
create mode 100644 solutions/0294-flip-game-ii.js
diff --git a/README.md b/README.md
index 7a374230..ac0c37d0 100644
--- a/README.md
+++ b/README.md
@@ -282,6 +282,7 @@
291|[Word Pattern II](./solutions/0291-word-pattern-ii.js)|Medium|
292|[Nim Game](./solutions/0292-nim-game.js)|Easy|
293|[Flip Game](./solutions/0293-flip-game.js)|Easy|
+294|[Flip Game II](./solutions/0294-flip-game-ii.js)|Medium|
295|[Find Median from Data Stream](./solutions/0295-find-median-from-data-stream.js)|Hard|
297|[Serialize and Deserialize Binary Tree](./solutions/0297-serialize-and-deserialize-binary-tree.js)|Hard|
299|[Bulls and Cows](./solutions/0299-bulls-and-cows.js)|Medium|
diff --git a/solutions/0294-flip-game-ii.js b/solutions/0294-flip-game-ii.js
new file mode 100644
index 00000000..d4baf073
--- /dev/null
+++ b/solutions/0294-flip-game-ii.js
@@ -0,0 +1,40 @@
+/**
+ * 294. Flip Game II
+ * https://leetcode.com/problems/flip-game-ii/
+ * Difficulty: Medium
+ *
+ * You are playing a Flip Game with your friend.
+ *
+ * You are given a string currentState that contains only '+' and '-'. You and your friend take
+ * turns to flip two consecutive "++" into "--". The game ends when a person can no longer make
+ * a move, and therefore the other person will be the winner.
+ *
+ * Return true if the starting player can guarantee a win, and false otherwise.
+ */
+
+/**
+ * @param {string} currentState
+ * @return {boolean}
+ */
+var canWin = function(currentState) {
+ const map = new Map();
+
+ return canWinFrom(currentState);
+
+ function canWinFrom(state) {
+ if (map.has(state)) return map.get(state);
+
+ for (let i = 0; i < state.length - 1; i++) {
+ if (state[i] === '+' && state[i + 1] === '+') {
+ const nextState = state.slice(0, i) + '--' + state.slice(i + 2);
+ if (!canWinFrom(nextState)) {
+ map.set(state, true);
+ return true;
+ }
+ }
+ }
+
+ map.set(state, false);
+ return false;
+ }
+};
From 275f5bb2394922408963e908704f7bee141cba6e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 11 Jun 2025 23:36:28 -0500
Subject: [PATCH 465/994] Add solution #296
---
README.md | 3 +-
solutions/0296-best-meeting-point.js | 42 ++++++++++++++++++++++++++++
2 files changed, 44 insertions(+), 1 deletion(-)
create mode 100644 solutions/0296-best-meeting-point.js
diff --git a/README.md b/README.md
index ac0c37d0..ff981607 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 2,000+ LeetCode solutions in JavaScript
+# 2,250+ LeetCode solutions in JavaScript
[https://leetcodejavascript.com](https://leetcodejavascript.com)
@@ -284,6 +284,7 @@
293|[Flip Game](./solutions/0293-flip-game.js)|Easy|
294|[Flip Game II](./solutions/0294-flip-game-ii.js)|Medium|
295|[Find Median from Data Stream](./solutions/0295-find-median-from-data-stream.js)|Hard|
+296|[Best Meeting Point](./solutions/0296-best-meeting-point.js)|Hard|
297|[Serialize and Deserialize Binary Tree](./solutions/0297-serialize-and-deserialize-binary-tree.js)|Hard|
299|[Bulls and Cows](./solutions/0299-bulls-and-cows.js)|Medium|
300|[Longest Increasing Subsequence](./solutions/0300-longest-increasing-subsequence.js)|Medium|
diff --git a/solutions/0296-best-meeting-point.js b/solutions/0296-best-meeting-point.js
new file mode 100644
index 00000000..d31e660b
--- /dev/null
+++ b/solutions/0296-best-meeting-point.js
@@ -0,0 +1,42 @@
+/**
+ * 296. Best Meeting Point
+ * https://leetcode.com/problems/best-meeting-point/
+ * Difficulty: Hard
+ *
+ * Given an m x n binary grid grid where each 1 marks the home of one friend, return the minimal
+ * total travel distance.
+ *
+ * The total travel distance is the sum of the distances between the houses of the friends and
+ * the meeting point.
+ *
+ * The distance is calculated using Manhattan Distance, where
+ * distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var minTotalDistance = function(grid) {
+ const rows = [];
+ const cols = [];
+
+ for (let i = 0; i < grid.length; i++) {
+ for (let j = 0; j < grid[0].length; j++) {
+ if (grid[i][j] === 1) {
+ rows.push(i);
+ cols.push(j);
+ }
+ }
+ }
+
+ rows.sort((a, b) => a - b);
+ cols.sort((a, b) => a - b);
+
+ let result = 0;
+ for (let i = 0; i < rows.length; i++) {
+ result += Math.abs(rows[i] - rows[Math.floor(rows.length / 2)]);
+ result += Math.abs(cols[i] - cols[Math.floor(cols.length / 2)]);
+ }
+ return result;
+};
From dca76338e6adb3735b1099c2d6707b9bd50ed8bb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 12 Jun 2025 23:42:37 -0500
Subject: [PATCH 466/994] Add solution #298
---
README.md | 1 +
...inary-tree-longest-consecutive-sequence.js | 40 +++++++++++++++++++
2 files changed, 41 insertions(+)
create mode 100644 solutions/0298-binary-tree-longest-consecutive-sequence.js
diff --git a/README.md b/README.md
index ff981607..9282f49f 100644
--- a/README.md
+++ b/README.md
@@ -286,6 +286,7 @@
295|[Find Median from Data Stream](./solutions/0295-find-median-from-data-stream.js)|Hard|
296|[Best Meeting Point](./solutions/0296-best-meeting-point.js)|Hard|
297|[Serialize and Deserialize Binary Tree](./solutions/0297-serialize-and-deserialize-binary-tree.js)|Hard|
+298|[Binary Tree Longest Consecutive Sequence](./solutions/0298-binary-tree-longest-consecutive-sequence.js)|Medium|
299|[Bulls and Cows](./solutions/0299-bulls-and-cows.js)|Medium|
300|[Longest Increasing Subsequence](./solutions/0300-longest-increasing-subsequence.js)|Medium|
301|[Remove Invalid Parentheses](./solutions/0301-remove-invalid-parentheses.js)|Hard|
diff --git a/solutions/0298-binary-tree-longest-consecutive-sequence.js b/solutions/0298-binary-tree-longest-consecutive-sequence.js
new file mode 100644
index 00000000..642f88bc
--- /dev/null
+++ b/solutions/0298-binary-tree-longest-consecutive-sequence.js
@@ -0,0 +1,40 @@
+/**
+ * 298. Binary Tree Longest Consecutive Sequence
+ * https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree, return the length of the longest consecutive sequence path.
+ *
+ * A consecutive sequence path is a path where the values increase by one along the path.
+ *
+ * Note that the path can start at any node in the tree, and you cannot go from a node to its
+ * parent in the path.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @return {number}
+ */
+var longestConsecutive = function(root) {
+ let result = 0;
+ traverse(root, root.val - 1, 0);
+ return result;
+
+ function traverse(node, parentValue, length) {
+ if (!node) return;
+
+ const currentLength = parentValue + 1 === node.val ? length + 1 : 1;
+ result = Math.max(result, currentLength);
+
+ traverse(node.left, node.val, currentLength);
+ traverse(node.right, node.val, currentLength);
+ }
+};
From 38ea889d3822b32ea28ab47a48ad30904171c269 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 12 Jun 2025 23:47:22 -0500
Subject: [PATCH 467/994] Add solution #302
---
README.md | 1 +
...allest-rectangle-enclosing-black-pixels.js | 63 +++++++++++++++++++
2 files changed, 64 insertions(+)
create mode 100644 solutions/0302-smallest-rectangle-enclosing-black-pixels.js
diff --git a/README.md b/README.md
index 9282f49f..f1031f88 100644
--- a/README.md
+++ b/README.md
@@ -290,6 +290,7 @@
299|[Bulls and Cows](./solutions/0299-bulls-and-cows.js)|Medium|
300|[Longest Increasing Subsequence](./solutions/0300-longest-increasing-subsequence.js)|Medium|
301|[Remove Invalid Parentheses](./solutions/0301-remove-invalid-parentheses.js)|Hard|
+302|[Smallest Rectangle Enclosing Black Pixels](./solutions/0302-smallest-rectangle-enclosing-black-pixels.js)|Hard|
303|[Range Sum Query - Immutable](./solutions/0303-range-sum-query-immutable.js)|Easy|
304|[Range Sum Query 2D - Immutable](./solutions/0304-range-sum-query-2d-immutable.js)|Medium|
306|[Additive Number](./solutions/0306-additive-number.js)|Medium|
diff --git a/solutions/0302-smallest-rectangle-enclosing-black-pixels.js b/solutions/0302-smallest-rectangle-enclosing-black-pixels.js
new file mode 100644
index 00000000..76de7a6e
--- /dev/null
+++ b/solutions/0302-smallest-rectangle-enclosing-black-pixels.js
@@ -0,0 +1,63 @@
+/**
+ * 302. Smallest Rectangle Enclosing Black Pixels
+ * https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/
+ * Difficulty: Hard
+ *
+ * You are given an m x n binary matrix image where 0 represents a white pixel and 1 represents
+ * a black pixel.
+ *
+ * The black pixels are connected (i.e., there is only one black region). Pixels are connected
+ * horizontally and vertically.
+ *
+ * Given two integers x and y that represents the location of one of the black pixels, return
+ * the area of the smallest (axis-aligned) rectangle that encloses all black pixels.
+ *
+ * You must write an algorithm with less than O(mn) runtime complexity
+ */
+
+/**
+ * @param {character[][]} image
+ * @param {number} x
+ * @param {number} y
+ * @return {number}
+ */
+var minArea = function(image, x, y) {
+ const rows = image.length;
+ const cols = image[0].length;
+ const top = binarySearch(0, x, true, true);
+ const bottom = binarySearch(x, rows - 1, true, false);
+ const left = binarySearch(0, y, false, true);
+ const right = binarySearch(y, cols - 1, false, false);
+
+ return (bottom - top + 1) * (right - left + 1);
+
+ function binarySearch(start, end, isRow, isMin) {
+ let result = isMin ? end : start;
+ while (start <= end) {
+ const mid = Math.floor((start + end) / 2);
+ let hasBlack = false;
+ for (let i = 0; i < (isRow ? cols : rows); i++) {
+ const pixel = isRow ? image[mid][i] : image[i][mid];
+ if (pixel === '1') {
+ hasBlack = true;
+ break;
+ }
+ }
+ if (hasBlack) {
+ result = mid;
+ if (isMin) {
+ end = mid - 1;
+ } else {
+ start = mid + 1;
+ }
+ } else {
+ if (isMin) {
+ start = mid + 1;
+ } else {
+ end = mid - 1;
+ }
+ }
+ }
+ return result;
+ }
+};
From 8a8f82a5b9f32754126e4ebfb16a2d82bd26e2a0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 12 Jun 2025 23:48:44 -0500
Subject: [PATCH 468/994] Add solution #305
---
README.md | 1 +
solutions/0305-number-of-islands-ii.js | 86 ++++++++++++++++++++++++++
2 files changed, 87 insertions(+)
create mode 100644 solutions/0305-number-of-islands-ii.js
diff --git a/README.md b/README.md
index f1031f88..1688d37c 100644
--- a/README.md
+++ b/README.md
@@ -293,6 +293,7 @@
302|[Smallest Rectangle Enclosing Black Pixels](./solutions/0302-smallest-rectangle-enclosing-black-pixels.js)|Hard|
303|[Range Sum Query - Immutable](./solutions/0303-range-sum-query-immutable.js)|Easy|
304|[Range Sum Query 2D - Immutable](./solutions/0304-range-sum-query-2d-immutable.js)|Medium|
+305|[Number of Islands II](./solutions/0305-number-of-islands-ii.js)|Hard|
306|[Additive Number](./solutions/0306-additive-number.js)|Medium|
307|[Range Sum Query - Mutable](./solutions/0307-range-sum-query-mutable.js)|Medium|
309|[Best Time to Buy and Sell Stock with Cooldown](./solutions/0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium|
diff --git a/solutions/0305-number-of-islands-ii.js b/solutions/0305-number-of-islands-ii.js
new file mode 100644
index 00000000..e5f5cd28
--- /dev/null
+++ b/solutions/0305-number-of-islands-ii.js
@@ -0,0 +1,86 @@
+/**
+ * 305. Number of Islands II
+ * https://leetcode.com/problems/number-of-islands-ii/
+ * Difficulty: Hard
+ *
+ * You are given an empty 2D binary grid grid of size m x n. The grid represents a map where 0's
+ * represent water and 1's represent land. Initially, all the cells of grid are water cells
+ * (i.e., all the cells are 0's).
+ *
+ * We may perform an add land operation which turns the water at position into a land. You are
+ * given an array positions where positions[i] = [ri, ci] is the position (ri, ci) at which we
+ * should operate the ith operation.
+ *
+ * Return an array of integers answer where answer[i] is the number of islands after turning
+ * the cell (ri, ci) into a land.
+ *
+ * An island is surrounded by water and is formed by connecting adjacent lands horizontally
+ * or vertically. You may assume all four edges of the grid are all surrounded by water.
+ */
+
+/**
+ * @param {number} m
+ * @param {number} n
+ * @param {number[][]} positions
+ * @return {number[]}
+ */
+var numIslands2 = function(m, n, positions) {
+ const parent = new Map();
+ const rank = new Map();
+ const result = [];
+ const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
+ let islandCount = 0;
+
+ for (const [row, col] of positions) {
+ const current = row * n + col;
+ if (parent.has(current)) {
+ result.push(islandCount);
+ continue;
+ }
+ islandCount++;
+ parent.set(current, current);
+ rank.set(current, 0);
+
+ for (const [dr, dc] of directions) {
+ const newRow = row + dr;
+ const newCol = col + dc;
+ if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n) {
+ const neighbor = newRow * n + newCol;
+ if (parent.has(neighbor)) {
+ union(current, neighbor);
+ }
+ }
+ }
+ result.push(islandCount);
+ }
+
+ return result;
+
+ function find(node) {
+ if (!parent.has(node)) {
+ parent.set(node, node);
+ rank.set(node, 0);
+ }
+ if (parent.get(node) !== node) {
+ parent.set(node, find(parent.get(node)));
+ }
+ return parent.get(node);
+ }
+
+ function union(node1, node2) {
+ const root1 = find(node1);
+ const root2 = find(node2);
+ if (root1 === root2) return;
+ const rank1 = rank.get(root1);
+ const rank2 = rank.get(root2);
+ if (rank1 < rank2) {
+ parent.set(root1, root2);
+ } else if (rank1 > rank2) {
+ parent.set(root2, root1);
+ } else {
+ parent.set(root2, root1);
+ rank.set(root1, rank1 + 1);
+ }
+ islandCount--;
+ }
+};
From 8bbdfc7556f325548f84578185abcda7a8b928e8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 12 Jun 2025 23:51:12 -0500
Subject: [PATCH 469/994] Add solution #308
---
README.md | 1 +
solutions/0308-range-sum-query-2d-mutable.js | 94 ++++++++++++++++++++
2 files changed, 95 insertions(+)
create mode 100644 solutions/0308-range-sum-query-2d-mutable.js
diff --git a/README.md b/README.md
index 1688d37c..044c22a2 100644
--- a/README.md
+++ b/README.md
@@ -296,6 +296,7 @@
305|[Number of Islands II](./solutions/0305-number-of-islands-ii.js)|Hard|
306|[Additive Number](./solutions/0306-additive-number.js)|Medium|
307|[Range Sum Query - Mutable](./solutions/0307-range-sum-query-mutable.js)|Medium|
+308|[Range Sum Query 2D - Mutable](./solutions/0308-range-sum-query-2d-mutable.js)|Medium|
309|[Best Time to Buy and Sell Stock with Cooldown](./solutions/0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium|
310|[Minimum Height Trees](./solutions/0310-minimum-height-trees.js)|Medium|
312|[Burst Balloons](./solutions/0312-burst-balloons.js)|Hard|
diff --git a/solutions/0308-range-sum-query-2d-mutable.js b/solutions/0308-range-sum-query-2d-mutable.js
new file mode 100644
index 00000000..670caca6
--- /dev/null
+++ b/solutions/0308-range-sum-query-2d-mutable.js
@@ -0,0 +1,94 @@
+/**
+ * 308. Range Sum Query 2D - Mutable
+ * https://leetcode.com/problems/range-sum-query-2d-mutable/
+ * Difficulty: Medium
+ *
+ * Given a 2D matrix matrix, handle multiple queries of the following types:
+ * 1. Update the value of a cell in matrix.
+ * 2. Calculate the sum of the elements of matrix inside the rectangle defined by its upper left
+ * corner (row1, col1) and lower right corner (row2, col2).
+ *
+ * Implement the NumMatrix class:
+ * - NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix.
+ * - void update(int row, int col, int val) Updates the value of matrix[row][col] to be val.
+ * - int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of
+ * matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right
+ * corner (row2, col2).
+ */
+
+/**
+ * @param {number[][]} matrix
+ */
+var NumMatrix = function(matrix) {
+ this.rows = matrix.length;
+ this.cols = matrix[0].length;
+ this.matrix = matrix;
+ this.tree = new Array(this.rows + 1).fill().map(() => new Array(this.cols + 1).fill(0));
+
+ for (let i = 0; i < this.rows; i++) {
+ for (let j = 0; j < this.cols; j++) {
+ this.updateTree(i + 1, j + 1, matrix[i][j]);
+ }
+ }
+};
+
+/**
+ * @param {number} row
+ * @param {number} col
+ * @param {number} val
+ * @return {void}
+ */
+NumMatrix.prototype.updateTree = function(row, col, val) {
+ while (row <= this.rows) {
+ let c = col;
+ while (c <= this.cols) {
+ this.tree[row][c] += val;
+ c += c & (-c);
+ }
+ row += row & (-row);
+ }
+};
+
+/**
+ * @param {number} row
+ * @param {number} col
+ * @return {number}
+ */
+NumMatrix.prototype.getSum = function(row, col) {
+ let sum = 0;
+ while (row > 0) {
+ let c = col;
+ while (c > 0) {
+ sum += this.tree[row][c];
+ c -= c & (-c);
+ }
+ row -= row & (-row);
+ }
+ return sum;
+};
+
+/**
+ * @param {number} row
+ * @param {number} col
+ * @param {number} val
+ * @return {void}
+ */
+NumMatrix.prototype.update = function(row, col, val) {
+ const diff = val - this.matrix[row][col];
+ this.matrix[row][col] = val;
+ this.updateTree(row + 1, col + 1, diff);
+};
+
+/**
+ * @param {number} row1
+ * @param {number} col1
+ * @param {number} row2
+ * @param {number} col2
+ * @return {number}
+ */
+NumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) {
+ return this.getSum(row2 + 1, col2 + 1)
+ - this.getSum(row2 + 1, col1)
+ - this.getSum(row1, col2 + 1)
+ + this.getSum(row1, col1);
+};
From 18afb13a514f88e6c3ea0b7258eab6323cb83d70 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 12 Jun 2025 23:52:00 -0500
Subject: [PATCH 470/994] Add solution #311
---
README.md | 1 +
.../0311-sparse-matrix-multiplication.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/0311-sparse-matrix-multiplication.js
diff --git a/README.md b/README.md
index 044c22a2..6ee4efae 100644
--- a/README.md
+++ b/README.md
@@ -299,6 +299,7 @@
308|[Range Sum Query 2D - Mutable](./solutions/0308-range-sum-query-2d-mutable.js)|Medium|
309|[Best Time to Buy and Sell Stock with Cooldown](./solutions/0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium|
310|[Minimum Height Trees](./solutions/0310-minimum-height-trees.js)|Medium|
+311|[Sparse Matrix Multiplication](./solutions/0311-sparse-matrix-multiplication.js)|Medium|
312|[Burst Balloons](./solutions/0312-burst-balloons.js)|Hard|
313|[Super Ugly Number](./solutions/0313-super-ugly-number.js)|Medium|
315|[Count of Smaller Numbers After Self](./solutions/0315-count-of-smaller-numbers-after-self.js)|Hard|
diff --git a/solutions/0311-sparse-matrix-multiplication.js b/solutions/0311-sparse-matrix-multiplication.js
new file mode 100644
index 00000000..7a69dca2
--- /dev/null
+++ b/solutions/0311-sparse-matrix-multiplication.js
@@ -0,0 +1,34 @@
+/**
+ * 311. Sparse Matrix Multiplication
+ * https://leetcode.com/problems/sparse-matrix-multiplication/
+ * Difficulty: Medium
+ *
+ * Given two sparse matrices mat1 of size m x k and mat2 of size k x n, return the result of
+ * mat1 x mat2. You may assume that multiplication is always possible.
+ */
+
+/**
+ * @param {number[][]} mat1
+ * @param {number[][]} mat2
+ * @return {number[][]}
+ */
+var multiply = function(mat1, mat2) {
+ const m = mat1.length;
+ const k = mat1[0].length;
+ const n = mat2[0].length;
+ const result = new Array(m).fill().map(() => new Array(n).fill(0));
+
+ for (let i = 0; i < m; i++) {
+ for (let j = 0; j < k; j++) {
+ if (mat1[i][j] !== 0) {
+ for (let l = 0; l < n; l++) {
+ if (mat2[j][l] !== 0) {
+ result[i][l] += mat1[i][j] * mat2[j][l];
+ }
+ }
+ }
+ }
+ }
+
+ return result;
+};
From 48830a592228646f8a9852a32ac54d07a9bf6fe2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 13 Jun 2025 18:40:57 -0500
Subject: [PATCH 471/994] Add solution #314
---
README.md | 1 +
...14-binary-tree-vertical-order-traversal.js | 53 +++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/0314-binary-tree-vertical-order-traversal.js
diff --git a/README.md b/README.md
index 6ee4efae..122c5057 100644
--- a/README.md
+++ b/README.md
@@ -302,6 +302,7 @@
311|[Sparse Matrix Multiplication](./solutions/0311-sparse-matrix-multiplication.js)|Medium|
312|[Burst Balloons](./solutions/0312-burst-balloons.js)|Hard|
313|[Super Ugly Number](./solutions/0313-super-ugly-number.js)|Medium|
+314|[Binary Tree Vertical Order Traversal](./solutions/0314-binary-tree-vertical-order-traversal.js)|Medium|
315|[Count of Smaller Numbers After Self](./solutions/0315-count-of-smaller-numbers-after-self.js)|Hard|
316|[Remove Duplicate Letters](./solutions/0316-remove-duplicate-letters.js)|Medium|
318|[Maximum Product of Word Lengths](./solutions/0318-maximum-product-of-word-lengths.js)|Medium|
diff --git a/solutions/0314-binary-tree-vertical-order-traversal.js b/solutions/0314-binary-tree-vertical-order-traversal.js
new file mode 100644
index 00000000..e93b1b43
--- /dev/null
+++ b/solutions/0314-binary-tree-vertical-order-traversal.js
@@ -0,0 +1,53 @@
+/**
+ * 314. Binary Tree Vertical Order Traversal
+ * https://leetcode.com/problems/binary-tree-vertical-order-traversal/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree, return the vertical order traversal of its nodes' values.
+ * (i.e., from top to bottom, column by column).
+ *
+ * If two nodes are in the same row and column, the order should be from left to right.
+ */
+
+/**
+ * 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 verticalOrder = function(root) {
+ if (!root) return [];
+
+ const columns = new Map();
+ const queue = [[root, 0]];
+ let minCol = 0;
+ let maxCol = 0;
+
+ while (queue.length) {
+ const [node, col] = queue.shift();
+ if (!columns.has(col)) columns.set(col, []);
+ columns.get(col).push(node.val);
+
+ if (node.left) {
+ queue.push([node.left, col - 1]);
+ minCol = Math.min(minCol, col - 1);
+ }
+ if (node.right) {
+ queue.push([node.right, col + 1]);
+ maxCol = Math.max(maxCol, col + 1);
+ }
+ }
+
+ const result = [];
+ for (let col = minCol; col <= maxCol; col++) {
+ if (columns.has(col)) result.push(columns.get(col));
+ }
+
+ return result;
+};
From b91a6752082f2b2a164e5b146d6b11d66f286d6e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 13 Jun 2025 18:42:57 -0500
Subject: [PATCH 472/994] Add solution #317
---
README.md | 1 +
...17-shortest-distance-from-all-buildings.js | 80 +++++++++++++++++++
2 files changed, 81 insertions(+)
create mode 100644 solutions/0317-shortest-distance-from-all-buildings.js
diff --git a/README.md b/README.md
index 122c5057..9988dcab 100644
--- a/README.md
+++ b/README.md
@@ -305,6 +305,7 @@
314|[Binary Tree Vertical Order Traversal](./solutions/0314-binary-tree-vertical-order-traversal.js)|Medium|
315|[Count of Smaller Numbers After Self](./solutions/0315-count-of-smaller-numbers-after-self.js)|Hard|
316|[Remove Duplicate Letters](./solutions/0316-remove-duplicate-letters.js)|Medium|
+317|[Shortest Distance from All Buildings](./solutions/0317-shortest-distance-from-all-buildings.js)|Hard|
318|[Maximum Product of Word Lengths](./solutions/0318-maximum-product-of-word-lengths.js)|Medium|
319|[Bulb Switcher](./solutions/0319-bulb-switcher.js)|Medium|
321|[Create Maximum Number](./solutions/0321-create-maximum-number.js)|Hard|
diff --git a/solutions/0317-shortest-distance-from-all-buildings.js b/solutions/0317-shortest-distance-from-all-buildings.js
new file mode 100644
index 00000000..f699b1b0
--- /dev/null
+++ b/solutions/0317-shortest-distance-from-all-buildings.js
@@ -0,0 +1,80 @@
+/**
+ * 317. Shortest Distance from All Buildings
+ * https://leetcode.com/problems/shortest-distance-from-all-buildings/
+ * Difficulty: Hard
+ *
+ * You are given an m x n grid grid of values 0, 1, or 2, where:
+ * - each 0 marks an empty land that you can pass by freely,
+ * - each 1 marks a building that you cannot pass through, and
+ * - each 2 marks an obstacle that you cannot pass through.
+ *
+ * You want to build a house on an empty land that reaches all buildings in the shortest total
+ * travel distance. You can only move up, down, left, and right.
+ *
+ * Return the shortest travel distance for such a house. If it is not possible to build such
+ * a house according to the above rules, return -1.
+ *
+ * The total travel distance is the sum of the distances between the houses of the friends and
+ * the meeting point.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var shortestDistance = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const distances = new Array(rows).fill().map(() => new Array(cols).fill(0));
+ const reachCounts = new Array(rows).fill().map(() => new Array(cols).fill(0));
+ let buildingCount = 0;
+
+ function bfs(startRow, startCol) {
+ const queue = [[startRow, startCol]];
+ const visited = new Array(rows).fill().map(() => new Array(cols).fill(false));
+ visited[startRow][startCol] = true;
+ let distance = 0;
+
+ const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
+
+ while (queue.length) {
+ const size = queue.length;
+ distance++;
+ for (let i = 0; i < size; i++) {
+ const [row, col] = queue.shift();
+ for (const [dr, dc] of directions) {
+ const newRow = row + dr;
+ const newCol = col + dc;
+ if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols
+ && !visited[newRow][newCol] && grid[newRow][newCol] !== 1
+ && grid[newRow][newCol] !== 2) {
+ queue.push([newRow, newCol]);
+ visited[newRow][newCol] = true;
+ distances[newRow][newCol] += distance;
+ reachCounts[newRow][newCol]++;
+ }
+ }
+ }
+ }
+ }
+
+ for (let i = 0; i < rows; i++) {
+ for (let j = 0; j < cols; j++) {
+ if (grid[i][j] === 1) {
+ buildingCount++;
+ bfs(i, j);
+ }
+ }
+ }
+
+ let minDistance = Infinity;
+ for (let i = 0; i < rows; i++) {
+ for (let j = 0; j < cols; j++) {
+ if (grid[i][j] === 0 && reachCounts[i][j] === buildingCount) {
+ minDistance = Math.min(minDistance, distances[i][j]);
+ }
+ }
+ }
+
+ return minDistance === Infinity ? -1 : minDistance;
+};
From a8e403a5a8b4d3b2059dac093126ffa384d9af83 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 13 Jun 2025 18:45:57 -0500
Subject: [PATCH 473/994] Add solution #320
---
README.md | 1 +
solutions/0320-generalized-abbreviation.js | 41 ++++++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/0320-generalized-abbreviation.js
diff --git a/README.md b/README.md
index 9988dcab..8bac5eab 100644
--- a/README.md
+++ b/README.md
@@ -308,6 +308,7 @@
317|[Shortest Distance from All Buildings](./solutions/0317-shortest-distance-from-all-buildings.js)|Hard|
318|[Maximum Product of Word Lengths](./solutions/0318-maximum-product-of-word-lengths.js)|Medium|
319|[Bulb Switcher](./solutions/0319-bulb-switcher.js)|Medium|
+320|[Generalized Abbreviation](./solutions/0320-generalized-abbreviation.js)|Medium|
321|[Create Maximum Number](./solutions/0321-create-maximum-number.js)|Hard|
322|[Coin Change](./solutions/0322-coin-change.js)|Medium|
324|[Wiggle Sort II](./solutions/0324-wiggle-sort-ii.js)|Medium|
diff --git a/solutions/0320-generalized-abbreviation.js b/solutions/0320-generalized-abbreviation.js
new file mode 100644
index 00000000..96ab102d
--- /dev/null
+++ b/solutions/0320-generalized-abbreviation.js
@@ -0,0 +1,41 @@
+/**
+ * 320. Generalized Abbreviation
+ * https://leetcode.com/problems/generalized-abbreviation/
+ * Difficulty: Medium
+ *
+ * A word's generalized abbreviation can be constructed by taking any number of non-overlapping
+ * and non-adjacent substrings and replacing them with their respective lengths.
+ * - For example, "abcde" can be abbreviated into:
+ * - "a3e" ("bcd" turned into "3")
+ * - "1bcd1" ("a" and "e" both turned into "1")
+ * - "5" ("abcde" turned into "5")
+ * - "abcde" (no substrings replaced)
+ * - However, these abbreviations are invalid:
+ * - "23" ("ab" turned into "2" and "cde" turned into "3") is invalid as the substrings
+ * chosen are adjacent.
+ * - "22de" ("ab" turned into "2" and "bc" turned into "2") is invalid as the substring
+ * chosen overlap.
+ *
+ * Given a string word, return a list of all the possible generalized abbreviations of word.
+ * Return the answer in any order.
+ */
+
+/**
+ * @param {string} word
+ * @return {string[]}
+ */
+var generateAbbreviations = function(word) {
+ const result = [];
+ backtrack('', 0, 0);
+ return result;
+
+ function backtrack(current, pos, count) {
+ if (pos === word.length) {
+ result.push(current + (count > 0 ? count : ''));
+ return;
+ }
+
+ backtrack(current + (count > 0 ? count : '') + word[pos], pos + 1, 0);
+ backtrack(current, pos + 1, count + 1);
+ }
+};
From d6b704bf17deb31cf1bccf0526c179613b690791 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 13 Jun 2025 18:47:30 -0500
Subject: [PATCH 474/994] Add solution #323
---
README.md | 1 +
...ected-components-in-an-undirected-graph.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/0323-number-of-connected-components-in-an-undirected-graph.js
diff --git a/README.md b/README.md
index 8bac5eab..a4e48639 100644
--- a/README.md
+++ b/README.md
@@ -311,6 +311,7 @@
320|[Generalized Abbreviation](./solutions/0320-generalized-abbreviation.js)|Medium|
321|[Create Maximum Number](./solutions/0321-create-maximum-number.js)|Hard|
322|[Coin Change](./solutions/0322-coin-change.js)|Medium|
+323|[Number of Connected Components in an Undirected Graph](./solutions/0323-number-of-connected-components-in-an-undirected-graph.js)|Medium|
324|[Wiggle Sort II](./solutions/0324-wiggle-sort-ii.js)|Medium|
326|[Power of Three](./solutions/0326-power-of-three.js)|Easy|
327|[Count of Range Sum](./solutions/0327-count-of-range-sum.js)|Hard|
diff --git a/solutions/0323-number-of-connected-components-in-an-undirected-graph.js b/solutions/0323-number-of-connected-components-in-an-undirected-graph.js
new file mode 100644
index 00000000..ba679b5f
--- /dev/null
+++ b/solutions/0323-number-of-connected-components-in-an-undirected-graph.js
@@ -0,0 +1,42 @@
+/**
+ * 323. Number of Connected Components in an Undirected Graph
+ * https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/
+ * Difficulty: Medium
+ *
+ * You have a graph of n nodes. You are given an integer n and an array edges where
+ * edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph.
+ *
+ * Return the number of connected components in the graph.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @return {number}
+ */
+var countComponents = function(n, edges) {
+ const parent = new Array(n).fill().map((_, i) => i);
+ let components = n;
+
+ for (const [node1, node2] of edges) {
+ union(node1, node2);
+ }
+
+ return components;
+
+ function find(node) {
+ if (parent[node] !== node) {
+ parent[node] = find(parent[node]);
+ }
+ return parent[node];
+ }
+
+ function union(node1, node2) {
+ const root1 = find(node1);
+ const root2 = find(node2);
+ if (root1 !== root2) {
+ parent[root1] = root2;
+ components--;
+ }
+ }
+};
From 0df80fb7095279dad768d4bf5f98c035ba6fda39 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 13 Jun 2025 18:48:51 -0500
Subject: [PATCH 475/994] Add solution #325
---
README.md | 1 +
...0325-maximum-size-subarray-sum-equals-k.js | 31 +++++++++++++++++++
2 files changed, 32 insertions(+)
create mode 100644 solutions/0325-maximum-size-subarray-sum-equals-k.js
diff --git a/README.md b/README.md
index a4e48639..545e4daa 100644
--- a/README.md
+++ b/README.md
@@ -313,6 +313,7 @@
322|[Coin Change](./solutions/0322-coin-change.js)|Medium|
323|[Number of Connected Components in an Undirected Graph](./solutions/0323-number-of-connected-components-in-an-undirected-graph.js)|Medium|
324|[Wiggle Sort II](./solutions/0324-wiggle-sort-ii.js)|Medium|
+325|[Maximum Size Subarray Sum Equals k](./solutions/0325-maximum-size-subarray-sum-equals-k.js)|Medium|
326|[Power of Three](./solutions/0326-power-of-three.js)|Easy|
327|[Count of Range Sum](./solutions/0327-count-of-range-sum.js)|Hard|
328|[Odd Even Linked List](./solutions/0328-odd-even-linked-list.js)|Medium|
diff --git a/solutions/0325-maximum-size-subarray-sum-equals-k.js b/solutions/0325-maximum-size-subarray-sum-equals-k.js
new file mode 100644
index 00000000..697c3a73
--- /dev/null
+++ b/solutions/0325-maximum-size-subarray-sum-equals-k.js
@@ -0,0 +1,31 @@
+/**
+ * 325. Maximum Size Subarray Sum Equals k
+ * https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/
+ * Difficulty: Medium
+ *
+ * Given an integer array nums and an integer k, return the maximum length of a subarray that
+ * sums to k. If there is not one, return 0 instead.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var maxSubArrayLen = function(nums, k) {
+ const sumIndex = new Map([[0, -1]]);
+ let currentSum = 0;
+ let result = 0;
+
+ for (let i = 0; i < nums.length; i++) {
+ currentSum += nums[i];
+ if (sumIndex.has(currentSum - k)) {
+ result = Math.max(result, i - sumIndex.get(currentSum - k));
+ }
+ if (!sumIndex.has(currentSum)) {
+ sumIndex.set(currentSum, i);
+ }
+ }
+
+ return result;
+};
From fe9820f08f14431b4a8b28cb8d7eefb80bef2ec8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 14 Jun 2025 00:08:45 -0500
Subject: [PATCH 476/994] Add solution #333
---
README.md | 1 +
solutions/0333-largest-bst-subtree.js | 52 +++++++++++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 solutions/0333-largest-bst-subtree.js
diff --git a/README.md b/README.md
index 545e4daa..26b957c4 100644
--- a/README.md
+++ b/README.md
@@ -321,6 +321,7 @@
330|[Patching Array](./solutions/0330-patching-array.js)|Hard|
331|[Verify Preorder Serialization of a Binary Tree](./solutions/0331-verify-preorder-serialization-of-a-binary-tree.js)|Medium|
332|[Reconstruct Itinerary](./solutions/0332-reconstruct-itinerary.js)|Hard|
+333|[Largest BST Subtree](./solutions/0333-largest-bst-subtree.js)|Medium|
334|[Increasing Triplet Subsequence](./solutions/0334-increasing-triplet-subsequence.js)|Medium|
335|[Self Crossing](./solutions/0335-self-crossing.js)|Hard|
336|[Palindrome Pairs](./solutions/0336-palindrome-pairs.js)|Hard|
diff --git a/solutions/0333-largest-bst-subtree.js b/solutions/0333-largest-bst-subtree.js
new file mode 100644
index 00000000..30c83e84
--- /dev/null
+++ b/solutions/0333-largest-bst-subtree.js
@@ -0,0 +1,52 @@
+/**
+ * 333. Largest BST Subtree
+ * https://leetcode.com/problems/largest-bst-subtree/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree, find the largest subtree, which is also a Binary Search
+ * Tree (BST), where the largest means subtree has the largest number of nodes.
+ *
+ * A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned
+ * properties:
+ * - The left subtree values are less than the value of their parent (root) node's value.
+ * - The right subtree values are greater than the value of their parent (root) node's value.
+ *
+ * Note: A subtree must include 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 largestBSTSubtree = function(root) {
+ let maxSize = 0;
+ traverse(root);
+ return maxSize;
+
+ function traverse(node) {
+ if (!node) return { isBST: true, size: 0, min: Infinity, max: -Infinity };
+
+ const left = traverse(node.left);
+ const right = traverse(node.right);
+ if (left.isBST && right.isBST && node.val > left.max && node.val < right.min) {
+ const size = left.size + right.size + 1;
+ maxSize = Math.max(maxSize, size);
+ return {
+ isBST: true,
+ size,
+ min: Math.min(left.min, node.val),
+ max: Math.max(right.max, node.val)
+ };
+ }
+
+ return { isBST: false, size: 0, min: 0, max: 0 };
+ }
+};
From 85bb78c8c418704c5198cdb76733909c88c1c6d1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 14 Jun 2025 00:09:52 -0500
Subject: [PATCH 477/994] Add solution #339
---
README.md | 1 +
solutions/0339-nested-list-weight-sum.js | 33 ++++++++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/0339-nested-list-weight-sum.js
diff --git a/README.md b/README.md
index 26b957c4..7b61e291 100644
--- a/README.md
+++ b/README.md
@@ -327,6 +327,7 @@
336|[Palindrome Pairs](./solutions/0336-palindrome-pairs.js)|Hard|
337|[House Robber III](./solutions/0337-house-robber-iii.js)|Medium|
338|[Counting Bits](./solutions/0338-counting-bits.js)|Easy|
+339|[Nested List Weight Sum](./solutions/0339-nested-list-weight-sum.js)|Medium|
341|[Flatten Nested List Iterator](./solutions/0341-flatten-nested-list-iterator.js)|Medium|
342|[Power of Four](./solutions/0342-power-of-four.js)|Easy|
343|[Integer Break](./solutions/0343-integer-break.js)|Medium|
diff --git a/solutions/0339-nested-list-weight-sum.js b/solutions/0339-nested-list-weight-sum.js
new file mode 100644
index 00000000..2ca1b16b
--- /dev/null
+++ b/solutions/0339-nested-list-weight-sum.js
@@ -0,0 +1,33 @@
+/**
+ * 339. Nested List Weight Sum
+ * https://leetcode.com/problems/nested-list-weight-sum/
+ * Difficulty: Medium
+ *
+ * You are given a nested list of integers nestedList. Each element is either an integer or
+ * a list whose elements may also be integers or other lists.
+ *
+ * The depth of an integer is the number of lists that it is inside of. For example, the nested
+ * list [1,[2,2],[[3],2],1] has each integer's value set to its depth.
+ *
+ * Return the sum of each integer in nestedList multiplied by its depth.
+ */
+
+/**
+ * @param {NestedInteger[]} nestedList
+ * @return {number}
+ */
+var depthSum = function(nestedList) {
+ return calculateDepth(nestedList, 1);
+
+ function calculateDepth(list, depth) {
+ let total = 0;
+ for (const element of list) {
+ if (element.isInteger()) {
+ total += element.getInteger() * depth;
+ } else {
+ total += calculateDepth(element.getList(), depth + 1);
+ }
+ }
+ return total;
+ }
+};
From d1a09b628608d56c624d7839a0b72cc636dc8a24 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 14 Jun 2025 00:10:52 -0500
Subject: [PATCH 478/994] Add solution #340
---
README.md | 1 +
...ring-with-at-most-k-distinct-characters.js | 35 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/0340-longest-substring-with-at-most-k-distinct-characters.js
diff --git a/README.md b/README.md
index 7b61e291..56d19aa3 100644
--- a/README.md
+++ b/README.md
@@ -328,6 +328,7 @@
337|[House Robber III](./solutions/0337-house-robber-iii.js)|Medium|
338|[Counting Bits](./solutions/0338-counting-bits.js)|Easy|
339|[Nested List Weight Sum](./solutions/0339-nested-list-weight-sum.js)|Medium|
+340|[Longest Substring with At Most K Distinct Characters](./solutions/0340-longest-substring-with-at-most-k-distinct-characters.js)|Medium|
341|[Flatten Nested List Iterator](./solutions/0341-flatten-nested-list-iterator.js)|Medium|
342|[Power of Four](./solutions/0342-power-of-four.js)|Easy|
343|[Integer Break](./solutions/0343-integer-break.js)|Medium|
diff --git a/solutions/0340-longest-substring-with-at-most-k-distinct-characters.js b/solutions/0340-longest-substring-with-at-most-k-distinct-characters.js
new file mode 100644
index 00000000..dfd6a5c3
--- /dev/null
+++ b/solutions/0340-longest-substring-with-at-most-k-distinct-characters.js
@@ -0,0 +1,35 @@
+/**
+ * 340. Longest Substring with At Most K Distinct Characters
+ * https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
+ * Difficulty: Medium
+ *
+ * Given a string s and an integer k, return the length of the longest substring of s that
+ * contains at most k distinct characters.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} k
+ * @return {number}
+ */
+var lengthOfLongestSubstringKDistinct = function(s, k) {
+ const map = new Map();
+ let result = 0;
+ let left = 0;
+
+ for (let right = 0; right < s.length; right++) {
+ map.set(s[right], (map.get(s[right]) || 0) + 1);
+
+ while (map.size > k) {
+ map.set(s[left], map.get(s[left]) - 1);
+ if (map.get(s[left]) === 0) {
+ map.delete(s[left]);
+ }
+ left++;
+ }
+
+ result = Math.max(result, right - left + 1);
+ }
+
+ return result;
+};
From 754988a2540a52fd0b0b359f117789ad6268ac3b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 14 Jun 2025 00:11:55 -0500
Subject: [PATCH 479/994] Add solution #346
---
README.md | 1 +
.../0346-moving-average-from-data-stream.js | 36 +++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/0346-moving-average-from-data-stream.js
diff --git a/README.md b/README.md
index 56d19aa3..5b8a6d2c 100644
--- a/README.md
+++ b/README.md
@@ -334,6 +334,7 @@
343|[Integer Break](./solutions/0343-integer-break.js)|Medium|
344|[Reverse String](./solutions/0344-reverse-string.js)|Easy|
345|[Reverse Vowels of a String](./solutions/0345-reverse-vowels-of-a-string.js)|Easy|
+346|[Moving Average from Data Stream](./solutions/0346-moving-average-from-data-stream.js)|Easy|
347|[Top K Frequent Elements](./solutions/0347-top-k-frequent-elements.js)|Medium|
349|[Intersection of Two Arrays](./solutions/0349-intersection-of-two-arrays.js)|Easy|
350|[Intersection of Two Arrays II](./solutions/0350-intersection-of-two-arrays-ii.js)|Easy|
diff --git a/solutions/0346-moving-average-from-data-stream.js b/solutions/0346-moving-average-from-data-stream.js
new file mode 100644
index 00000000..6c2981a8
--- /dev/null
+++ b/solutions/0346-moving-average-from-data-stream.js
@@ -0,0 +1,36 @@
+/**
+ * 346. Moving Average from Data Stream
+ * https://leetcode.com/problems/moving-average-from-data-stream/
+ * Difficulty: Easy
+ *
+ * Given a stream of integers and a window size, calculate the moving average of all integers
+ * in the sliding window.
+ *
+ * Implement the MovingAverage class:
+ * - MovingAverage(int size) Initializes the object with the size of the window size.
+ * - double next(int val) Returns the moving average of the last size values of the stream.
+ */
+
+/**
+ * @param {number} size
+ */
+var MovingAverage = function(size) {
+ this.window = [];
+ this.maxSize = size;
+ this.sum = 0;
+};
+
+/**
+ * @param {number} val
+ * @return {number}
+ */
+MovingAverage.prototype.next = function(val) {
+ this.window.push(val);
+ this.sum += val;
+
+ if (this.window.length > this.maxSize) {
+ this.sum -= this.window.shift();
+ }
+
+ return this.sum / this.window.length;
+};
From 6cabf2bcb38f741b5a09ef3ba6aa96b4852f0abc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 14 Jun 2025 00:13:42 -0500
Subject: [PATCH 480/994] Add solution #348
---
README.md | 1 +
solutions/0348-design-tic-tac-toe.js | 59 ++++++++++++++++++++++++++++
2 files changed, 60 insertions(+)
create mode 100644 solutions/0348-design-tic-tac-toe.js
diff --git a/README.md b/README.md
index 5b8a6d2c..d94532c8 100644
--- a/README.md
+++ b/README.md
@@ -336,6 +336,7 @@
345|[Reverse Vowels of a String](./solutions/0345-reverse-vowels-of-a-string.js)|Easy|
346|[Moving Average from Data Stream](./solutions/0346-moving-average-from-data-stream.js)|Easy|
347|[Top K Frequent Elements](./solutions/0347-top-k-frequent-elements.js)|Medium|
+348|[Design Tic-Tac-Toe](./solutions/0348-design-tic-tac-toe.js)|Medium|
349|[Intersection of Two Arrays](./solutions/0349-intersection-of-two-arrays.js)|Easy|
350|[Intersection of Two Arrays II](./solutions/0350-intersection-of-two-arrays-ii.js)|Easy|
352|[Data Stream as Disjoint Intervals](./solutions/0352-data-stream-as-disjoint-intervals.js)|Hard|
diff --git a/solutions/0348-design-tic-tac-toe.js b/solutions/0348-design-tic-tac-toe.js
new file mode 100644
index 00000000..9b517913
--- /dev/null
+++ b/solutions/0348-design-tic-tac-toe.js
@@ -0,0 +1,59 @@
+/**
+ * 348. Design Tic-Tac-Toe
+ * https://leetcode.com/problems/design-tic-tac-toe/
+ * Difficulty: Medium
+ *
+ * Assume the following rules are for the tic-tac-toe game on an n x n board between two players:
+ * 1. A move is guaranteed to be valid and is placed on an empty block.
+ * 2. Once a winning condition is reached, no more moves are allowed.
+ * 3. A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal
+ * row wins the game.
+ *
+ * Implement the TicTacToe class:
+ * - TicTacToe(int n) Initializes the object the size of the board n.
+ * - int move(int row, int col, int player) Indicates that the player with id player plays at the
+ * cell (row, col) of the board. The move is guaranteed to be a valid move, and the two players
+ * alternate in making moves. Return
+ * - 0 if there is no winner after the move,
+ * - 1 if player 1 is the winner after the move, or
+ * - 2 if player 2 is the winner after the move.
+ */
+
+/**
+ * @param {number} n
+ */
+var TicTacToe = function(n) {
+ this.size = n;
+ this.rows = new Array(n).fill(0);
+ this.cols = new Array(n).fill(0);
+ this.diagonal = 0;
+ this.antiDiagonal = 0;
+};
+
+/**
+ * @param {number} row
+ * @param {number} col
+ * @param {number} player
+ * @return {number}
+ */
+TicTacToe.prototype.move = function(row, col, player) {
+ const value = player === 1 ? 1 : -1;
+
+ this.rows[row] += value;
+ this.cols[col] += value;
+
+ if (row === col) {
+ this.diagonal += value;
+ }
+
+ if (row + col === this.size - 1) {
+ this.antiDiagonal += value;
+ }
+
+ if (Math.abs(this.rows[row]) === this.size || Math.abs(this.cols[col]) === this.size
+ || Math.abs(this.diagonal) === this.size || Math.abs(this.antiDiagonal) === this.size) {
+ return player;
+ }
+
+ return 0;
+};
From 5228884b3a5df32cbf22ee15738ff92ff7ceaf50 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 14 Jun 2025 18:32:45 -0500
Subject: [PATCH 481/994] Add solution #351
---
README.md | 1 +
solutions/0351-android-unlock-patterns.js | 68 +++++++++++++++++++++++
2 files changed, 69 insertions(+)
create mode 100644 solutions/0351-android-unlock-patterns.js
diff --git a/README.md b/README.md
index d94532c8..38794736 100644
--- a/README.md
+++ b/README.md
@@ -339,6 +339,7 @@
348|[Design Tic-Tac-Toe](./solutions/0348-design-tic-tac-toe.js)|Medium|
349|[Intersection of Two Arrays](./solutions/0349-intersection-of-two-arrays.js)|Easy|
350|[Intersection of Two Arrays II](./solutions/0350-intersection-of-two-arrays-ii.js)|Easy|
+351|[Android Unlock Patterns](./solutions/0351-android-unlock-patterns.js)|Medium|
352|[Data Stream as Disjoint Intervals](./solutions/0352-data-stream-as-disjoint-intervals.js)|Hard|
354|[Russian Doll Envelopes](./solutions/0354-russian-doll-envelopes.js)|Hard|
355|[Design Twitter](./solutions/0355-design-twitter.js)|Medium|
diff --git a/solutions/0351-android-unlock-patterns.js b/solutions/0351-android-unlock-patterns.js
new file mode 100644
index 00000000..ef71439d
--- /dev/null
+++ b/solutions/0351-android-unlock-patterns.js
@@ -0,0 +1,68 @@
+/**
+ * 351. Android Unlock Patterns
+ * https://leetcode.com/problems/android-unlock-patterns/
+ * Difficulty: Medium
+ *
+ * Android devices have a special lock screen with a 3 x 3 grid of dots. Users can set an
+ * "unlock pattern" by connecting the dots in a specific sequence, forming a series of joined
+ * line segments where each segment's endpoints are two consecutive dots in the sequence.
+ * A sequence of k dots is a valid unlock pattern if both of the following are true:
+ * - All the dots in the sequence are distinct.
+ * - If the line segment connecting two consecutive dots in the sequence passes through the
+ * center of any other dot, the other dot must have previously appeared in the sequence.
+ * No jumps through the center non-selected dots are allowed.
+ * - For example, connecting dots 2 and 9 without dots 5 or 6 appearing beforehand is valid
+ * because the line from dot 2 to dot 9 does not pass through the center of either dot 5 or 6.
+ * - However, connecting dots 1 and 3 without dot 2 appearing beforehand is invalid because
+ * the line from dot 1 to dot 3 passes through the center of dot 2.
+ *
+ * Here are some example valid and invalid unlock patterns:
+ */
+
+/**
+ * @param {number} m
+ * @param {number} n
+ * @return {number}
+ */
+var numberOfPatterns = function(m, n) {
+ const jumps = new Array(10).fill().map(() => new Array(10).fill(0));
+ jumps[1][3] = jumps[3][1] = 2;
+ jumps[1][7] = jumps[7][1] = 4;
+ jumps[3][9] = jumps[9][3] = 6;
+ jumps[7][9] = jumps[9][7] = 8;
+ jumps[1][9] = jumps[9][1] = jumps[2][8] = jumps[8][2] = jumps[3][7]
+ = jumps[7][3] = jumps[4][6] = jumps[6][4] = 5;
+
+ function backtrack(current, visited, length) {
+ if (length > n) return 0;
+ let count = length >= m ? 1 : 0;
+ if (length === n) return count;
+
+ for (let next = 1; next <= 9; next++) {
+ if (!visited.has(next)) {
+ const jump = jumps[current][next];
+ if (jump === 0 || visited.has(jump)) {
+ visited.add(next);
+ count += backtrack(next, visited, length + 1);
+ visited.delete(next);
+ }
+ }
+ }
+ return count;
+ }
+
+ let total = 0;
+ const visited = new Set();
+ visited.add(1);
+ total += backtrack(1, visited, 1) * 4;
+ visited.delete(1);
+
+ visited.add(2);
+ total += backtrack(2, visited, 1) * 4;
+ visited.delete(2);
+
+ visited.add(5);
+ total += backtrack(5, visited, 1);
+
+ return total;
+};
From e6f42ed94eb9d56f1f64e7edab5fff50d07935ff Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 14 Jun 2025 18:34:19 -0500
Subject: [PATCH 482/994] Add solution #353
---
README.md | 1 +
solutions/0353-design-snake-game.js | 82 +++++++++++++++++++++++++++++
2 files changed, 83 insertions(+)
create mode 100644 solutions/0353-design-snake-game.js
diff --git a/README.md b/README.md
index 38794736..dfabb272 100644
--- a/README.md
+++ b/README.md
@@ -341,6 +341,7 @@
350|[Intersection of Two Arrays II](./solutions/0350-intersection-of-two-arrays-ii.js)|Easy|
351|[Android Unlock Patterns](./solutions/0351-android-unlock-patterns.js)|Medium|
352|[Data Stream as Disjoint Intervals](./solutions/0352-data-stream-as-disjoint-intervals.js)|Hard|
+353|[Design Snake Game](./solutions/0353-design-snake-game.js)|Medium|
354|[Russian Doll Envelopes](./solutions/0354-russian-doll-envelopes.js)|Hard|
355|[Design Twitter](./solutions/0355-design-twitter.js)|Medium|
357|[Count Numbers with Unique Digits](./solutions/0357-count-numbers-with-unique-digits.js)|Medium|
diff --git a/solutions/0353-design-snake-game.js b/solutions/0353-design-snake-game.js
new file mode 100644
index 00000000..4f615906
--- /dev/null
+++ b/solutions/0353-design-snake-game.js
@@ -0,0 +1,82 @@
+/**
+ * 353. Design Snake Game
+ * https://leetcode.com/problems/design-snake-game/
+ * Difficulty: Medium
+ *
+ * Design a Snake game that is played on a device with screen size height x width. Play the
+ * game online if you are not familiar with the game.
+ *
+ * The snake is initially positioned at the top left corner (0, 0) with a length of 1 unit.
+ *
+ * You are given an array food where food[i] = (ri, ci) is the row and column position of a
+ * piece of food that the snake can eat. When a snake eats a piece of food, its length and
+ * the game's score both increase by 1.
+ *
+ * Each piece of food appears one by one on the screen, meaning the second piece of food will
+ * not appear until the snake eats the first piece of food.
+ *
+ * When a piece of food appears on the screen, it is guaranteed that it will not appear on a
+ * block occupied by the snake.
+ *
+ * The game is over if the snake goes out of bounds (hits a wall) or if its head occupies a
+ * space that its body occupies after moving (i.e. a snake of length 4 cannot run into itself).
+ *
+ * Implement the SnakeGame class:
+ * - SnakeGame(int width, int height, int[][] food) Initializes the object with a screen of size
+ * height x width and the positions of the food.
+ * - int move(String direction) Returns the score of the game after applying one direction move
+ * by the snake. If the game is over, return -1.
+ */
+
+/**
+ * @param {number} width
+ * @param {number} height
+ * @param {number[][]} food
+ */
+var SnakeGame = function(width, height, food) {
+ this.width = width;
+ this.height = height;
+ this.food = food;
+ this.foodIndex = 0;
+ this.score = 0;
+ this.snake = [[0, 0]];
+ this.bodySet = new Set(['0,0']);
+};
+
+/**
+ * @param {string} direction
+ * @return {number}
+ */
+SnakeGame.prototype.move = function(direction) {
+ const head = [...this.snake[0]];
+
+ if (direction === 'U') head[0]--;
+ else if (direction === 'D') head[0]++;
+ else if (direction === 'L') head[1]--;
+ else if (direction === 'R') head[1]++;
+
+ if (head[0] < 0 || head[0] >= this.height || head[1] < 0 || head[1] >= this.width) {
+ return -1;
+ }
+
+ const tail = this.snake.pop();
+ this.bodySet.delete(`${tail[0]},${tail[1]}`);
+
+ const headKey = `${head[0]},${head[1]}`;
+ if (this.bodySet.has(headKey)) {
+ return -1;
+ }
+
+ this.snake.unshift(head);
+ this.bodySet.add(headKey);
+
+ if (this.foodIndex < this.food.length && head[0] === this.food[this.foodIndex][0]
+ && head[1] === this.food[this.foodIndex][1]) {
+ this.snake.push(tail);
+ this.bodySet.add(`${tail[0]},${tail[1]}`);
+ this.foodIndex++;
+ this.score++;
+ }
+
+ return this.score;
+};
From f16cf7c6cdbba949d515f0d0602b96ad2a988772 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 14 Jun 2025 18:45:18 -0500
Subject: [PATCH 483/994] Add solution #356
---
README.md | 1 +
solutions/0356-line-reflection.js | 37 +++++++++++++++++++++++++++++++
2 files changed, 38 insertions(+)
create mode 100644 solutions/0356-line-reflection.js
diff --git a/README.md b/README.md
index dfabb272..0116f009 100644
--- a/README.md
+++ b/README.md
@@ -344,6 +344,7 @@
353|[Design Snake Game](./solutions/0353-design-snake-game.js)|Medium|
354|[Russian Doll Envelopes](./solutions/0354-russian-doll-envelopes.js)|Hard|
355|[Design Twitter](./solutions/0355-design-twitter.js)|Medium|
+356|[Line Reflection](./solutions/0356-line-reflection.js)|Medium|
357|[Count Numbers with Unique Digits](./solutions/0357-count-numbers-with-unique-digits.js)|Medium|
363|[Max Sum of Rectangle No Larger Than K](./solutions/0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard|
365|[Water and Jug Problem](./solutions/0365-water-and-jug-problem.js)|Medium|
diff --git a/solutions/0356-line-reflection.js b/solutions/0356-line-reflection.js
new file mode 100644
index 00000000..76722159
--- /dev/null
+++ b/solutions/0356-line-reflection.js
@@ -0,0 +1,37 @@
+/**
+ * 356. Line Reflection
+ * https://leetcode.com/problems/line-reflection/
+ * Difficulty: Medium
+ *
+ * Given n points on a 2D plane, find if there is such a line parallel to the y-axis that reflects
+ * the given points symmetrically.
+ *
+ * In other words, answer whether or not if there exists a line that after reflecting all points
+ * over the given line, the original points' set is the same as the reflected ones.
+ *
+ * Note that there can be repeated points.
+ */
+
+/**
+ * @param {number[][]} points
+ * @return {boolean}
+ */
+var isReflected = function(points) {
+ const pointSet = new Set(points.map(([x, y]) => `${x},${y}`));
+ let minX = Infinity;
+ let maxX = -Infinity;
+
+ for (const [x] of points) {
+ minX = Math.min(minX, x);
+ maxX = Math.max(maxX, x);
+ }
+
+ const sum = minX + maxX;
+ for (const [x, y] of points) {
+ if (!pointSet.has(`${sum - x},${y}`)) {
+ return false;
+ }
+ }
+
+ return true;
+};
From d891f694aaff9390f786ecc2ff3112a579c9e86b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 14 Jun 2025 18:50:55 -0500
Subject: [PATCH 484/994] Add solution #358
---
README.md | 1 +
.../0358-rearrange-string-k-distance-apart.js | 65 +++++++++++++++++++
2 files changed, 66 insertions(+)
create mode 100644 solutions/0358-rearrange-string-k-distance-apart.js
diff --git a/README.md b/README.md
index 0116f009..706d525c 100644
--- a/README.md
+++ b/README.md
@@ -346,6 +346,7 @@
355|[Design Twitter](./solutions/0355-design-twitter.js)|Medium|
356|[Line Reflection](./solutions/0356-line-reflection.js)|Medium|
357|[Count Numbers with Unique Digits](./solutions/0357-count-numbers-with-unique-digits.js)|Medium|
+358|[Rearrange String k Distance Apart](./solutions/0358-rearrange-string-k-distance-apart.js)|Hard|
363|[Max Sum of Rectangle No Larger Than K](./solutions/0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard|
365|[Water and Jug Problem](./solutions/0365-water-and-jug-problem.js)|Medium|
367|[Valid Perfect Square](./solutions/0367-valid-perfect-square.js)|Easy|
diff --git a/solutions/0358-rearrange-string-k-distance-apart.js b/solutions/0358-rearrange-string-k-distance-apart.js
new file mode 100644
index 00000000..9d498ae4
--- /dev/null
+++ b/solutions/0358-rearrange-string-k-distance-apart.js
@@ -0,0 +1,65 @@
+/**
+ * 358. Rearrange String k Distance Apart
+ * https://leetcode.com/problems/rearrange-string-k-distance-apart/
+ * Difficulty: Hard
+ *
+ * Given a string s and an integer k, rearrange s such that the same characters are at least
+ * distance k from each other. If it is not possible to rearrange the string, return an empty
+ * string "".
+ */
+
+/**
+ * @param {string} s
+ * @param {number} k
+ * @return {string}
+ */
+var rearrangeString = function(s, k) {
+ if (k <= 1) return s;
+
+ const charCount = new Array(26).fill(0);
+ for (const char of s) {
+ charCount[char.charCodeAt(0) - 97]++;
+ }
+
+ const maxHeap = [];
+ for (let i = 0; i < 26; i++) {
+ if (charCount[i] > 0) {
+ maxHeap.push([charCount[i], String.fromCharCode(i + 97)]);
+ }
+ }
+ maxHeap.sort((a, b) => b[0] - a[0]);
+
+ const maxFreq = maxHeap[0] ? maxHeap[0][0] : 0;
+ if (maxFreq > Math.ceil(s.length / k)) return '';
+
+ const result = new Array(s.length).fill('');
+ let index = 0;
+
+ while (maxHeap.length) {
+ const temp = [];
+ for (let i = 0; i < k && maxHeap.length; i++) {
+ const [count, char] = maxHeap.shift();
+ while (index < s.length && result[index] !== '') {
+ index++;
+ }
+ if (index >= s.length) index = 0;
+ result[index] = char;
+ index++;
+ if (count > 1) temp.push([count - 1, char]);
+ }
+
+ temp.sort((a, b) => b[0] - a[0]);
+ maxHeap.push(...temp);
+ maxHeap.sort((a, b) => b[0] - a[0]);
+ }
+
+ for (let i = 0; i <= s.length - k; i++) {
+ const seen = new Set();
+ for (let j = i; j < i + k; j++) {
+ if (seen.has(result[j])) return '';
+ seen.add(result[j]);
+ }
+ }
+
+ return result.join('');
+};
From 54c12c8939822ac334413a5568d140bb6864d45c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 14 Jun 2025 18:54:30 -0500
Subject: [PATCH 485/994] Add solution #359
---
README.md | 1 +
solutions/0359-logger-rate-limiter.js | 35 +++++++++++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/0359-logger-rate-limiter.js
diff --git a/README.md b/README.md
index 706d525c..52a876ed 100644
--- a/README.md
+++ b/README.md
@@ -347,6 +347,7 @@
356|[Line Reflection](./solutions/0356-line-reflection.js)|Medium|
357|[Count Numbers with Unique Digits](./solutions/0357-count-numbers-with-unique-digits.js)|Medium|
358|[Rearrange String k Distance Apart](./solutions/0358-rearrange-string-k-distance-apart.js)|Hard|
+359|[Logger Rate Limiter](./solutions/0359-logger-rate-limiter.js)|Easy|
363|[Max Sum of Rectangle No Larger Than K](./solutions/0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard|
365|[Water and Jug Problem](./solutions/0365-water-and-jug-problem.js)|Medium|
367|[Valid Perfect Square](./solutions/0367-valid-perfect-square.js)|Easy|
diff --git a/solutions/0359-logger-rate-limiter.js b/solutions/0359-logger-rate-limiter.js
new file mode 100644
index 00000000..9dacbd78
--- /dev/null
+++ b/solutions/0359-logger-rate-limiter.js
@@ -0,0 +1,35 @@
+/**
+ * 359. Logger Rate Limiter
+ * https://leetcode.com/problems/logger-rate-limiter/
+ * Difficulty: Easy
+ *
+ * Design a logger system that receives a stream of messages along with their timestamps.
+ * Each unique message should only be printed at most every 10 seconds (i.e. a message
+ * printed at timestamp t will prevent other identical messages from being printed until
+ * timestamp t + 10).
+ *
+ * All messages will come in chronological order. Several messages may arrive at the same timestamp.
+ *
+ * Implement the Logger class:
+ * - Logger() Initializes the logger object.
+ * - bool shouldPrintMessage(int timestamp, string message) Returns true if the message should
+ * be printed in the given timestamp, otherwise returns false.
+ */
+
+var Logger = function() {
+ this.messageTimestamps = new Map();
+};
+
+/**
+ * @param {number} timestamp
+ * @param {string} message
+ * @return {boolean}
+ */
+Logger.prototype.shouldPrintMessage = function(timestamp, message) {
+ const nextAllowed = this.messageTimestamps.get(message) || 0;
+ if (timestamp >= nextAllowed) {
+ this.messageTimestamps.set(message, timestamp + 10);
+ return true;
+ }
+ return false;
+};
From 89c6381e290ac18f4d9f8274b70e65b24569eeaf Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 14 Jun 2025 18:56:28 -0500
Subject: [PATCH 486/994] Add solution #360
---
README.md | 1 +
solutions/0360-sort-transformed-array.js | 52 ++++++++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 solutions/0360-sort-transformed-array.js
diff --git a/README.md b/README.md
index 52a876ed..0cda5cca 100644
--- a/README.md
+++ b/README.md
@@ -348,6 +348,7 @@
357|[Count Numbers with Unique Digits](./solutions/0357-count-numbers-with-unique-digits.js)|Medium|
358|[Rearrange String k Distance Apart](./solutions/0358-rearrange-string-k-distance-apart.js)|Hard|
359|[Logger Rate Limiter](./solutions/0359-logger-rate-limiter.js)|Easy|
+360|[Sort Transformed Array](./solutions/0360-sort-transformed-array.js)|Medium|
363|[Max Sum of Rectangle No Larger Than K](./solutions/0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard|
365|[Water and Jug Problem](./solutions/0365-water-and-jug-problem.js)|Medium|
367|[Valid Perfect Square](./solutions/0367-valid-perfect-square.js)|Easy|
diff --git a/solutions/0360-sort-transformed-array.js b/solutions/0360-sort-transformed-array.js
new file mode 100644
index 00000000..30badca3
--- /dev/null
+++ b/solutions/0360-sort-transformed-array.js
@@ -0,0 +1,52 @@
+/**
+ * 360. Sort Transformed Array
+ * https://leetcode.com/problems/sort-transformed-array/
+ * Difficulty: Medium
+ *
+ * Given a sorted integer array nums and three integers a, b and c, apply a quadratic function
+ * of the form f(x) = ax2 + bx + c to each element nums[i] in the array, and return the array
+ * in a sorted order.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} a
+ * @param {number} b
+ * @param {number} c
+ * @return {number[]}
+ */
+var sortTransformedArray = function(nums, a, b, c) {
+ const result = new Array(nums.length);
+ let left = 0;
+ let right = nums.length - 1;
+ let index = a >= 0 ? nums.length - 1 : 0;
+
+ while (left <= right) {
+ const leftVal = transform(nums[left]);
+ const rightVal = transform(nums[right]);
+
+ if (a >= 0) {
+ if (leftVal > rightVal) {
+ result[index--] = leftVal;
+ left++;
+ } else {
+ result[index--] = rightVal;
+ right--;
+ }
+ } else {
+ if (leftVal < rightVal) {
+ result[index++] = leftVal;
+ left++;
+ } else {
+ result[index++] = rightVal;
+ right--;
+ }
+ }
+ }
+
+ return result;
+
+ function transform(x) {
+ return a * x * x + b * x + c;
+ }
+};
From 137a6aece15c42c40d62c0a89156f31e742b1cb4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 14 Jun 2025 18:57:32 -0500
Subject: [PATCH 487/994] Add solution #361
---
README.md | 1 +
solutions/0361-bomb-enemy.js | 46 ++++++++++++++++++++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/0361-bomb-enemy.js
diff --git a/README.md b/README.md
index 0cda5cca..22c9c812 100644
--- a/README.md
+++ b/README.md
@@ -349,6 +349,7 @@
358|[Rearrange String k Distance Apart](./solutions/0358-rearrange-string-k-distance-apart.js)|Hard|
359|[Logger Rate Limiter](./solutions/0359-logger-rate-limiter.js)|Easy|
360|[Sort Transformed Array](./solutions/0360-sort-transformed-array.js)|Medium|
+361|[Bomb Enemy](./solutions/0361-bomb-enemy.js)|Medium|
363|[Max Sum of Rectangle No Larger Than K](./solutions/0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard|
365|[Water and Jug Problem](./solutions/0365-water-and-jug-problem.js)|Medium|
367|[Valid Perfect Square](./solutions/0367-valid-perfect-square.js)|Easy|
diff --git a/solutions/0361-bomb-enemy.js b/solutions/0361-bomb-enemy.js
new file mode 100644
index 00000000..ffa279e8
--- /dev/null
+++ b/solutions/0361-bomb-enemy.js
@@ -0,0 +1,46 @@
+/**
+ * 361. Bomb Enemy
+ * https://leetcode.com/problems/bomb-enemy/
+ * Difficulty: Medium
+ *
+ * Given an m x n matrix grid where each cell is either a wall 'W', an enemy 'E' or empty '0',
+ * return the maximum enemies you can kill using one bomb. You can only place the bomb in an
+ * empty cell.
+ *
+ * The bomb kills all the enemies in the same row and column from the planted point until it
+ * hits the wall since it is too strong to be destroyed.
+ */
+
+/**
+ * @param {character[][]} grid
+ * @return {number}
+ */
+var maxKilledEnemies = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const colHits = new Array(cols).fill(0);
+ let rowHits = 0;
+ let result = 0;
+
+ for (let i = 0; i < rows; i++) {
+ for (let j = 0; j < cols; j++) {
+ if (j === 0 || grid[i][j-1] === 'W') {
+ rowHits = 0;
+ for (let k = j; k < cols && grid[i][k] !== 'W'; k++) {
+ if (grid[i][k] === 'E') rowHits++;
+ }
+ }
+ if (i === 0 || grid[i-1][j] === 'W') {
+ colHits[j] = 0;
+ for (let k = i; k < rows && grid[k][j] !== 'W'; k++) {
+ if (grid[k][j] === 'E') colHits[j]++;
+ }
+ }
+ if (grid[i][j] === '0') {
+ result = Math.max(result, rowHits + colHits[j]);
+ }
+ }
+ }
+
+ return result;
+};
From 4d1dac8948c90bd42902f42b42e29d9faafb217e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 14 Jun 2025 18:59:20 -0500
Subject: [PATCH 488/994] Add solution #362
---
README.md | 1 +
solutions/0362-design-hit-counter.js | 43 ++++++++++++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/0362-design-hit-counter.js
diff --git a/README.md b/README.md
index 22c9c812..255750d9 100644
--- a/README.md
+++ b/README.md
@@ -350,6 +350,7 @@
359|[Logger Rate Limiter](./solutions/0359-logger-rate-limiter.js)|Easy|
360|[Sort Transformed Array](./solutions/0360-sort-transformed-array.js)|Medium|
361|[Bomb Enemy](./solutions/0361-bomb-enemy.js)|Medium|
+362|[Design Hit Counter](./solutions/0362-design-hit-counter.js)|Medium|
363|[Max Sum of Rectangle No Larger Than K](./solutions/0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard|
365|[Water and Jug Problem](./solutions/0365-water-and-jug-problem.js)|Medium|
367|[Valid Perfect Square](./solutions/0367-valid-perfect-square.js)|Easy|
diff --git a/solutions/0362-design-hit-counter.js b/solutions/0362-design-hit-counter.js
new file mode 100644
index 00000000..ebe1aeef
--- /dev/null
+++ b/solutions/0362-design-hit-counter.js
@@ -0,0 +1,43 @@
+/**
+ * 362. Design Hit Counter
+ * https://leetcode.com/problems/design-hit-counter/
+ * Difficulty: Medium
+ *
+ * Design a hit counter which counts the number of hits received in the past 5 minutes
+ * (i.e., the past 300 seconds).
+ *
+ * Your system should accept a timestamp parameter (in seconds granularity), and you may
+ * assume that calls are being made to the system in chronological order (i.e., timestamp
+ * is monotonically increasing). Several hits may arrive roughly at the same time.
+ *
+ * Implement the HitCounter class:
+ * - HitCounter() Initializes the object of the hit counter system.
+ * - void hit(int timestamp) Records a hit that happened at timestamp (in seconds). Several
+ * hits may happen at the same timestamp.
+ * - int getHits(int timestamp) Returns the number of hits in the past 5 minutes from timestamp
+ * (i.e., the past 300 seconds).
+ */
+
+var HitCounter = function() {
+ this.hits = [];
+};
+
+/**
+ * @param {number} timestamp
+ * @return {void}
+ */
+HitCounter.prototype.hit = function(timestamp) {
+ this.hits.push(timestamp);
+};
+
+/**
+ * @param {number} timestamp
+ * @return {number}
+ */
+HitCounter.prototype.getHits = function(timestamp) {
+ const threshold = timestamp - 300;
+ while (this.hits.length && this.hits[0] <= threshold) {
+ this.hits.shift();
+ }
+ return this.hits.length;
+};
From 7171461fdc69f72ac1d1a0d8ff337f82846f2af3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 14 Jun 2025 19:00:52 -0500
Subject: [PATCH 489/994] Add solution #364
---
README.md | 1 +
solutions/0364-nested-list-weight-sum-ii.js | 47 +++++++++++++++++++++
2 files changed, 48 insertions(+)
create mode 100644 solutions/0364-nested-list-weight-sum-ii.js
diff --git a/README.md b/README.md
index 255750d9..f0e30ed1 100644
--- a/README.md
+++ b/README.md
@@ -352,6 +352,7 @@
361|[Bomb Enemy](./solutions/0361-bomb-enemy.js)|Medium|
362|[Design Hit Counter](./solutions/0362-design-hit-counter.js)|Medium|
363|[Max Sum of Rectangle No Larger Than K](./solutions/0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard|
+364|[Nested List Weight Sum II](./solutions/0364-nested-list-weight-sum-ii.js)|Medium|
365|[Water and Jug Problem](./solutions/0365-water-and-jug-problem.js)|Medium|
367|[Valid Perfect Square](./solutions/0367-valid-perfect-square.js)|Easy|
368|[Largest Divisible Subset](./solutions/0368-largest-divisible-subset.js)|Medium|
diff --git a/solutions/0364-nested-list-weight-sum-ii.js b/solutions/0364-nested-list-weight-sum-ii.js
new file mode 100644
index 00000000..dea3ecd0
--- /dev/null
+++ b/solutions/0364-nested-list-weight-sum-ii.js
@@ -0,0 +1,47 @@
+/**
+ * 364. Nested List Weight Sum II
+ * https://leetcode.com/problems/nested-list-weight-sum-ii/
+ * Difficulty: Medium
+ *
+ * You are given a nested list of integers nestedList. Each element is either an integer or
+ * a list whose elements may also be integers or other lists.
+ *
+ * The depth of an integer is the number of lists that it is inside of. For example, the
+ * nested list [1,[2,2],[[3],2],1] has each integer's value set to its depth. Let maxDepth
+ * be the maximum depth of any integer.
+ *
+ * The weight of an integer is maxDepth - (the depth of the integer) + 1.
+ *
+ * Return the sum of each integer in nestedList multiplied by its weight.
+ */
+
+/**
+ * @param {NestedInteger[]} nestedList
+ * @return {number}
+ */
+var depthSumInverse = function(nestedList) {
+ const maxDepth = findMaxDepth(nestedList, 1);
+ return calculateSum(nestedList, 1, maxDepth);
+
+ function findMaxDepth(list, depth) {
+ let maxDepth = depth;
+ for (const element of list) {
+ if (!element.isInteger()) {
+ maxDepth = Math.max(maxDepth, findMaxDepth(element.getList(), depth + 1));
+ }
+ }
+ return maxDepth;
+ }
+
+ function calculateSum(list, depth, maxDepth) {
+ let total = 0;
+ for (const element of list) {
+ if (element.isInteger()) {
+ total += element.getInteger() * (maxDepth - depth + 1);
+ } else {
+ total += calculateSum(element.getList(), depth + 1, maxDepth);
+ }
+ }
+ return total;
+ }
+};
From f7d749dc46b22c95fd6dc280c165335eb5f1adbc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 14 Jun 2025 19:02:01 -0500
Subject: [PATCH 490/994] Add solution #366
---
README.md | 1 +
solutions/0366-find-leaves-of-binary-tree.js | 43 ++++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/0366-find-leaves-of-binary-tree.js
diff --git a/README.md b/README.md
index f0e30ed1..407f31ea 100644
--- a/README.md
+++ b/README.md
@@ -354,6 +354,7 @@
363|[Max Sum of Rectangle No Larger Than K](./solutions/0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard|
364|[Nested List Weight Sum II](./solutions/0364-nested-list-weight-sum-ii.js)|Medium|
365|[Water and Jug Problem](./solutions/0365-water-and-jug-problem.js)|Medium|
+366|[Find Leaves of Binary Tree](./solutions/0366-find-leaves-of-binary-tree.js)|Medium|
367|[Valid Perfect Square](./solutions/0367-valid-perfect-square.js)|Easy|
368|[Largest Divisible Subset](./solutions/0368-largest-divisible-subset.js)|Medium|
371|[Sum of Two Integers](./solutions/0371-sum-of-two-integers.js)|Medium|
diff --git a/solutions/0366-find-leaves-of-binary-tree.js b/solutions/0366-find-leaves-of-binary-tree.js
new file mode 100644
index 00000000..45159fed
--- /dev/null
+++ b/solutions/0366-find-leaves-of-binary-tree.js
@@ -0,0 +1,43 @@
+/**
+ * 366. Find Leaves of Binary Tree
+ * https://leetcode.com/problems/find-leaves-of-binary-tree/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree, collect a tree's nodes as if you were doing this:
+ * - Collect all the leaf nodes.
+ * - Remove all the leaf nodes.
+ * - Repeat until the tree is empty.
+ */
+
+/**
+ * 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 findLeaves = function(root) {
+ const levels = [];
+ getHeight(root);
+ return levels;
+
+ function getHeight(node) {
+ if (!node) return -1;
+
+ const leftHeight = getHeight(node.left);
+ const rightHeight = getHeight(node.right);
+ const height = Math.max(leftHeight, rightHeight) + 1;
+
+ if (levels.length <= height) {
+ levels.push([]);
+ }
+ levels[height].push(node.val);
+
+ return height;
+ }
+};
From d2400611da0cc99ac016f780e27117aa5141ad18 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 15 Jun 2025 00:11:28 -0500
Subject: [PATCH 491/994] Add solution #369
---
README.md | 1 +
solutions/0369-plus-one-linked-list.js | 40 ++++++++++++++++++++++++++
2 files changed, 41 insertions(+)
create mode 100644 solutions/0369-plus-one-linked-list.js
diff --git a/README.md b/README.md
index 407f31ea..5f0e1860 100644
--- a/README.md
+++ b/README.md
@@ -357,6 +357,7 @@
366|[Find Leaves of Binary Tree](./solutions/0366-find-leaves-of-binary-tree.js)|Medium|
367|[Valid Perfect Square](./solutions/0367-valid-perfect-square.js)|Easy|
368|[Largest Divisible Subset](./solutions/0368-largest-divisible-subset.js)|Medium|
+369|[Plus One Linked List](./solutions/0369-plus-one-linked-list.js)|Medium|
371|[Sum of Two Integers](./solutions/0371-sum-of-two-integers.js)|Medium|
372|[Super Pow](./solutions/0372-super-pow.js)|Medium|
373|[Find K Pairs with Smallest Sums](./solutions/0373-find-k-pairs-with-smallest-sums.js)|Medium|
diff --git a/solutions/0369-plus-one-linked-list.js b/solutions/0369-plus-one-linked-list.js
new file mode 100644
index 00000000..0dbb048d
--- /dev/null
+++ b/solutions/0369-plus-one-linked-list.js
@@ -0,0 +1,40 @@
+/**
+ * 369. Plus One Linked List
+ * https://leetcode.com/problems/plus-one-linked-list/
+ * Difficulty: Medium
+ *
+ * Given a non-negative integer represented as a linked list of digits, plus one to the integer.
+ *
+ * The digits are stored such that the most significant digit is at the head of the 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 plusOne = function(head) {
+ const list = new ListNode(0, head);
+ let notNine = list;
+
+ while (head) {
+ if (head.val !== 9) notNine = head;
+ head = head.next;
+ }
+
+ notNine.val++;
+ notNine = notNine.next;
+
+ while (notNine) {
+ notNine.val = 0;
+ notNine = notNine.next;
+ }
+
+ return list.val === 0 ? list.next : list;
+};
From c441cb7a81f9ebfd7b4c21e8a5e3a8b71eaf90fe Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 15 Jun 2025 00:12:44 -0500
Subject: [PATCH 492/994] Add solution #370
---
README.md | 1 +
solutions/0370-range-addition.js | 34 ++++++++++++++++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/0370-range-addition.js
diff --git a/README.md b/README.md
index 5f0e1860..3d76cafd 100644
--- a/README.md
+++ b/README.md
@@ -358,6 +358,7 @@
367|[Valid Perfect Square](./solutions/0367-valid-perfect-square.js)|Easy|
368|[Largest Divisible Subset](./solutions/0368-largest-divisible-subset.js)|Medium|
369|[Plus One Linked List](./solutions/0369-plus-one-linked-list.js)|Medium|
+370|[Range Addition](./solutions/0370-range-addition.js)|Medium|
371|[Sum of Two Integers](./solutions/0371-sum-of-two-integers.js)|Medium|
372|[Super Pow](./solutions/0372-super-pow.js)|Medium|
373|[Find K Pairs with Smallest Sums](./solutions/0373-find-k-pairs-with-smallest-sums.js)|Medium|
diff --git a/solutions/0370-range-addition.js b/solutions/0370-range-addition.js
new file mode 100644
index 00000000..b10a3991
--- /dev/null
+++ b/solutions/0370-range-addition.js
@@ -0,0 +1,34 @@
+/**
+ * 370. Range Addition
+ * https://leetcode.com/problems/range-addition/
+ * Difficulty: Medium
+ *
+ * You are given an integer length and an array updates where
+ * updates[i] = [startIdxi, endIdxi, inci].
+ *
+ * You have an array arr of length length with all zeros, and you have some operation
+ * to apply on arr. In the ith operation, you should increment all the elements
+ * arr[startIdxi], arr[startIdxi + 1], ..., arr[endIdxi] by inci.
+ *
+ * Return arr after applying all the updates.
+ */
+
+/**
+ * @param {number} length
+ * @param {number[][]} updates
+ * @return {number[]}
+ */
+var getModifiedArray = function(length, updates) {
+ const result = new Array(length).fill(0);
+
+ for (const [start, end, inc] of updates) {
+ result[start] += inc;
+ if (end + 1 < length) result[end + 1] -= inc;
+ }
+
+ for (let i = 1; i < length; i++) {
+ result[i] += result[i - 1];
+ }
+
+ return result;
+};
From edd396e78e9e6769073f5a7303acf09739878c2a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 15 Jun 2025 09:25:11 -0500
Subject: [PATCH 493/994] Add solution #379
---
README.md | 1 +
solutions/0379-design-phone-directory.js | 64 ++++++++++++++++++++++++
2 files changed, 65 insertions(+)
create mode 100644 solutions/0379-design-phone-directory.js
diff --git a/README.md b/README.md
index 3d76cafd..50d81549 100644
--- a/README.md
+++ b/README.md
@@ -367,6 +367,7 @@
376|[Wiggle Subsequence](./solutions/0376-wiggle-subsequence.js)|Medium|
377|[Combination Sum IV](./solutions/0377-combination-sum-iv.js)|Medium|
378|[Kth Smallest Element in a Sorted Matrix](./solutions/0378-kth-smallest-element-in-a-sorted-matrix.js)|Medium|
+379|[Design Phone Directory](./solutions/0379-design-phone-directory.js)|Medium|
380|[Insert Delete GetRandom O(1)](./solutions/0380-insert-delete-getrandom-o1.js)|Medium|
381|[Insert Delete GetRandom O(1) - Duplicates allowed](./solutions/0381-insert-delete-getrandom-o1-duplicates-allowed.js)|Hard|
382|[Linked List Random Node](./solutions/0382-linked-list-random-node.js)|Medium|
diff --git a/solutions/0379-design-phone-directory.js b/solutions/0379-design-phone-directory.js
new file mode 100644
index 00000000..4973efa9
--- /dev/null
+++ b/solutions/0379-design-phone-directory.js
@@ -0,0 +1,64 @@
+/**
+ * 379. Design Phone Directory
+ * https://leetcode.com/problems/design-phone-directory/
+ * Difficulty: Medium
+ *
+ * Design a phone directory that initially has maxNumbers empty slots that can store numbers.
+ * The directory should store numbers, check if a certain slot is empty or not, and empty a
+ * given slot.
+ *
+ * Implement the PhoneDirectory class:
+ * - PhoneDirectory(int maxNumbers) Initializes the phone directory with the number of
+ * available slots maxNumbers.
+ * - int get() Provides a number that is not assigned to anyone. Returns -1 if no number
+ * is available.
+ * - bool check(int number) Returns true if the slot number is available and false otherwise.
+ * - void release(int number) Recycles or releases the slot number.
+ */
+
+/**
+ * @param {number} maxNumbers
+ */
+var PhoneDirectory = function(maxNumbers) {
+ this.available = new Set();
+ this.released = [];
+ this.max = maxNumbers;
+ for (let i = 0; i < maxNumbers; i++) {
+ this.available.add(i);
+ }
+};
+
+/**
+ * @return {number}
+ */
+PhoneDirectory.prototype.get = function() {
+ if (this.available.size === 0 && this.released.length === 0) return -1;
+ let number;
+ if (this.released.length > 0) {
+ number = this.released.pop();
+ } else {
+ number = this.available.values().next().value;
+ this.available.delete(number);
+ }
+ return number;
+};
+
+/**
+ * @param {number} number
+ * @return {boolean}
+ */
+PhoneDirectory.prototype.check = function(number) {
+ return number >= 0 && number < this.max
+ && (this.available.has(number) || this.released.includes(number));
+};
+
+/**
+ * @param {number} number
+ * @return {void}
+ */
+PhoneDirectory.prototype.release = function(number) {
+ if (number >= 0 && number < this.max
+ && !this.available.has(number) && !this.released.includes(number)) {
+ this.released.push(number);
+ }
+};
From b4c06b1329e68855bec9dd28af03700facbc9f01 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 15 Jun 2025 09:26:45 -0500
Subject: [PATCH 494/994] Add solution #408
---
README.md | 1 +
solutions/0408-valid-word-abbreviation.js | 55 +++++++++++++++++++++++
2 files changed, 56 insertions(+)
create mode 100644 solutions/0408-valid-word-abbreviation.js
diff --git a/README.md b/README.md
index 50d81549..8c4c39ee 100644
--- a/README.md
+++ b/README.md
@@ -396,6 +396,7 @@
405|[Convert a Number to Hexadecimal](./solutions/0405-convert-a-number-to-hexadecimal.js)|Easy|
406|[Queue Reconstruction by Height](./solutions/0406-queue-reconstruction-by-height.js)|Medium|
407|[Trapping Rain Water II](./solutions/0407-trapping-rain-water-ii.js)|Hard|
+408|[Valid Word Abbreviation](./solutions/0408-valid-word-abbreviation.js)|Easy|
409|[Longest Palindrome](./solutions/0409-longest-palindrome.js)|Easy|
410|[Split Array Largest Sum](./solutions/0410-split-array-largest-sum.js)|Hard|
412|[Fizz Buzz](./solutions/0412-fizz-buzz.js)|Easy|
diff --git a/solutions/0408-valid-word-abbreviation.js b/solutions/0408-valid-word-abbreviation.js
new file mode 100644
index 00000000..9dde3f72
--- /dev/null
+++ b/solutions/0408-valid-word-abbreviation.js
@@ -0,0 +1,55 @@
+/**
+ * 408. Valid Word Abbreviation
+ * https://leetcode.com/problems/valid-word-abbreviation/
+ * Difficulty: Easy
+ *
+ * A string can be abbreviated by replacing any number of non-adjacent, non-empty substrings
+ * with their lengths. The lengths should not have leading zeros.
+ *
+ * For example, a string such as "substitution" could be abbreviated as (but not limited to):
+ * - "s10n" ("s ubstitutio n")
+ * - "sub4u4" ("sub stit u tion")
+ * - "12" ("substitution")
+ * - "su3i1u2on" ("su bst i t u ti on")
+ * - "substitution" (no substrings replaced)
+ *
+ * The following are not valid abbreviations:
+ * - "s55n" ("s ubsti tutio n", the replaced substrings are adjacent)
+ * - "s010n" (has leading zeros)
+ * - "s0ubstitution" (replaces an empty substring)
+ *
+ * Given a string word and an abbreviation abbr, return whether the string matches the given
+ * abbreviation.
+ *
+ * A substring is a contiguous non-empty sequence of characters within a string.
+ */
+
+/**
+ * @param {string} word
+ * @param {string} abbr
+ * @return {boolean}
+ */
+var validWordAbbreviation = function(word, abbr) {
+ let wordIndex = 0;
+ let abbrIndex = 0;
+
+ while (wordIndex < word.length && abbrIndex < abbr.length) {
+ if (word[wordIndex] === abbr[abbrIndex]) {
+ wordIndex++;
+ abbrIndex++;
+ continue;
+ }
+
+ if (abbr[abbrIndex] < '0' || abbr[abbrIndex] > '9') return false;
+ if (abbr[abbrIndex] === '0') return false;
+
+ let num = 0;
+ while (abbrIndex < abbr.length && /[0-9]/.test(abbr[abbrIndex])) {
+ num = num * 10 + Number(abbr[abbrIndex]);
+ abbrIndex++;
+ }
+ wordIndex += num;
+ }
+
+ return wordIndex === word.length && abbrIndex === abbr.length;
+};
From a58fa8f88bd79c0e6212b13389fcf9cb23fd7fc5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 15 Jun 2025 09:29:11 -0500
Subject: [PATCH 495/994] Add solution #411
---
README.md | 1 +
.../0411-minimum-unique-word-abbreviation.js | 97 +++++++++++++++++++
2 files changed, 98 insertions(+)
create mode 100644 solutions/0411-minimum-unique-word-abbreviation.js
diff --git a/README.md b/README.md
index 8c4c39ee..21b2efdb 100644
--- a/README.md
+++ b/README.md
@@ -399,6 +399,7 @@
408|[Valid Word Abbreviation](./solutions/0408-valid-word-abbreviation.js)|Easy|
409|[Longest Palindrome](./solutions/0409-longest-palindrome.js)|Easy|
410|[Split Array Largest Sum](./solutions/0410-split-array-largest-sum.js)|Hard|
+411|[Minimum Unique Word Abbreviation](./solutions/0411-minimum-unique-word-abbreviation.js)|Hard|
412|[Fizz Buzz](./solutions/0412-fizz-buzz.js)|Easy|
413|[Arithmetic Slices](./solutions/0413-arithmetic-slices.js)|Medium|
414|[Third Maximum Number](./solutions/0414-third-maximum-number.js)|Easy|
diff --git a/solutions/0411-minimum-unique-word-abbreviation.js b/solutions/0411-minimum-unique-word-abbreviation.js
new file mode 100644
index 00000000..f595afd4
--- /dev/null
+++ b/solutions/0411-minimum-unique-word-abbreviation.js
@@ -0,0 +1,97 @@
+/**
+ * 411. Minimum Unique Word Abbreviation
+ * https://leetcode.com/problems/minimum-unique-word-abbreviation/
+ * Difficulty: Hard
+ *
+ * A string can be abbreviated by replacing any number of non-adjacent substrings with their
+ * lengths. For example, a string such as "substitution" could be abbreviated as (but not
+ * limited to):
+ * - "s10n" ("s ubstitutio n")
+ * - "sub4u4" ("sub stit u tion")
+ * - "12" ("substitution")
+ * - "su3i1u2on" ("su bst i t u ti on")
+ * - "substitution" (no substrings replaced)
+ *
+ * Note that "s55n" ("s ubsti tutio n") is not a valid abbreviation of "substitution" because
+ * the replaced substrings are adjacent.
+ *
+ * The length of an abbreviation is the number of letters that were not replaced plus the
+ * number of substrings that were replaced. For example, the abbreviation "s10n" has a length
+ * of 3 (2 letters + 1 substring) and "su3i1u2on" has a length of 9 (6 letters + 3 substrings).
+ *
+ * Given a target string target and an array of strings dictionary, return an abbreviation
+ * of target with the shortest possible length such that it is not an abbreviation of any
+ * string in dictionary. If there are multiple shortest abbreviations, return any of them.
+ */
+
+/**
+ * @param {string} target
+ * @param {string[]} dictionary
+ * @return {string}
+ */
+var minAbbreviation = function(target, dictionary) {
+ let minLength = target.length;
+ let result = target;
+ const validDict = dictionary.filter(word => word.length === target.length);
+
+ for (let mask = 0; mask < (1 << target.length); mask++) {
+ const abbr = getAbbr(target, mask);
+ if (abbr.length <= minLength) {
+ let isValid = true;
+ for (const word of validDict) {
+ if (conflicts(abbr, word)) {
+ isValid = false;
+ break;
+ }
+ }
+ if (isValid) {
+ if (abbr.length < minLength) {
+ minLength = abbr.length;
+ result = abbr;
+ } else if (abbr.length === minLength && abbr < result) {
+ result = abbr;
+ }
+ }
+ }
+ }
+
+ return result;
+
+ function getAbbr(str, mask) {
+ let abbr = '';
+ let count = 0;
+ for (let i = 0; i < str.length; i++) {
+ if (mask & (1 << i)) {
+ if (count) {
+ abbr += count;
+ count = 0;
+ }
+ abbr += str[i];
+ } else {
+ count++;
+ }
+ }
+ if (count) abbr += count;
+ return abbr;
+ }
+
+ function conflicts(abbr, word) {
+ let i = 0;
+ let j = 0;
+ while (i < abbr.length && j < word.length) {
+ if (i < abbr.length && j < word.length && abbr[i] === word[j]) {
+ i++;
+ j++;
+ } else if (i < abbr.length && /\d/.test(abbr[i])) {
+ let num = 0;
+ while (i < abbr.length && /\d/.test(abbr[i])) {
+ num = num * 10 + Number(abbr[i++]);
+ }
+ j += num;
+ } else {
+ return false;
+ }
+ }
+ return i === abbr.length && j === word.length;
+ }
+};
From dc20cb2d4a8fda487c481e067ae96304bb948985 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 16 Jun 2025 23:46:42 -0500
Subject: [PATCH 496/994] Add solution #3405
---
README.md | 1 +
...rrays-with-k-matching-adjacent-elements.js | 69 +++++++++++++++++++
2 files changed, 70 insertions(+)
create mode 100644 solutions/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.js
diff --git a/README.md b/README.md
index 21b2efdb..467d9ed0 100644
--- a/README.md
+++ b/README.md
@@ -2278,6 +2278,7 @@
3397|[Maximum Number of Distinct Elements After Operations](./solutions/3397-maximum-number-of-distinct-elements-after-operations.js)|Medium|
3402|[Minimum Operations to Make Columns Strictly Increasing](./solutions/3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy|
3403|[Find the Lexicographically Largest String From the Box I](./solutions/3403-find-the-lexicographically-largest-string-from-the-box-i.js)|Medium|
+3405|[Count the Number of Arrays with K Matching Adjacent Elements](./solutions/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.js)|Hard|
3423|[Maximum Difference Between Adjacent Elements in a Circular Array](./solutions/3423-maximum-difference-between-adjacent-elements-in-a-circular-array.js)|Easy|
3442|[Maximum Difference Between Even and Odd Frequency I](./solutions/3442-maximum-difference-between-even-and-odd-frequency-i.js)|Easy|
3445|[Maximum Difference Between Even and Odd Frequency II](./solutions/3445-maximum-difference-between-even-and-odd-frequency-ii.js)|Hard|
diff --git a/solutions/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.js b/solutions/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.js
new file mode 100644
index 00000000..493e1f28
--- /dev/null
+++ b/solutions/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.js
@@ -0,0 +1,69 @@
+/**
+ * 3405. Count the Number of Arrays with K Matching Adjacent Elements
+ * https://leetcode.com/problems/count-the-number-of-arrays-with-k-matching-adjacent-elements/
+ * Difficulty: Hard
+ *
+ * You are given three integers n, m, k. A good array arr of size n is defined as follows:
+ * - Each element in arr is in the inclusive range [1, m].
+ * - Exactly k indices i (where 1 <= i < n) satisfy the condition arr[i - 1] == arr[i].
+ *
+ * Return the number of good arrays that can be formed.
+ *
+ * Since the answer may be very large, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} m
+ * @param {number} k
+ * @return {number}
+ */
+var countGoodArrays = function(n, m, k) {
+ const MOD = 1e9 + 7;
+
+ if (m === 1) {
+ return k === n - 1 ? 1 : 0;
+ }
+
+ const choose = binomialCoeff(n - 1, k);
+ const power = modPow(m - 1, n - 1 - k, MOD);
+ const result = Number((BigInt(choose) * BigInt(m) * BigInt(power)) % BigInt(MOD));
+
+ return result;
+
+ function modPow(base, exp, mod) {
+ let result = 1n;
+ base = ((BigInt(base) % BigInt(mod)) + BigInt(mod)) % BigInt(mod);
+ exp = BigInt(exp);
+ mod = BigInt(mod);
+
+ while (exp > 0n) {
+ if (exp & 1n) result = (result * base) % mod;
+ base = (base * base) % mod;
+ exp >>= 1n;
+ }
+ return Number(result);
+ }
+
+ function modInverse(a, mod) {
+ return modPow(a, mod - 2, mod);
+ }
+
+ function binomialCoeff(n, k) {
+ if (k > n || k < 0) return 0;
+ if (k === 0 || k === n) return 1;
+
+ if (k > n - k) k = n - k;
+
+ let numerator = 1n;
+ let denominator = 1n;
+
+ for (let i = 0; i < k; i++) {
+ numerator = (numerator * BigInt(n - i)) % BigInt(MOD);
+ denominator = (denominator * BigInt(i + 1)) % BigInt(MOD);
+ }
+
+ const invDenom = modInverse(Number(denominator), MOD);
+ return Number((numerator * BigInt(invDenom)) % BigInt(MOD));
+ }
+};
From c35d51b292a138c042b02a443c51ea99a1776741 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 16 Jun 2025 23:49:43 -0500
Subject: [PATCH 497/994] Add solution #418
---
README.md | 1 +
solutions/0418-sentence-screen-fitting.js | 42 +++++++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/0418-sentence-screen-fitting.js
diff --git a/README.md b/README.md
index 467d9ed0..b75d9a17 100644
--- a/README.md
+++ b/README.md
@@ -406,6 +406,7 @@
415|[Add Strings](./solutions/0415-add-strings.js)|Easy|
416|[Partition Equal Subset Sum](./solutions/0416-partition-equal-subset-sum.js)|Medium|
417|[Pacific Atlantic Water Flow](./solutions/0417-pacific-atlantic-water-flow.js)|Medium|
+418|[Sentence Screen Fitting](./solutions/0418-sentence-screen-fitting.js)|Medium|
419|[Battleships in a Board](./solutions/0419-battleships-in-a-board.js)|Medium|
420|[Strong Password Checker](./solutions/0420-strong-password-checker.js)|Hard|
421|[Maximum XOR of Two Numbers in an Array](./solutions/0421-maximum-xor-of-two-numbers-in-an-array.js)|Medium|
diff --git a/solutions/0418-sentence-screen-fitting.js b/solutions/0418-sentence-screen-fitting.js
new file mode 100644
index 00000000..68a6a992
--- /dev/null
+++ b/solutions/0418-sentence-screen-fitting.js
@@ -0,0 +1,42 @@
+/**
+ * 418. Sentence Screen Fitting
+ * https://leetcode.com/problems/sentence-screen-fitting/
+ * Difficulty: Medium
+ *
+ * Given a rows x cols screen and a sentence represented as a list of strings, return the number
+ * of times the given sentence can be fitted on the screen.
+ *
+ * The order of words in the sentence must remain unchanged, and a word cannot be split into two
+ * lines. A single space must separate two consecutive words in a line.
+ */
+
+/**
+ * @param {string[]} sentence
+ * @param {number} rows
+ * @param {number} cols
+ * @return {number}
+ */
+var wordsTyping = function(sentence, rows, cols) {
+ const sentenceLength = sentence.length;
+ const wordLengths = sentence.map(word => word.length + 1);
+ let rowIndex = 0;
+ let colIndex = 0;
+ let wordIndex = 0;
+ let result = 0;
+
+ while (rowIndex < rows) {
+ if (colIndex + wordLengths[wordIndex] - 1 <= cols) {
+ colIndex += wordLengths[wordIndex];
+ wordIndex++;
+ if (wordIndex === sentenceLength) {
+ result++;
+ wordIndex = 0;
+ }
+ } else {
+ rowIndex++;
+ colIndex = 0;
+ }
+ }
+
+ return result;
+};
From 592944fe8f33bdc6d94d43170deece7bf799ef4b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 16 Jun 2025 23:50:32 -0500
Subject: [PATCH 498/994] Add solution #422
---
README.md | 1 +
solutions/0422-valid-word-square.js | 30 +++++++++++++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 solutions/0422-valid-word-square.js
diff --git a/README.md b/README.md
index b75d9a17..057d89a4 100644
--- a/README.md
+++ b/README.md
@@ -410,6 +410,7 @@
419|[Battleships in a Board](./solutions/0419-battleships-in-a-board.js)|Medium|
420|[Strong Password Checker](./solutions/0420-strong-password-checker.js)|Hard|
421|[Maximum XOR of Two Numbers in an Array](./solutions/0421-maximum-xor-of-two-numbers-in-an-array.js)|Medium|
+422|[Valid Word Square](./solutions/0422-valid-word-square.js)|Easy|
423|[Reconstruct Original Digits from English](./solutions/0423-reconstruct-original-digits-from-english.js)|Medium|
424|[Longest Repeating Character Replacement](./solutions/0424-longest-repeating-character-replacement.js)|Medium|
427|[Construct Quad Tree](./solutions/0427-construct-quad-tree.js)|Medium|
diff --git a/solutions/0422-valid-word-square.js b/solutions/0422-valid-word-square.js
new file mode 100644
index 00000000..36f46305
--- /dev/null
+++ b/solutions/0422-valid-word-square.js
@@ -0,0 +1,30 @@
+/**
+ * 422. Valid Word Square
+ * https://leetcode.com/problems/valid-word-square/
+ * Difficulty: Easy
+ *
+ * Given an array of strings words, return true if it forms a valid word square.
+ *
+ * A sequence of strings forms a valid word square if the kth row and column read the same
+ * string, where 0 <= k < max(numRows, numColumns).
+ */
+
+/**
+ * @param {string[]} words
+ * @return {boolean}
+ */
+var validWordSquare = function(words) {
+ const rowCount = words.length;
+
+ for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
+ const row = words[rowIndex];
+ for (let colIndex = 0; colIndex < row.length; colIndex++) {
+ if (colIndex >= rowCount || rowIndex >= words[colIndex].length
+ || row[colIndex] !== words[colIndex][rowIndex]) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+};
From 51ac1cce6cb853a146ca8437b7d5a73bb0fa7469 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 16 Jun 2025 23:55:56 -0500
Subject: [PATCH 499/994] Add solution #425
---
README.md | 1 +
solutions/0425-word-squares.js | 59 ++++++++++++++++++++++++++++++++++
2 files changed, 60 insertions(+)
create mode 100644 solutions/0425-word-squares.js
diff --git a/README.md b/README.md
index 057d89a4..9ae2415b 100644
--- a/README.md
+++ b/README.md
@@ -413,6 +413,7 @@
422|[Valid Word Square](./solutions/0422-valid-word-square.js)|Easy|
423|[Reconstruct Original Digits from English](./solutions/0423-reconstruct-original-digits-from-english.js)|Medium|
424|[Longest Repeating Character Replacement](./solutions/0424-longest-repeating-character-replacement.js)|Medium|
+425|[Word Squares](./solutions/0425-word-squares.js)|Hard|
427|[Construct Quad Tree](./solutions/0427-construct-quad-tree.js)|Medium|
429|[N-ary Tree Level Order Traversal](./solutions/0429-n-ary-tree-level-order-traversal.js)|Medium|
430|[Flatten a Multilevel Doubly Linked List](./solutions/0430-flatten-a-multilevel-doubly-linked-list.js)|Medium|
diff --git a/solutions/0425-word-squares.js b/solutions/0425-word-squares.js
new file mode 100644
index 00000000..4a124ea3
--- /dev/null
+++ b/solutions/0425-word-squares.js
@@ -0,0 +1,59 @@
+/**
+ * 425. Word Squares
+ * https://leetcode.com/problems/word-squares/
+ * Difficulty: Hard
+ *
+ * Given an array of unique strings words, return all the word squares you can build from
+ * words. The same word from words can be used multiple times. You can return the answer
+ * in any order.
+ *
+ * A sequence of strings forms a valid word square if the kth row and column read the same
+ * string, where 0 <= k < max(numRows, numColumns).
+ *
+ * - For example, the word sequence ["ball","area","lead","lady"] forms a word square because
+ * each word reads the same both horizontally and vertically.
+ */
+
+/**
+ * @param {string[]} words
+ * @return {string[][]}
+ */
+var wordSquares = function(words) {
+ const result = [];
+ const prefixMap = new Map();
+ const wordLength = words[0].length;
+
+ for (const word of words) {
+ for (let i = 0; i < word.length; i++) {
+ const prefix = word.slice(0, i);
+ if (!prefixMap.has(prefix)) {
+ prefixMap.set(prefix, []);
+ }
+ prefixMap.get(prefix).push(word);
+ }
+ }
+
+ function buildSquare(currentSquare) {
+ if (currentSquare.length === wordLength) {
+ result.push([...currentSquare]);
+ return;
+ }
+
+ const prefix = currentSquare
+ .map(word => word[currentSquare.length])
+ .join('');
+
+ const candidates = prefixMap.get(prefix) || [];
+ for (const candidate of candidates) {
+ currentSquare.push(candidate);
+ buildSquare(currentSquare);
+ currentSquare.pop();
+ }
+ }
+
+ for (const word of words) {
+ buildSquare([word]);
+ }
+
+ return result;
+};
From 8ee3d92135a982f0471b07c5b02805aaca35703e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 16 Jun 2025 23:57:22 -0500
Subject: [PATCH 500/994] Add solution #426
---
README.md | 1 +
...earch-tree-to-sorted-doubly-linked-list.js | 58 +++++++++++++++++++
2 files changed, 59 insertions(+)
create mode 100644 solutions/0426-convert-binary-search-tree-to-sorted-doubly-linked-list.js
diff --git a/README.md b/README.md
index 9ae2415b..31c111b3 100644
--- a/README.md
+++ b/README.md
@@ -414,6 +414,7 @@
423|[Reconstruct Original Digits from English](./solutions/0423-reconstruct-original-digits-from-english.js)|Medium|
424|[Longest Repeating Character Replacement](./solutions/0424-longest-repeating-character-replacement.js)|Medium|
425|[Word Squares](./solutions/0425-word-squares.js)|Hard|
+426|[Convert Binary Search Tree to Sorted Doubly Linked List](./solutions/0426-convert-binary-search-tree-to-sorted-doubly-linked-list.js)|Medium|
427|[Construct Quad Tree](./solutions/0427-construct-quad-tree.js)|Medium|
429|[N-ary Tree Level Order Traversal](./solutions/0429-n-ary-tree-level-order-traversal.js)|Medium|
430|[Flatten a Multilevel Doubly Linked List](./solutions/0430-flatten-a-multilevel-doubly-linked-list.js)|Medium|
diff --git a/solutions/0426-convert-binary-search-tree-to-sorted-doubly-linked-list.js b/solutions/0426-convert-binary-search-tree-to-sorted-doubly-linked-list.js
new file mode 100644
index 00000000..77ba2440
--- /dev/null
+++ b/solutions/0426-convert-binary-search-tree-to-sorted-doubly-linked-list.js
@@ -0,0 +1,58 @@
+/**
+ * 426. Convert Binary Search Tree to Sorted Doubly Linked List
+ * https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/
+ * Difficulty: Medium
+ *
+ * Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place.
+ *
+ * You can think of the left and right pointers as synonymous to the predecessor and successor
+ * pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the
+ * first element is the last element, and the successor of the last element is the first element.
+ *
+ * We want to do the transformation in place. After the transformation, the left pointer of the
+ * tree node should point to its predecessor, and the right pointer should point to its successor.
+ * You should return the pointer to the smallest element of the linked list.
+ */
+
+/**
+ * // Definition for a _Node.
+ * function _Node(val, left, right) {
+ * this.val = val;
+ * this.left = left;
+ * this.right = right;
+ * };
+ */
+
+/**
+ * @param {_Node} root
+ * @return {_Node}
+ */
+var treeToDoublyList = function(root) {
+ if (!root) return null;
+
+ let first = null;
+ let last = null;
+
+ inorder(root);
+
+ last.right = first;
+ first.left = last;
+
+ return first;
+
+ function inorder(node) {
+ if (!node) return;
+
+ inorder(node.left);
+
+ if (last) {
+ last.right = node;
+ node.left = last;
+ } else {
+ first = node;
+ }
+ last = node;
+
+ inorder(node.right);
+ }
+};
From 1af36bb078fa6475d88ee6472ffd8596651a8ad2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 17 Jun 2025 23:19:36 -0500
Subject: [PATCH 501/994] Add solution #428
---
README.md | 1 +
...28-serialize-and-deserialize-n-ary-tree.js | 74 +++++++++++++++++++
2 files changed, 75 insertions(+)
create mode 100644 solutions/0428-serialize-and-deserialize-n-ary-tree.js
diff --git a/README.md b/README.md
index 31c111b3..c6a8986f 100644
--- a/README.md
+++ b/README.md
@@ -416,6 +416,7 @@
425|[Word Squares](./solutions/0425-word-squares.js)|Hard|
426|[Convert Binary Search Tree to Sorted Doubly Linked List](./solutions/0426-convert-binary-search-tree-to-sorted-doubly-linked-list.js)|Medium|
427|[Construct Quad Tree](./solutions/0427-construct-quad-tree.js)|Medium|
+428|[Serialize and Deserialize N-ary Tree](./solutions/0428-serialize-and-deserialize-n-ary-tree.js)|Hard|
429|[N-ary Tree Level Order Traversal](./solutions/0429-n-ary-tree-level-order-traversal.js)|Medium|
430|[Flatten a Multilevel Doubly Linked List](./solutions/0430-flatten-a-multilevel-doubly-linked-list.js)|Medium|
432|[All O`one Data Structure](./solutions/0432-all-oone-data-structure.js)|Hard|
diff --git a/solutions/0428-serialize-and-deserialize-n-ary-tree.js b/solutions/0428-serialize-and-deserialize-n-ary-tree.js
new file mode 100644
index 00000000..8128bde1
--- /dev/null
+++ b/solutions/0428-serialize-and-deserialize-n-ary-tree.js
@@ -0,0 +1,74 @@
+/**
+ * 428. Serialize and Deserialize N-ary Tree
+ * https://leetcode.com/problems/serialize-and-deserialize-n-ary-tree/
+ * Difficulty: Hard
+ *
+ * Serialization is the process of converting a data structure or object into a sequence of
+ * bits so that it can be stored in a file or memory buffer, or transmitted across a network
+ * connection link to be reconstructed later in the same or another computer environment.
+ *
+ * Design an algorithm to serialize and deserialize an N-ary tree. An N-ary tree is a rooted
+ * tree in which each node has no more than N children. There is no restriction on how your
+ * serialization/deserialization algorithm should work. You just need to ensure that an N-ary
+ * tree can be serialized to a string and this string can be deserialized to the original
+ * tree structure.
+ *
+ * For example, you may serialize the following 3-ary tree as [1 [3[5 6] 2 4]]. Note that
+ * this is just an example, you do not necessarily need to follow this format.
+ *
+ * Or you can follow LeetCode's level order traversal serialization format, where each
+ * group of children is separated by the null value.
+ *
+ * For example, the above tree may be serialized as
+ * [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14].
+ *
+ * You do not necessarily need to follow the above-suggested formats, there are many more
+ * different formats that work so please be creative and come up with different approaches
+ * yourself.
+ */
+
+/**
+ * // Definition for a _Node.
+ * function _Node(val,children) {
+ * this.val = val;
+ * this.children = children;
+ * };
+ */
+
+class Codec {
+ constructor() {}
+
+ serialize = function(root) {
+ if (!root) return '';
+ const result = [];
+
+ function serializeNode(node) {
+ result.push(node.val);
+ result.push(node.children.length);
+ for (const child of node.children) {
+ serializeNode(child);
+ }
+ }
+
+ serializeNode(root);
+ return result.join(',');
+ };
+
+ deserialize = function(data) {
+ if (!data) return null;
+ const values = data.split(',').map(Number);
+ let index = 0;
+
+ function deserializeNode() {
+ const val = values[index++];
+ const childCount = values[index++];
+ const children = [];
+ for (let i = 0; i < childCount; i++) {
+ children.push(deserializeNode());
+ }
+ return new _Node(val, children);
+ }
+
+ return deserializeNode();
+ };
+}
From d775c97629f26fba277b3694a3bf0ab1357c0d91 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 17 Jun 2025 23:22:33 -0500
Subject: [PATCH 502/994] Add solution #431
---
README.md | 1 +
.../0431-encode-n-ary-tree-to-binary-tree.js | 74 +++++++++++++++++++
2 files changed, 75 insertions(+)
create mode 100644 solutions/0431-encode-n-ary-tree-to-binary-tree.js
diff --git a/README.md b/README.md
index c6a8986f..47f62550 100644
--- a/README.md
+++ b/README.md
@@ -419,6 +419,7 @@
428|[Serialize and Deserialize N-ary Tree](./solutions/0428-serialize-and-deserialize-n-ary-tree.js)|Hard|
429|[N-ary Tree Level Order Traversal](./solutions/0429-n-ary-tree-level-order-traversal.js)|Medium|
430|[Flatten a Multilevel Doubly Linked List](./solutions/0430-flatten-a-multilevel-doubly-linked-list.js)|Medium|
+431|[Encode N-ary Tree to Binary Tree](./solutions/0431-encode-n-ary-tree-to-binary-tree.js)|Hard|
432|[All O`one Data Structure](./solutions/0432-all-oone-data-structure.js)|Hard|
433|[Minimum Genetic Mutation](./solutions/0433-minimum-genetic-mutation.js)|Medium|
434|[Number of Segments in a String](./solutions/0434-number-of-segments-in-a-string.js)|Easy|
diff --git a/solutions/0431-encode-n-ary-tree-to-binary-tree.js b/solutions/0431-encode-n-ary-tree-to-binary-tree.js
new file mode 100644
index 00000000..6a7cf758
--- /dev/null
+++ b/solutions/0431-encode-n-ary-tree-to-binary-tree.js
@@ -0,0 +1,74 @@
+/**
+ * 431. Encode N-ary Tree to Binary Tree
+ * https://leetcode.com/problems/encode-n-ary-tree-to-binary-tree/
+ * Difficulty: Hard
+ *
+ * Design an algorithm to encode an N-ary tree into a binary tree and decode the binary tree
+ * to get the original N-ary tree. An N-ary tree is a rooted tree in which each node has no
+ * more than N children. Similarly, a binary tree is a rooted tree in which each node has no
+ * more than 2 children. There is no restriction on how your encode/decode algorithm should
+ * work. You just need to ensure that an N-ary tree can be encoded to a binary tree and this
+ * binary tree can be decoded to the original N-nary tree structure.
+ *
+ * Nary-Tree input serialization is represented in their level order traversal, each group
+ * of children is separated by the null value (See following example).
+ *
+ * For example, you may encode the following 3-ary tree to a binary tree in this way:
+ * - Input: root = [1,null,3,2,4,null,5,6]
+ *
+ * Note that the above is just an example which might or might not work. You do not necessarily
+ * need to follow this format, so please be creative and come up with different approaches yourself.
+ */
+
+/**
+ * // Definition for a _Node.
+ * function _Node(val,children) {
+ * this.val = val;
+ * this.children = children;
+ * };
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val) {
+ * this.val = val;
+ * this.left = this.right = null;
+ * }
+ */
+
+class Codec {
+ constructor() {}
+
+ encode = function(root) {
+ if (!root) return null;
+
+ const binaryRoot = new TreeNode(root.val);
+
+ if (root.children.length > 0) {
+ binaryRoot.left = this.encode(root.children[0]);
+ }
+
+ let sibling = binaryRoot.left;
+ for (let i = 1; i < root.children.length; i++) {
+ if (sibling) {
+ sibling.right = this.encode(root.children[i]);
+ sibling = sibling.right;
+ }
+ }
+
+ return binaryRoot;
+ };
+
+ decode = function(root) {
+ if (!root) return null;
+
+ const updated = new _Node(root.val, []);
+ let sibling = root.left;
+ while (sibling) {
+ updated.children.push(this.decode(sibling));
+ sibling = sibling.right;
+ }
+
+ return updated;
+ };
+}
From fef47470de32b5610f1ec5e66637ebc3441d985b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 17 Jun 2025 23:30:59 -0500
Subject: [PATCH 503/994] Add solution #439
---
README.md | 1 +
solutions/0439-ternary-expression-parser.js | 38 +++++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/0439-ternary-expression-parser.js
diff --git a/README.md b/README.md
index 47f62550..83fd9733 100644
--- a/README.md
+++ b/README.md
@@ -427,6 +427,7 @@
436|[Find Right Interval](./solutions/0436-find-right-interval.js)|Medium|
437|[Path Sum III](./solutions/0437-path-sum-iii.js)|Medium|
438|[Find All Anagrams in a String](./solutions/0438-find-all-anagrams-in-a-string.js)|Medium|
+439|[Ternary Expression Parser](./solutions/0439-ternary-expression-parser.js)|Medium|
440|[K-th Smallest in Lexicographical Order](./solutions/0440-k-th-smallest-in-lexicographical-order.js)|Hard|
441|[Arranging Coins](./solutions/0441-arranging-coins.js)|Easy|
442|[Find All Duplicates in an Array](./solutions/0442-find-all-duplicates-in-an-array.js)|Medium|
diff --git a/solutions/0439-ternary-expression-parser.js b/solutions/0439-ternary-expression-parser.js
new file mode 100644
index 00000000..586a3b73
--- /dev/null
+++ b/solutions/0439-ternary-expression-parser.js
@@ -0,0 +1,38 @@
+/**
+ * 439. Ternary Expression Parser
+ * https://leetcode.com/problems/ternary-expression-parser/
+ * Difficulty: Medium
+ *
+ * Given a string expression representing arbitrarily nested ternary expressions,
+ * evaluate the expression, and return the result of it.
+ *
+ * You can always assume that the given expression is valid and only contains digits,
+ * '?', ':', 'T', and 'F' where 'T' is true and 'F' is false. All the numbers in the
+ * expression are one-digit numbers (i.e., in the range [0, 9]).
+ *
+ * The conditional expressions group right-to-left (as usual in most languages), and
+ * the result of the expression will always evaluate to either a digit, 'T' or 'F'.
+ */
+
+/**
+ * @param {string} expression
+ * @return {string}
+ */
+var parseTernary = function(expression) {
+ const stack = [];
+
+ for (let i = expression.length - 1; i >= 0; i--) {
+ const char = expression[i];
+ if (char !== ':' && char !== '?') {
+ stack.push(char);
+ } else if (char === '?') {
+ const condition = expression[i - 1];
+ const trueValue = stack.pop();
+ const falseValue = stack.pop();
+ stack.push(condition === 'T' ? trueValue : falseValue);
+ i--;
+ }
+ }
+
+ return stack[0];
+};
From 4a3975667c07a591fe3697d527071d78e6eaec45 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 17 Jun 2025 23:32:23 -0500
Subject: [PATCH 504/994] Add solution #444
---
README.md | 1 +
solutions/0444-sequence-reconstruction.js | 70 +++++++++++++++++++++++
2 files changed, 71 insertions(+)
create mode 100644 solutions/0444-sequence-reconstruction.js
diff --git a/README.md b/README.md
index 83fd9733..84a92d4c 100644
--- a/README.md
+++ b/README.md
@@ -432,6 +432,7 @@
441|[Arranging Coins](./solutions/0441-arranging-coins.js)|Easy|
442|[Find All Duplicates in an Array](./solutions/0442-find-all-duplicates-in-an-array.js)|Medium|
443|[String Compression](./solutions/0443-string-compression.js)|Medium|
+444|[Sequence Reconstruction](./solutions/0444-sequence-reconstruction.js)|Medium|
445|[Add Two Numbers II](./solutions/0445-add-two-numbers-ii.js)|Medium|
446|[Arithmetic Slices II - Subsequence](./solutions/0446-arithmetic-slices-ii-subsequence.js)|Hard|
447|[Number of Boomerangs](./solutions/0447-number-of-boomerangs.js)|Medium|
diff --git a/solutions/0444-sequence-reconstruction.js b/solutions/0444-sequence-reconstruction.js
new file mode 100644
index 00000000..a972a0ca
--- /dev/null
+++ b/solutions/0444-sequence-reconstruction.js
@@ -0,0 +1,70 @@
+/**
+ * 444. Sequence Reconstruction
+ * https://leetcode.com/problems/sequence-reconstruction/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums of length n where nums is a permutation of the
+ * integers in the range [1, n]. You are also given a 2D integer array sequences where
+ * sequences[i] is a subsequence of nums.
+ *
+ * Check if nums is the shortest possible and the only supersequence. The shortest
+ * supersequence is a sequence with the shortest length and has all sequences[i] as
+ * subsequences. There could be multiple valid supersequences for the given array sequences.
+ * - For example, for sequences = [[1,2],[1,3]], there are two shortest supersequences,
+ * [1,2,3] and [1,3,2].
+ * - While for sequences = [[1,2],[1,3],[1,2,3]], the only shortest supersequence possible
+ * is [1,2,3]. [1,2,3,4] is a possible supersequence but not the shortest.
+ *
+ * Return true if nums is the only shortest supersequence for sequences, or false otherwise.
+ *
+ * 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[][]} sequences
+ * @return {boolean}
+ */
+var sequenceReconstruction = function(nums, sequences) {
+ const n = nums.length;
+ const graph = new Map();
+ const inDegree = new Array(n + 1).fill(0);
+
+ for (let i = 1; i <= n; i++) {
+ graph.set(i, []);
+ }
+
+ for (const seq of sequences) {
+ for (let i = 1; i < seq.length; i++) {
+ graph.get(seq[i - 1]).push(seq[i]);
+ inDegree[seq[i]]++;
+ }
+ }
+
+ const queue = [];
+ for (let i = 1; i <= n; i++) {
+ if (inDegree[i] === 0) {
+ queue.push(i);
+ }
+ }
+
+ if (queue.length !== 1) return false;
+
+ const result = [];
+ while (queue.length) {
+ if (queue.length > 1) return false;
+ const curr = queue.shift();
+ result.push(curr);
+
+ const nextNodes = graph.get(curr);
+ for (const next of nextNodes) {
+ inDegree[next]--;
+ if (inDegree[next] === 0) {
+ queue.push(next);
+ }
+ }
+ }
+
+ return result.length === n && result.every((val, i) => val === nums[i]);
+};
From 366886d6a2f2d53d4770b07fd26add55265bb7bf Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 17 Jun 2025 23:38:40 -0500
Subject: [PATCH 505/994] Add solution #465
---
README.md | 1 +
solutions/0465-optimal-account-balancing.js | 46 +++++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/0465-optimal-account-balancing.js
diff --git a/README.md b/README.md
index 84a92d4c..2342c90e 100644
--- a/README.md
+++ b/README.md
@@ -453,6 +453,7 @@
462|[Minimum Moves to Equal Array Elements II](./solutions/0462-minimum-moves-to-equal-array-elements-ii.js)|Medium|
463|[Island Perimeter](./solutions/0463-island-perimeter.js)|Medium|
464|[Can I Win](./solutions/0464-can-i-win.js)|Medium|
+465|[Optimal Account Balancing](./solutions/0465-optimal-account-balancing.js)|Hard|
466|[Count The Repetitions](./solutions/0466-count-the-repetitions.js)|Hard|
467|[Unique Substrings in Wraparound String](./solutions/0467-unique-substrings-in-wraparound-string.js)|Medium|
468|[Validate IP Address](./solutions/0468-validate-ip-address.js)|Medium|
diff --git a/solutions/0465-optimal-account-balancing.js b/solutions/0465-optimal-account-balancing.js
new file mode 100644
index 00000000..14b6f3f5
--- /dev/null
+++ b/solutions/0465-optimal-account-balancing.js
@@ -0,0 +1,46 @@
+/**
+ * 465. Optimal Account Balancing
+ * https://leetcode.com/problems/optimal-account-balancing/
+ * Difficulty: Hard
+ *
+ * You are given an array of transactions transactions where
+ * transactions[i] = [fromi, toi, amounti] indicates that the person with ID = fromi
+ * gave amounti $ to the person with ID = toi.
+ *
+ * Return the minimum number of transactions required to settle the debt.
+ */
+
+/**
+ * @param {number[][]} transactions
+ * @return {number}
+ */
+var minTransfers = function(transactions) {
+ const balances = new Array(12).fill(0);
+
+ for (const [from, to, amount] of transactions) {
+ balances[from] -= amount;
+ balances[to] += amount;
+ }
+
+ const debts = balances.filter(balance => balance !== 0);
+ return helper(0, 0);
+
+ function helper(index, count) {
+ if (index === debts.length) return count;
+
+ if (debts[index] === 0) return helper(index + 1, count);
+
+ let minTransactions = Infinity;
+ const currentDebt = debts[index];
+
+ for (let i = index + 1; i < debts.length; i++) {
+ if (debts[i] * currentDebt < 0) {
+ debts[i] += currentDebt;
+ minTransactions = Math.min(minTransactions, helper(index + 1, count + 1));
+ debts[i] -= currentDebt;
+ }
+ }
+
+ return minTransactions;
+ }
+};
From 7d94a04e8dc8b8948aeaa77c443e3dcf27fd793f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 17 Jun 2025 23:47:42 -0500
Subject: [PATCH 506/994] Add solution #469
---
README.md | 1 +
solutions/0469-convex-polygon.js | 44 ++++++++++++++++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/0469-convex-polygon.js
diff --git a/README.md b/README.md
index 2342c90e..d782b135 100644
--- a/README.md
+++ b/README.md
@@ -457,6 +457,7 @@
466|[Count The Repetitions](./solutions/0466-count-the-repetitions.js)|Hard|
467|[Unique Substrings in Wraparound String](./solutions/0467-unique-substrings-in-wraparound-string.js)|Medium|
468|[Validate IP Address](./solutions/0468-validate-ip-address.js)|Medium|
+469|[Convex Polygon](./solutions/0469-convex-polygon.js)|Medium|
470|[Implement Rand10() Using Rand7()](./solutions/0470-implement-rand10-using-rand7.js)|Medium|
472|[Concatenated Words](./solutions/0472-concatenated-words.js)|Hard|
473|[Matchsticks to Square](./solutions/0473-matchsticks-to-square.js)|Medium|
diff --git a/solutions/0469-convex-polygon.js b/solutions/0469-convex-polygon.js
new file mode 100644
index 00000000..d61e33e4
--- /dev/null
+++ b/solutions/0469-convex-polygon.js
@@ -0,0 +1,44 @@
+/**
+ * 469. Convex Polygon
+ * https://leetcode.com/problems/convex-polygon/
+ * Difficulty: Medium
+ *
+ * You are given an array of points on the X-Y plane points where points[i] = [xi, yi].
+ * The points form a polygon when joined sequentially.
+ *
+ * Return true if this polygon is convex and false otherwise.
+ *
+ * You may assume the polygon formed by given points is always a simple polygon. In other
+ * words, we ensure that exactly two edges intersect at each vertex and that edges otherwise
+ * don't intersect each other.
+ */
+
+/**
+ * @param {number[][]} points
+ * @return {boolean}
+ */
+var isConvex = function(points) {
+ const n = points.length;
+ let prevSign = 0;
+
+ for (let i = 0; i < n; i++) {
+ const p1 = points[i];
+ const p2 = points[(i + 1) % n];
+ const p3 = points[(i + 2) % n];
+ const dx1 = p2[0] - p1[0];
+ const dy1 = p2[1] - p1[1];
+ const dx2 = p3[0] - p2[0];
+ const dy2 = p3[1] - p2[1];
+ const crossProduct = dx1 * dy2 - dy1 * dx2;
+ const currentSign = Math.sign(crossProduct);
+
+ if (currentSign !== 0) {
+ if (prevSign !== 0 && currentSign !== prevSign) {
+ return false;
+ }
+ prevSign = currentSign;
+ }
+ }
+
+ return true;
+};
From e2aeeaaec8aca0db03bc7736424a89dfaccd9cdd Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 17 Jun 2025 23:49:10 -0500
Subject: [PATCH 507/994] Add solution #471
---
README.md | 1 +
...0471-encode-string-with-shortest-length.js | 65 +++++++++++++++++++
2 files changed, 66 insertions(+)
create mode 100644 solutions/0471-encode-string-with-shortest-length.js
diff --git a/README.md b/README.md
index d782b135..5eb2a5fd 100644
--- a/README.md
+++ b/README.md
@@ -459,6 +459,7 @@
468|[Validate IP Address](./solutions/0468-validate-ip-address.js)|Medium|
469|[Convex Polygon](./solutions/0469-convex-polygon.js)|Medium|
470|[Implement Rand10() Using Rand7()](./solutions/0470-implement-rand10-using-rand7.js)|Medium|
+471|[Encode String with Shortest Length](./solutions/0471-encode-string-with-shortest-length.js)|Hard|
472|[Concatenated Words](./solutions/0472-concatenated-words.js)|Hard|
473|[Matchsticks to Square](./solutions/0473-matchsticks-to-square.js)|Medium|
474|[Ones and Zeroes](./solutions/0474-ones-and-zeroes.js)|Medium|
diff --git a/solutions/0471-encode-string-with-shortest-length.js b/solutions/0471-encode-string-with-shortest-length.js
new file mode 100644
index 00000000..70a96646
--- /dev/null
+++ b/solutions/0471-encode-string-with-shortest-length.js
@@ -0,0 +1,65 @@
+/**
+ * 471. Encode String with Shortest Length
+ * https://leetcode.com/problems/encode-string-with-shortest-length/
+ * Difficulty: Hard
+ *
+ * Given a string s, encode the string such that its encoded length is the shortest.
+ *
+ * The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets
+ * is being repeated exactly k times. k should be a positive integer.
+ *
+ * If an encoding process does not make the string shorter, then do not encode it. If there are
+ * several solutions, return any of them.
+ */
+
+/**
+ * @param {string} s
+ * @return {string}
+ */
+var encode = function(s) {
+ const n = s.length;
+ const dp = Array.from({ length: n }, () => new Array(n).fill(''));
+
+ for (let len = 1; len <= n; len++) {
+ for (let start = 0; start + len <= n; start++) {
+ const end = start + len - 1;
+ const substr = s.slice(start, end + 1);
+
+ dp[start][end] = substr;
+
+ for (let k = 1; k < len; k++) {
+ const left = dp[start][start + k - 1];
+ const right = dp[start + k][end];
+ const combined = left + right;
+ if (combined.length < dp[start][end].length) {
+ dp[start][end] = combined;
+ }
+ }
+
+ let repeat = 1;
+ const patternLen = len;
+ while (repeat * patternLen <= n && s.slice(start, start + patternLen).repeat(repeat)
+ === s.slice(start, start + repeat * patternLen)) {
+ const encoded = `${repeat}[${dp[start][start + patternLen - 1]}]`;
+ if (encoded.length < dp[start][end].length) {
+ dp[start][end] = encoded;
+ }
+ repeat++;
+ }
+
+ for (let k = 1; k < len; k++) {
+ if (len % k === 0) {
+ const pattern = s.slice(start, start + k);
+ if (pattern.repeat(len / k) === substr) {
+ const encoded = `${len / k}[${dp[start][start + k - 1]}]`;
+ if (encoded.length < dp[start][end].length) {
+ dp[start][end] = encoded;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return dp[0][n - 1];
+};
From 412d0247f8f0c4f0095f2a1f2f4916dfdd7596d6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 17 Jun 2025 23:50:15 -0500
Subject: [PATCH 508/994] Add solution #484
---
README.md | 1 +
solutions/0484-find-permutation.js | 39 ++++++++++++++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/0484-find-permutation.js
diff --git a/README.md b/README.md
index 5eb2a5fd..598eff28 100644
--- a/README.md
+++ b/README.md
@@ -472,6 +472,7 @@
481|[Magical String](./solutions/0481-magical-string.js)|Medium|
482|[License Key Formatting](./solutions/0482-license-key-formatting.js)|Easy|
483|[Smallest Good Base](./solutions/0483-smallest-good-base.js)|Hard|
+484|[Find Permutation](./solutions/0484-find-permutation.js)|Medium|
485|[Max Consecutive Ones](./solutions/0485-max-consecutive-ones.js)|Easy|
486|[Predict the Winner](./solutions/0486-predict-the-winner.js)|Medium|
488|[Zuma Game](./solutions/0488-zuma-game.js)|Hard|
diff --git a/solutions/0484-find-permutation.js b/solutions/0484-find-permutation.js
new file mode 100644
index 00000000..62bbfabf
--- /dev/null
+++ b/solutions/0484-find-permutation.js
@@ -0,0 +1,39 @@
+/**
+ * 484. Find Permutation
+ * https://leetcode.com/problems/find-permutation/
+ * Difficulty: Medium
+ *
+ * A permutation perm of n integers of all the integers in the range [1, n] can be
+ * represented as a string s of length n - 1 where:
+ * - s[i] == 'I' if perm[i] < perm[i + 1], and
+ * - s[i] == 'D' if perm[i] > perm[i + 1].
+ *
+ * Given a string s, reconstruct the lexicographically smallest permutation perm and return it.
+ */
+
+/**
+ * @param {string} s
+ * @return {number[]}
+ */
+var findPermutation = function(s) {
+ const n = s.length + 1;
+ const result = new Array(n).fill(0).map((_, i) => i + 1);
+
+ for (let i = 0; i < s.length; i++) {
+ if (s[i] === 'D') {
+ let start = i;
+ while (i < s.length && s[i] === 'D') {
+ i++;
+ }
+ let end = i;
+ while (start < end) {
+ [result[start], result[end]] = [result[end], result[start]];
+ start++;
+ end--;
+ }
+ i--;
+ }
+ }
+
+ return result;
+};
From c392b126bd999bf88fba043b8f9521bca6ab941b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 17 Jun 2025 23:51:12 -0500
Subject: [PATCH 509/994] Add solution #487
---
README.md | 1 +
solutions/0487-max-consecutive-ones-ii.js | 38 +++++++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/0487-max-consecutive-ones-ii.js
diff --git a/README.md b/README.md
index 598eff28..c51dd119 100644
--- a/README.md
+++ b/README.md
@@ -475,6 +475,7 @@
484|[Find Permutation](./solutions/0484-find-permutation.js)|Medium|
485|[Max Consecutive Ones](./solutions/0485-max-consecutive-ones.js)|Easy|
486|[Predict the Winner](./solutions/0486-predict-the-winner.js)|Medium|
+487|[Max Consecutive Ones II](./solutions/0487-max-consecutive-ones-ii.js)|Medium|
488|[Zuma Game](./solutions/0488-zuma-game.js)|Hard|
491|[Non-decreasing Subsequences](./solutions/0491-non-decreasing-subsequences.js)|Medium|
492|[Construct the Rectangle](./solutions/0492-construct-the-rectangle.js)|Easy|
diff --git a/solutions/0487-max-consecutive-ones-ii.js b/solutions/0487-max-consecutive-ones-ii.js
new file mode 100644
index 00000000..d96259b6
--- /dev/null
+++ b/solutions/0487-max-consecutive-ones-ii.js
@@ -0,0 +1,38 @@
+/**
+ * 487. Max Consecutive Ones II
+ * https://leetcode.com/problems/max-consecutive-ones-ii/
+ * Difficulty: Medium
+ *
+ * Given a binary array nums, return the maximum number of consecutive 1's in the array
+ * if you can flip at most one 0.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var findMaxConsecutiveOnes = function(nums) {
+ let result = 0;
+ let currentConsecutive = 0;
+ let zeroCount = 0;
+ let left = 0;
+
+ for (let right = 0; right < nums.length; right++) {
+ if (nums[right] === 0) {
+ zeroCount++;
+ }
+
+ while (zeroCount > 1) {
+ if (nums[left] === 0) {
+ zeroCount--;
+ }
+ currentConsecutive--;
+ left++;
+ }
+
+ currentConsecutive++;
+ result = Math.max(result, currentConsecutive);
+ }
+
+ return result;
+};
From 6ca92e693c1560e0622a60d112b60e6b0212db8d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 17 Jun 2025 23:53:38 -0500
Subject: [PATCH 510/994] Add solution #489
---
README.md | 1 +
solutions/0489-robot-room-cleaner.js | 78 ++++++++++++++++++++++++++++
2 files changed, 79 insertions(+)
create mode 100644 solutions/0489-robot-room-cleaner.js
diff --git a/README.md b/README.md
index c51dd119..6676125d 100644
--- a/README.md
+++ b/README.md
@@ -477,6 +477,7 @@
486|[Predict the Winner](./solutions/0486-predict-the-winner.js)|Medium|
487|[Max Consecutive Ones II](./solutions/0487-max-consecutive-ones-ii.js)|Medium|
488|[Zuma Game](./solutions/0488-zuma-game.js)|Hard|
+489|[Robot Room Cleaner](./solutions/0489-robot-room-cleaner.js)|Hard|
491|[Non-decreasing Subsequences](./solutions/0491-non-decreasing-subsequences.js)|Medium|
492|[Construct the Rectangle](./solutions/0492-construct-the-rectangle.js)|Easy|
493|[Reverse Pairs](./solutions/0493-reverse-pairs.js)|Hard|
diff --git a/solutions/0489-robot-room-cleaner.js b/solutions/0489-robot-room-cleaner.js
new file mode 100644
index 00000000..2eea307d
--- /dev/null
+++ b/solutions/0489-robot-room-cleaner.js
@@ -0,0 +1,78 @@
+/**
+ * 489. Robot Room Cleaner
+ * https://leetcode.com/problems/robot-room-cleaner/
+ * Difficulty: Hard
+ *
+ * You are controlling a robot that is located somewhere in a room. The room is modeled as an m x n
+ * binary grid where 0 represents a wall and 1 represents an empty slot.
+ *
+ * The robot starts at an unknown location in the room that is guaranteed to be empty, and you do
+ * not have access to the grid, but you can move the robot using the given API Robot.
+ *
+ * You are tasked to use the robot to clean the entire room (i.e., clean every empty cell in the
+ * room). The robot with the four given APIs can move forward, turn left, or turn right. Each turn
+ * is 90 degrees.
+ *
+ * When the robot tries to move into a wall cell, its bumper sensor detects the obstacle, and it
+ * stays on the current cell.
+ *
+ * Design an algorithm to clean the entire room using the following APIs:
+ *
+ * interface Robot {
+ * // returns true if next cell is open and robot moves into the cell.
+ * // returns false if next cell is obstacle and robot stays on the current cell.
+ * boolean move();
+ *
+ * // Robot will stay on the same cell after calling turnLeft/turnRight.
+ * // Each turn will be 90 degrees.
+ * void turnLeft();
+ * void turnRight();
+ *
+ * // Clean the current cell.
+ * void clean();
+ * }
+ *
+ * Note that the initial direction of the robot will be facing up. You can assume all four edges of
+ * the grid are all surrounded by a wall.
+ *
+ * Custom testing:
+ * The input is only given to initialize the room and the robot's position internally. You must
+ * solve this problem "blindfolded". In other words, you must control the robot using only the
+ * four mentioned APIs without knowing the room layout and the initial robot's position.
+ */
+
+/**
+ * @param {Robot} robot
+ * @return {void}
+ */
+var cleanRoom = function(robot) {
+ const visited = new Set();
+ const directions = [[-1, 0], [0, 1], [1, 0], [0, -1]];
+
+ backtrack(0, 0, 0);
+
+ function backtrack(row, col, dir) {
+ const key = `${row},${col}`;
+ if (visited.has(key)) return;
+
+ visited.add(key);
+ robot.clean();
+
+ for (let i = 0; i < 4; i++) {
+ const newDir = (dir + i) % 4;
+ const [dx, dy] = directions[newDir];
+ const newRow = row + dx;
+ const newCol = col + dy;
+
+ if (robot.move()) {
+ backtrack(newRow, newCol, newDir);
+ robot.turnRight();
+ robot.turnRight();
+ robot.move();
+ robot.turnLeft();
+ robot.turnLeft();
+ }
+ robot.turnRight();
+ }
+ }
+};
From 0d044daa06b6803ee4f1b4af4c1bdd36db9c85aa Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 18 Jun 2025 23:35:31 -0500
Subject: [PATCH 511/994] Add solution #490
---
README.md | 1 +
solutions/0490-the-maze.js | 52 ++++++++++++++++++++++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 solutions/0490-the-maze.js
diff --git a/README.md b/README.md
index 6676125d..e2120403 100644
--- a/README.md
+++ b/README.md
@@ -478,6 +478,7 @@
487|[Max Consecutive Ones II](./solutions/0487-max-consecutive-ones-ii.js)|Medium|
488|[Zuma Game](./solutions/0488-zuma-game.js)|Hard|
489|[Robot Room Cleaner](./solutions/0489-robot-room-cleaner.js)|Hard|
+490|[The Maze](./solutions/0490-the-maze.js)|Medium|
491|[Non-decreasing Subsequences](./solutions/0491-non-decreasing-subsequences.js)|Medium|
492|[Construct the Rectangle](./solutions/0492-construct-the-rectangle.js)|Easy|
493|[Reverse Pairs](./solutions/0493-reverse-pairs.js)|Hard|
diff --git a/solutions/0490-the-maze.js b/solutions/0490-the-maze.js
new file mode 100644
index 00000000..cca94171
--- /dev/null
+++ b/solutions/0490-the-maze.js
@@ -0,0 +1,52 @@
+/**
+ * 490. The Maze
+ * https://leetcode.com/problems/the-maze/
+ * Difficulty: Medium
+ *
+ * There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1).
+ * The ball can go through the empty spaces by rolling up, down, left or right, but it won't
+ * stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
+ *
+ * Given the m x n maze, the ball's start position and the destination, where
+ * start = [startrow, startcol] and destination = [destinationrow, destinationcol],
+ * return true if the ball can stop at the destination, otherwise return false.
+ *
+ * You may assume that the borders of the maze are all walls (see examples).
+ */
+
+/**
+ * @param {number[][]} maze
+ * @param {number[]} start
+ * @param {number[]} destination
+ * @return {boolean}
+ */
+var hasPath = function(maze, start, destination) {
+ const rows = maze.length;
+ const cols = maze[0].length;
+ const visited = new Set();
+ const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
+
+ return helper(start[0], start[1]);
+
+ function helper(row, col) {
+ if (visited.has(`${row},${col}`)) return false;
+ visited.add(`${row},${col}`);
+
+ if (row === destination[0] && col === destination[1]) return true;
+
+ for (const [dr, dc] of directions) {
+ let newRow = row;
+ let newCol = col;
+
+ while (newRow + dr >= 0 && newRow + dr < rows && newCol + dc >= 0 && newCol + dc < cols
+ && maze[newRow + dr][newCol + dc] === 0) {
+ newRow += dr;
+ newCol += dc;
+ }
+
+ if (helper(newRow, newCol)) return true;
+ }
+
+ return false;
+ }
+};
From df82d68e76f2960657cfdb9dfbf5c63a0c49707f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 19 Jun 2025 11:57:06 -0500
Subject: [PATCH 512/994] Add solution #499
---
README.md | 1 +
solutions/0499-the-maze-iii.js | 80 ++++++++++++++++++++++++++++++++++
2 files changed, 81 insertions(+)
create mode 100644 solutions/0499-the-maze-iii.js
diff --git a/README.md b/README.md
index e2120403..37f9bcba 100644
--- a/README.md
+++ b/README.md
@@ -487,6 +487,7 @@
496|[Next Greater Element I](./solutions/0496-next-greater-element-i.js)|Easy|
497|[Random Point in Non-overlapping Rectangles](./solutions/0497-random-point-in-non-overlapping-rectangles.js)|Medium|
498|[Diagonal Traverse](./solutions/0498-diagonal-traverse.js)|Medium|
+499|[The Maze III](./solutions/0499-the-maze-iii.js)|Hard|
500|[Keyboard Row](./solutions/0500-keyboard-row.js)|Easy|
501|[Find Mode in Binary Search Tree](./solutions/0501-find-mode-in-binary-search-tree.js)|Easy|
502|[IPO](./solutions/0502-ipo.js)|Hard|
diff --git a/solutions/0499-the-maze-iii.js b/solutions/0499-the-maze-iii.js
new file mode 100644
index 00000000..22079773
--- /dev/null
+++ b/solutions/0499-the-maze-iii.js
@@ -0,0 +1,80 @@
+/**
+ * 499. The Maze III
+ * https://leetcode.com/problems/the-maze-iii/
+ * Difficulty: Hard
+ *
+ * There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1).
+ * The ball can go through the empty spaces by rolling up, down, left or right, but it won't
+ * stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
+ * There is also a hole in this maze. The ball will drop into the hole if it rolls onto the hole.
+ *
+ * Given the m x n maze, the ball's position ball and the hole's position hole, where
+ * ball = [ballrow, ballcol] and hole = [holerow, holecol], return a string instructions of
+ * all the instructions that the ball should follow to drop in the hole with the shortest
+ * distance possible. If there are multiple valid instructions, return the lexicographically
+ * minimum one. If the ball can't drop in the hole, return "impossible".
+ *
+ * If there is a way for the ball to drop in the hole, the answer instructions should contain
+ * the characters 'u' (i.e., up), 'd' (i.e., down), 'l' (i.e., left), and 'r' (i.e., right).
+ *
+ * The distance is the number of empty spaces traveled by the ball from the start position
+ * (excluded) to the destination (included).
+ *
+ * You may assume that the borders of the maze are all walls (see examples).
+ */
+
+var findShortestWay = function(maze, ball, hole) {
+ const rows = maze.length;
+ const cols = maze[0].length;
+ const directions = [[-1, 0, 'u'], [1, 0, 'd'], [0, -1, 'l'], [0, 1, 'r']];
+ const distances = new Array(rows).fill().map(() => new Array(cols).fill(Infinity));
+ const paths = new Array(rows).fill().map(() => new Array(cols).fill(''));
+
+ const pq = [[0, ball[0], ball[1], '']];
+ distances[ball[0]][ball[1]] = 0;
+
+ while (pq.length > 0) {
+ pq.sort((a, b) => a[0] - b[0] || a[3].localeCompare(b[3]));
+ const [currentDist, row, col, path] = pq.shift();
+
+ if (row === hole[0] && col === hole[1]) {
+ return path;
+ }
+
+ if (currentDist > distances[row][col]
+ || (currentDist === distances[row][col] && path > paths[row][col])) {
+ continue;
+ }
+
+ for (const [dr, dc, dir] of directions) {
+ let newRow = row;
+ let newCol = col;
+ let steps = 0;
+
+ while (newRow + dr >= 0 && newRow + dr < rows && newCol + dc >= 0 && newCol + dc < cols
+ && maze[newRow + dr][newCol + dc] === 0) {
+ newRow += dr;
+ newCol += dc;
+ steps++;
+
+ if (newRow === hole[0] && newCol === hole[1]) {
+ break;
+ }
+ }
+
+ if (steps > 0) {
+ const newDist = currentDist + steps;
+ const newPath = path + dir;
+
+ if (newDist < distances[newRow][newCol]
+ || (newDist === distances[newRow][newCol] && newPath < paths[newRow][newCol])) {
+ distances[newRow][newCol] = newDist;
+ paths[newRow][newCol] = newPath;
+ pq.push([newDist, newRow, newCol, newPath]);
+ }
+ }
+ }
+ }
+
+ return 'impossible';
+};
From 6ff5d0093b76f8b461309113961f1543db4cbe5e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 19 Jun 2025 12:02:45 -0500
Subject: [PATCH 513/994] Add solution #505
---
README.md | 1 +
solutions/0505-the-maze-ii.js | 62 +++++++++++++++++++++++++++++++++++
2 files changed, 63 insertions(+)
create mode 100644 solutions/0505-the-maze-ii.js
diff --git a/README.md b/README.md
index 37f9bcba..a4b5a4eb 100644
--- a/README.md
+++ b/README.md
@@ -493,6 +493,7 @@
502|[IPO](./solutions/0502-ipo.js)|Hard|
503|[Next Greater Element II](./solutions/0503-next-greater-element-ii.js)|Medium|
504|[Base 7](./solutions/0504-base-7.js)|Easy|
+505|[The Maze II](./solutions/0505-the-maze-ii.js)|Medium|
506|[Relative Ranks](./solutions/0506-relative-ranks.js)|Easy|
507|[Perfect Number](./solutions/0507-perfect-number.js)|Easy|
508|[Most Frequent Subtree Sum](./solutions/0508-most-frequent-subtree-sum.js)|Medium|
diff --git a/solutions/0505-the-maze-ii.js b/solutions/0505-the-maze-ii.js
new file mode 100644
index 00000000..3d84611e
--- /dev/null
+++ b/solutions/0505-the-maze-ii.js
@@ -0,0 +1,62 @@
+/**
+ * 505. The Maze II
+ * https://leetcode.com/problems/the-maze-ii/
+ * Difficulty: Medium
+ *
+ * There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1).
+ * The ball can go through the empty spaces by rolling up, down, left or right, but it won't
+ * stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
+ *
+ * Given the m x n maze, the ball's start position and the destination, where
+ * start = [startrow, startcol] and destination = [destinationrow, destinationcol], return
+ * the shortest distance for the ball to stop at the destination. If the ball cannot stop
+ * at destination, return -1.
+ *
+ * The distance is the number of empty spaces traveled by the ball from the start position
+ * (excluded) to the destination (included).
+ *
+ * You may assume that the borders of the maze are all walls (see examples).
+ */
+
+/**
+ * @param {number[][]} maze
+ * @param {number[]} start
+ * @param {number[]} destination
+ * @return {number}
+ */
+var shortestDistance = function(maze, start, destination) {
+ const rows = maze.length;
+ const cols = maze[0].length;
+ const distances = new Array(rows).fill().map(() => new Array(cols).fill(Infinity));
+ const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
+ const queue = [[start[0], start[1], 0]];
+ distances[start[0]][start[1]] = 0;
+
+ while (queue.length) {
+ const [row, col, distance] = queue.shift();
+ if (distance > distances[row][col]) continue;
+
+ for (const [dx, dy] of directions) {
+ let nextRow = row;
+ let nextCol = col;
+ let steps = 0;
+
+ while (nextRow + dx >= 0 && nextRow + dx < rows && nextCol + dy >= 0
+ && nextCol + dy < cols && maze[nextRow + dx][nextCol + dy] === 0
+ ) {
+ nextRow += dx;
+ nextCol += dy;
+ steps++;
+ }
+
+ const newDistance = distance + steps;
+ if (newDistance < distances[nextRow][nextCol]) {
+ distances[nextRow][nextCol] = newDistance;
+ queue.push([nextRow, nextCol, newDistance]);
+ }
+ }
+ }
+
+ const result = distances[destination[0]][destination[1]];
+ return result === Infinity ? -1 : result;
+};
From 64c6d840f6bb6245624b5b888e5ccfc4fdcb5e6d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 19 Jun 2025 12:04:20 -0500
Subject: [PATCH 514/994] Add solution #510
---
README.md | 1 +
solutions/0510-inorder-successor-in-bst-ii.js | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/0510-inorder-successor-in-bst-ii.js
diff --git a/README.md b/README.md
index a4b5a4eb..c697c84a 100644
--- a/README.md
+++ b/README.md
@@ -498,6 +498,7 @@
507|[Perfect Number](./solutions/0507-perfect-number.js)|Easy|
508|[Most Frequent Subtree Sum](./solutions/0508-most-frequent-subtree-sum.js)|Medium|
509|[Fibonacci Number](./solutions/0509-fibonacci-number.js)|Easy|
+510|[Inorder Successor in BST II](./solutions/0510-inorder-successor-in-bst-ii.js)|Medium|
513|[Find Bottom Left Tree Value](./solutions/0513-find-bottom-left-tree-value.js)|Medium|
514|[Freedom Trail](./solutions/0514-freedom-trail.js)|Hard|
515|[Find Largest Value in Each Tree Row](./solutions/0515-find-largest-value-in-each-tree-row.js)|Medium|
diff --git a/solutions/0510-inorder-successor-in-bst-ii.js b/solutions/0510-inorder-successor-in-bst-ii.js
new file mode 100644
index 00000000..db87a419
--- /dev/null
+++ b/solutions/0510-inorder-successor-in-bst-ii.js
@@ -0,0 +1,50 @@
+/**
+ * 510. Inorder Successor in BST II
+ * https://leetcode.com/problems/inorder-successor-in-bst-ii/
+ * Difficulty: Medium
+ *
+ * Given a node in a binary search tree, return the in-order successor of that node in the BST.
+ * If that node has no in-order successor, return null.
+ *
+ * The successor of a node is the node with the smallest key greater than node.val.
+ *
+ * You will have direct access to the node but not to the root of the tree. Each node will have
+ * a reference to its parent node. Below is the definition for Node:
+ *
+ * class Node {
+ * public int val;
+ * public Node left;
+ * public Node right;
+ * public Node parent;
+ * }
+ */
+
+/**
+ * // Definition for a _Node.
+ * function _Node(val) {
+ * this.val = val;
+ * this.left = null;
+ * this.right = null;
+ * this.parent = null;
+ * };
+ */
+
+/**
+ * @param {_Node} node
+ * @return {_Node}
+ */
+var inorderSuccessor = function(node) {
+ if (node.right) {
+ let successor = node.right;
+ while (successor.left) {
+ successor = successor.left;
+ }
+ return successor;
+ }
+
+ let current = node;
+ while (current.parent && current.parent.right === current) {
+ current = current.parent;
+ }
+ return current.parent;
+};
From 48637c4fbf1372735edf545f80b4d980160de75e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 19 Jun 2025 12:06:36 -0500
Subject: [PATCH 515/994] Add solution #527
---
README.md | 1 +
solutions/0527-word-abbreviation.js | 80 +++++++++++++++++++++++++++++
2 files changed, 81 insertions(+)
create mode 100644 solutions/0527-word-abbreviation.js
diff --git a/README.md b/README.md
index c697c84a..d3ae25d8 100644
--- a/README.md
+++ b/README.md
@@ -513,6 +513,7 @@
524|[Longest Word in Dictionary through Deleting](./solutions/0524-longest-word-in-dictionary-through-deleting.js)|Medium|
525|[Contiguous Array](./solutions/0525-contiguous-array.js)|Medium|
526|[Beautiful Arrangement](./solutions/0526-beautiful-arrangement.js)|Medium|
+527|[Word Abbreviation](./solutions/0527-word-abbreviation.js)|Hard|
528|[Random Pick with Weight](./solutions/0528-random-pick-with-weight.js)|Medium|
529|[Minesweeper](./solutions/0529-minesweeper.js)|Medium|
530|[Minimum Absolute Difference in BST](./solutions/0530-minimum-absolute-difference-in-bst.js)|Easy|
diff --git a/solutions/0527-word-abbreviation.js b/solutions/0527-word-abbreviation.js
new file mode 100644
index 00000000..59447b55
--- /dev/null
+++ b/solutions/0527-word-abbreviation.js
@@ -0,0 +1,80 @@
+/**
+ * 527. Word Abbreviation
+ * https://leetcode.com/problems/word-abbreviation/
+ * Difficulty: Hard
+ *
+ * Given an array of distinct strings words, return the minimal possible abbreviations for
+ * every word.
+ *
+ * The following are the rules for a string abbreviation:
+ * 1. The initial abbreviation for each word is: the first character, then the number of
+ * characters in between, followed by the last character.
+ * 2. If more than one word shares the same abbreviation, then perform the following operation:
+ * - Increase the prefix (characters in the first part) of each of their abbreviations by 1.
+ * - For example, say you start with the words ["abcdef","abndef"] both initially abbreviated
+ * as "a4f". Then, a sequence of operations would be
+ * ["a4f","a4f"] -> ["ab3f","ab3f"] -> ["abc2f","abn2f"].
+ * - This operation is repeated until every abbreviation is unique.
+ * 3. At the end, if an abbreviation did not make a word shorter, then keep it as the original word.
+ */
+
+/**
+ * @param {string[]} words
+ * @return {string[]}
+ */
+var wordsAbbreviation = function(words) {
+ const n = words.length;
+ const result = new Array(n).fill('');
+ const groups = new Map();
+
+ function getAbbreviation(word, prefixLen) {
+ const len = word.length;
+ if (len <= prefixLen + 2) return word;
+ return word.slice(0, prefixLen) + (len - prefixLen - 1) + word[len - 1];
+ }
+
+ for (let i = 0; i < n; i++) {
+ const word = words[i];
+ const prefixLen = 1;
+ const abbr = getAbbreviation(word, prefixLen);
+
+ if (!groups.has(abbr)) {
+ groups.set(abbr, []);
+ }
+ groups.get(abbr).push([i, prefixLen]);
+ }
+
+ while (true) {
+ let resolved = true;
+ const newGroups = new Map();
+
+ for (const [abbr, indices] of groups) {
+ if (indices.length === 1) {
+ const [index, prefixLen] = indices[0];
+ const word = words[index];
+ const finalAbbr = getAbbreviation(word, prefixLen);
+ result[index] = finalAbbr.length < word.length ? finalAbbr : word;
+ continue;
+ }
+
+ resolved = false;
+ for (const [index, prefixLen] of indices) {
+ const word = words[index];
+ const newAbbr = getAbbreviation(word, prefixLen + 1);
+
+ if (!newGroups.has(newAbbr)) {
+ newGroups.set(newAbbr, []);
+ }
+ newGroups.get(newAbbr).push([index, prefixLen + 1]);
+ }
+ }
+
+ if (resolved) break;
+ groups.clear();
+ for (const [abbr, indices] of newGroups) {
+ groups.set(abbr, indices);
+ }
+ }
+
+ return result;
+};
From 1a9eeb68593f90efe0005d3ae0a2a5933e75bb5e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 20 Jun 2025 17:45:11 -0500
Subject: [PATCH 516/994] Add solution #3443
---
README.md | 3 +-
...imum-manhattan-distance-after-k-changes.js | 51 +++++++++++++++++++
2 files changed, 53 insertions(+), 1 deletion(-)
create mode 100644 solutions/3443-maximum-manhattan-distance-after-k-changes.js
diff --git a/README.md b/README.md
index d3ae25d8..144679b1 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 2,250+ LeetCode solutions in JavaScript
+# 2,300+ LeetCode solutions in JavaScript
[https://leetcodejavascript.com](https://leetcodejavascript.com)
@@ -2300,6 +2300,7 @@
3405|[Count the Number of Arrays with K Matching Adjacent Elements](./solutions/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.js)|Hard|
3423|[Maximum Difference Between Adjacent Elements in a Circular Array](./solutions/3423-maximum-difference-between-adjacent-elements-in-a-circular-array.js)|Easy|
3442|[Maximum Difference Between Even and Odd Frequency I](./solutions/3442-maximum-difference-between-even-and-odd-frequency-i.js)|Easy|
+3443|[Maximum Manhattan Distance After K Changes](./solutions/3443-maximum-manhattan-distance-after-k-changes.js)|Medium|
3445|[Maximum Difference Between Even and Odd Frequency II](./solutions/3445-maximum-difference-between-even-and-odd-frequency-ii.js)|Hard|
3452|[Sum of Good Numbers](./solutions/3452-sum-of-good-numbers.js)|Easy|
3461|[Check If Digits Are Equal in String After Operations I](./solutions/3461-check-if-digits-are-equal-in-string-after-operations-i.js)|Easy|
diff --git a/solutions/3443-maximum-manhattan-distance-after-k-changes.js b/solutions/3443-maximum-manhattan-distance-after-k-changes.js
new file mode 100644
index 00000000..21f7f3c7
--- /dev/null
+++ b/solutions/3443-maximum-manhattan-distance-after-k-changes.js
@@ -0,0 +1,51 @@
+/**
+ * 3443. Maximum Manhattan Distance After K Changes
+ * https://leetcode.com/problems/maximum-manhattan-distance-after-k-changes/
+ * Difficulty: Medium
+ *
+ * You are given a string s consisting of the characters 'N', 'S', 'E', and 'W', where s[i]
+ * indicates movements in an infinite grid:
+ * - 'N' : Move north by 1 unit.
+ * - 'S' : Move south by 1 unit.
+ * - 'E' : Move east by 1 unit.
+ * - 'W' : Move west by 1 unit.
+ *
+ * Initially, you are at the origin (0, 0). You can change at most k characters to any of the
+ * four directions.
+ *
+ * Find the maximum Manhattan distance from the origin that can be achieved at any time while
+ * performing the movements in order.
+ *
+ * The Manhattan Distance between two cells (xi, yi) and (xj, yj) is |xi - xj| + |yi - yj|.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} k
+ * @return {number}
+ */
+var maxDistance = function(s, k) {
+ const directions = {
+ 'N': [0, 1],
+ 'S': [0, -1],
+ 'E': [1, 0],
+ 'W': [-1, 0]
+ };
+
+ let x = 0;
+ let y = 0;
+ let result = 0;
+
+ for (let i = 0; i < s.length; i++) {
+ const [dx, dy] = directions[s[i]];
+ x += dx;
+ y += dy;
+
+ const currentDistance = Math.abs(x) + Math.abs(y);
+ const maxPossibleExtra = Math.min(2 * k, i + 1 - currentDistance);
+
+ result = Math.max(result, currentDistance + maxPossibleExtra);
+ }
+
+ return result;
+};
From 35ce1ae69132aa8b28496b464160a45b2ad1ef4a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 20 Jun 2025 17:47:08 -0500
Subject: [PATCH 517/994] Add solution #531
---
README.md | 1 +
solutions/0531-lonely-pixel-i.js | 42 ++++++++++++++++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/0531-lonely-pixel-i.js
diff --git a/README.md b/README.md
index 144679b1..a65c8ca5 100644
--- a/README.md
+++ b/README.md
@@ -517,6 +517,7 @@
528|[Random Pick with Weight](./solutions/0528-random-pick-with-weight.js)|Medium|
529|[Minesweeper](./solutions/0529-minesweeper.js)|Medium|
530|[Minimum Absolute Difference in BST](./solutions/0530-minimum-absolute-difference-in-bst.js)|Easy|
+531|[Lonely Pixel I](./solutions/0531-lonely-pixel-i.js)|Medium|
532|[K-diff Pairs in an Array](./solutions/0532-k-diff-pairs-in-an-array.js)|Medium|
535|[Encode and Decode TinyURL](./solutions/0535-encode-and-decode-tinyurl.js)|Medium|
537|[Complex Number Multiplication](./solutions/0537-complex-number-multiplication.js)|Medium|
diff --git a/solutions/0531-lonely-pixel-i.js b/solutions/0531-lonely-pixel-i.js
new file mode 100644
index 00000000..41a2f956
--- /dev/null
+++ b/solutions/0531-lonely-pixel-i.js
@@ -0,0 +1,42 @@
+/**
+ * 531. Lonely Pixel I
+ * https://leetcode.com/problems/lonely-pixel-i/
+ * Difficulty: Medium
+ *
+ * Given an m x n picture consisting of black 'B' and white 'W' pixels, return the number of
+ * black lonely pixels.
+ *
+ * A black lonely pixel is a character 'B' that located at a specific position where the same
+ * row and same column don't have any other black pixels.
+ */
+
+/**
+ * @param {character[][]} picture
+ * @return {number}
+ */
+var findLonelyPixel = function(picture) {
+ const rows = picture.length;
+ const cols = picture[0].length;
+ const rowCounts = new Array(rows).fill(0);
+ const colCounts = new Array(cols).fill(0);
+ let result = 0;
+
+ for (let row = 0; row < rows; row++) {
+ for (let col = 0; col < cols; col++) {
+ if (picture[row][col] === 'B') {
+ rowCounts[row]++;
+ colCounts[col]++;
+ }
+ }
+ }
+
+ for (let row = 0; row < rows; row++) {
+ for (let col = 0; col < cols; col++) {
+ if (picture[row][col] === 'B' && rowCounts[row] === 1 && colCounts[col] === 1) {
+ result++;
+ }
+ }
+ }
+
+ return result;
+};
From 01a72d3139a122f4e6b94ecc2959e5b34cb4cfb9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 20 Jun 2025 17:48:12 -0500
Subject: [PATCH 518/994] Add solution #533
---
README.md | 1 +
solutions/0533-lonely-pixel-ii.js | 57 +++++++++++++++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/0533-lonely-pixel-ii.js
diff --git a/README.md b/README.md
index a65c8ca5..b4447801 100644
--- a/README.md
+++ b/README.md
@@ -519,6 +519,7 @@
530|[Minimum Absolute Difference in BST](./solutions/0530-minimum-absolute-difference-in-bst.js)|Easy|
531|[Lonely Pixel I](./solutions/0531-lonely-pixel-i.js)|Medium|
532|[K-diff Pairs in an Array](./solutions/0532-k-diff-pairs-in-an-array.js)|Medium|
+533|[Lonely Pixel II](./solutions/0533-lonely-pixel-ii.js)|Medium|
535|[Encode and Decode TinyURL](./solutions/0535-encode-and-decode-tinyurl.js)|Medium|
537|[Complex Number Multiplication](./solutions/0537-complex-number-multiplication.js)|Medium|
538|[Convert BST to Greater Tree](./solutions/0538-convert-bst-to-greater-tree.js)|Medium|
diff --git a/solutions/0533-lonely-pixel-ii.js b/solutions/0533-lonely-pixel-ii.js
new file mode 100644
index 00000000..c615bb36
--- /dev/null
+++ b/solutions/0533-lonely-pixel-ii.js
@@ -0,0 +1,57 @@
+/**
+ * 533. Lonely Pixel II
+ * https://leetcode.com/problems/lonely-pixel-ii/
+ * Difficulty: Medium
+ *
+ * Given an m x n picture consisting of black 'B' and white 'W' pixels and an integer target,
+ * return the number of black lonely pixels.
+ *
+ * A black lonely pixel is a character 'B' that located at a specific position (r, c) where:
+ * - Row r and column c both contain exactly target black pixels.
+ * - For all rows that have a black pixel at column c, they should be exactly the same as row r.
+ */
+
+/**
+ * @param {character[][]} picture
+ * @param {number} target
+ * @return {number}
+ */
+var findBlackPixel = function(picture, target) {
+ const rows = picture.length;
+ const cols = picture[0].length;
+ const rowCounts = new Array(rows).fill(0);
+ const colCounts = new Array(cols).fill(0);
+ const rowPatterns = new Map();
+
+ for (let row = 0; row < rows; row++) {
+ let blackCount = 0;
+ for (let col = 0; col < cols; col++) {
+ if (picture[row][col] === 'B') {
+ blackCount++;
+ colCounts[col]++;
+ }
+ }
+ rowCounts[row] = blackCount;
+ if (blackCount === target) {
+ const pattern = picture[row].join('');
+ rowPatterns.set(pattern, (rowPatterns.get(pattern) || 0) + 1);
+ }
+ }
+
+ let result = 0;
+ for (let col = 0; col < cols; col++) {
+ if (colCounts[col] === target) {
+ for (let row = 0; row < rows; row++) {
+ if (picture[row][col] === 'B' && rowCounts[row] === target) {
+ const pattern = picture[row].join('');
+ if (rowPatterns.get(pattern) === target) {
+ result += target;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ return result;
+};
From f498eab190fefe322934babc9c0f7c1e7aafebab Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 20 Jun 2025 17:51:04 -0500
Subject: [PATCH 519/994] Add solution #536
---
README.md | 1 +
.../0536-construct-binary-tree-from-string.js | 64 +++++++++++++++++++
2 files changed, 65 insertions(+)
create mode 100644 solutions/0536-construct-binary-tree-from-string.js
diff --git a/README.md b/README.md
index b4447801..7d84e0da 100644
--- a/README.md
+++ b/README.md
@@ -521,6 +521,7 @@
532|[K-diff Pairs in an Array](./solutions/0532-k-diff-pairs-in-an-array.js)|Medium|
533|[Lonely Pixel II](./solutions/0533-lonely-pixel-ii.js)|Medium|
535|[Encode and Decode TinyURL](./solutions/0535-encode-and-decode-tinyurl.js)|Medium|
+536|[Construct Binary Tree from String](./solutions/0536-construct-binary-tree-from-string.js)|Medium|
537|[Complex Number Multiplication](./solutions/0537-complex-number-multiplication.js)|Medium|
538|[Convert BST to Greater Tree](./solutions/0538-convert-bst-to-greater-tree.js)|Medium|
539|[Minimum Time Difference](./solutions/0539-minimum-time-difference.js)|Medium|
diff --git a/solutions/0536-construct-binary-tree-from-string.js b/solutions/0536-construct-binary-tree-from-string.js
new file mode 100644
index 00000000..a6a9cb1a
--- /dev/null
+++ b/solutions/0536-construct-binary-tree-from-string.js
@@ -0,0 +1,64 @@
+/**
+ * 536. Construct Binary Tree from String
+ * https://leetcode.com/problems/construct-binary-tree-from-string/
+ * Difficulty: Medium
+ *
+ * You need to construct a binary tree from a string consisting of parenthesis and integers.
+ *
+ * The whole input represents a binary tree. It contains an integer followed by zero, one or
+ * two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis
+ * contains a child binary tree with the same structure.
+ *
+ * You always start to construct the left child node of the parent first if it exists.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {string} s
+ * @return {TreeNode}
+ */
+var str2tree = function(s) {
+ if (!s) return null;
+ let index = 0;
+ return constructTree();
+
+ function parseNumber() {
+ const isNegative = s[index] === '-';
+ if (isNegative) index++;
+
+ let num = 0;
+ while (index < s.length && /[0-9]/.test(s[index])) {
+ num = num * 10 + parseInt(s[index]);
+ index++;
+ }
+
+ return isNegative ? -num : num;
+ }
+
+ function constructTree() {
+ if (index >= s.length) return null;
+
+ const value = parseNumber();
+ const node = new TreeNode(value);
+ if (index < s.length && s[index] === '(') {
+ index++;
+ node.left = constructTree();
+ index++;
+ }
+
+ if (index < s.length && s[index] === '(') {
+ index++;
+ node.right = constructTree();
+ index++;
+ }
+
+ return node;
+ }
+};
From ea2913db2a7360277b2a12b6d51d33b6733acdaf Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 20 Jun 2025 17:52:28 -0500
Subject: [PATCH 520/994] Add solution #544
---
README.md | 1 +
solutions/0544-output-contest-matches.js | 39 ++++++++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/0544-output-contest-matches.js
diff --git a/README.md b/README.md
index 7d84e0da..e02ccdfb 100644
--- a/README.md
+++ b/README.md
@@ -529,6 +529,7 @@
541|[Reverse String II](./solutions/0541-reverse-string-ii.js)|Easy|
542|[01 Matrix](./solutions/0542-01-matrix.js)|Medium|
543|[Diameter of Binary Tree](./solutions/0543-diameter-of-binary-tree.js)|Easy|
+544|[Output Contest Matches](./solutions/0544-output-contest-matches.js)|Medium|
546|[Remove Boxes](./solutions/0546-remove-boxes.js)|Hard|
547|[Number of Provinces](./solutions/0547-number-of-provinces.js)|Medium|
551|[Student Attendance Record I](./solutions/0551-student-attendance-record-i.js)|Easy|
diff --git a/solutions/0544-output-contest-matches.js b/solutions/0544-output-contest-matches.js
new file mode 100644
index 00000000..e1392dd0
--- /dev/null
+++ b/solutions/0544-output-contest-matches.js
@@ -0,0 +1,39 @@
+/**
+ * 544. Output Contest Matches
+ * https://leetcode.com/problems/output-contest-matches/
+ * Difficulty: Medium
+ *
+ * During the NBA playoffs, we always set the rather strong team to play with the rather weak
+ * team, like making the rank 1 team play with the rank nth team, which is a good strategy to
+ * make the contest more interesting.
+ *
+ * Given n teams, return their final contest matches in the form of a string.
+ *
+ * The n teams are labeled from 1 to n, which represents their initial rank (i.e., Rank 1 is
+ * the strongest team and Rank n is the weakest team).
+ *
+ * We will use parentheses '(', and ')' and commas ',' to represent the contest team pairing.
+ * We use the parentheses for pairing and the commas for partition. During the pairing process
+ * in each round, you always need to follow the strategy of making the rather strong one pair
+ * with the rather weak one.
+ */
+
+/**
+ * @param {number} n
+ * @return {string}
+ */
+var findContestMatch = function(n) {
+ const teams = Array.from({ length: n }, (_, i) => (i + 1).toString());
+ return pairTeams(teams);
+
+ function pairTeams(arr) {
+ if (arr.length === 1) return arr[0];
+
+ const nextRound = [];
+ for (let i = 0; i < arr.length / 2; i++) {
+ nextRound.push(`(${arr[i]},${arr[arr.length - 1 - i]})`);
+ }
+
+ return pairTeams(nextRound);
+ }
+};
From 5da2a8d52e3065f680ffb466f12e6f941e28d5dc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 20 Jun 2025 18:49:47 -0500
Subject: [PATCH 521/994] Add solution #545
---
README.md | 1 +
solutions/0545-boundary-of-binary-tree.js | 84 +++++++++++++++++++++++
2 files changed, 85 insertions(+)
create mode 100644 solutions/0545-boundary-of-binary-tree.js
diff --git a/README.md b/README.md
index e02ccdfb..18b091d0 100644
--- a/README.md
+++ b/README.md
@@ -530,6 +530,7 @@
542|[01 Matrix](./solutions/0542-01-matrix.js)|Medium|
543|[Diameter of Binary Tree](./solutions/0543-diameter-of-binary-tree.js)|Easy|
544|[Output Contest Matches](./solutions/0544-output-contest-matches.js)|Medium|
+545|[Boundary of Binary Tree](./solutions/0545-boundary-of-binary-tree.js)|Medium|
546|[Remove Boxes](./solutions/0546-remove-boxes.js)|Hard|
547|[Number of Provinces](./solutions/0547-number-of-provinces.js)|Medium|
551|[Student Attendance Record I](./solutions/0551-student-attendance-record-i.js)|Easy|
diff --git a/solutions/0545-boundary-of-binary-tree.js b/solutions/0545-boundary-of-binary-tree.js
new file mode 100644
index 00000000..eabf126a
--- /dev/null
+++ b/solutions/0545-boundary-of-binary-tree.js
@@ -0,0 +1,84 @@
+/**
+ * 545. Boundary of Binary Tree
+ * https://leetcode.com/problems/boundary-of-binary-tree/
+ * Difficulty: Medium
+ *
+ * The boundary of a binary tree is the concatenation of the root, the left boundary, the leaves
+ * ordered from left-to-right, and the reverse order of the right boundary.
+ *
+ * The left boundary is the set of nodes defined by the following:
+ * - The root node's left child is in the left boundary. If the root does not have a left child,
+ * then the left boundary is empty.
+ * - If a node in the left boundary and has a left child, then the left child is in the left
+ * boundary.
+ * - If a node is in the left boundary, has no left child, but has a right child, then the right
+ * child is in the left boundary.
+ * - The leftmost leaf is not in the left boundary.
+ *
+ * The right boundary is similar to the left boundary, except it is the right side of the root's
+ * right subtree. Again, the leaf is not part of the right boundary, and the right boundary is
+ * empty if the root does not have a right child.
+ *
+ * The leaves are nodes that do not have any children. For this problem, the root is not a leaf.
+ *
+ * Given the root of a binary tree, return the values of its boundary.
+ */
+
+/**
+ * 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 boundaryOfBinaryTree = function(root) {
+ if (!root) return [];
+ if (!root.left && !root.right) return [root.val];
+
+ const result = [root.val];
+
+ collectLeftBoundary(root.left);
+ collectLeaves(root);
+ collectRightBoundary(root.right);
+
+ return result;
+
+ function isLeaf(node) {
+ return node && !node.left && !node.right;
+ }
+
+ function collectLeftBoundary(node) {
+ if (!node || isLeaf(node)) return;
+ result.push(node.val);
+ if (node.left) {
+ collectLeftBoundary(node.left);
+ } else {
+ collectLeftBoundary(node.right);
+ }
+ }
+
+ function collectLeaves(node) {
+ if (!node) return;
+ if (isLeaf(node)) {
+ result.push(node.val);
+ return;
+ }
+ collectLeaves(node.left);
+ collectLeaves(node.right);
+ }
+
+ function collectRightBoundary(node) {
+ if (!node || isLeaf(node)) return;
+ if (node.right) {
+ collectRightBoundary(node.right);
+ } else {
+ collectRightBoundary(node.left);
+ }
+ result.push(node.val);
+ }
+};
From fa5abdb2bb5fd1b774ab0cd4c4190f4167b25bca Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 20 Jun 2025 18:50:58 -0500
Subject: [PATCH 522/994] Add solution #548
---
README.md | 1 +
solutions/0548-split-array-with-equal-sum.js | 48 ++++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/0548-split-array-with-equal-sum.js
diff --git a/README.md b/README.md
index 18b091d0..fdc27904 100644
--- a/README.md
+++ b/README.md
@@ -533,6 +533,7 @@
545|[Boundary of Binary Tree](./solutions/0545-boundary-of-binary-tree.js)|Medium|
546|[Remove Boxes](./solutions/0546-remove-boxes.js)|Hard|
547|[Number of Provinces](./solutions/0547-number-of-provinces.js)|Medium|
+548|[Split Array with Equal Sum](./solutions/0548-split-array-with-equal-sum.js)|Hard|
551|[Student Attendance Record I](./solutions/0551-student-attendance-record-i.js)|Easy|
552|[Student Attendance Record II](./solutions/0552-student-attendance-record-ii.js)|Hard|
553|[Optimal Division](./solutions/0553-optimal-division.js)|Medium|
diff --git a/solutions/0548-split-array-with-equal-sum.js b/solutions/0548-split-array-with-equal-sum.js
new file mode 100644
index 00000000..672843be
--- /dev/null
+++ b/solutions/0548-split-array-with-equal-sum.js
@@ -0,0 +1,48 @@
+/**
+ * 548. Split Array with Equal Sum
+ * https://leetcode.com/problems/split-array-with-equal-sum/
+ * Difficulty: Hard
+ *
+ * Given an integer array nums of length n, return true if there is a triplet (i, j, k) which
+ * satisfies the following conditions:
+ * - 0 < i, i + 1 < j, j + 1 < k < n - 1
+ * - The sum of subarrays (0, i - 1), (i + 1, j - 1), (j + 1, k - 1) and (k + 1, n - 1) is equal.
+ *
+ * A subarray (l, r) represents a slice of the original array starting from the element
+ * indexed l to the element indexed r.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {boolean}
+ */
+var splitArray = function(nums) {
+ const length = nums.length;
+ if (length < 7) return false;
+
+ const prefixSums = new Array(length + 1).fill(0);
+ for (let i = 0; i < length; i++) {
+ prefixSums[i + 1] = prefixSums[i] + nums[i];
+ }
+
+ const getSum = (start, end) => prefixSums[end + 1] - prefixSums[start];
+
+ for (let j = 3; j < length - 3; j++) {
+ const seenSums = new Set();
+ for (let i = 1; i < j - 1; i++) {
+ const firstSum = getSum(0, i - 1);
+ const secondSum = getSum(i + 1, j - 1);
+ if (firstSum === secondSum) {
+ seenSums.add(firstSum);
+ }
+ }
+ for (let k = j + 2; k < length - 1; k++) {
+ const thirdSum = getSum(j + 1, k - 1);
+ const fourthSum = getSum(k + 1, length - 1);
+ if (thirdSum === fourthSum && seenSums.has(thirdSum)) {
+ return true;
+ }
+ }
+ }
+ return false;
+};
From f1be4692968700903cdee00b1dca1b7c9f16a765 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 20 Jun 2025 18:52:10 -0500
Subject: [PATCH 523/994] Add solution #549
---
README.md | 1 +
...ry-tree-longest-consecutive-sequence-ii.js | 61 +++++++++++++++++++
2 files changed, 62 insertions(+)
create mode 100644 solutions/0549-binary-tree-longest-consecutive-sequence-ii.js
diff --git a/README.md b/README.md
index fdc27904..386eac72 100644
--- a/README.md
+++ b/README.md
@@ -534,6 +534,7 @@
546|[Remove Boxes](./solutions/0546-remove-boxes.js)|Hard|
547|[Number of Provinces](./solutions/0547-number-of-provinces.js)|Medium|
548|[Split Array with Equal Sum](./solutions/0548-split-array-with-equal-sum.js)|Hard|
+549|[Binary Tree Longest Consecutive Sequence II](./solutions/0549-binary-tree-longest-consecutive-sequence-ii.js)|Medium|
551|[Student Attendance Record I](./solutions/0551-student-attendance-record-i.js)|Easy|
552|[Student Attendance Record II](./solutions/0552-student-attendance-record-ii.js)|Hard|
553|[Optimal Division](./solutions/0553-optimal-division.js)|Medium|
diff --git a/solutions/0549-binary-tree-longest-consecutive-sequence-ii.js b/solutions/0549-binary-tree-longest-consecutive-sequence-ii.js
new file mode 100644
index 00000000..158a829e
--- /dev/null
+++ b/solutions/0549-binary-tree-longest-consecutive-sequence-ii.js
@@ -0,0 +1,61 @@
+/**
+ * 549. Binary Tree Longest Consecutive Sequence II
+ * https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree, return the length of the longest consecutive path in the tree.
+ *
+ * A consecutive path is a path where the values of the consecutive nodes in the path differ by one.
+ * This path can be either increasing or decreasing.
+ * - For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is
+ * not valid.
+ *
+ * On the other hand, the path can be in the child-Parent-child order, where not necessarily be
+ * parent-child order.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @return {number}
+ */
+var longestConsecutive = function(root) {
+ let maxLength = 0;
+ traverse(root);
+ return maxLength;
+
+ function traverse(node) {
+ if (!node) return [0, 0];
+
+ let inc = 1;
+ let dec = 1;
+
+ if (node.left) {
+ const [leftInc, leftDec] = traverse(node.left);
+ if (node.val === node.left.val + 1) {
+ dec = Math.max(dec, leftDec + 1);
+ } else if (node.val === node.left.val - 1) {
+ inc = Math.max(inc, leftInc + 1);
+ }
+ }
+
+ if (node.right) {
+ const [rightInc, rightDec] = traverse(node.right);
+ if (node.val === node.right.val + 1) {
+ dec = Math.max(dec, rightDec + 1);
+ } else if (node.val === node.right.val - 1) {
+ inc = Math.max(inc, rightInc + 1);
+ }
+ }
+
+ maxLength = Math.max(maxLength, inc + dec - 1);
+ return [inc, dec];
+ }
+};
From 2ed6d563d791bfa857ca2dc12eb8148378a89a5d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 20 Jun 2025 18:53:28 -0500
Subject: [PATCH 524/994] Add solution #555
---
README.md | 1 +
solutions/0555-split-concatenated-strings.js | 50 ++++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/0555-split-concatenated-strings.js
diff --git a/README.md b/README.md
index 386eac72..25a1843e 100644
--- a/README.md
+++ b/README.md
@@ -539,6 +539,7 @@
552|[Student Attendance Record II](./solutions/0552-student-attendance-record-ii.js)|Hard|
553|[Optimal Division](./solutions/0553-optimal-division.js)|Medium|
554|[Brick Wall](./solutions/0554-brick-wall.js)|Medium|
+555|[Split Concatenated Strings](./solutions/0555-split-concatenated-strings.js)|Medium|
556|[Next Greater Element III](./solutions/0556-next-greater-element-iii.js)|Medium|
557|[Reverse Words in a String III](./solutions/0557-reverse-words-in-a-string-iii.js)|Easy|
558|[Logical OR of Two Binary Grids Represented as Quad-Trees](./solutions/0558-logical-or-of-two-binary-grids-represented-as-quad-trees.js)|Medium|
diff --git a/solutions/0555-split-concatenated-strings.js b/solutions/0555-split-concatenated-strings.js
new file mode 100644
index 00000000..9f353e18
--- /dev/null
+++ b/solutions/0555-split-concatenated-strings.js
@@ -0,0 +1,50 @@
+/**
+ * 555. Split Concatenated Strings
+ * https://leetcode.com/problems/split-concatenated-strings/
+ * Difficulty: Medium
+ *
+ * You are given an array of strings strs. You could concatenate these strings together into a
+ * loop, where for each string, you could choose to reverse it or not. Among all the possible loops
+ *
+ * Return the lexicographically largest string after cutting the loop, which will make the looped
+ * string into a regular one.
+ *
+ *
+ * Specifically, to find the lexicographically largest string, you need to experience two phases:
+ * 1. Concatenate all the strings into a loop, where you can reverse some strings or not and connect
+ * them in the same order as given.
+ * 2. Cut and make one breakpoint in any place of the loop, which will make the looped string into
+ * a regular one starting from the character at the cutpoint.
+ *
+ * And your job is to find the lexicographically largest one among all the possible regular strings.
+ */
+
+/**
+ * @param {string[]} strs
+ * @return {string}
+ */
+var splitLoopedString = function(strs) {
+ const normalized = strs.map(str => {
+ const reversed = str.split('').reverse().join('');
+ return str > reversed ? str : reversed;
+ });
+
+ let result = '';
+ for (let i = 0; i < normalized.length; i++) {
+ const current = normalized[i];
+ const prefix = normalized.slice(i + 1).join('') + normalized.slice(0, i).join('');
+ const original = current;
+ const reversed = current.split('').reverse().join('');
+
+ for (const str of [original, reversed]) {
+ for (let j = 0; j <= str.length; j++) {
+ const candidate = str.slice(j) + prefix + str.slice(0, j);
+ if (candidate > result) {
+ result = candidate;
+ }
+ }
+ }
+ }
+
+ return result;
+};
From 0b3dfa440fd04489f944985c066585cd255251fd Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 20 Jun 2025 18:54:31 -0500
Subject: [PATCH 525/994] Add solution #562
---
README.md | 1 +
...ngest-line-of-consecutive-one-in-matrix.js | 35 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/0562-longest-line-of-consecutive-one-in-matrix.js
diff --git a/README.md b/README.md
index 25a1843e..17b14375 100644
--- a/README.md
+++ b/README.md
@@ -546,6 +546,7 @@
559|[Maximum Depth of N-ary Tree](./solutions/0559-maximum-depth-of-n-ary-tree.js)|Easy|
560|[Subarray Sum Equals K](./solutions/0560-subarray-sum-equals-k.js)|Medium|
561|[Array Partition](./solutions/0561-array-partition.js)|Easy|
+562|[Longest Line of Consecutive One in Matrix](./solutions/0562-longest-line-of-consecutive-one-in-matrix.js)|Medium|
563|[Binary Tree Tilt](./solutions/0563-binary-tree-tilt.js)|Easy|
564|[Find the Closest Palindrome](./solutions/0564-find-the-closest-palindrome.js)|Hard|
565|[Array Nesting](./solutions/0565-array-nesting.js)|Medium|
diff --git a/solutions/0562-longest-line-of-consecutive-one-in-matrix.js b/solutions/0562-longest-line-of-consecutive-one-in-matrix.js
new file mode 100644
index 00000000..601f0203
--- /dev/null
+++ b/solutions/0562-longest-line-of-consecutive-one-in-matrix.js
@@ -0,0 +1,35 @@
+/**
+ * 562. Longest Line of Consecutive One in Matrix
+ * https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix/
+ * Difficulty: Medium
+ *
+ * Given an m x n binary matrix mat, return the length of the longest line of consecutive one
+ * in the matrix.
+ *
+ * The line could be horizontal, vertical, diagonal, or anti-diagonal.
+ */
+
+/**
+ * @param {number[][]} mat
+ * @return {number}
+ */
+var longestLine = function(mat) {
+ const rows = mat.length;
+ const cols = mat[0].length;
+ const dp = new Array(rows).fill().map(() => new Array(cols).fill().map(() => [0, 0, 0, 0]));
+ let maxLength = 0;
+
+ for (let i = 0; i < rows; i++) {
+ for (let j = 0; j < cols; j++) {
+ if (mat[i][j] === 1) {
+ dp[i][j][0] = j > 0 ? dp[i][j - 1][0] + 1 : 1;
+ dp[i][j][1] = i > 0 ? dp[i - 1][j][1] + 1 : 1;
+ dp[i][j][2] = (i > 0 && j > 0) ? dp[i - 1][j - 1][2] + 1 : 1;
+ dp[i][j][3] = (i > 0 && j < cols - 1) ? dp[i - 1][j + 1][3] + 1 : 1;
+ maxLength = Math.max(maxLength, ...dp[i][j]);
+ }
+ }
+ }
+
+ return maxLength;
+};
From 14096cc2edb22574009e34bf772649b158946a6f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 20 Jun 2025 18:59:00 -0500
Subject: [PATCH 526/994] Add solution #568
---
README.md | 1 +
solutions/0568-maximum-vacation-days.js | 61 +++++++++++++++++++++++++
2 files changed, 62 insertions(+)
create mode 100644 solutions/0568-maximum-vacation-days.js
diff --git a/README.md b/README.md
index 17b14375..4447f96b 100644
--- a/README.md
+++ b/README.md
@@ -552,6 +552,7 @@
565|[Array Nesting](./solutions/0565-array-nesting.js)|Medium|
566|[Reshape the Matrix](./solutions/0566-reshape-the-matrix.js)|Easy|
567|[Permutation in String](./solutions/0567-permutation-in-string.js)|Medium|
+568|[Maximum Vacation Days](./solutions/0568-maximum-vacation-days.js)|Hard|
572|[Subtree of Another Tree](./solutions/0572-subtree-of-another-tree.js)|Easy|
575|[Distribute Candies](./solutions/0575-distribute-candies.js)|Easy|
576|[Out of Boundary Paths](./solutions/0576-out-of-boundary-paths.js)|Medium|
diff --git a/solutions/0568-maximum-vacation-days.js b/solutions/0568-maximum-vacation-days.js
new file mode 100644
index 00000000..3ad9a277
--- /dev/null
+++ b/solutions/0568-maximum-vacation-days.js
@@ -0,0 +1,61 @@
+/**
+ * 568. Maximum Vacation Days
+ * https://leetcode.com/problems/maximum-vacation-days/
+ * Difficulty: Hard
+ *
+ * LeetCode wants to give one of its best employees the option to travel among n cities to collect
+ * algorithm problems. But all work and no play makes Jack a dull boy, you could take vacations in
+ * some particular cities and weeks. Your job is to schedule the traveling to maximize the number
+ * of vacation days you could take, but there are certain rules and restrictions you need to follow.
+ *
+ * Rules and restrictions:
+ * 1. You can only travel among n cities, represented by indexes from 0 to n - 1. Initially, you
+ * are in the city indexed 0 on Monday.
+ * 2. The cities are connected by flights. The flights are represented as an n x n matrix (not
+ * necessarily symmetrical), called flights representing the airline status from the city i to
+ * the city j. If there is no flight from the city i to the city j, flights[i][j] == 0;
+ * Otherwise, flights[i][j] == 1. Also, flights[i][i] == 0 for all i.
+ * 3. You totally have k weeks (each week has seven days) to travel. You can only take flights at
+ * most once per day and can only take flights on each week's Monday morning. Since flight time
+ * is so short, we do not consider the impact of flight time.
+ * 4. For each city, you can only have restricted vacation days in different weeks, given an n x k
+ * matrix called days representing this relationship. For the value of days[i][j], it represents
+ * the maximum days you could take a vacation in the city i in the week j.
+ * 5. You could stay in a city beyond the number of vacation days, but you should work on the extra
+ * days, which will not be counted as vacation days.
+ * 6. If you fly from city A to city B and take the vacation on that day, the deduction towards
+ * vacation days will count towards the vacation days of city B in that week.
+ * 7. We do not consider the impact of flight hours on the calculation of vacation days.
+ *
+ * Given the two matrices flights and days, return the maximum vacation days you could take during
+ * k weeks.
+ */
+
+/**
+ * @param {number[][]} flights
+ * @param {number[][]} days
+ * @return {number}
+ */
+var maxVacationDays = function(flights, days) {
+ const cities = flights.length;
+ const weeks = days[0].length;
+ const dp = new Array(weeks + 1).fill().map(() => new Array(cities).fill(-Infinity));
+
+ dp[0][0] = 0;
+
+ for (let week = 1; week <= weeks; week++) {
+ for (let currCity = 0; currCity < cities; currCity++) {
+ for (let prevCity = 0; prevCity < cities; prevCity++) {
+ if (dp[week - 1][prevCity] !== -Infinity
+ && (flights[prevCity][currCity] || prevCity === currCity)) {
+ dp[week][currCity] = Math.max(
+ dp[week][currCity],
+ dp[week - 1][prevCity] + days[currCity][week - 1]
+ );
+ }
+ }
+ }
+ }
+
+ return Math.max(0, ...dp[weeks]);
+};
From 63408c1847fda0a0e92a4198bbe7f25d5ddb334e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 20 Jun 2025 19:00:38 -0500
Subject: [PATCH 527/994] Add solution #573
---
README.md | 1 +
solutions/0573-squirrel-simulation.js | 44 +++++++++++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/0573-squirrel-simulation.js
diff --git a/README.md b/README.md
index 4447f96b..4ecb868b 100644
--- a/README.md
+++ b/README.md
@@ -554,6 +554,7 @@
567|[Permutation in String](./solutions/0567-permutation-in-string.js)|Medium|
568|[Maximum Vacation Days](./solutions/0568-maximum-vacation-days.js)|Hard|
572|[Subtree of Another Tree](./solutions/0572-subtree-of-another-tree.js)|Easy|
+573|[Squirrel Simulation](./solutions/0573-squirrel-simulation.js)|Medium|
575|[Distribute Candies](./solutions/0575-distribute-candies.js)|Easy|
576|[Out of Boundary Paths](./solutions/0576-out-of-boundary-paths.js)|Medium|
581|[Shortest Unsorted Continuous Subarray](./solutions/0581-shortest-unsorted-continuous-subarray.js)|Medium|
diff --git a/solutions/0573-squirrel-simulation.js b/solutions/0573-squirrel-simulation.js
new file mode 100644
index 00000000..0e6c74c9
--- /dev/null
+++ b/solutions/0573-squirrel-simulation.js
@@ -0,0 +1,44 @@
+/**
+ * 573. Squirrel Simulation
+ * https://leetcode.com/problems/squirrel-simulation/
+ * Difficulty: Medium
+ *
+ * You are given two integers height and width representing a garden of size height x width.
+ * You are also given:
+ * - an array tree where tree = [treer, treec] is the position of the tree in the garden,
+ * - an array squirrel where squirrel = [squirrelr, squirrelc] is the position of the squirrel
+ * in the garden,
+ * - and an array nuts where nuts[i] = [nutir, nutic] is the position of the ith nut in the garden.
+ *
+ * The squirrel can only take at most one nut at one time and can move in four directions: up, down,
+ * left, and right, to the adjacent cell.
+ *
+ * Return the minimal distance for the squirrel to collect all the nuts and put them under the tree
+ * one by one.
+ *
+ * The distance is the number of moves.
+ */
+
+/**
+ * @param {number} height
+ * @param {number} width
+ * @param {number[]} tree
+ * @param {number[]} squirrel
+ * @param {number[][]} nuts
+ * @return {number}
+ */
+var minDistance = function(height, width, tree, squirrel, nuts) {
+ const helper = (p1, p2) => Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1]);
+
+ let totalDistance = 0;
+ let maxSaving = -Infinity;
+
+ for (const nut of nuts) {
+ const nutToTree = helper(nut, tree);
+ totalDistance += 2 * nutToTree;
+ const squirrelToNut = helper(squirrel, nut);
+ maxSaving = Math.max(maxSaving, nutToTree - squirrelToNut);
+ }
+
+ return totalDistance - maxSaving;
+};
From 807a70debed0cd7043423e2005e9fce92f6d958c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 20 Jun 2025 19:02:20 -0500
Subject: [PATCH 528/994] Add solution #582
---
README.md | 1 +
solutions/0582-kill-process.js | 46 ++++++++++++++++++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/0582-kill-process.js
diff --git a/README.md b/README.md
index 4ecb868b..57823c54 100644
--- a/README.md
+++ b/README.md
@@ -558,6 +558,7 @@
575|[Distribute Candies](./solutions/0575-distribute-candies.js)|Easy|
576|[Out of Boundary Paths](./solutions/0576-out-of-boundary-paths.js)|Medium|
581|[Shortest Unsorted Continuous Subarray](./solutions/0581-shortest-unsorted-continuous-subarray.js)|Medium|
+582|[Kill Process](./solutions/0582-kill-process.js)|Medium|
583|[Delete Operation for Two Strings](./solutions/0583-delete-operation-for-two-strings.js)|Medium|
587|[Erect the Fence](./solutions/0587-erect-the-fence.js)|Hard|
589|[N-ary Tree Preorder Traversal](./solutions/0589-n-ary-tree-preorder-traversal.js)|Easy|
diff --git a/solutions/0582-kill-process.js b/solutions/0582-kill-process.js
new file mode 100644
index 00000000..bc550c4f
--- /dev/null
+++ b/solutions/0582-kill-process.js
@@ -0,0 +1,46 @@
+/**
+ * 582. Kill Process
+ * https://leetcode.com/problems/kill-process/
+ * Difficulty: Medium
+ *
+ * You have n processes forming a rooted tree structure. You are given two integer arrays pid
+ * and ppid, where pid[i] is the ID of the ith process and ppid[i] is the ID of the ith process's
+ * parent process.
+ *
+ * Each process has only one parent process but may have multiple children processes. Only one
+ * process has ppid[i] = 0, which means this process has no parent process (the root of the tree).
+ *
+ * When a process is killed, all of its children processes will also be killed.
+ *
+ * Given an integer kill representing the ID of a process you want to kill, return a list of the
+ * IDs of the processes that will be killed. You may return the answer in any order.
+ */
+
+/**
+ * @param {number[]} pid
+ * @param {number[]} ppid
+ * @param {number} kill
+ * @return {number[]}
+ */
+var killProcess = function(pid, ppid, kill) {
+ const map = new Map();
+ for (let i = 0; i < ppid.length; i++) {
+ if (!map.has(ppid[i])) {
+ map.set(ppid[i], []);
+ }
+ map.get(ppid[i]).push(pid[i]);
+ }
+
+ const result = [];
+ traverse(kill);
+ return result;
+
+ function traverse(process) {
+ result.push(process);
+ if (map.has(process)) {
+ for (const child of map.get(process)) {
+ traverse(child);
+ }
+ }
+ }
+};
From 7ad1dbb79431fd0f52ba2170a23d29838241eb20 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 20 Jun 2025 19:14:39 -0500
Subject: [PATCH 529/994] Add solution #588
---
README.md | 1 +
.../0588-design-in-memory-file-system.js | 97 +++++++++++++++++++
2 files changed, 98 insertions(+)
create mode 100644 solutions/0588-design-in-memory-file-system.js
diff --git a/README.md b/README.md
index 57823c54..f97429dc 100644
--- a/README.md
+++ b/README.md
@@ -561,6 +561,7 @@
582|[Kill Process](./solutions/0582-kill-process.js)|Medium|
583|[Delete Operation for Two Strings](./solutions/0583-delete-operation-for-two-strings.js)|Medium|
587|[Erect the Fence](./solutions/0587-erect-the-fence.js)|Hard|
+588|[Design In-Memory File System](./solutions/0588-design-in-memory-file-system.js)|Hard|
589|[N-ary Tree Preorder Traversal](./solutions/0589-n-ary-tree-preorder-traversal.js)|Easy|
590|[N-ary Tree Postorder Traversal](./solutions/0590-n-ary-tree-postorder-traversal.js)|Easy|
591|[Tag Validator](./solutions/0591-tag-validator.js)|Hard|
diff --git a/solutions/0588-design-in-memory-file-system.js b/solutions/0588-design-in-memory-file-system.js
new file mode 100644
index 00000000..a3e2e20a
--- /dev/null
+++ b/solutions/0588-design-in-memory-file-system.js
@@ -0,0 +1,97 @@
+/**
+ * 588. Design In-Memory File System
+ * https://leetcode.com/problems/design-in-memory-file-system/
+ * Difficulty: Hard
+ *
+ * Design a data structure that simulates an in-memory file system.
+ *
+ * Implement the FileSystem class:
+ * - FileSystem() Initializes the object of the system.
+ * - List ls(String path)
+ * - If path is a file path, returns a list that only contains this file's name.
+ * - If path is a directory path, returns the list of file and directory names in this directory.
+ * - The answer should in lexicographic order.
+ * - void mkdir(String path) Makes a new directory according to the given path. The given directory
+ * path does not exist. If the middle directories in the path do not exist, you should create
+ * them as well.
+ * - void addContentToFile(String filePath, String content)
+ * - If filePath does not exist, creates that file containing given content.
+ * - If filePath already exists, appends the given content to original content.
+ * - String readContentFromFile(String filePath) Returns the content in the file at filePath.
+ */
+
+var FileSystem = function() {
+ this.root = new Map();
+};
+
+/**
+ * @param {string} path
+ * @return {string[]}
+ */
+FileSystem.prototype.ls = function(path) {
+ const parts = path === '/' ? [] : path.split('/').slice(1);
+ let current = this.root;
+
+ for (const part of parts) {
+ current = current.get(part);
+ }
+
+ if (typeof current === 'string') {
+ return [parts[parts.length - 1]];
+ }
+
+ return Array.from(current.keys()).sort();
+};
+
+/**
+ * @param {string} path
+ * @return {void}
+ */
+FileSystem.prototype.mkdir = function(path) {
+ const parts = path.split('/').slice(1);
+ let current = this.root;
+
+ for (const part of parts) {
+ if (!current.has(part)) {
+ current.set(part, new Map());
+ }
+ current = current.get(part);
+ }
+};
+
+/**
+ * @param {string} filePath
+ * @param {string} content
+ * @return {void}
+ */
+FileSystem.prototype.addContentToFile = function(filePath, content) {
+ const parts = filePath.split('/').slice(1);
+ const fileName = parts.pop();
+ let current = this.root;
+
+ for (const part of parts) {
+ if (!current.has(part)) {
+ current.set(part, new Map());
+ }
+ current = current.get(part);
+ }
+
+ const existingContent = current.get(fileName) || '';
+ current.set(fileName, existingContent + content);
+};
+
+/**
+ * @param {string} filePath
+ * @return {string}
+ */
+FileSystem.prototype.readContentFromFile = function(filePath) {
+ const parts = filePath.split('/').slice(1);
+ const fileName = parts.pop();
+ let current = this.root;
+
+ for (const part of parts) {
+ current = current.get(part);
+ }
+
+ return current.get(fileName);
+};
From 7f1e2ddf0b7ff528f32578699edc8280dc9d0af8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 20 Jun 2025 19:16:09 -0500
Subject: [PATCH 530/994] Add solution #604
---
README.md | 1 +
.../0604-design-compressed-string-iterator.js | 65 +++++++++++++++++++
2 files changed, 66 insertions(+)
create mode 100644 solutions/0604-design-compressed-string-iterator.js
diff --git a/README.md b/README.md
index f97429dc..26434225 100644
--- a/README.md
+++ b/README.md
@@ -571,6 +571,7 @@
598|[Range Addition II](./solutions/0598-range-addition-ii.js)|Easy|
599|[Minimum Index Sum of Two Lists](./solutions/0599-minimum-index-sum-of-two-lists.js)|Easy|
600|[Non-negative Integers without Consecutive Ones](./solutions/0600-non-negative-integers-without-consecutive-ones.js)|Hard|
+604|[Design Compressed String Iterator](./solutions/0604-design-compressed-string-iterator.js)|Easy|
605|[Can Place Flowers](./solutions/0605-can-place-flowers.js)|Easy|
606|[Construct String from Binary Tree](./solutions/0606-construct-string-from-binary-tree.js)|Easy|
609|[Find Duplicate File in System](./solutions/0609-find-duplicate-file-in-system.js)|Medium|
diff --git a/solutions/0604-design-compressed-string-iterator.js b/solutions/0604-design-compressed-string-iterator.js
new file mode 100644
index 00000000..e79f8beb
--- /dev/null
+++ b/solutions/0604-design-compressed-string-iterator.js
@@ -0,0 +1,65 @@
+/**
+ * 604. Design Compressed String Iterator
+ * https://leetcode.com/problems/design-compressed-string-iterator/
+ * Difficulty: Easy
+ *
+ * Design and implement a data structure for a compressed string iterator. The given compressed
+ * string will be in the form of each letter followed by a positive integer representing the
+ * number of this letter existing in the original uncompressed string.
+ *
+ * Implement the StringIterator class:
+ * - next() Returns the next character if the original string still has uncompressed characters,
+ * otherwise returns a white space.
+ * - hasNext() Returns true if there is any letter needs to be uncompressed in the original string,
+ * otherwise returns false.
+ */
+
+/**
+ * @param {string} compressedString
+ */
+var StringIterator = function(compressedString) {
+ this.segments = [];
+ this.currentIndex = 0;
+ this.currentCount = 0;
+
+ let i = 0;
+ while (i < compressedString.length) {
+ const character = compressedString[i];
+ i++;
+ let count = '';
+ while (i < compressedString.length && /\d/.test(compressedString[i])) {
+ count += compressedString[i];
+ i++;
+ }
+ this.segments.push([character, parseInt(count)]);
+ }
+};
+
+/**
+ * @return {character}
+ */
+StringIterator.prototype.next = function() {
+ if (!this.hasNext()) {
+ return ' ';
+ }
+
+ if (this.currentCount === 0) {
+ this.currentCount = this.segments[this.currentIndex][1];
+ }
+
+ const character = this.segments[this.currentIndex][0];
+ this.currentCount--;
+
+ if (this.currentCount === 0) {
+ this.currentIndex++;
+ }
+
+ return character;
+};
+
+/**
+ * @return {boolean}
+ */
+StringIterator.prototype.hasNext = function() {
+ return this.currentIndex < this.segments.length;
+};
From 5d874b5d8ed10775c3def8e115664779974f834a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 00:31:47 -0500
Subject: [PATCH 531/994] Add solution #616
---
README.md | 1 +
solutions/0616-add-bold-tag-in-string.js | 61 ++++++++++++++++++++++++
2 files changed, 62 insertions(+)
create mode 100644 solutions/0616-add-bold-tag-in-string.js
diff --git a/README.md b/README.md
index 26434225..cf44dab4 100644
--- a/README.md
+++ b/README.md
@@ -576,6 +576,7 @@
606|[Construct String from Binary Tree](./solutions/0606-construct-string-from-binary-tree.js)|Easy|
609|[Find Duplicate File in System](./solutions/0609-find-duplicate-file-in-system.js)|Medium|
611|[Valid Triangle Number](./solutions/0611-valid-triangle-number.js)|Medium|
+616|[Add Bold Tag in String](./solutions/0616-add-bold-tag-in-string.js)|Medium|
617|[Merge Two Binary Trees](./solutions/0617-merge-two-binary-trees.js)|Easy|
621|[Task Scheduler](./solutions/0621-task-scheduler.js)|Medium|
622|[Design Circular Queue](./solutions/0622-design-circular-queue.js)|Medium|
diff --git a/solutions/0616-add-bold-tag-in-string.js b/solutions/0616-add-bold-tag-in-string.js
new file mode 100644
index 00000000..563c80c5
--- /dev/null
+++ b/solutions/0616-add-bold-tag-in-string.js
@@ -0,0 +1,61 @@
+/**
+ * 616. Add Bold Tag in String
+ * https://leetcode.com/problems/add-bold-tag-in-string/
+ * Difficulty: Medium
+ *
+ * You are given a string s and an array of strings words.
+ *
+ * You should add a closed pair of bold tag and to wrap the substrings in s that
+ * exist in words.
+ * - If two such substrings overlap, you should wrap them together with only one pair of
+ * closed bold-tag.
+ * - If two substrings wrapped by bold tags are consecutive, you should combine them.
+ *
+ * Return s after adding the bold tags.
+ */
+
+/**
+ * @param {string} s
+ * @param {string[]} words
+ * @return {string}
+ */
+var addBoldTag = function(s, words) {
+ const boldIntervals = [];
+
+ for (const word of words) {
+ let start = s.indexOf(word);
+ while (start !== -1) {
+ boldIntervals.push([start, start + word.length]);
+ start = s.indexOf(word, start + 1);
+ }
+ }
+
+ if (!boldIntervals.length) return s;
+
+ boldIntervals.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
+
+ const mergedIntervals = [];
+ let [currentStart, currentEnd] = boldIntervals[0];
+
+ for (let i = 1; i < boldIntervals.length; i++) {
+ const [nextStart, nextEnd] = boldIntervals[i];
+ if (nextStart <= currentEnd) {
+ currentEnd = Math.max(currentEnd, nextEnd);
+ } else {
+ mergedIntervals.push([currentStart, currentEnd]);
+ [currentStart, currentEnd] = [nextStart, nextEnd];
+ }
+ }
+ mergedIntervals.push([currentStart, currentEnd]);
+
+ let result = '';
+ let lastEnd = 0;
+ for (const [start, end] of mergedIntervals) {
+ result += s.slice(lastEnd, start) + '' + s.slice(start, end) + '';
+ lastEnd = end;
+ }
+
+ result += s.slice(lastEnd);
+
+ return result;
+};
From 3b7bfb20536e92a56cfdf970b230571763532b03 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 00:32:41 -0500
Subject: [PATCH 532/994] Add solution #758
---
README.md | 1 +
solutions/0758-bold-words-in-string.js | 57 ++++++++++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/0758-bold-words-in-string.js
diff --git a/README.md b/README.md
index cf44dab4..3540c374 100644
--- a/README.md
+++ b/README.md
@@ -687,6 +687,7 @@
754|[Reach a Number](./solutions/0754-reach-a-number.js)|Medium|
756|[Pyramid Transition Matrix](./solutions/0756-pyramid-transition-matrix.js)|Medium|
757|[Set Intersection Size At Least Two](./solutions/0757-set-intersection-size-at-least-two.js)|Hard|
+758|[Bold Words in String](./solutions/0758-bold-words-in-string.js)|Medium|
761|[Special Binary String](./solutions/0761-special-binary-string.js)|Hard|
762|[Prime Number of Set Bits in Binary Representation](./solutions/0762-prime-number-of-set-bits-in-binary-representation.js)|Easy|
763|[Partition Labels](./solutions/0763-partition-labels.js)|Medium|
diff --git a/solutions/0758-bold-words-in-string.js b/solutions/0758-bold-words-in-string.js
new file mode 100644
index 00000000..5187a17d
--- /dev/null
+++ b/solutions/0758-bold-words-in-string.js
@@ -0,0 +1,57 @@
+/**
+ * 758. Bold Words in String
+ * https://leetcode.com/problems/bold-words-in-string/
+ * Difficulty: Medium
+ *
+ * Given an array of keywords words and a string s, make all appearances of all keywords words[i]
+ * in s bold. Any letters between and tags become bold.
+ *
+ * Return s after adding the bold tags. The returned string should use the least number of tags
+ * possible, and the tags should form a valid combination.
+ */
+
+/**
+ * @param {string[]} words
+ * @param {string} s
+ * @return {string}
+ */
+var boldWords = function(words, s) {
+ const boldIntervals = [];
+
+ for (const word of words) {
+ let start = s.indexOf(word);
+ while (start !== -1) {
+ boldIntervals.push([start, start + word.length]);
+ start = s.indexOf(word, start + 1);
+ }
+ }
+
+ if (!boldIntervals.length) return s;
+
+ boldIntervals.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
+
+ const mergedIntervals = [];
+ let [currentStart, currentEnd] = boldIntervals[0];
+
+ for (let i = 1; i < boldIntervals.length; i++) {
+ const [nextStart, nextEnd] = boldIntervals[i];
+ if (nextStart <= currentEnd) {
+ currentEnd = Math.max(currentEnd, nextEnd);
+ } else {
+ mergedIntervals.push([currentStart, currentEnd]);
+ [currentStart, currentEnd] = [nextStart, nextEnd];
+ }
+ }
+ mergedIntervals.push([currentStart, currentEnd]);
+
+ let result = '';
+ let lastEnd = 0;
+ for (const [start, end] of mergedIntervals) {
+ result += s.slice(lastEnd, start) + '' + s.slice(start, end) + '';
+ lastEnd = end;
+ }
+
+ result += s.slice(lastEnd);
+
+ return result;
+};
From 5e26512f406190f0b6e9656c5ca7cf79f027f61e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 00:33:40 -0500
Subject: [PATCH 533/994] Add solution #625
---
README.md | 1 +
solutions/0625-minimum-factorization.js | 35 +++++++++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/0625-minimum-factorization.js
diff --git a/README.md b/README.md
index 3540c374..e6355181 100644
--- a/README.md
+++ b/README.md
@@ -582,6 +582,7 @@
622|[Design Circular Queue](./solutions/0622-design-circular-queue.js)|Medium|
623|[Add One Row to Tree](./solutions/0623-add-one-row-to-tree.js)|Medium|
624|[Maximum Distance in Arrays](./solutions/0624-maximum-distance-in-arrays.js)|Medium|
+625|[Minimum Factorization](./solutions/0625-minimum-factorization.js)|Medium|
628|[Maximum Product of Three Numbers](./solutions/0628-maximum-product-of-three-numbers.js)|Easy|
629|[K Inverse Pairs Array](./solutions/0629-k-inverse-pairs-array.js)|Hard|
630|[Course Schedule III](./solutions/0630-course-schedule-iii.js)|Hard|
diff --git a/solutions/0625-minimum-factorization.js b/solutions/0625-minimum-factorization.js
new file mode 100644
index 00000000..80019298
--- /dev/null
+++ b/solutions/0625-minimum-factorization.js
@@ -0,0 +1,35 @@
+/**
+ * 625. Minimum Factorization
+ * https://leetcode.com/problems/minimum-factorization/
+ * Difficulty: Medium
+ *
+ * Given a positive integer num, return the smallest positive integer x whose multiplication
+ * of each digit equals num. If there is no answer or the answer is not fit in 32-bit signed
+ * integer, return 0.
+ */
+
+/**
+ * @param {number} num
+ * @return {number}
+ */
+var smallestFactorization = function(num) {
+ if (num < 2) return num;
+
+ const digits = [];
+ for (let divisor = 9; divisor > 1; divisor--) {
+ while (num % divisor === 0) {
+ digits.push(divisor);
+ num /= divisor;
+ }
+ }
+
+ if (num > 1) return 0;
+
+ let result = 0;
+ for (const digit of digits.reverse()) {
+ result = result * 10 + digit;
+ if (result > 2**31 - 1) return 0;
+ }
+
+ return result;
+};
From c1384c639cd1f73955c23a021cebdf879040ab92 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 00:39:51 -0500
Subject: [PATCH 534/994] Add solution #631
---
README.md | 1 +
solutions/0631-design-excel-sum-formula.js | 141 +++++++++++++++++++++
2 files changed, 142 insertions(+)
create mode 100644 solutions/0631-design-excel-sum-formula.js
diff --git a/README.md b/README.md
index e6355181..38ba3de0 100644
--- a/README.md
+++ b/README.md
@@ -586,6 +586,7 @@
628|[Maximum Product of Three Numbers](./solutions/0628-maximum-product-of-three-numbers.js)|Easy|
629|[K Inverse Pairs Array](./solutions/0629-k-inverse-pairs-array.js)|Hard|
630|[Course Schedule III](./solutions/0630-course-schedule-iii.js)|Hard|
+631|[Design Excel Sum Formula](./solutions/0631-design-excel-sum-formula.js)|Hard|
632|[Smallest Range Covering Elements from K Lists](./solutions/0632-smallest-range-covering-elements-from-k-lists.js)|Hard|
633|[Sum of Square Numbers](./solutions/0633-sum-of-square-numbers.js)|Medium|
636|[Exclusive Time of Functions](./solutions/0636-exclusive-time-of-functions.js)|Medium|
diff --git a/solutions/0631-design-excel-sum-formula.js b/solutions/0631-design-excel-sum-formula.js
new file mode 100644
index 00000000..83af1528
--- /dev/null
+++ b/solutions/0631-design-excel-sum-formula.js
@@ -0,0 +1,141 @@
+/**
+ * 631. Design Excel Sum Formula
+ * https://leetcode.com/problems/design-excel-sum-formula/
+ * Difficulty: Hard
+ *
+ * Design the basic function of Excel and implement the function of the sum formula.
+ *
+ * Implement the Excel class:
+ * - Excel(int height, char width) Initializes the object with the height and the width
+ * of the sheet. The sheet is an integer matrix mat of size height x width with the row
+ * index in the range [1, height] and the column index in the range ['A', width]. All the
+ * values should be zero initially.
+ * - void set(int row, char column, int val) Changes the value at mat[row][column] to be val.
+ * - int get(int row, char column) Returns the value at mat[row][column].
+ * - int sum(int row, char column, List numbers) Sets the value at mat[row][column] to
+ * be the sum of cells represented by numbers and returns the value at mat[row][column].
+ * This sum formula should exist until this cell is overlapped by another value or another
+ * sum formula. numbers[i] could be on the format:
+ * - "ColRow" that represents a single cell.
+ * - For example, "F7" represents the cell mat[7]['F'].
+ * - "ColRow1:ColRow2" that represents a range of cells. The range will always be a rectangle
+ * where "ColRow1" represent the position of the top-left cell, and "ColRow2" represents the
+ * position of the bottom-right cell.
+ * - For example, "B3:F7" represents the cells mat[i][j] for 3 <= i <= 7 and 'B' <= j <= 'F'.
+ *
+ * Note: You could assume that there will not be any circular sum reference.
+ *
+ * For example, mat[1]['A'] == sum(1, "B") and mat[1]['B'] == sum(1, "A").
+ */
+
+/**
+ * @param {number} height
+ * @param {character} width
+ */
+var Excel = function(height, width) {
+ this.height = height;
+ this.width = width.charCodeAt(0) - 64;
+ this.matrix = new Array(height).fill().map(() => new Array(this.width).fill(0));
+ this.formulas = new Map();
+ this.dependencies = new Map();
+};
+
+/**
+ * @param {number} row
+ * @param {character} column
+ * @param {number} val
+ * @return {void}
+ */
+Excel.prototype.set = function(row, column, val) {
+ const col = column.charCodeAt(0) - 65;
+ const key = `${row}:${column}`;
+ this.matrix[row - 1][col] = val;
+ if (this.formulas.has(key)) {
+ this.formulas.delete(key);
+ this.dependencies.get(key)?.delete(key);
+ }
+ this.updateDependents(row, column);
+};
+
+/**
+ * @param {number} row
+ * @param {character} column
+ * @return {number}
+ */
+Excel.prototype.get = function(row, column) {
+ const col = column.charCodeAt(0) - 65;
+ return this.matrix[row - 1][col];
+};
+
+/**
+ * @param {number} row
+ * @param {character} column
+ * @param {string[]} numbers
+ * @return {number}
+ */
+Excel.prototype.sum = function(row, column, numbers) {
+ const col = column.charCodeAt(0) - 65;
+ const cellKey = `${row}:${column}`;
+ const cells = [];
+
+ for (const num of numbers) {
+ if (num.includes(':')) {
+ const [start, end] = num.split(':');
+ const startCol = start[0].charCodeAt(0) - 65;
+ const startRow = parseInt(start.slice(1)) - 1;
+ const endCol = end[0].charCodeAt(0) - 65;
+ const endRow = parseInt(end.slice(1)) - 1;
+
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startCol; c <= endCol; c++) {
+ cells.push([r, c]);
+ }
+ }
+ } else {
+ const c = num[0].charCodeAt(0) - 65;
+ const r = parseInt(num.slice(1)) - 1;
+ cells.push([r, c]);
+ }
+ }
+
+ if (this.formulas.has(cellKey)) {
+ for (const [r, c] of this.formulas.get(cellKey)) {
+ const depKey = `${r + 1}:${String.fromCharCode(c + 65)}`;
+ this.dependencies.get(depKey)?.delete(cellKey);
+ }
+ }
+
+ this.formulas.set(cellKey, cells);
+ for (const [r, c] of cells) {
+ const depKey = `${r + 1}:${String.fromCharCode(c + 65)}`;
+ if (!this.dependencies.has(depKey)) {
+ this.dependencies.set(depKey, new Set());
+ }
+ this.dependencies.get(depKey).add(cellKey);
+ }
+
+ const total = this.calculateSum(cells);
+ this.matrix[row - 1][col] = total;
+ this.updateDependents(row, column);
+ return total;
+};
+
+Excel.prototype.calculateSum = function(cells) {
+ return cells.reduce((sum, [r, c]) => sum + this.matrix[r][c], 0);
+};
+
+Excel.prototype.updateDependents = function(row, column) {
+ const key = `${row}:${column}`;
+ if (!this.dependencies.has(key)) return;
+
+ for (const depKey of this.dependencies.get(key)) {
+ const [depRow, depCol] = depKey.split(':');
+ const col = depCol.charCodeAt(0) - 65;
+ const cells = this.formulas.get(depKey);
+ if (cells) {
+ const newSum = this.calculateSum(cells);
+ this.matrix[parseInt(depRow) - 1][col] = newSum;
+ this.updateDependents(parseInt(depRow), depCol);
+ }
+ }
+};
From 461c6b20792b065a3a164a880fa89ef19ed46f6a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 00:40:52 -0500
Subject: [PATCH 535/994] Add solution #634
---
README.md | 1 +
.../0634-find-the-derangement-of-an-array.js | 32 +++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/0634-find-the-derangement-of-an-array.js
diff --git a/README.md b/README.md
index 38ba3de0..049db064 100644
--- a/README.md
+++ b/README.md
@@ -589,6 +589,7 @@
631|[Design Excel Sum Formula](./solutions/0631-design-excel-sum-formula.js)|Hard|
632|[Smallest Range Covering Elements from K Lists](./solutions/0632-smallest-range-covering-elements-from-k-lists.js)|Hard|
633|[Sum of Square Numbers](./solutions/0633-sum-of-square-numbers.js)|Medium|
+634|[Find the Derangement of An Array](./solutions/0634-find-the-derangement-of-an-array.js)|Medium|
636|[Exclusive Time of Functions](./solutions/0636-exclusive-time-of-functions.js)|Medium|
637|[Average of Levels in Binary Tree](./solutions/0637-average-of-levels-in-binary-tree.js)|Easy|
638|[Shopping Offers](./solutions/0638-shopping-offers.js)|Medium|
diff --git a/solutions/0634-find-the-derangement-of-an-array.js b/solutions/0634-find-the-derangement-of-an-array.js
new file mode 100644
index 00000000..7efca728
--- /dev/null
+++ b/solutions/0634-find-the-derangement-of-an-array.js
@@ -0,0 +1,32 @@
+/**
+ * 634. Find the Derangement of An Array
+ * https://leetcode.com/problems/find-the-derangement-of-an-array/
+ * Difficulty: Medium
+ *
+ * In combinatorial mathematics, a derangement is a permutation of the elements of a set,
+ * such that no element appears in its original position.
+ *
+ * You are given an integer n. There is originally an array consisting of n integers from
+ * 1 to n in ascending order, return the number of derangements it can generate. Since the
+ * answer may be huge, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var findDerangement = function(n) {
+ const MOD = 1e9 + 7;
+ if (n === 1) return 0;
+ if (n === 2) return 1;
+
+ let prev2 = 0;
+ let prev1 = 1;
+ for (let i = 3; i <= n; i++) {
+ const current = ((i - 1) * (prev1 + prev2)) % MOD;
+ prev2 = prev1;
+ prev1 = current;
+ }
+
+ return prev1;
+};
From 491d9e47a2cce983ea66e7ca9d5a94ea3a17a4f8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 17:29:43 -0500
Subject: [PATCH 536/994] Add solution #635
---
README.md | 1 +
solutions/0635-design-log-storage-system.js | 63 +++++++++++++++++++++
2 files changed, 64 insertions(+)
create mode 100644 solutions/0635-design-log-storage-system.js
diff --git a/README.md b/README.md
index 049db064..40d56d7d 100644
--- a/README.md
+++ b/README.md
@@ -590,6 +590,7 @@
632|[Smallest Range Covering Elements from K Lists](./solutions/0632-smallest-range-covering-elements-from-k-lists.js)|Hard|
633|[Sum of Square Numbers](./solutions/0633-sum-of-square-numbers.js)|Medium|
634|[Find the Derangement of An Array](./solutions/0634-find-the-derangement-of-an-array.js)|Medium|
+635|[Design Log Storage System](./solutions/0635-design-log-storage-system.js)|Medium|
636|[Exclusive Time of Functions](./solutions/0636-exclusive-time-of-functions.js)|Medium|
637|[Average of Levels in Binary Tree](./solutions/0637-average-of-levels-in-binary-tree.js)|Easy|
638|[Shopping Offers](./solutions/0638-shopping-offers.js)|Medium|
diff --git a/solutions/0635-design-log-storage-system.js b/solutions/0635-design-log-storage-system.js
new file mode 100644
index 00000000..50a8b303
--- /dev/null
+++ b/solutions/0635-design-log-storage-system.js
@@ -0,0 +1,63 @@
+/**
+ * 635. Design Log Storage System
+ * https://leetcode.com/problems/design-log-storage-system/
+ * Difficulty: Medium
+ *
+ * You are given several logs, where each log contains a unique ID and timestamp. Timestamp is a
+ * string that has the following format: Year:Month:Day:Hour:Minute:Second, for example,
+ * 2017:01:01:23:59:59. All domains are zero-padded decimal numbers.
+ *
+ * Implement the LogSystem class:
+ * - LogSystem() Initializes the LogSystem object.
+ * - void put(int id, string timestamp) Stores the given log (id, timestamp) in your storage system.
+ * - int[] retrieve(string start, string end, string granularity) Returns the IDs of the logs whose
+ * timestamps are within the range from start to end inclusive. start and end all have the same
+ * format as timestamp, and granularity means how precise the range should be (i.e. to the exact
+ * Day, Minute, etc.). For example, start = "2017:01:01:23:59:59", end = "2017:01:02:23:59:59",
+ * and granularity = "Day" means that we need to find the logs within the inclusive range from
+ * Jan. 1st 2017 to Jan. 2nd 2017, and the Hour, Minute, and Second for each log entry can be
+ * ignored.
+ */
+
+var LogSystem = function() {
+ this.logs = [];
+ this.granularities = {
+ Year: 4,
+ Month: 7,
+ Day: 10,
+ Hour: 13,
+ Minute: 16,
+ Second: 19
+ };
+};
+
+/**
+ * @param {number} id
+ * @param {string} timestamp
+ * @return {void}
+ */
+LogSystem.prototype.put = function(id, timestamp) {
+ this.logs.push([timestamp, id]);
+};
+
+/**
+ * @param {string} start
+ * @param {string} end
+ * @param {string} granularity
+ * @return {number[]}
+ */
+LogSystem.prototype.retrieve = function(start, end, granularity) {
+ const precision = this.granularities[granularity];
+ const startKey = start.slice(0, precision).padEnd(19, '0');
+ const endKey = end.slice(0, precision).padEnd(19, '9');
+
+ const result = [];
+ for (const [timestamp, id] of this.logs) {
+ const key = timestamp.slice(0, precision).padEnd(19, '0');
+ if (key >= startKey && key <= endKey) {
+ result.push(id);
+ }
+ }
+
+ return result.sort((a, b) => a - b);
+};
From 8ff463893b4cdedf22242ea624a6fa7902f5d4f4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 17:32:42 -0500
Subject: [PATCH 537/994] Add solution #642
---
README.md | 1 +
.../0642-design-search-autocomplete-system.js | 97 +++++++++++++++++++
2 files changed, 98 insertions(+)
create mode 100644 solutions/0642-design-search-autocomplete-system.js
diff --git a/README.md b/README.md
index 40d56d7d..52c6c2cc 100644
--- a/README.md
+++ b/README.md
@@ -597,6 +597,7 @@
639|[Decode Ways II](./solutions/0639-decode-ways-ii.js)|Hard|
640|[Solve the Equation](./solutions/0640-solve-the-equation.js)|Medium|
641|[Design Circular Deque](./solutions/0641-design-circular-deque.js)|Medium|
+642|[Design Search Autocomplete System](./solutions/0642-design-search-autocomplete-system.js)|Hard|
643|[Maximum Average Subarray I](./solutions/0643-maximum-average-subarray-i.js)|Easy|
645|[Set Mismatch](./solutions/0645-set-mismatch.js)|Medium|
646|[Maximum Length of Pair Chain](./solutions/0646-maximum-length-of-pair-chain.js)|Medium|
diff --git a/solutions/0642-design-search-autocomplete-system.js b/solutions/0642-design-search-autocomplete-system.js
new file mode 100644
index 00000000..d6e63851
--- /dev/null
+++ b/solutions/0642-design-search-autocomplete-system.js
@@ -0,0 +1,97 @@
+/**
+ * 642. Design Search Autocomplete System
+ * https://leetcode.com/problems/design-search-autocomplete-system/
+ * Difficulty: Hard
+ *
+ * Design a search autocomplete system for a search engine. Users may input a sentence (at
+ * least one word and end with a special character '#').
+ *
+ * You are given a string array sentences and an integer array times both of length n where
+ * sentences[i] is a previously typed sentence and times[i] is the corresponding number of
+ * times the sentence was typed. For each input character except '#', return the top 3
+ * historical hot sentences that have the same prefix as the part of the sentence already typed.
+ *
+ * Here are the specific rules:
+ * - The hot degree for a sentence is defined as the number of times a user typed the exactly
+ * same sentence before.
+ * - The returned top 3 hot sentences should be sorted by hot degree (The first is the hottest
+ * one). If several sentences have the same hot degree, use ASCII-code order (smaller one
+ * appears first).
+ * - If less than 3 hot sentences exist, return as many as you can.
+ * - When the input is a special character, it means the sentence ends, and in this case, you
+ * need to return an empty list.
+ *
+ * Implement the AutocompleteSystem class:
+ * - AutocompleteSystem(String[] sentences, int[] times) Initializes the object with the
+ * sentences and times arrays.
+ * - List input(char c) This indicates that the user typed the character c.
+ * - Returns an empty array [] if c == '#' and stores the inputted sentence in the system.
+ * - Returns the top 3 historical hot sentences that have the same prefix as the part of the
+ * sentence already typed. If there are fewer than 3 matches, return them all.
+ */
+
+/**
+ * @param {string[]} sentences
+ * @param {number[]} times
+ */
+var AutocompleteSystem = function(sentences, times) {
+ this.trie = {};
+ this.current = '';
+ this.root = this.trie;
+
+ for (let i = 0; i < sentences.length; i++) {
+ this.insert(sentences[i], times[i]);
+ }
+};
+
+/**
+ * @param {character} c
+ * @return {string[]}
+ */
+AutocompleteSystem.prototype.input = function(c) {
+ if (c === '#') {
+ this.insert(this.current, 1);
+ this.current = '';
+ this.root = this.trie;
+ return [];
+ }
+
+ this.current += c;
+ if (!this.root[c]) {
+ this.root[c] = {};
+ this.root = this.root[c];
+ return [];
+ }
+
+ this.root = this.root[c];
+ const candidates = [];
+ this.search(this.root, this.current, candidates);
+
+ candidates.sort((a, b) => {
+ if (a.count !== b.count) return b.count - a.count;
+ return a.sentence < b.sentence ? -1 : 1;
+ });
+
+ return candidates.slice(0, 3).map(item => item.sentence);
+};
+
+AutocompleteSystem.prototype.insert = function(sentence, count) {
+ let node = this.trie;
+ for (const char of sentence) {
+ if (!node[char]) node[char] = {};
+ node = node[char];
+ }
+ node.isEnd = (node.isEnd || 0) + count;
+};
+
+AutocompleteSystem.prototype.search = function(node, prefix, candidates) {
+ if (node.isEnd) {
+ candidates.push({ sentence: prefix, count: node.isEnd });
+ }
+
+ for (const char in node) {
+ if (char !== 'isEnd') {
+ this.search(node[char], prefix + char, candidates);
+ }
+ }
+};
From 4bb7c2d210df92e46f3fb89629c0871ad8730256 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 17:33:56 -0500
Subject: [PATCH 538/994] Add solution #644
---
README.md | 1 +
solutions/0644-maximum-average-subarray-ii.js | 54 +++++++++++++++++++
2 files changed, 55 insertions(+)
create mode 100644 solutions/0644-maximum-average-subarray-ii.js
diff --git a/README.md b/README.md
index 52c6c2cc..2df1153a 100644
--- a/README.md
+++ b/README.md
@@ -599,6 +599,7 @@
641|[Design Circular Deque](./solutions/0641-design-circular-deque.js)|Medium|
642|[Design Search Autocomplete System](./solutions/0642-design-search-autocomplete-system.js)|Hard|
643|[Maximum Average Subarray I](./solutions/0643-maximum-average-subarray-i.js)|Easy|
+644|[Maximum Average Subarray II](./solutions/0644-maximum-average-subarray-ii.js)|Hard|
645|[Set Mismatch](./solutions/0645-set-mismatch.js)|Medium|
646|[Maximum Length of Pair Chain](./solutions/0646-maximum-length-of-pair-chain.js)|Medium|
647|[Palindromic Substrings](./solutions/0647-palindromic-substrings.js)|Medium|
diff --git a/solutions/0644-maximum-average-subarray-ii.js b/solutions/0644-maximum-average-subarray-ii.js
new file mode 100644
index 00000000..b2f7549a
--- /dev/null
+++ b/solutions/0644-maximum-average-subarray-ii.js
@@ -0,0 +1,54 @@
+/**
+ * 644. Maximum Average Subarray II
+ * https://leetcode.com/problems/maximum-average-subarray-ii/
+ * Difficulty: Hard
+ *
+ * You are given an integer array nums consisting of n elements, and an integer k.
+ *
+ * Find a contiguous subarray whose length is greater than or equal to k that has the maximum
+ * average value and return this value. Any answer with a calculation error less than 10-5 will
+ * be accepted.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var findMaxAverage = function(nums, k) {
+ const n = nums.length;
+ let minVal = Math.min(...nums);
+ let maxVal = Math.max(...nums);
+
+ while (maxVal - minVal > 1e-5) {
+ const mid = (minVal + maxVal) / 2;
+ if (canFindLargerAverage(nums, k, mid)) {
+ minVal = mid;
+ } else {
+ maxVal = mid;
+ }
+ }
+
+ return minVal;
+};
+
+function canFindLargerAverage(nums, k, target) {
+ let sum = 0;
+ let prevSum = 0;
+ let minPrevSum = 0;
+
+ for (let i = 0; i < k; i++) {
+ sum += nums[i] - target;
+ }
+
+ if (sum >= 0) return true;
+
+ for (let i = k; i < nums.length; i++) {
+ sum += nums[i] - target;
+ prevSum += nums[i - k] - target;
+ minPrevSum = Math.min(minPrevSum, prevSum);
+ if (sum - minPrevSum >= 0) return true;
+ }
+
+ return false;
+}
From 394ffe8c5f621f5cb83c6796b4580af4cf994711 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 17:38:49 -0500
Subject: [PATCH 539/994] Add solution #651
---
README.md | 1 +
solutions/0651-4-keys-keyboard.js | 31 +++++++++++++++++++++++++++++++
2 files changed, 32 insertions(+)
create mode 100644 solutions/0651-4-keys-keyboard.js
diff --git a/README.md b/README.md
index 2df1153a..3931d59e 100644
--- a/README.md
+++ b/README.md
@@ -606,6 +606,7 @@
648|[Replace Words](./solutions/0648-replace-words.js)|Medium|
649|[Dota2 Senate](./solutions/0649-dota2-senate.js)|Medium|
650|[2 Keys Keyboard](./solutions/0650-2-keys-keyboard.js)|Medium|
+651|[4 Keys Keyboard](./solutions/0651-4-keys-keyboard.js)|Medium|
652|[Find Duplicate Subtrees](./solutions/0652-find-duplicate-subtrees.js)|Medium|
653|[Two Sum IV - Input is a BST](./solutions/0653-two-sum-iv-input-is-a-bst.js)|Easy|
654|[Maximum Binary Tree](./solutions/0654-maximum-binary-tree.js)|Medium|
diff --git a/solutions/0651-4-keys-keyboard.js b/solutions/0651-4-keys-keyboard.js
new file mode 100644
index 00000000..5420a8c9
--- /dev/null
+++ b/solutions/0651-4-keys-keyboard.js
@@ -0,0 +1,31 @@
+/**
+ * 651. 4 Keys Keyboard
+ * https://leetcode.com/problems/4-keys-keyboard/
+ * Difficulty: Medium
+ *
+ * Imagine you have a special keyboard with the following keys:
+ * - A: Print one 'A' on the screen.
+ * - Ctrl-A: Select the whole screen.
+ * - Ctrl-C: Copy selection to buffer.
+ * - Ctrl-V: Print buffer on screen appending it after what has already been printed.
+ *
+ * Given an integer n, return the maximum number of 'A' you can print on the screen with at
+ * most n presses on the keys.
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var maxA = function(n) {
+ const dp = new Array(n + 1).fill(0);
+
+ for (let i = 1; i <= n; i++) {
+ dp[i] = dp[i - 1] + 1;
+ for (let j = 2; j < i; j++) {
+ dp[i] = Math.max(dp[i], dp[j - 2] * (i - j + 1));
+ }
+ }
+
+ return dp[n];
+};
From b77f3a40f098dfcce776a56cff357f3f268be32b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 17:48:13 -0500
Subject: [PATCH 540/994] Add solution #656
---
README.md | 1 +
solutions/0656-coin-path.js | 88 +++++++++++++++++++++++++++++++++++++
2 files changed, 89 insertions(+)
create mode 100644 solutions/0656-coin-path.js
diff --git a/README.md b/README.md
index 3931d59e..24748fc3 100644
--- a/README.md
+++ b/README.md
@@ -611,6 +611,7 @@
653|[Two Sum IV - Input is a BST](./solutions/0653-two-sum-iv-input-is-a-bst.js)|Easy|
654|[Maximum Binary Tree](./solutions/0654-maximum-binary-tree.js)|Medium|
655|[Print Binary Tree](./solutions/0655-print-binary-tree.js)|Medium|
+656|[Coin Path](./solutions/0656-coin-path.js)|Hard|
657|[Robot Return to Origin](./solutions/0657-robot-return-to-origin.js)|Easy|
658|[Find K Closest Elements](./solutions/0658-find-k-closest-elements.js)|Medium|
659|[Split Array into Consecutive Subsequences](./solutions/0659-split-array-into-consecutive-subsequences.js)|Medium|
diff --git a/solutions/0656-coin-path.js b/solutions/0656-coin-path.js
new file mode 100644
index 00000000..f5c3e9ee
--- /dev/null
+++ b/solutions/0656-coin-path.js
@@ -0,0 +1,88 @@
+/**
+ * 656. Coin Path
+ * https://leetcode.com/problems/coin-path/
+ * Difficulty: Hard
+ *
+ * You are given an integer array coins (1-indexed) of length n and an integer maxJump. You can
+ * jump to any index i of the array coins if coins[i] != -1 and you have to pay coins[i] when you
+ * visit index i. In addition to that, if you are currently at index i, you can only jump to any
+ * index i + k where i + k <= n and k is a value in the range [1, maxJump].
+ *
+ * You are initially positioned at index 1 (coins[1] is not -1). You want to find the path that
+ * reaches index n with the minimum cost.
+ *
+ * Return an integer array of the indices that you will visit in order so that you can reach
+ * index n with the minimum cost. If there are multiple paths with the same cost, return the
+ * lexicographically smallest such path. If it is not possible to reach index n, return an
+ * empty array.
+ *
+ * A path p1 = [Pa1, Pa2, ..., Pax] of length x is lexicographically smaller than
+ * p2 = [Pb1, Pb2, ..., Pbx] of length y, if and only if at the first j where Paj and Pbj
+ * differ, Paj < Pbj; when no such j exists, then x < y.
+ */
+
+/**
+ * @param {number[]} coins
+ * @param {number} maxJump
+ * @return {number[]}
+ */
+var cheapestJump = function(coins, maxJump) {
+ const n = coins.length;
+ const minCost = new Array(n + 1).fill(Infinity);
+ const parent = new Array(n + 1).fill(-1);
+
+ minCost[1] = coins[0];
+
+ for (let i = 1; i <= n; i++) {
+ if (coins[i - 1] === -1 || minCost[i] === Infinity) continue;
+
+ for (let j = i + 1; j <= Math.min(i + maxJump, n); j++) {
+ if (coins[j - 1] === -1) continue;
+
+ const newCost = minCost[i] + coins[j - 1];
+ if (newCost < minCost[j]) {
+ minCost[j] = newCost;
+ parent[j] = i;
+ } else if (newCost === minCost[j] && parent[j] !== -1) {
+ const currentPath = buildPath(parent, j);
+ const newPath = buildPath(parent, j, i);
+ if (compare(newPath, currentPath)) {
+ parent[j] = i;
+ }
+ }
+ }
+ }
+
+ if (minCost[n] === Infinity) return [];
+
+ const result = [];
+ let current = n;
+ while (current !== -1) {
+ result.unshift(current);
+ current = parent[current];
+ }
+
+ return result;
+};
+
+function buildPath(parent, end, newParent = null) {
+ const path = [];
+ let current = end;
+ if (newParent !== null) {
+ path.unshift(current);
+ current = newParent;
+ }
+ while (current !== -1) {
+ path.unshift(current);
+ current = parent[current];
+ }
+ return path;
+}
+
+function compare(path1, path2) {
+ for (let i = 0; i < Math.min(path1.length, path2.length); i++) {
+ if (path1[i] < path2[i]) return true;
+ if (path1[i] > path2[i]) return false;
+ }
+ return path1.length < path2.length;
+}
From 7ac24b114c0c4ca465868a3e5b22c49ca83264a0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 17:50:25 -0500
Subject: [PATCH 541/994] Add solution #660
---
README.md | 1 +
solutions/0660-remove-9.js | 28 ++++++++++++++++++++++++++++
2 files changed, 29 insertions(+)
create mode 100644 solutions/0660-remove-9.js
diff --git a/README.md b/README.md
index 24748fc3..b2f77bae 100644
--- a/README.md
+++ b/README.md
@@ -615,6 +615,7 @@
657|[Robot Return to Origin](./solutions/0657-robot-return-to-origin.js)|Easy|
658|[Find K Closest Elements](./solutions/0658-find-k-closest-elements.js)|Medium|
659|[Split Array into Consecutive Subsequences](./solutions/0659-split-array-into-consecutive-subsequences.js)|Medium|
+660|[Remove 9](./solutions/0660-remove-9.js)|Hard|
661|[Image Smoother](./solutions/0661-image-smoother.js)|Easy|
662|[Maximum Width of Binary Tree](./solutions/0662-maximum-width-of-binary-tree.js)|Medium|
664|[Strange Printer](./solutions/0664-strange-printer.js)|Hard|
diff --git a/solutions/0660-remove-9.js b/solutions/0660-remove-9.js
new file mode 100644
index 00000000..02b239a0
--- /dev/null
+++ b/solutions/0660-remove-9.js
@@ -0,0 +1,28 @@
+/**
+ * 660. Remove 9
+ * https://leetcode.com/problems/remove-9/
+ * Difficulty: Hard
+ *
+ * Start from integer 1, remove any integer that contains 9 such as 9, 19, 29...
+ *
+ * Now, you will have a new integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ...].
+ *
+ * Given an integer n, return the nth (1-indexed) integer in the new sequence.
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var newInteger = function(n) {
+ let result = 0;
+ let base = 1;
+
+ while (n > 0) {
+ result += (n % 9) * base;
+ n = Math.floor(n / 9);
+ base *= 10;
+ }
+
+ return result;
+};
From 8dbd9c7f4b33d4b265aa3c2de52c45cda01780ac Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 17:51:47 -0500
Subject: [PATCH 542/994] Add solution #663
---
README.md | 1 +
solutions/0663-equal-tree-partition.js | 41 ++++++++++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/0663-equal-tree-partition.js
diff --git a/README.md b/README.md
index b2f77bae..a6e86f24 100644
--- a/README.md
+++ b/README.md
@@ -618,6 +618,7 @@
660|[Remove 9](./solutions/0660-remove-9.js)|Hard|
661|[Image Smoother](./solutions/0661-image-smoother.js)|Easy|
662|[Maximum Width of Binary Tree](./solutions/0662-maximum-width-of-binary-tree.js)|Medium|
+663|[Equal Tree Partition](./solutions/0663-equal-tree-partition.js)|Medium|
664|[Strange Printer](./solutions/0664-strange-printer.js)|Hard|
665|[Non-decreasing Array](./solutions/0665-non-decreasing-array.js)|Medium|
667|[Beautiful Arrangement II](./solutions/0667-beautiful-arrangement-ii.js)|Medium|
diff --git a/solutions/0663-equal-tree-partition.js b/solutions/0663-equal-tree-partition.js
new file mode 100644
index 00000000..7c93c6e1
--- /dev/null
+++ b/solutions/0663-equal-tree-partition.js
@@ -0,0 +1,41 @@
+/**
+ * 663. Equal Tree Partition
+ * https://leetcode.com/problems/equal-tree-partition/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree, return true if you can partition the tree into two trees
+ * with equal sums of values after removing exactly one edge on the original tree.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @return {boolean}
+ */
+var checkEqualTree = function(root) {
+ const subtreeSums = new Set();
+ const totalSum = calculateSum(root);
+
+ return totalSum % 2 === 0 && subtreeSums.has(totalSum / 2);
+
+ function calculateSum(node) {
+ if (!node) return 0;
+
+ const leftSum = calculateSum(node.left);
+ const rightSum = calculateSum(node.right);
+ const currentSum = node.val + leftSum + rightSum;
+
+ if (node !== root) {
+ subtreeSums.add(currentSum);
+ }
+
+ return currentSum;
+ }
+};
From b5b4de8c6396b8605090a82705fbe277258a63b2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 17:53:46 -0500
Subject: [PATCH 543/994] Add solution #666
---
README.md | 1 +
solutions/0666-path-sum-iv.js | 52 +++++++++++++++++++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 solutions/0666-path-sum-iv.js
diff --git a/README.md b/README.md
index a6e86f24..6ebe50ed 100644
--- a/README.md
+++ b/README.md
@@ -621,6 +621,7 @@
663|[Equal Tree Partition](./solutions/0663-equal-tree-partition.js)|Medium|
664|[Strange Printer](./solutions/0664-strange-printer.js)|Hard|
665|[Non-decreasing Array](./solutions/0665-non-decreasing-array.js)|Medium|
+666|[Path Sum IV](./solutions/0666-path-sum-iv.js)|Medium|
667|[Beautiful Arrangement II](./solutions/0667-beautiful-arrangement-ii.js)|Medium|
668|[Kth Smallest Number in Multiplication Table](./solutions/0668-kth-smallest-number-in-multiplication-table.js)|Hard|
669|[Trim a Binary Search Tree](./solutions/0669-trim-a-binary-search-tree.js)|Medium|
diff --git a/solutions/0666-path-sum-iv.js b/solutions/0666-path-sum-iv.js
new file mode 100644
index 00000000..b3f637a5
--- /dev/null
+++ b/solutions/0666-path-sum-iv.js
@@ -0,0 +1,52 @@
+/**
+ * 666. Path Sum IV
+ * https://leetcode.com/problems/path-sum-iv/
+ * Difficulty: Medium
+ *
+ * If the depth of a tree is smaller than 5, then this tree can be represented by an array
+ * of three-digit integers. You are given an ascending array nums consisting of three-digit
+ * integers representing a binary tree with a depth smaller than 5, where for each integer:
+ * - The hundreds digit represents the depth d of this node, where 1 <= d <= 4.
+ * - The tens digit represents the position p of this node within its level, where 1 <= p <= 8,
+ * corresponding to its position in a full binary tree.
+ * - The units digit represents the value v of this node, where 0 <= v <= 9.
+ *
+ * Return the sum of all paths from the root towards the leaves.
+ *
+ * It is guaranteed that the given array represents a valid connected binary tree.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var pathSum = function(nums) {
+ const nodeMap = new Map();
+
+ for (const num of nums) {
+ const depth = Math.floor(num / 100);
+ const position = Math.floor((num % 100) / 10);
+ const value = num % 10;
+ nodeMap.set(`${depth}-${position}`, value);
+ }
+
+ return dfs(1, 1, 0);
+
+ function dfs(depth, position, currentSum) {
+ const key = `${depth}-${position}`;
+ if (!nodeMap.has(key)) return 0;
+
+ const nodeValue = nodeMap.get(key);
+ const pathSum = currentSum + nodeValue;
+
+ const leftChild = `${depth + 1}-${position * 2 - 1}`;
+ const rightChild = `${depth + 1}-${position * 2}`;
+
+ if (!nodeMap.has(leftChild) && !nodeMap.has(rightChild)) {
+ return pathSum;
+ }
+
+ return dfs(depth + 1, position * 2 - 1, pathSum)
+ + dfs(depth + 1, position * 2, pathSum);
+ }
+};
From 4298b0074a0a114954ca0e9c448d82ec49e27bb7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 17:54:54 -0500
Subject: [PATCH 544/994] Add solution #681
---
README.md | 1 +
solutions/0681-next-closest-time.js | 50 +++++++++++++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/0681-next-closest-time.js
diff --git a/README.md b/README.md
index 6ebe50ed..9753391d 100644
--- a/README.md
+++ b/README.md
@@ -636,6 +636,7 @@
678|[Valid Parenthesis String](./solutions/0678-valid-parenthesis-string.js)|Medium|
679|[24 Game](./solutions/0679-24-game.js)|Hard|
680|[Valid Palindrome II](./solutions/0680-valid-palindrome-ii.js)|Easy|
+681|[Next Closest Time](./solutions/0681-next-closest-time.js)|Medium|
682|[Baseball Game](./solutions/0682-baseball-game.js)|Easy|
684|[Redundant Connection](./solutions/0684-redundant-connection.js)|Medium|
685|[Redundant Connection II](./solutions/0685-redundant-connection-ii.js)|Hard|
diff --git a/solutions/0681-next-closest-time.js b/solutions/0681-next-closest-time.js
new file mode 100644
index 00000000..78d06313
--- /dev/null
+++ b/solutions/0681-next-closest-time.js
@@ -0,0 +1,50 @@
+/**
+ * 681. Next Closest Time
+ * https://leetcode.com/problems/next-closest-time/
+ * Difficulty: Medium
+ *
+ * Given a time represented in the format "HH:MM", form the next closest time by reusing the
+ * current digits. There is no limit on how many times a digit can be reused.
+ *
+ * You may assume the given input string is always valid. For example, "01:34", "12:09" are
+ * all valid. "1:34", "12:9" are all invalid.
+ */
+
+/**
+ * @param {string} time
+ * @return {string}
+ */
+var nextClosestTime = function(time) {
+ const digits = new Set(time.replace(':', ''));
+ const sortedDigits = [...digits].sort();
+
+ return generateNextTime(time);
+
+ function isValidTime(h, m) {
+ return h < 24 && m < 60;
+ }
+
+ function generateNextTime(timeStr) {
+ const [hours, minutes] = timeStr.split(':');
+
+ for (let i = 3; i >= 0; i--) {
+ const pos = i < 2 ? i : i + 1;
+ const currentDigit = timeStr[pos];
+
+ for (const digit of sortedDigits) {
+ if (digit > currentDigit) {
+ const newTime = timeStr.substring(0, pos) + digit + timeStr.substring(pos + 1);
+ const [h, m] = newTime.split(':').map(Number);
+ if (isValidTime(h, m)) {
+ return newTime;
+ }
+ }
+ }
+
+ const newTime = timeStr.substring(0, pos) + sortedDigits[0] + timeStr.substring(pos + 1);
+ timeStr = newTime;
+ }
+
+ return sortedDigits[0].repeat(2) + ':' + sortedDigits[0].repeat(2);
+ }
+};
From bd9d33a5d08153fb03703bbbedbcc426bb5a55cb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 17:56:13 -0500
Subject: [PATCH 545/994] Add solution #683
---
README.md | 1 +
solutions/0683-k-empty-slots.js | 55 +++++++++++++++++++++++++++++++++
2 files changed, 56 insertions(+)
create mode 100644 solutions/0683-k-empty-slots.js
diff --git a/README.md b/README.md
index 9753391d..41351d4b 100644
--- a/README.md
+++ b/README.md
@@ -638,6 +638,7 @@
680|[Valid Palindrome II](./solutions/0680-valid-palindrome-ii.js)|Easy|
681|[Next Closest Time](./solutions/0681-next-closest-time.js)|Medium|
682|[Baseball Game](./solutions/0682-baseball-game.js)|Easy|
+683|[K Empty Slots](./solutions/0683-k-empty-slots.js)|Hard|
684|[Redundant Connection](./solutions/0684-redundant-connection.js)|Medium|
685|[Redundant Connection II](./solutions/0685-redundant-connection-ii.js)|Hard|
686|[Repeated String Match](./solutions/0686-repeated-string-match.js)|Easy|
diff --git a/solutions/0683-k-empty-slots.js b/solutions/0683-k-empty-slots.js
new file mode 100644
index 00000000..f3b23181
--- /dev/null
+++ b/solutions/0683-k-empty-slots.js
@@ -0,0 +1,55 @@
+/**
+ * 683. K Empty Slots
+ * https://leetcode.com/problems/k-empty-slots/
+ * Difficulty: Hard
+ *
+ * You have n bulbs in a row numbered from 1 to n. Initially, all the bulbs are turned off.
+ * We turn on exactly one bulb every day until all bulbs are on after n days.
+ *
+ * You are given an array bulbs of length n where bulbs[i] = x means that on the (i+1)th day,
+ * we will turn on the bulb at position x where i is 0-indexed and x is 1-indexed.
+ *
+ * Given an integer k, return the minimum day number such that there exists two turned on
+ * bulbs that have exactly k bulbs between them that are all turned off. If there isn't
+ * such day, return -1.
+ */
+
+/**
+ * @param {number[]} bulbs
+ * @param {number} k
+ * @return {number}
+ */
+var kEmptySlots = function(bulbs, k) {
+ const days = new Array(bulbs.length + 1);
+
+ for (let i = 0; i < bulbs.length; i++) {
+ days[bulbs[i]] = i + 1;
+ }
+
+ let left = 1;
+ let right = k + 2;
+ let minDay = Infinity;
+
+ while (right <= bulbs.length) {
+ let mid = left + 1;
+ let isValid = true;
+
+ while (mid < right) {
+ if (days[mid] < Math.max(days[left], days[right])) {
+ isValid = false;
+ left = mid;
+ right = mid + k + 1;
+ break;
+ }
+ mid++;
+ }
+
+ if (isValid) {
+ minDay = Math.min(minDay, Math.max(days[left], days[right]));
+ left++;
+ right++;
+ }
+ }
+
+ return minDay === Infinity ? -1 : minDay;
+};
From ca5baf405900cf1f266ee0f7bb85a41a69d1e3f4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 18:42:08 -0500
Subject: [PATCH 546/994] Add solution #694
---
README.md | 1 +
solutions/0694-number-of-distinct-islands.js | 52 ++++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 solutions/0694-number-of-distinct-islands.js
diff --git a/README.md b/README.md
index 41351d4b..a85fa6c0 100644
--- a/README.md
+++ b/README.md
@@ -649,6 +649,7 @@
691|[Stickers to Spell Word](./solutions/0691-stickers-to-spell-word.js)|Hard|
692|[Top K Frequent Words](./solutions/0692-top-k-frequent-words.js)|Medium|
693|[Binary Number with Alternating Bits](./solutions/0693-binary-number-with-alternating-bits.js)|Easy|
+694|[Number of Distinct Islands](./solutions/0694-number-of-distinct-islands.js)|Medium|
695|[Max Area of Island](./solutions/0695-max-area-of-island.js)|Medium|
696|[Count Binary Substrings](./solutions/0696-count-binary-substrings.js)|Easy|
697|[Degree of an Array](./solutions/0697-degree-of-an-array.js)|Easy|
diff --git a/solutions/0694-number-of-distinct-islands.js b/solutions/0694-number-of-distinct-islands.js
new file mode 100644
index 00000000..cd7baca6
--- /dev/null
+++ b/solutions/0694-number-of-distinct-islands.js
@@ -0,0 +1,52 @@
+/**
+ * 694. Number of Distinct Islands
+ * https://leetcode.com/problems/number-of-distinct-islands/
+ * Difficulty: Medium
+ *
+ * You are given an m x n binary matrix grid. An island is a group of 1's (representing land)
+ * connected 4-directionally (horizontal or vertical.) You may assume all four edges of the
+ * grid are surrounded by water.
+ *
+ * An island is considered to be the same as another if and only if one island can be translated
+ * (and not rotated or reflected) to equal the other.
+ *
+ * Return the number of distinct islands.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var numDistinctIslands = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const visited = Array.from({ length: rows }, () => new Array(cols).fill(false));
+ const islandShapes = new Set();
+
+ for (let i = 0; i < rows; i++) {
+ for (let j = 0; j < cols; j++) {
+ if (grid[i][j] === 1 && !visited[i][j]) {
+ const shape = [];
+ dfs(i, j, i, j, shape);
+ islandShapes.add(shape.join('|'));
+ }
+ }
+ }
+
+ return islandShapes.size;
+
+ function dfs(row, col, baseRow, baseCol, shape) {
+ if (row < 0 || row >= rows || col < 0 || col >= cols
+ || visited[row][col] || grid[row][col] === 0) {
+ return;
+ }
+
+ visited[row][col] = true;
+ shape.push(`${row - baseRow},${col - baseCol}`);
+
+ dfs(row + 1, col, baseRow, baseCol, shape);
+ dfs(row - 1, col, baseRow, baseCol, shape);
+ dfs(row, col + 1, baseRow, baseCol, shape);
+ dfs(row, col - 1, baseRow, baseCol, shape);
+ }
+};
From 685fc369d8563105dcadb7e1b7d85164262bca1b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 18:43:26 -0500
Subject: [PATCH 547/994] Add solution #702
---
README.md | 1 +
...earch-in-a-sorted-array-of-unknown-size.js | 49 +++++++++++++++++++
2 files changed, 50 insertions(+)
create mode 100644 solutions/0702-search-in-a-sorted-array-of-unknown-size.js
diff --git a/README.md b/README.md
index a85fa6c0..14eb02ff 100644
--- a/README.md
+++ b/README.md
@@ -657,6 +657,7 @@
699|[Falling Squares](./solutions/0699-falling-squares.js)|Hard|
700|[Search in a Binary Search Tree](./solutions/0700-search-in-a-binary-search-tree.js)|Easy|
701|[Insert into a Binary Search Tree](./solutions/0701-insert-into-a-binary-search-tree.js)|Medium|
+702|[Search in a Sorted Array of Unknown Size](./solutions/0702-search-in-a-sorted-array-of-unknown-size.js)|Medium|
703|[Kth Largest Element in a Stream](./solutions/0703-kth-largest-element-in-a-stream.js)|Easy|
704|[Binary Search](./solutions/0704-binary-search.js)|Easy|
705|[Design HashSet](./solutions/0705-design-hashset.js)|Easy|
diff --git a/solutions/0702-search-in-a-sorted-array-of-unknown-size.js b/solutions/0702-search-in-a-sorted-array-of-unknown-size.js
new file mode 100644
index 00000000..865bda15
--- /dev/null
+++ b/solutions/0702-search-in-a-sorted-array-of-unknown-size.js
@@ -0,0 +1,49 @@
+/**
+ * 702. Search in a Sorted Array of Unknown Size
+ * https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size/
+ * Difficulty: Medium
+ *
+ * This is an interactive problem.
+ *
+ * You have a sorted array of unique elements and an unknown size. You do not have an access
+ * to the array but you can use the ArrayReader interface to access it. You can call
+ * ArrayReader.get(i) that:
+ * - returns the value at the ith index (0-indexed) of the secret array (i.e., secret[i]), or
+ * - returns 231 - 1 if the i is out of the boundary of the array.
+ *
+ * You are also given an integer target.
+ *
+ * Return the index k of the hidden array where secret[k] == target or return -1 otherwise.
+ *
+ * You must write an algorithm with O(log n) runtime complexity.
+ */
+
+/**
+ * @param {ArrayReader} reader
+ * @param {number} target
+ * @return {number}
+ */
+var search = function(reader, target) {
+ let left = 0;
+ let right = 1;
+
+ while (reader.get(right) < target) {
+ left = right;
+ right *= 2;
+ }
+
+ while (left <= right) {
+ const mid = Math.floor((left + right) / 2);
+ const value = reader.get(mid);
+
+ if (value === target) {
+ return mid;
+ } else if (value < target) {
+ left = mid + 1;
+ } else {
+ right = mid - 1;
+ }
+ }
+
+ return -1;
+};
From 9650be71ac68c161e779e9c8501f4884801df31e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 18:45:13 -0500
Subject: [PATCH 548/994] Add solution #708
---
README.md | 1 +
...sert-into-a-sorted-circular-linked-list.js | 53 +++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/0708-insert-into-a-sorted-circular-linked-list.js
diff --git a/README.md b/README.md
index 14eb02ff..67f86d77 100644
--- a/README.md
+++ b/README.md
@@ -663,6 +663,7 @@
705|[Design HashSet](./solutions/0705-design-hashset.js)|Easy|
706|[Design HashMap](./solutions/0706-design-hashmap.js)|Easy|
707|[Design Linked List](./solutions/0707-design-linked-list.js)|Medium|
+708|[Insert into a Sorted Circular Linked List](./solutions/0708-insert-into-a-sorted-circular-linked-list.js)|Medium|
709|[To Lower Case](./solutions/0709-to-lower-case.js)|Easy|
710|[Random Pick with Blacklist](./solutions/0710-random-pick-with-blacklist.js)|Hard|
712|[Minimum ASCII Delete Sum for Two Strings](./solutions/0712-minimum-ascii-delete-sum-for-two-strings.js)|Medium|
diff --git a/solutions/0708-insert-into-a-sorted-circular-linked-list.js b/solutions/0708-insert-into-a-sorted-circular-linked-list.js
new file mode 100644
index 00000000..ff17f2de
--- /dev/null
+++ b/solutions/0708-insert-into-a-sorted-circular-linked-list.js
@@ -0,0 +1,53 @@
+/**
+ * 708. Insert into a Sorted Circular Linked List
+ * https://leetcode.com/problems/insert-into-a-sorted-circular-linked-list/
+ * Difficulty: Medium
+ *
+ * Given a Circular Linked List node, which is sorted in non-descending order, write a
+ * function to insert a value insertVal into the list such that it remains a sorted
+ * circular list. The given node can be a reference to any single node in the list and
+ * may not necessarily be the smallest value in the circular list.
+ *
+ * If there are multiple suitable places for insertion, you may choose any place to
+ * insert the new value. After the insertion, the circular list should remain sorted.
+ *
+ * If the list is empty (i.e., the given node is null), you should create a new single
+ * circular list and return the reference to that single node. Otherwise, you should
+ * return the originally given node.
+ */
+
+/**
+ * @param {_Node} head
+ * @param {number} insertVal
+ * @return {_Node}
+ */
+var insert = function(head, insertVal) {
+ const newNode = new _Node(insertVal, null);
+
+ if (!head) {
+ newNode.next = newNode;
+ return newNode;
+ }
+
+ if (head.next === head) {
+ newNode.next = head;
+ head.next = newNode;
+ return head;
+ }
+
+ let prev = head;
+ let curr = head.next;
+ do {
+ if ((prev.val <= insertVal && insertVal <= curr.val)
+ || (prev.val > curr.val && (insertVal >= prev.val || insertVal <= curr.val))) {
+ break;
+ }
+ prev = curr;
+ curr = curr.next;
+ } while (prev !== head);
+
+ prev.next = newNode;
+ newNode.next = curr;
+
+ return head;
+};
From 35667500efa7859bf43e15c96c255db01c23f2bb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 18:46:55 -0500
Subject: [PATCH 549/994] Add solution #711
---
README.md | 1 +
.../0711-number-of-distinct-islands-ii.js | 82 +++++++++++++++++++
2 files changed, 83 insertions(+)
create mode 100644 solutions/0711-number-of-distinct-islands-ii.js
diff --git a/README.md b/README.md
index 67f86d77..9617eacf 100644
--- a/README.md
+++ b/README.md
@@ -666,6 +666,7 @@
708|[Insert into a Sorted Circular Linked List](./solutions/0708-insert-into-a-sorted-circular-linked-list.js)|Medium|
709|[To Lower Case](./solutions/0709-to-lower-case.js)|Easy|
710|[Random Pick with Blacklist](./solutions/0710-random-pick-with-blacklist.js)|Hard|
+711|[Number of Distinct Islands II](./solutions/0711-number-of-distinct-islands-ii.js)|Hard|
712|[Minimum ASCII Delete Sum for Two Strings](./solutions/0712-minimum-ascii-delete-sum-for-two-strings.js)|Medium|
713|[Subarray Product Less Than K](./solutions/0713-subarray-product-less-than-k.js)|Medium|
714|[Best Time to Buy and Sell Stock with Transaction Fee](./solutions/0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js)|Medium|
diff --git a/solutions/0711-number-of-distinct-islands-ii.js b/solutions/0711-number-of-distinct-islands-ii.js
new file mode 100644
index 00000000..309f9d51
--- /dev/null
+++ b/solutions/0711-number-of-distinct-islands-ii.js
@@ -0,0 +1,82 @@
+/**
+ * 711. Number of Distinct Islands II
+ * https://leetcode.com/problems/number-of-distinct-islands-ii/
+ * Difficulty: Hard
+ *
+ * You are given an m x n binary matrix grid. An island is a group of 1's (representing land)
+ * connected 4-directionally (horizontal or vertical.) You may assume all four edges of the
+ * grid are surrounded by water.
+ *
+ * An island is considered to be the same as another if they have the same shape, or have
+ * the same shape after rotation (90, 180, or 270 degrees only) or reflection (left/right
+ * direction or up/down direction).
+ *
+ * Return the number of distinct islands.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var numDistinctIslands2 = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const visited = Array.from({ length: rows }, () => new Array(cols).fill(false));
+ const uniqueShapes = new Set();
+
+ for (let i = 0; i < rows; i++) {
+ for (let j = 0; j < cols; j++) {
+ if (grid[i][j] === 1 && !visited[i][j]) {
+ const cells = [];
+ dfs(i, j, cells);
+ const canonical = normalize(cells);
+ uniqueShapes.add(canonical);
+ }
+ }
+ }
+
+ return uniqueShapes.size;
+
+ function dfs(row, col, cells) {
+ if (row < 0 || row >= rows || col < 0 || col >= cols
+ || visited[row][col] || grid[row][col] === 0) {
+ return;
+ }
+
+ visited[row][col] = true;
+ cells.push([row, col]);
+
+ dfs(row + 1, col, cells);
+ dfs(row - 1, col, cells);
+ dfs(row, col + 1, cells);
+ dfs(row, col - 1, cells);
+ }
+
+ function normalize(cells) {
+ const transformations = [
+ (r, c) => [r, c],
+ (r, c) => [r, -c],
+ (r, c) => [-r, c],
+ (r, c) => [-r, -c],
+ (r, c) => [c, r],
+ (r, c) => [c, -r],
+ (r, c) => [-c, r],
+ (r, c) => [-c, -r]
+ ];
+
+ const shapes = [];
+
+ for (const transform of transformations) {
+ const transformed = cells.map(([r, c]) => transform(r, c));
+ transformed.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]);
+
+ const minR = transformed[0][0];
+ const minC = transformed[0][1];
+ const normalized = transformed.map(([r, c]) => [r - minR, c - minC]);
+
+ shapes.push(normalized.map(([r, c]) => `${r},${c}`).join('|'));
+ }
+
+ return shapes.sort()[0];
+ }
+};
From 460838a4bd2467afaafd6ce1f6b70b21130ea56f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 21 Jun 2025 18:55:39 -0500
Subject: [PATCH 550/994] Add solution #716
---
README.md | 1 +
solutions/0716-max-stack.js | 92 +++++++++++++++++++++++++++++++++++++
2 files changed, 93 insertions(+)
create mode 100644 solutions/0716-max-stack.js
diff --git a/README.md b/README.md
index 9617eacf..cf74cc2e 100644
--- a/README.md
+++ b/README.md
@@ -671,6 +671,7 @@
713|[Subarray Product Less Than K](./solutions/0713-subarray-product-less-than-k.js)|Medium|
714|[Best Time to Buy and Sell Stock with Transaction Fee](./solutions/0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js)|Medium|
715|[Range Module](./solutions/0715-range-module.js)|Hard|
+716|[Max Stack](./solutions/0716-max-stack.js)|Hard|
717|[1-bit and 2-bit Characters](./solutions/0717-1-bit-and-2-bit-characters.js)|Easy|
718|[Maximum Length of Repeated Subarray](./solutions/0718-maximum-length-of-repeated-subarray.js)|Medium|
719|[Find K-th Smallest Pair Distance](./solutions/0719-find-k-th-smallest-pair-distance.js)|Hard|
diff --git a/solutions/0716-max-stack.js b/solutions/0716-max-stack.js
new file mode 100644
index 00000000..f12bdc59
--- /dev/null
+++ b/solutions/0716-max-stack.js
@@ -0,0 +1,92 @@
+/**
+ * 716. Max Stack
+ * https://leetcode.com/problems/max-stack/
+ * Difficulty: Hard
+ *
+ * Design a max stack data structure that supports the stack operations and supports finding
+ * the stack's maximum element.
+ *
+ * Implement the MaxStack class:
+ * - MaxStack() Initializes the stack object.
+ * - void push(int x) Pushes element x onto the stack.
+ * - int pop() Removes the element on top of the stack and returns it.
+ * - int top() Gets the element on the top of the stack without removing it.
+ * - int peekMax() Retrieves the maximum element in the stack without removing it.
+ * - int popMax() Retrieves the maximum element in the stack and removes it. If there is more
+ * than one maximum element, only remove the top-most one.
+ *
+ * You must come up with a solution that supports O(1) for each top call and O(logn) for each
+ * other call.
+ */
+
+var MaxStack = function() {
+ this.stack = [];
+ this.maxHeap = new PriorityQueue((a, b) => a.val === b.val ? b.id - a.id : b.val - a.val);
+ this.nodeId = 0;
+ this.deleted = new Set();
+};
+
+/**
+* @param {number} x
+* @return {void}
+*/
+MaxStack.prototype.push = function(x) {
+ const id = this.nodeId++;
+ const node = { val: x, id };
+ this.stack.push(node);
+ this.maxHeap.enqueue(node);
+};
+
+/**
+* @return {number}
+*/
+MaxStack.prototype.pop = function() {
+ this.cleanStack();
+ const node = this.stack.pop();
+ this.deleted.add(node.id);
+ return node.val;
+};
+
+/**
+* @return {number}
+*/
+MaxStack.prototype.top = function() {
+ this.cleanStack();
+ return this.stack[this.stack.length - 1].val;
+};
+
+/**
+* @return {number}
+*/
+MaxStack.prototype.peekMax = function() {
+ this.cleanMaxHeap();
+ return this.maxHeap.front().val;
+};
+
+/**
+* @return {number}
+*/
+MaxStack.prototype.popMax = function() {
+ this.cleanMaxHeap();
+ const maxNode = this.maxHeap.dequeue();
+ this.deleted.add(maxNode.id);
+ return maxNode.val;
+};
+
+/**
+* @return {void}
+*/
+MaxStack.prototype.cleanStack = function() {
+ while (this.stack.length && this.deleted.has(this.stack[this.stack.length - 1].id)) {
+ this.stack.pop();
+ }
+};
+
+/**
+* @return {void}
+*/
+MaxStack.prototype.cleanMaxHeap = function() {
+ while (this.maxHeap.size() && this.deleted.has(this.maxHeap.front().id)) {
+ this.maxHeap.dequeue();
+ }
+};
From 5710b778f234fede5cd83359ea795a297be825fa Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 22 Jun 2025 09:37:19 -0500
Subject: [PATCH 551/994] Add solution #723
---
README.md | 1 +
solutions/0723-candy-crush.js | 88 +++++++++++++++++++++++++++++++++++
2 files changed, 89 insertions(+)
create mode 100644 solutions/0723-candy-crush.js
diff --git a/README.md b/README.md
index cf74cc2e..3e8fc073 100644
--- a/README.md
+++ b/README.md
@@ -678,6 +678,7 @@
720|[Longest Word in Dictionary](./solutions/0720-longest-word-in-dictionary.js)|Medium|
721|[Accounts Merge](./solutions/0721-accounts-merge.js)|Medium|
722|[Remove Comments](./solutions/0722-remove-comments.js)|Medium|
+723|[Candy Crush](./solutions/0723-candy-crush.js)|Medium|
724|[Find Pivot Index](./solutions/0724-find-pivot-index.js)|Easy|
725|[Split Linked List in Parts](./solutions/0725-split-linked-list-in-parts.js)|Medium|
726|[Number of Atoms](./solutions/0726-number-of-atoms.js)|Hard|
diff --git a/solutions/0723-candy-crush.js b/solutions/0723-candy-crush.js
new file mode 100644
index 00000000..39cd84ec
--- /dev/null
+++ b/solutions/0723-candy-crush.js
@@ -0,0 +1,88 @@
+/**
+ * 723. Candy Crush
+ * https://leetcode.com/problems/candy-crush/
+ * Difficulty: Medium
+ *
+ * This question is about implementing a basic elimination algorithm for Candy Crush.
+ *
+ * Given an m x n integer array board representing the grid of candy where board[i][j] represents
+ * the type of candy. A value of board[i][j] == 0 represents that the cell is empty.
+ *
+ * The given board represents the state of the game following the player's move. Now, you need to
+ * restore the board to a stable state by crushing candies according to the following rules:
+ * - If three or more candies of the same type are adjacent vertically or horizontally, crush them
+ * all at the same time - these positions become empty.
+ * - After crushing all candies simultaneously, if an empty space on the board has candies on top
+ * of itself, then these candies will drop until they hit a candy or bottom at the same time.
+ * No new candies will drop outside the top boundary.
+ * - After the above steps, there may exist more candies that can be crushed. If so, you need to
+ * repeat the above steps.
+ * - If there does not exist more candies that can be crushed (i.e., the board is stable), then
+ * return the current board.
+ *
+ * You need to perform the above rules until the board becomes stable, then return the stable board.
+ */
+
+/**
+ * @param {number[][]} board
+ * @return {number[][]}
+ */
+var candyCrush = function(board) {
+ const rows = board.length;
+ const cols = board[0].length;
+
+ while (markCrushables()) {
+ dropCandies();
+ }
+
+ return board;
+
+ function markCrushables() {
+ let hasCrushables = false;
+
+ for (let row = 0; row < rows; row++) {
+ for (let col = 0; col < cols - 2; col++) {
+ const candy = Math.abs(board[row][col]);
+ if (candy !== 0 && candy === Math.abs(board[row][col + 1])
+ && candy === Math.abs(board[row][col + 2])) {
+ hasCrushables = true;
+ board[row][col] = -candy;
+ board[row][col + 1] = -candy;
+ board[row][col + 2] = -candy;
+ }
+ }
+ }
+
+ for (let col = 0; col < cols; col++) {
+ for (let row = 0; row < rows - 2; row++) {
+ const candy = Math.abs(board[row][col]);
+ if (candy !== 0 && candy === Math.abs(board[row + 1][col])
+ && candy === Math.abs(board[row + 2][col])) {
+ hasCrushables = true;
+ board[row][col] = -candy;
+ board[row + 1][col] = -candy;
+ board[row + 2][col] = -candy;
+ }
+ }
+ }
+
+ return hasCrushables;
+ }
+
+ function dropCandies() {
+ for (let col = 0; col < cols; col++) {
+ let bottom = rows - 1;
+ for (let row = rows - 1; row >= 0; row--) {
+ if (board[row][col] > 0) {
+ board[bottom][col] = board[row][col];
+ if (bottom !== row) {
+ board[row][col] = 0;
+ }
+ bottom--;
+ } else if (board[row][col] < 0) {
+ board[row][col] = 0;
+ }
+ }
+ }
+ }
+};
From 3cc75bec9cdc84c509ef019df18a89db6bda31e4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 23 Jun 2025 22:54:15 -0500
Subject: [PATCH 552/994] Add solution #727
---
README.md | 1 +
solutions/0727-minimum-window-subsequence.js | 46 ++++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/0727-minimum-window-subsequence.js
diff --git a/README.md b/README.md
index 3e8fc073..5c423075 100644
--- a/README.md
+++ b/README.md
@@ -682,6 +682,7 @@
724|[Find Pivot Index](./solutions/0724-find-pivot-index.js)|Easy|
725|[Split Linked List in Parts](./solutions/0725-split-linked-list-in-parts.js)|Medium|
726|[Number of Atoms](./solutions/0726-number-of-atoms.js)|Hard|
+727|[Minimum Window Subsequence](./solutions/0727-minimum-window-subsequence.js)|Hard|
728|[Self Dividing Numbers](./solutions/0728-self-dividing-numbers.js)|Easy|
729|[My Calendar I](./solutions/0729-my-calendar-i.js)|Medium|
730|[Count Different Palindromic Subsequences](./solutions/0730-count-different-palindromic-subsequences.js)|Hard|
diff --git a/solutions/0727-minimum-window-subsequence.js b/solutions/0727-minimum-window-subsequence.js
new file mode 100644
index 00000000..ddc0e2d4
--- /dev/null
+++ b/solutions/0727-minimum-window-subsequence.js
@@ -0,0 +1,46 @@
+/**
+ * 727. Minimum Window Subsequence
+ * https://leetcode.com/problems/minimum-window-subsequence/
+ * Difficulty: Hard
+ *
+ * Given strings s1 and s2, return the minimum contiguous substring part of s1, so that
+ * s2 is a subsequence of the part.
+ *
+ * If there is no such window in s1 that covers all characters in s2, return the empty
+ * string "". If there are multiple such minimum-length windows, return the one with the
+ * left-most starting index.
+ */
+
+/**
+ * @param {string} s1
+ * @param {string} s2
+ * @return {string}
+ */
+var minWindow = function(s1, s2) {
+ const n = s1.length;
+ const m = s2.length;
+ const dp = new Array(m + 1).fill().map(() => new Array(n + 1).fill(Infinity));
+ dp[0][0] = 0;
+
+ for (let j = 1; j <= n; j++) {
+ dp[0][j] = 0;
+ for (let i = 1; i <= m; i++) {
+ if (s1[j - 1] === s2[i - 1]) {
+ dp[i][j] = dp[i - 1][j - 1] + 1;
+ } else {
+ dp[i][j] = dp[i][j - 1] !== Infinity ? dp[i][j - 1] + 1 : Infinity;
+ }
+ }
+ }
+
+ let minLength = Infinity;
+ let endIndex = -1;
+ for (let j = 1; j <= n; j++) {
+ if (dp[m][j] < minLength) {
+ minLength = dp[m][j];
+ endIndex = j;
+ }
+ }
+
+ return minLength === Infinity ? '' : s1.slice(endIndex - minLength, endIndex);
+};
From af3f5573961dad43cff70a089023ca41dd948433 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 24 Jun 2025 23:26:42 -0500
Subject: [PATCH 553/994] Add solution #734
---
README.md | 1 +
solutions/0734-sentence-similarity.js | 50 +++++++++++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/0734-sentence-similarity.js
diff --git a/README.md b/README.md
index 5c423075..d213893a 100644
--- a/README.md
+++ b/README.md
@@ -689,6 +689,7 @@
731|[My Calendar II](./solutions/0731-my-calendar-ii.js)|Medium|
732|[My Calendar III](./solutions/0732-my-calendar-iii.js)|Hard|
733|[Flood Fill](./solutions/0733-flood-fill.js)|Easy|
+734|[Sentence Similarity](./solutions/0734-sentence-similarity.js)|Easy|
735|[Asteroid Collision](./solutions/0735-asteroid-collision.js)|Medium|
736|[Parse Lisp Expression](./solutions/0736-parse-lisp-expression.js)|Hard|
738|[Monotone Increasing Digits](./solutions/0738-monotone-increasing-digits.js)|Medium|
diff --git a/solutions/0734-sentence-similarity.js b/solutions/0734-sentence-similarity.js
new file mode 100644
index 00000000..2beae535
--- /dev/null
+++ b/solutions/0734-sentence-similarity.js
@@ -0,0 +1,50 @@
+/**
+ * 734. Sentence Similarity
+ * https://leetcode.com/problems/sentence-similarity/
+ * Difficulty: Easy
+ *
+ * We can represent a sentence as an array of words, for example, the sentence
+ * "I am happy with leetcode" can be represented as arr = ["I","am",happy","with","leetcode"].
+ *
+ * Given two sentences sentence1 and sentence2 each represented as a string array and given an
+ * array of string pairs similarPairs where similarPairs[i] = [xi, yi] indicates that the two
+ * words xi and yi are similar.
+ *
+ * Return true if sentence1 and sentence2 are similar, or false if they are not similar.
+ *
+ * Two sentences are similar if:
+ * - They have the same length (i.e., the same number of words)
+ * - sentence1[i] and sentence2[i] are similar.
+ *
+ * Notice that a word is always similar to itself, also notice that the similarity relation is
+ * not transitive. For example, if the words a and b are similar, and the words b and c are
+ * similar, a and c are not necessarily similar.
+ */
+
+/**
+ * @param {string[]} sentence1
+ * @param {string[]} sentence2
+ * @param {string[][]} similarPairs
+ * @return {boolean}
+ */
+var areSentencesSimilar = function(sentence1, sentence2, similarPairs) {
+ if (sentence1.length !== sentence2.length) {
+ return false;
+ }
+
+ const similarWords = new Set();
+ for (const [word1, word2] of similarPairs) {
+ similarWords.add(`${word1}:${word2}`);
+ similarWords.add(`${word2}:${word1}`);
+ }
+
+ for (let i = 0; i < sentence1.length; i++) {
+ const word1 = sentence1[i];
+ const word2 = sentence2[i];
+ if (word1 !== word2 && !similarWords.has(`${word1}:${word2}`)) {
+ return false;
+ }
+ }
+
+ return true;
+};
From 15c216996196685d4aa258a5c27e3e0cb8a4ae2f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 24 Jun 2025 23:28:35 -0500
Subject: [PATCH 554/994] Add solution #737
---
README.md | 1 +
solutions/0737-sentence-similarity-ii.js | 69 ++++++++++++++++++++++++
2 files changed, 70 insertions(+)
create mode 100644 solutions/0737-sentence-similarity-ii.js
diff --git a/README.md b/README.md
index d213893a..2d5ce9a8 100644
--- a/README.md
+++ b/README.md
@@ -692,6 +692,7 @@
734|[Sentence Similarity](./solutions/0734-sentence-similarity.js)|Easy|
735|[Asteroid Collision](./solutions/0735-asteroid-collision.js)|Medium|
736|[Parse Lisp Expression](./solutions/0736-parse-lisp-expression.js)|Hard|
+737|[Sentence Similarity II](./solutions/0737-sentence-similarity-ii.js)|Medium|
738|[Monotone Increasing Digits](./solutions/0738-monotone-increasing-digits.js)|Medium|
739|[Daily Temperatures](./solutions/0739-daily-temperatures.js)|Medium|
740|[Delete and Earn](./solutions/0740-delete-and-earn.js)|Medium|
diff --git a/solutions/0737-sentence-similarity-ii.js b/solutions/0737-sentence-similarity-ii.js
new file mode 100644
index 00000000..cc370b6f
--- /dev/null
+++ b/solutions/0737-sentence-similarity-ii.js
@@ -0,0 +1,69 @@
+/**
+ * 737. Sentence Similarity II
+ * https://leetcode.com/problems/sentence-similarity-ii/
+ * Difficulty: Medium
+ *
+ * We can represent a sentence as an array of words, for example, the sentence
+ * "I am happy with leetcode" can be represented as arr = ["I","am",happy","with","leetcode"].
+ *
+ * Given two sentences sentence1 and sentence2 each represented as a string array and given an
+ * array of string pairs similarPairs where similarPairs[i] = [xi, yi] indicates that the two
+ * words xi and yi are similar.
+ *
+ * Return true if sentence1 and sentence2 are similar, or false if they are not similar.
+ *
+ * Two sentences are similar if:
+ * - They have the same length (i.e., the same number of words)
+ * - sentence1[i] and sentence2[i] are similar.
+ *
+ * Notice that a word is always similar to itself, also notice that the similarity relation is
+ * transitive. For example, if the words a and b are similar, and the words b and c are similar,
+ * then a and c are similar.
+ */
+
+/**
+ * @param {string[]} sentence1
+ * @param {string[]} sentence2
+ * @param {string[][]} similarPairs
+ * @return {boolean}
+ */
+var areSentencesSimilarTwo = function(sentence1, sentence2, similarPairs) {
+ if (sentence1.length !== sentence2.length) {
+ return false;
+ }
+
+ const graph = new Map();
+ for (const [word1, word2] of similarPairs) {
+ if (!graph.has(word1)) graph.set(word1, new Set());
+ if (!graph.has(word2)) graph.set(word2, new Set());
+ graph.get(word1).add(word2);
+ graph.get(word2).add(word1);
+ }
+
+ for (let i = 0; i < sentence1.length; i++) {
+ if (!areSimilar(sentence1[i], sentence2[i])) {
+ return false;
+ }
+ }
+
+ return true;
+
+ function areSimilar(start, target) {
+ if (start === target) return true;
+ const visited = new Set();
+ const queue = [start];
+ visited.add(start);
+
+ while (queue.length) {
+ const word = queue.shift();
+ for (const neighbor of graph.get(word) || []) {
+ if (neighbor === target) return true;
+ if (!visited.has(neighbor)) {
+ visited.add(neighbor);
+ queue.push(neighbor);
+ }
+ }
+ }
+ return false;
+ }
+};
From 2dbb5161588ad35961931651f8c34ae70fc31b83 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 24 Jun 2025 23:29:43 -0500
Subject: [PATCH 555/994] Add solution #742
---
README.md | 1 +
.../0742-closest-leaf-in-a-binary-tree.js | 61 +++++++++++++++++++
2 files changed, 62 insertions(+)
create mode 100644 solutions/0742-closest-leaf-in-a-binary-tree.js
diff --git a/README.md b/README.md
index 2d5ce9a8..4538cc3f 100644
--- a/README.md
+++ b/README.md
@@ -697,6 +697,7 @@
739|[Daily Temperatures](./solutions/0739-daily-temperatures.js)|Medium|
740|[Delete and Earn](./solutions/0740-delete-and-earn.js)|Medium|
741|[Cherry Pickup](./solutions/0741-cherry-pickup.js)|Hard|
+742|[Closest Leaf in a Binary Tree](./solutions/0742-closest-leaf-in-a-binary-tree.js)|Medium|
743|[Network Delay Time](./solutions/0743-network-delay-time.js)|Medium|
744|[Find Smallest Letter Greater Than Target](./solutions/0744-find-smallest-letter-greater-than-target.js)|Easy|
745|[Prefix and Suffix Search](./solutions/0745-prefix-and-suffix-search.js)|Hard|
diff --git a/solutions/0742-closest-leaf-in-a-binary-tree.js b/solutions/0742-closest-leaf-in-a-binary-tree.js
new file mode 100644
index 00000000..8367bf08
--- /dev/null
+++ b/solutions/0742-closest-leaf-in-a-binary-tree.js
@@ -0,0 +1,61 @@
+/**
+ * 742. Closest Leaf in a Binary Tree
+ * https://leetcode.com/problems/closest-leaf-in-a-binary-tree/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree where every node has a unique value and a target integer k,
+ * return the value of the nearest leaf node to the target k in the tree.
+ *
+ * Nearest to a leaf means the least number of edges traveled on the binary tree to reach any
+ * leaf of the tree. Also, a node is called a leaf if it 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} root
+ * @param {number} k
+ * @return {number}
+ */
+var findClosestLeaf = function(root, k) {
+ const graph = new Map();
+ const leaves = new Set();
+
+ buildGraph(root, null);
+
+ const queue = [k];
+ const visited = new Set([k]);
+
+ while (queue.length) {
+ const current = queue.shift();
+ if (leaves.has(current)) return current;
+
+ for (const neighbor of graph.get(current) || []) {
+ if (!visited.has(neighbor)) {
+ visited.add(neighbor);
+ queue.push(neighbor);
+ }
+ }
+ }
+
+ return -1;
+
+ function buildGraph(node, parent) {
+ if (!node) return;
+ if (!node.left && !node.right) leaves.add(node.val);
+ if (parent) {
+ if (!graph.has(node.val)) graph.set(node.val, new Set());
+ if (!graph.has(parent.val)) graph.set(parent.val, new Set());
+ graph.get(node.val).add(parent.val);
+ graph.get(parent.val).add(node.val);
+ }
+ buildGraph(node.left, node);
+ buildGraph(node.right, node);
+ }
+};
From 98afd00bb94b39938f985973ad30da99330899be Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 25 Jun 2025 22:48:40 -0500
Subject: [PATCH 556/994] Add solution #2311
---
README.md | 1 +
...ary-subsequence-less-than-or-equal-to-k.js | 44 +++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/2311-longest-binary-subsequence-less-than-or-equal-to-k.js
diff --git a/README.md b/README.md
index 4538cc3f..f4676c27 100644
--- a/README.md
+++ b/README.md
@@ -1891,6 +1891,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|
+2311|[Longest Binary Subsequence Less Than or Equal to K](./solutions/2311-longest-binary-subsequence-less-than-or-equal-to-k.js)|Medium|
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|
diff --git a/solutions/2311-longest-binary-subsequence-less-than-or-equal-to-k.js b/solutions/2311-longest-binary-subsequence-less-than-or-equal-to-k.js
new file mode 100644
index 00000000..b9a6e646
--- /dev/null
+++ b/solutions/2311-longest-binary-subsequence-less-than-or-equal-to-k.js
@@ -0,0 +1,44 @@
+/**
+ * 2311. Longest Binary Subsequence Less Than or Equal to K
+ * https://leetcode.com/problems/longest-binary-subsequence-less-than-or-equal-to-k/
+ * Difficulty: Medium
+ *
+ * You are given a binary string s and a positive integer k.
+ *
+ * Return the length of the longest subsequence of s that makes up a binary number less than
+ * or equal to k.
+ *
+ * Note:
+ * - The subsequence can contain leading zeroes.
+ * - The empty string is considered to be equal to 0.
+ * - 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 {number} k
+ * @return {number}
+ */
+var longestSubsequence = function(s, k) {
+ let zeros = 0;
+ let ones = 0;
+ let value = 0;
+ let power = 1;
+
+ for (let i = s.length - 1; i >= 0; i--) {
+ if (s[i] === '0') {
+ zeros++;
+ } else {
+ if (power <= k && value + power <= k) {
+ value += power;
+ ones++;
+ }
+ }
+ if (power <= k) {
+ power *= 2;
+ }
+ }
+
+ return zeros + ones;
+};
From 587517715a8ba3ff99f2dcb7fb3dab2071aec6d0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 25 Jun 2025 22:50:41 -0500
Subject: [PATCH 557/994] Add solution #750
---
README.md | 1 +
solutions/0750-number-of-corner-rectangles.js | 35 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/0750-number-of-corner-rectangles.js
diff --git a/README.md b/README.md
index f4676c27..d209431c 100644
--- a/README.md
+++ b/README.md
@@ -705,6 +705,7 @@
747|[Largest Number At Least Twice of Others](./solutions/0747-largest-number-at-least-twice-of-others.js)|Easy|
748|[Shortest Completing Word](./solutions/0748-shortest-completing-word.js)|Easy|
749|[Contain Virus](./solutions/0749-contain-virus.js)|Hard|
+750|[Number Of Corner Rectangles](./solutions/0750-number-of-corner-rectangles.js)|Medium|
752|[Open the Lock](./solutions/0752-open-the-lock.js)|Medium|
753|[Cracking the Safe](./solutions/0753-cracking-the-safe.js)|Hard|
754|[Reach a Number](./solutions/0754-reach-a-number.js)|Medium|
diff --git a/solutions/0750-number-of-corner-rectangles.js b/solutions/0750-number-of-corner-rectangles.js
new file mode 100644
index 00000000..815559fa
--- /dev/null
+++ b/solutions/0750-number-of-corner-rectangles.js
@@ -0,0 +1,35 @@
+/**
+ * 750. Number Of Corner Rectangles
+ * https://leetcode.com/problems/number-of-corner-rectangles/
+ * Difficulty: Medium
+ *
+ * Given an m x n integer matrix grid where each entry is only 0 or 1, return the number of
+ * corner rectangles.
+ *
+ * A corner rectangle is four distinct 1's on the grid that forms an axis-aligned rectangle.
+ * Note that only the corners need to have the value 1. Also, all four 1's used must be distinct.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var countCornerRectangles = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ let result = 0;
+
+ for (let row1 = 0; row1 < rows; row1++) {
+ for (let row2 = row1 + 1; row2 < rows; row2++) {
+ let sharedOnes = 0;
+ for (let col = 0; col < cols; col++) {
+ if (grid[row1][col] === 1 && grid[row2][col] === 1) {
+ sharedOnes++;
+ }
+ }
+ result += sharedOnes * (sharedOnes - 1) / 2;
+ }
+ }
+
+ return result;
+};
From c88e3e484248a7f734d52f51dae01d030b83fa80 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 25 Jun 2025 23:03:38 -0500
Subject: [PATCH 558/994] Add solution #751
---
README.md | 1 +
solutions/0751-ip-to-cidr.js | 74 ++++++++++++++++++++++++++++++++++++
2 files changed, 75 insertions(+)
create mode 100644 solutions/0751-ip-to-cidr.js
diff --git a/README.md b/README.md
index d209431c..31e6457e 100644
--- a/README.md
+++ b/README.md
@@ -706,6 +706,7 @@
748|[Shortest Completing Word](./solutions/0748-shortest-completing-word.js)|Easy|
749|[Contain Virus](./solutions/0749-contain-virus.js)|Hard|
750|[Number Of Corner Rectangles](./solutions/0750-number-of-corner-rectangles.js)|Medium|
+751|[IP to CIDR](./solutions/0751-ip-to-cidr.js)|Medium|
752|[Open the Lock](./solutions/0752-open-the-lock.js)|Medium|
753|[Cracking the Safe](./solutions/0753-cracking-the-safe.js)|Hard|
754|[Reach a Number](./solutions/0754-reach-a-number.js)|Medium|
diff --git a/solutions/0751-ip-to-cidr.js b/solutions/0751-ip-to-cidr.js
new file mode 100644
index 00000000..b9bf5540
--- /dev/null
+++ b/solutions/0751-ip-to-cidr.js
@@ -0,0 +1,74 @@
+/**
+ * 751. IP to CIDR
+ * https://leetcode.com/problems/ip-to-cidr/
+ * Difficulty: Medium
+ *
+ * An IP address is a formatted 32-bit unsigned integer where each group of 8 bits is printed as
+ * a decimal number and the dot character '.' splits the groups.
+ * - For example, the binary number 00001111 10001000 11111111 01101011 (spaces added for clarity)
+ * formatted as an IP address would be "15.136.255.107".
+ *
+ * A CIDR block is a format used to denote a specific set of IP addresses. It is a string consisting
+ * of a base IP address, followed by a slash, followed by a prefix length k. The addresses it covers
+ * are all the IPs whose first k bits are the same as the base IP address.
+ * - For example, "123.45.67.89/20" is a CIDR block with a prefix length of 20. Any IP address whose
+ * binary representation matches 01111011 00101101 0100xxxx xxxxxxxx, where x can be either 0 or
+ * 1, is in the set covered by the CIDR block.
+ *
+ * You are given a start IP address ip and the number of IP addresses we need to cover n. Your goal
+ * is to use as few CIDR blocks as possible to cover all the IP addresses in the inclusive
+ * range [ip, ip + n - 1] exactly. No other IP addresses outside of the range should be covered.
+ *
+ * Return the shortest list of CIDR blocks that covers the range of IP addresses. If there are
+ * multiple answers, return any of them.
+ */
+
+/**
+ * @param {string} ip
+ * @param {number} n
+ * @return {string[]}
+ */
+var ipToCIDR = function(ip, n) {
+ let start = ipToNumber(ip);
+ const result = [];
+
+ while (n > 0) {
+ let rightmostOneBit = start & (-start);
+ if (rightmostOneBit === 0) rightmostOneBit = 4294967296;
+
+ let blockSize = Math.min(rightmostOneBit, n);
+ let temp = blockSize;
+ while ((temp & (temp - 1)) !== 0) {
+ temp = temp & (temp - 1);
+ }
+ blockSize = temp;
+
+ let prefixLength = 32;
+ let mask = blockSize;
+ while (mask > 1) {
+ mask >>>= 1;
+ prefixLength--;
+ }
+
+ result.push(`${numberToIp(start)}/${prefixLength}`);
+
+ start += blockSize;
+ n -= blockSize;
+ }
+
+ return result;
+
+ function ipToNumber(ip) {
+ const parts = ip.split('.').map(Number);
+ return (parts[0] << 24) + (parts[1] << 16) + (parts[2] << 8) + parts[3];
+ }
+
+ function numberToIp(num) {
+ return [
+ (num >>> 24) & 255,
+ (num >>> 16) & 255,
+ (num >>> 8) & 255,
+ num & 255
+ ].join('.');
+ }
+};
From e3d27e012ad135a1208f971e13adbd6a8b7a63fd Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 25 Jun 2025 23:06:27 -0500
Subject: [PATCH 559/994] Add solution #755
---
README.md | 1 +
solutions/0755-pour-water.js | 95 ++++++++++++++++++++++++++++++++++++
2 files changed, 96 insertions(+)
create mode 100644 solutions/0755-pour-water.js
diff --git a/README.md b/README.md
index 31e6457e..923079f2 100644
--- a/README.md
+++ b/README.md
@@ -710,6 +710,7 @@
752|[Open the Lock](./solutions/0752-open-the-lock.js)|Medium|
753|[Cracking the Safe](./solutions/0753-cracking-the-safe.js)|Hard|
754|[Reach a Number](./solutions/0754-reach-a-number.js)|Medium|
+755|[Pour Water](./solutions/0755-pour-water.js)|Medium|
756|[Pyramid Transition Matrix](./solutions/0756-pyramid-transition-matrix.js)|Medium|
757|[Set Intersection Size At Least Two](./solutions/0757-set-intersection-size-at-least-two.js)|Hard|
758|[Bold Words in String](./solutions/0758-bold-words-in-string.js)|Medium|
diff --git a/solutions/0755-pour-water.js b/solutions/0755-pour-water.js
new file mode 100644
index 00000000..f5e3ae88
--- /dev/null
+++ b/solutions/0755-pour-water.js
@@ -0,0 +1,95 @@
+/**
+ * 755. Pour Water
+ * https://leetcode.com/problems/pour-water/
+ * Difficulty: Medium
+ *
+ * You are given an elevation map represents as an integer array heights where heights[i]
+ * representing the height of the terrain at index i. The width at each index is 1. You
+ * are also given two integers volume and k. volume units of water will fall at index k.
+ *
+ * Water first drops at the index k and rests on top of the highest terrain or water at
+ * that index. Then, it flows according to the following rules:
+ * - If the droplet would eventually fall by moving left, then move left.
+ * - Otherwise, if the droplet would eventually fall by moving right, then move right.
+ * - Otherwise, rise to its current position.
+ *
+ * Here, "eventually fall" means that the droplet will eventually be at a lower level if
+ * it moves in that direction. Also, level means the height of the terrain plus any water
+ * in that column.
+ *
+ * We can assume there is infinitely high terrain on the two sides out of bounds of the
+ * array. Also, there could not be partial water being spread out evenly on more than one
+ * grid block, and each unit of water has to be in exactly one block.
+ */
+
+/**
+ * @param {number[]} heights
+ * @param {number} volume
+ * @param {number} k
+ * @return {number[]}
+ */
+var pourWater = function(heights, volume, k) {
+ const water = new Array(heights.length).fill(0);
+
+ for (let drop = 0; drop < volume; drop++) {
+ if (canFallLeft(k)) {
+ water[findLeftPosition(k)]++;
+ } else if (canFallRight(k)) {
+ water[findRightPosition(k)]++;
+ } else {
+ water[k]++;
+ }
+ }
+
+ return heights.map((h, i) => h + water[i]);
+
+ function canFallLeft(index) {
+ let currentLevel = heights[index] + water[index];
+ for (let i = index - 1; i >= 0; i--) {
+ const level = heights[i] + water[i];
+ if (level < currentLevel) return true;
+ if (level > currentLevel) return false;
+ currentLevel = level;
+ }
+ return false;
+ }
+
+ function canFallRight(index) {
+ let currentLevel = heights[index] + water[index];
+ for (let i = index + 1; i < heights.length; i++) {
+ const level = heights[i] + water[i];
+ if (level < currentLevel) return true;
+ if (level > currentLevel) return false;
+ currentLevel = level;
+ }
+ return false;
+ }
+
+ function findLeftPosition(index) {
+ let minHeight = heights[index] + water[index];
+ let position = index;
+ for (let i = index - 1; i >= 0; i--) {
+ const level = heights[i] + water[i];
+ if (level > minHeight) break;
+ if (level < minHeight) {
+ minHeight = level;
+ position = i;
+ }
+ }
+ return position;
+ }
+
+ function findRightPosition(index) {
+ let minHeight = heights[index] + water[index];
+ let position = index;
+ for (let i = index + 1; i < heights.length; i++) {
+ const level = heights[i] + water[i];
+ if (level > minHeight) break;
+ if (level < minHeight) {
+ minHeight = level;
+ position = i;
+ }
+ }
+ return position;
+ }
+};
From ad2d9a3d3d12fb4480f95f718d85a15bc32f7326 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 25 Jun 2025 23:07:39 -0500
Subject: [PATCH 560/994] Add solution #759
---
README.md | 1 +
solutions/0759-employee-free-time.js | 51 ++++++++++++++++++++++++++++
2 files changed, 52 insertions(+)
create mode 100644 solutions/0759-employee-free-time.js
diff --git a/README.md b/README.md
index 923079f2..7a757abf 100644
--- a/README.md
+++ b/README.md
@@ -714,6 +714,7 @@
756|[Pyramid Transition Matrix](./solutions/0756-pyramid-transition-matrix.js)|Medium|
757|[Set Intersection Size At Least Two](./solutions/0757-set-intersection-size-at-least-two.js)|Hard|
758|[Bold Words in String](./solutions/0758-bold-words-in-string.js)|Medium|
+759|[Employee Free Time](./solutions/0759-employee-free-time.js)|Hard|
761|[Special Binary String](./solutions/0761-special-binary-string.js)|Hard|
762|[Prime Number of Set Bits in Binary Representation](./solutions/0762-prime-number-of-set-bits-in-binary-representation.js)|Easy|
763|[Partition Labels](./solutions/0763-partition-labels.js)|Medium|
diff --git a/solutions/0759-employee-free-time.js b/solutions/0759-employee-free-time.js
new file mode 100644
index 00000000..5b29cb37
--- /dev/null
+++ b/solutions/0759-employee-free-time.js
@@ -0,0 +1,51 @@
+/**
+ * 759. Employee Free Time
+ * https://leetcode.com/problems/employee-free-time/
+ * Difficulty: Hard
+ *
+ * We are given a list schedule of employees, which represents the working time for each employee.
+ *
+ * Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.
+ *
+ * Return the list of finite intervals representing common, positive-length free time for all
+ * employees, also in sorted order.
+ *
+ * (Even though we are representing Intervals in the form [x, y], the objects inside are Intervals,
+ * not lists or arrays. For example, schedule[0][0].start = 1, schedule[0][0].end = 2, and
+ * schedule[0][0][0] is not defined). Also, we wouldn't include intervals like [5, 5] in our
+ * answer, as they have zero length.
+ */
+
+/**
+ * @param {Interval[][]} schedule
+ * @return {Interval[]}
+ */
+var employeeFreeTime = function(schedule) {
+ const allIntervals = [];
+
+ for (const employee of schedule) {
+ for (const interval of employee) {
+ allIntervals.push(interval);
+ }
+ }
+
+ allIntervals.sort((a, b) => a.start - b.start);
+
+ const merged = [];
+ for (const interval of allIntervals) {
+ if (merged.length === 0 || merged[merged.length - 1].end < interval.start) {
+ merged.push(interval);
+ } else {
+ merged[merged.length - 1].end = Math.max(merged[merged.length - 1].end, interval.end);
+ }
+ }
+
+ const result = [];
+ for (let i = 0; i < merged.length - 1; i++) {
+ if (merged[i].end < merged[i + 1].start) {
+ result.push(new Interval(merged[i].end, merged[i + 1].start));
+ }
+ }
+
+ return result;
+};
From dc2722a62cd788d229ea1adc27f04f2b929b6618 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 25 Jun 2025 23:10:28 -0500
Subject: [PATCH 561/994] Add solution #760
---
README.md | 1 +
solutions/0760-find-anagram-mappings.js | 38 +++++++++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/0760-find-anagram-mappings.js
diff --git a/README.md b/README.md
index 7a757abf..3e3edbca 100644
--- a/README.md
+++ b/README.md
@@ -715,6 +715,7 @@
757|[Set Intersection Size At Least Two](./solutions/0757-set-intersection-size-at-least-two.js)|Hard|
758|[Bold Words in String](./solutions/0758-bold-words-in-string.js)|Medium|
759|[Employee Free Time](./solutions/0759-employee-free-time.js)|Hard|
+760|[Find Anagram Mappings](./solutions/0760-find-anagram-mappings.js)|Easy|
761|[Special Binary String](./solutions/0761-special-binary-string.js)|Hard|
762|[Prime Number of Set Bits in Binary Representation](./solutions/0762-prime-number-of-set-bits-in-binary-representation.js)|Easy|
763|[Partition Labels](./solutions/0763-partition-labels.js)|Medium|
diff --git a/solutions/0760-find-anagram-mappings.js b/solutions/0760-find-anagram-mappings.js
new file mode 100644
index 00000000..f6bc9fa6
--- /dev/null
+++ b/solutions/0760-find-anagram-mappings.js
@@ -0,0 +1,38 @@
+/**
+ * 760. Find Anagram Mappings
+ * https://leetcode.com/problems/find-anagram-mappings/
+ * Difficulty: Easy
+ *
+ * You are given two integer arrays nums1 and nums2 where nums2 is an anagram of nums1. Both
+ * arrays may contain duplicates.
+ *
+ * Return an index mapping array mapping from nums1 to nums2 where mapping[i] = j means the
+ * ith element in nums1 appears in nums2 at index j. If there are multiple answers, return
+ * any of them.
+ *
+ * An array a is an anagram of an array b means b is made by randomizing the order of the
+ * elements in a.
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @return {number[]}
+ */
+var anagramMappings = function(nums1, nums2) {
+ const map = new Map();
+
+ for (let i = 0; i < nums2.length; i++) {
+ if (!map.has(nums2[i])) {
+ map.set(nums2[i], []);
+ }
+ map.get(nums2[i]).push(i);
+ }
+
+ const result = [];
+ for (const num of nums1) {
+ result.push(map.get(num).pop());
+ }
+
+ return result;
+};
From e2de86961f4666c22e135374fe8032bb7cdc137b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 25 Jun 2025 23:17:21 -0500
Subject: [PATCH 562/994] Add solution #772
---
README.md | 1 +
solutions/0772-basic-calculator-iii.js | 77 ++++++++++++++++++++++++++
2 files changed, 78 insertions(+)
create mode 100644 solutions/0772-basic-calculator-iii.js
diff --git a/README.md b/README.md
index 3e3edbca..5a663eaf 100644
--- a/README.md
+++ b/README.md
@@ -727,6 +727,7 @@
769|[Max Chunks To Make Sorted](./solutions/0769-max-chunks-to-make-sorted.js)|Medium|
770|[Basic Calculator IV](./solutions/0770-basic-calculator-iv.js)|Hard|
771|[Jewels and Stones](./solutions/0771-jewels-and-stones.js)|Easy|
+772|[Basic Calculator III](./solutions/0772-basic-calculator-iii.js)|Hard|
773|[Sliding Puzzle](./solutions/0773-sliding-puzzle.js)|Hard|
775|[Global and Local Inversions](./solutions/0775-global-and-local-inversions.js)|Medium|
777|[Swap Adjacent in LR String](./solutions/0777-swap-adjacent-in-lr-string.js)|Medium|
diff --git a/solutions/0772-basic-calculator-iii.js b/solutions/0772-basic-calculator-iii.js
new file mode 100644
index 00000000..4520c1cc
--- /dev/null
+++ b/solutions/0772-basic-calculator-iii.js
@@ -0,0 +1,77 @@
+/**
+ * 772. Basic Calculator III
+ * https://leetcode.com/problems/basic-calculator-iii/
+ * Difficulty: Hard
+ *
+ * Implement a basic calculator to evaluate a simple expression string.
+ *
+ * The expression string contains only non-negative integers, '+', '-', '*', '/' operators, and
+ * open '(' and closing parentheses ')'. The integer division should truncate toward zero.
+ *
+ * You may assume that the given expression is always valid. All intermediate results will be
+ * in the range of [-231, 231 - 1].
+ *
+ * Note: You are not allowed to use any built-in function which evaluates strings as mathematical
+ * expressions, such as eval().
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var calculate = function(s) {
+ let index = 0;
+ return parseExpression();
+
+ function parseExpression() {
+ let result = parseTerm();
+
+ while (index < s.length && (s[index] === '+' || s[index] === '-')) {
+ const operator = s[index++];
+ const term = parseTerm();
+ result = operator === '+' ? result + term : result - term;
+ }
+
+ return result;
+ }
+
+ function parseTerm() {
+ let result = parseFactor();
+
+ while (index < s.length && (s[index] === '*' || s[index] === '/')) {
+ const operator = s[index++];
+ const factor = parseFactor();
+ if (operator === '*') {
+ result *= factor;
+ } else {
+ result = Math.trunc(result / factor);
+ }
+ }
+
+ return result;
+ }
+
+ function parseFactor() {
+ skipSpaces();
+
+ if (s[index] === '(') {
+ index++;
+ const result = parseExpression();
+ index++;
+ return result;
+ }
+
+ let result = 0;
+ while (index < s.length && s[index] >= '0' && s[index] <= '9') {
+ result = result * 10 + parseInt(s[index++]);
+ }
+
+ return result;
+ }
+
+ function skipSpaces() {
+ while (index < s.length && s[index] === ' ') {
+ index++;
+ }
+ }
+};
From 1db15c22fe0accd5fdb4b7a500a27c2e9400d63f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 25 Jun 2025 23:18:33 -0500
Subject: [PATCH 563/994] Add solution #774
---
README.md | 1 +
...74-minimize-max-distance-to-gas-station.js | 49 +++++++++++++++++++
2 files changed, 50 insertions(+)
create mode 100644 solutions/0774-minimize-max-distance-to-gas-station.js
diff --git a/README.md b/README.md
index 5a663eaf..074a04fc 100644
--- a/README.md
+++ b/README.md
@@ -729,6 +729,7 @@
771|[Jewels and Stones](./solutions/0771-jewels-and-stones.js)|Easy|
772|[Basic Calculator III](./solutions/0772-basic-calculator-iii.js)|Hard|
773|[Sliding Puzzle](./solutions/0773-sliding-puzzle.js)|Hard|
+774|[Minimize Max Distance to Gas Station](./solutions/0774-minimize-max-distance-to-gas-station.js)|Hard|
775|[Global and Local Inversions](./solutions/0775-global-and-local-inversions.js)|Medium|
777|[Swap Adjacent in LR String](./solutions/0777-swap-adjacent-in-lr-string.js)|Medium|
778|[Swim in Rising Water](./solutions/0778-swim-in-rising-water.js)|Hard|
diff --git a/solutions/0774-minimize-max-distance-to-gas-station.js b/solutions/0774-minimize-max-distance-to-gas-station.js
new file mode 100644
index 00000000..27930e3b
--- /dev/null
+++ b/solutions/0774-minimize-max-distance-to-gas-station.js
@@ -0,0 +1,49 @@
+/**
+ * 774. Minimize Max Distance to Gas Station
+ * https://leetcode.com/problems/minimize-max-distance-to-gas-station/
+ * Difficulty: Hard
+ *
+ * You are given an integer array stations that represents the positions of the gas stations
+ * on the x-axis. You are also given an integer k.
+ *
+ * You should add k new gas stations. You can add the stations anywhere on the x-axis, and
+ * not necessarily on an integer position.
+ *
+ * Let penalty() be the maximum distance between adjacent gas stations after adding the k
+ * new stations.
+ *
+ * Return the smallest possible value of penalty(). Answers within 10-6 of the actual answer
+ * will be accepted.
+ */
+
+/**
+ * @param {number[]} stations
+ * @param {number} k
+ * @return {number}
+ */
+var minmaxGasDist = function(stations, k) {
+ const gaps = [];
+ for (let i = 1; i < stations.length; i++) {
+ gaps.push(stations[i] - stations[i - 1]);
+ }
+
+ let left = 0;
+ let right = Math.max(...gaps);
+
+ while (right - left > 1e-6) {
+ const mid = (left + right) / 2;
+
+ let stationsNeeded = 0;
+ for (const gap of gaps) {
+ stationsNeeded += Math.floor(gap / mid);
+ }
+
+ if (stationsNeeded <= k) {
+ right = mid;
+ } else {
+ left = mid;
+ }
+ }
+
+ return right;
+};
From 77bc6935aca206e321ab4edfff1c9f2cdd221c6b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 25 Jun 2025 23:19:40 -0500
Subject: [PATCH 564/994] Add solution #776
---
README.md | 1 +
solutions/0776-split-bst.js | 43 +++++++++++++++++++++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/0776-split-bst.js
diff --git a/README.md b/README.md
index 074a04fc..0d6fd68c 100644
--- a/README.md
+++ b/README.md
@@ -731,6 +731,7 @@
773|[Sliding Puzzle](./solutions/0773-sliding-puzzle.js)|Hard|
774|[Minimize Max Distance to Gas Station](./solutions/0774-minimize-max-distance-to-gas-station.js)|Hard|
775|[Global and Local Inversions](./solutions/0775-global-and-local-inversions.js)|Medium|
+776|[Split BST](./solutions/0776-split-bst.js)|Medium|
777|[Swap Adjacent in LR String](./solutions/0777-swap-adjacent-in-lr-string.js)|Medium|
778|[Swim in Rising Water](./solutions/0778-swim-in-rising-water.js)|Hard|
779|[K-th Symbol in Grammar](./solutions/0779-k-th-symbol-in-grammar.js)|Medium|
diff --git a/solutions/0776-split-bst.js b/solutions/0776-split-bst.js
new file mode 100644
index 00000000..2b4dbd05
--- /dev/null
+++ b/solutions/0776-split-bst.js
@@ -0,0 +1,43 @@
+/**
+ * 776. Split BST
+ * https://leetcode.com/problems/split-bst/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary search tree (BST) and an integer target, split the tree into
+ * two subtrees where the first subtree has nodes that are all smaller or equal to the
+ * target value, while the second subtree has all nodes that are greater than the target
+ * value. It is not necessarily the case that the tree contains a node with the value target.
+ *
+ * Additionally, most of the structure of the original tree should remain. Formally, for
+ * any child c with parent p in the original tree, if they are both in the same subtree
+ * after the split, then node c should still have the parent p.
+ *
+ * Return an array of the two roots of the two subtrees in order.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @param {number} target
+ * @return {TreeNode[]}
+ */
+var splitBST = function(root, target) {
+ if (!root) return [null, null];
+
+ if (root.val <= target) {
+ const [smaller, larger] = splitBST(root.right, target);
+ root.right = smaller;
+ return [root, larger];
+ } else {
+ const [smaller, larger] = splitBST(root.left, target);
+ root.left = larger;
+ return [smaller, root];
+ }
+};
From 0d9b57a0561a65976c0ab8848989b5cc481059af Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 25 Jun 2025 23:21:56 -0500
Subject: [PATCH 565/994] Add solution #800
---
README.md | 3 +-
solutions/0800-similar-rgb-color.js | 51 +++++++++++++++++++++++++++++
2 files changed, 53 insertions(+), 1 deletion(-)
create mode 100644 solutions/0800-similar-rgb-color.js
diff --git a/README.md b/README.md
index 0d6fd68c..db41b277 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 2,300+ LeetCode solutions in JavaScript
+# 2,350+ LeetCode solutions in JavaScript
[https://leetcodejavascript.com](https://leetcodejavascript.com)
@@ -755,6 +755,7 @@
797|[All Paths From Source to Target](./solutions/0797-all-paths-from-source-to-target.js)|Medium|
798|[Smallest Rotation with Highest Score](./solutions/0798-smallest-rotation-with-highest-score.js)|Hard|
799|[Champagne Tower](./solutions/0799-champagne-tower.js)|Medium|
+800|[Similar RGB Color](./solutions/0800-similar-rgb-color.js)|Easy|
801|[Minimum Swaps To Make Sequences Increasing](./solutions/0801-minimum-swaps-to-make-sequences-increasing.js)|Hard|
802|[Find Eventual Safe States](./solutions/0802-find-eventual-safe-states.js)|Medium|
803|[Bricks Falling When Hit](./solutions/0803-bricks-falling-when-hit.js)|Hard|
diff --git a/solutions/0800-similar-rgb-color.js b/solutions/0800-similar-rgb-color.js
new file mode 100644
index 00000000..5e545dbf
--- /dev/null
+++ b/solutions/0800-similar-rgb-color.js
@@ -0,0 +1,51 @@
+/**
+ * 800. Similar RGB Color
+ * https://leetcode.com/problems/similar-rgb-color/
+ * Difficulty: Easy
+ *
+ * The red-green-blue color "#AABBCC" can be written as "#ABC" in shorthand.
+ * - For example, "#15c" is shorthand for the color "#1155cc".
+ *
+ * The similarity between the two colors "#ABCDEF" and "#UVWXYZ"
+ * is -(AB - UV)2 - (CD - WX)2 - (EF - YZ)2.
+ *
+ * Given a string color that follows the format "#ABCDEF", return a string represents
+ * the color that is most similar to the given color and has a shorthand (i.e., it can
+ * be represented as some "#XYZ").
+ *
+ * Any answer which has the same highest similarity as the best answer will be accepted.
+ */
+
+/**
+ * @param {string} color
+ * @return {string}
+ */
+var similarRGB = function(color) {
+ const shorthandValues = [
+ '00', '11', '22', '33', '44', '55', '66', '77',
+ '88', '99', 'aa', 'bb', 'cc', 'dd', 'ee', 'ff'
+ ];
+
+ const red = helper(color.slice(1, 3));
+ const green = helper(color.slice(3, 5));
+ const blue = helper(color.slice(5, 7));
+
+ return `#${red}${green}${blue}`;
+
+ function helper(hex) {
+ const value = parseInt(hex, 16);
+ let minDiff = Infinity;
+ let closest = '';
+
+ for (const shorthand of shorthandValues) {
+ const shorthandValue = parseInt(shorthand, 16);
+ const diff = Math.abs(value - shorthandValue);
+ if (diff < minDiff) {
+ minDiff = diff;
+ closest = shorthand;
+ }
+ }
+
+ return closest;
+ }
+};
From 5bd16270cd78dfabb4f4a5482c1a37e550a64ef3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 22:42:01 -0500
Subject: [PATCH 566/994] Add solution #1055
---
README.md | 1 +
solutions/1055-shortest-way-to-form-string.js | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/1055-shortest-way-to-form-string.js
diff --git a/README.md b/README.md
index db41b277..92cf6cd2 100644
--- a/README.md
+++ b/README.md
@@ -1008,6 +1008,7 @@
1052|[Grumpy Bookstore Owner](./solutions/1052-grumpy-bookstore-owner.js)|Medium|
1053|[Previous Permutation With One Swap](./solutions/1053-previous-permutation-with-one-swap.js)|Medium|
1054|[Distant Barcodes](./solutions/1054-distant-barcodes.js)|Medium|
+1055|[Shortest Way to Form String](./solutions/1055-shortest-way-to-form-string.js)|Medium|
1061|[Lexicographically Smallest Equivalent String](./solutions/1061-lexicographically-smallest-equivalent-string.js)|Medium|
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
diff --git a/solutions/1055-shortest-way-to-form-string.js b/solutions/1055-shortest-way-to-form-string.js
new file mode 100644
index 00000000..57957f92
--- /dev/null
+++ b/solutions/1055-shortest-way-to-form-string.js
@@ -0,0 +1,50 @@
+/**
+ * 1055. Shortest Way to Form String
+ * https://leetcode.com/problems/shortest-way-to-form-string/
+ * Difficulty: Medium
+ *
+ * A subsequence of a string is a new string that is formed from the original string by deleting
+ * some (can be none) of the characters without disturbing the relative positions of the remaining
+ * characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).
+ *
+ * Given two strings source and target, return the minimum number of subsequences of source such
+ * that their concatenation equals target. If the task is impossible, return -1.
+ */
+
+/**
+ * @param {string} source
+ * @param {string} target
+ * @return {number}
+ */
+var shortestWay = function(source, target) {
+ const sourceSet = new Set(source);
+
+ for (const char of target) {
+ if (!sourceSet.has(char)) {
+ return -1;
+ }
+ }
+
+ let subsequences = 0;
+ let targetIndex = 0;
+
+ while (targetIndex < target.length) {
+ let sourceIndex = 0;
+ const startTargetIndex = targetIndex;
+
+ while (sourceIndex < source.length && targetIndex < target.length) {
+ if (source[sourceIndex] === target[targetIndex]) {
+ targetIndex++;
+ }
+ sourceIndex++;
+ }
+
+ if (targetIndex === startTargetIndex) {
+ return -1;
+ }
+
+ subsequences++;
+ }
+
+ return subsequences;
+};
From 9aa0f307961fce40538c0d9a5ec0ca2c47e3922c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 22:44:01 -0500
Subject: [PATCH 567/994] Add solution #1056
---
README.md | 1 +
solutions/1056-confusing-number.js | 36 ++++++++++++++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/1056-confusing-number.js
diff --git a/README.md b/README.md
index 92cf6cd2..b2f71af1 100644
--- a/README.md
+++ b/README.md
@@ -1009,6 +1009,7 @@
1053|[Previous Permutation With One Swap](./solutions/1053-previous-permutation-with-one-swap.js)|Medium|
1054|[Distant Barcodes](./solutions/1054-distant-barcodes.js)|Medium|
1055|[Shortest Way to Form String](./solutions/1055-shortest-way-to-form-string.js)|Medium|
+1056|[Confusing Number](./solutions/1056-confusing-number.js)|Easy|
1061|[Lexicographically Smallest Equivalent String](./solutions/1061-lexicographically-smallest-equivalent-string.js)|Medium|
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
diff --git a/solutions/1056-confusing-number.js b/solutions/1056-confusing-number.js
new file mode 100644
index 00000000..da6ef82d
--- /dev/null
+++ b/solutions/1056-confusing-number.js
@@ -0,0 +1,36 @@
+/**
+ * 1056. Confusing Number
+ * https://leetcode.com/problems/confusing-number/
+ * Difficulty: Easy
+ *
+ * A confusing number is a number that when rotated 180 degrees becomes a different number with
+ * each digit valid.
+ *
+ * We can rotate digits of a number by 180 degrees to form new digits.
+ * - When 0, 1, 6, 8, and 9 are rotated 180 degrees, they become 0, 1, 9, 8, and 6 respectively.
+ * - When 2, 3, 4, 5, and 7 are rotated 180 degrees, they become invalid.
+ *
+ * Note that after rotating a number, we can ignore leading zeros.
+ * - For example, after rotating 8000, we have 0008 which is considered as just 8.
+ *
+ * Given an integer n, return true if it is a confusing number, or false otherwise.
+ */
+
+/**
+ * @param {number} n
+ * @return {boolean}
+ */
+var confusingNumber = function(n) {
+ const rotationMap = { '0': '0', '1': '1', '6': '9', '8': '8', '9': '6' };
+ const digits = n.toString();
+
+ let rotated = '';
+ for (let i = digits.length - 1; i >= 0; i--) {
+ if (!(digits[i] in rotationMap)) {
+ return false;
+ }
+ rotated += rotationMap[digits[i]];
+ }
+
+ return parseInt(rotated, 10) !== n;
+};
From 67f278b47fcc96cbe31d97370f82f6b95169d4f0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 22:45:52 -0500
Subject: [PATCH 568/994] Add solution #1057
---
README.md | 1 +
solutions/1057-campus-bikes.js | 64 ++++++++++++++++++++++++++++++++++
2 files changed, 65 insertions(+)
create mode 100644 solutions/1057-campus-bikes.js
diff --git a/README.md b/README.md
index b2f71af1..a7e01b10 100644
--- a/README.md
+++ b/README.md
@@ -1010,6 +1010,7 @@
1054|[Distant Barcodes](./solutions/1054-distant-barcodes.js)|Medium|
1055|[Shortest Way to Form String](./solutions/1055-shortest-way-to-form-string.js)|Medium|
1056|[Confusing Number](./solutions/1056-confusing-number.js)|Easy|
+1057|[Campus Bikes](./solutions/1057-campus-bikes.js)|Medium|
1061|[Lexicographically Smallest Equivalent String](./solutions/1061-lexicographically-smallest-equivalent-string.js)|Medium|
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
diff --git a/solutions/1057-campus-bikes.js b/solutions/1057-campus-bikes.js
new file mode 100644
index 00000000..65811be2
--- /dev/null
+++ b/solutions/1057-campus-bikes.js
@@ -0,0 +1,64 @@
+/**
+ * 1057. Campus Bikes
+ * https://leetcode.com/problems/campus-bikes/
+ * Difficulty: Medium
+ *
+ * On a campus represented on the X-Y plane, there are n workers and m bikes, with n <= m.
+ *
+ * You are given an array workers of length n where workers[i] = [xi, yi] is the position of
+ * the ith worker. You are also given an array bikes of length m where bikes[j] = [xj, yj]
+ * is the position of the jth bike. All the given positions are unique.
+ *
+ * Assign a bike to each worker. Among the available bikes and workers, we choose the
+ * (workeri, bikej) pair with the shortest Manhattan distance between each other and assign
+ * the bike to that worker.
+ *
+ * If there are multiple (workeri, bikej) pairs with the same shortest Manhattan distance,
+ * we choose the pair with the smallest worker index. If there are multiple ways to do that,
+ * we choose the pair with the smallest bike index. Repeat this process until there are no
+ * available workers.
+ *
+ * Return an array answer of length n, where answer[i] is the index (0-indexed) of the bike
+ * that the ith worker is assigned to.
+ *
+ * The Manhattan distance between two points p1 and p2 is
+ * Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|.
+ */
+
+/**
+ * @param {number[][]} workers
+ * @param {number[][]} bikes
+ * @return {number[]}
+ */
+var assignBikes = function(workers, bikes) {
+ const distances = [];
+
+ for (let i = 0; i < workers.length; i++) {
+ for (let j = 0; j < bikes.length; j++) {
+ const distance = Math.abs(
+ workers[i][0] - bikes[j][0]) + Math.abs(workers[i][1] - bikes[j][1]
+ );
+ distances.push([distance, i, j]);
+ }
+ }
+
+ distances.sort((a, b) => {
+ if (a[0] !== b[0]) return a[0] - b[0];
+ if (a[1] !== b[1]) return a[1] - b[1];
+ return a[2] - b[2];
+ });
+
+ const result = new Array(workers.length);
+ const usedBikes = new Set();
+ const assignedWorkers = new Set();
+
+ for (const [distance, workerIndex, bikeIndex] of distances) {
+ if (!assignedWorkers.has(workerIndex) && !usedBikes.has(bikeIndex)) {
+ result[workerIndex] = bikeIndex;
+ assignedWorkers.add(workerIndex);
+ usedBikes.add(bikeIndex);
+ }
+ }
+
+ return result;
+};
From 95ed24d8b19109f66696c94743fb3dcec621f858 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 22:48:16 -0500
Subject: [PATCH 569/994] Add solution #1058
---
README.md | 1 +
...-minimize-rounding-error-to-meet-target.js | 53 +++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/1058-minimize-rounding-error-to-meet-target.js
diff --git a/README.md b/README.md
index a7e01b10..b7b5c565 100644
--- a/README.md
+++ b/README.md
@@ -1011,6 +1011,7 @@
1055|[Shortest Way to Form String](./solutions/1055-shortest-way-to-form-string.js)|Medium|
1056|[Confusing Number](./solutions/1056-confusing-number.js)|Easy|
1057|[Campus Bikes](./solutions/1057-campus-bikes.js)|Medium|
+1058|[Minimize Rounding Error to Meet Target](./solutions/1058-minimize-rounding-error-to-meet-target.js)|Medium|
1061|[Lexicographically Smallest Equivalent String](./solutions/1061-lexicographically-smallest-equivalent-string.js)|Medium|
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
diff --git a/solutions/1058-minimize-rounding-error-to-meet-target.js b/solutions/1058-minimize-rounding-error-to-meet-target.js
new file mode 100644
index 00000000..6ddd5138
--- /dev/null
+++ b/solutions/1058-minimize-rounding-error-to-meet-target.js
@@ -0,0 +1,53 @@
+/**
+ * 1058. Minimize Rounding Error to Meet Target
+ * https://leetcode.com/problems/minimize-rounding-error-to-meet-target/
+ * Difficulty: Medium
+ *
+ * Given an array of prices [p1,p2...,pn] and a target, round each price pi to Roundi(pi) so
+ * that the rounded array [Round1(p1),Round2(p2)...,Roundn(pn)] sums to the given target.
+ * Each operation Roundi(pi) could be either Floor(pi) or Ceil(pi).
+ *
+ * Return the string "-1" if the rounded array is impossible to sum to target. Otherwise,
+ * return the smallest rounding error, which is defined as Σ |Roundi(pi) - (pi)| for i from
+ * 1 to n, as a string with three places after the decimal.
+ */
+
+/**
+ * @param {string[]} prices
+ * @param {number} target
+ * @return {string}
+ */
+var minimizeError = function(prices, target) {
+ const nums = prices.map(p => parseFloat(p));
+ const floors = nums.map(n => Math.floor(n));
+ const ceils = nums.map(n => Math.ceil(n));
+
+ const minSum = floors.reduce((sum, f) => sum + f, 0);
+ const maxSum = ceils.reduce((sum, c) => sum + c, 0);
+
+ if (target < minSum || target > maxSum) {
+ return '-1';
+ }
+
+ const ceilsNeeded = target - minSum;
+
+ const items = nums.map((n, i) => ({
+ floorError: n - floors[i],
+ ceilError: ceils[i] - n,
+ diff: (ceils[i] - n) - (n - floors[i])
+ }));
+
+ items.sort((a, b) => a.diff - b.diff);
+
+ let totalError = 0;
+
+ for (let i = 0; i < nums.length; i++) {
+ if (i < ceilsNeeded) {
+ totalError += items[i].ceilError;
+ } else {
+ totalError += items[i].floorError;
+ }
+ }
+
+ return totalError.toFixed(3);
+};
From 9296f63d25b426d848ade92bb52ec1aaabdaebd5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 22:50:22 -0500
Subject: [PATCH 570/994] Add solution #1059
---
README.md | 1 +
...l-paths-from-source-lead-to-destination.js | 57 +++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/1059-all-paths-from-source-lead-to-destination.js
diff --git a/README.md b/README.md
index b7b5c565..cd6cc5b2 100644
--- a/README.md
+++ b/README.md
@@ -1012,6 +1012,7 @@
1056|[Confusing Number](./solutions/1056-confusing-number.js)|Easy|
1057|[Campus Bikes](./solutions/1057-campus-bikes.js)|Medium|
1058|[Minimize Rounding Error to Meet Target](./solutions/1058-minimize-rounding-error-to-meet-target.js)|Medium|
+1059|[All Paths from Source Lead to Destination](./solutions/1059-all-paths-from-source-lead-to-destination.js)|Medium|
1061|[Lexicographically Smallest Equivalent String](./solutions/1061-lexicographically-smallest-equivalent-string.js)|Medium|
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
diff --git a/solutions/1059-all-paths-from-source-lead-to-destination.js b/solutions/1059-all-paths-from-source-lead-to-destination.js
new file mode 100644
index 00000000..b6862441
--- /dev/null
+++ b/solutions/1059-all-paths-from-source-lead-to-destination.js
@@ -0,0 +1,57 @@
+/**
+ * 1059. All Paths from Source Lead to Destination
+ * https://leetcode.com/problems/all-paths-from-source-lead-to-destination/
+ * Difficulty: Medium
+ *
+ * Given the edges of a directed graph where edges[i] = [ai, bi] indicates there is an edge
+ * between nodes ai and bi, and two nodes source and destination of this graph, determine
+ * whether or not all paths starting from source eventually, end at destination, that is:
+ * - At least one path exists from the source node to the destination node
+ * - If a path exists from the source node to a node with no outgoing edges, then that node
+ * is equal to destination.
+ * - The number of possible paths from source to destination is a finite number.
+ *
+ * Return true if and only if all roads from source lead to destination.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @param {number} source
+ * @param {number} destination
+ * @return {boolean}
+ */
+var leadsToDestination = function(n, edges, source, destination) {
+ const graph = new Map();
+ const states = new Array(n).fill(0);
+
+ for (const [from, to] of edges) {
+ if (!graph.has(from)) {
+ graph.set(from, []);
+ }
+ graph.get(from).push(to);
+ }
+
+ return dfs(source);
+
+ function dfs(node) {
+ if (states[node] === 1) return false;
+ if (states[node] === 2) return true;
+
+ states[node] = 1;
+
+ if (!graph.has(node)) {
+ states[node] = 2;
+ return node === destination;
+ }
+
+ for (const neighbor of graph.get(node)) {
+ if (!dfs(neighbor)) {
+ return false;
+ }
+ }
+
+ states[node] = 2;
+ return true;
+ }
+};
From 07b87a62d9f309c061f68a5c94140c31314fbeb3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 23:29:33 -0500
Subject: [PATCH 571/994] Add solution #1060
---
README.md | 1 +
.../1060-missing-element-in-sorted-array.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/1060-missing-element-in-sorted-array.js
diff --git a/README.md b/README.md
index cd6cc5b2..7d979429 100644
--- a/README.md
+++ b/README.md
@@ -1013,6 +1013,7 @@
1057|[Campus Bikes](./solutions/1057-campus-bikes.js)|Medium|
1058|[Minimize Rounding Error to Meet Target](./solutions/1058-minimize-rounding-error-to-meet-target.js)|Medium|
1059|[All Paths from Source Lead to Destination](./solutions/1059-all-paths-from-source-lead-to-destination.js)|Medium|
+1060|[Missing Element in Sorted Array](./solutions/1060-missing-element-in-sorted-array.js)|Medium|
1061|[Lexicographically Smallest Equivalent String](./solutions/1061-lexicographically-smallest-equivalent-string.js)|Medium|
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
diff --git a/solutions/1060-missing-element-in-sorted-array.js b/solutions/1060-missing-element-in-sorted-array.js
new file mode 100644
index 00000000..2a168e83
--- /dev/null
+++ b/solutions/1060-missing-element-in-sorted-array.js
@@ -0,0 +1,41 @@
+/**
+ * 1060. Missing Element in Sorted Array
+ * https://leetcode.com/problems/missing-element-in-sorted-array/
+ * Difficulty: Medium
+ *
+ * Given an integer array nums which is sorted in ascending order and all of its elements are
+ * unique and given also an integer k, return the kth missing number starting from the leftmost
+ * number of the array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var missingElement = function(nums, k) {
+ const n = nums.length;
+
+ if (k > getMissingCount(n - 1)) {
+ return nums[n - 1] + k - getMissingCount(n - 1);
+ }
+
+ let left = 0;
+ let right = n - 1;
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+
+ if (getMissingCount(mid) < k) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+
+ return nums[left - 1] + k - getMissingCount(left - 1);
+
+ function getMissingCount(index) {
+ return nums[index] - nums[0] - index;
+ }
+};
From 6a58984e0b199b1c46274ab316ea53e36800ac1c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 23:30:39 -0500
Subject: [PATCH 572/994] Add solution #1062
---
README.md | 1 +
solutions/1062-longest-repeating-substring.js | 29 +++++++++++++++++++
2 files changed, 30 insertions(+)
create mode 100644 solutions/1062-longest-repeating-substring.js
diff --git a/README.md b/README.md
index 7d979429..a494a2e8 100644
--- a/README.md
+++ b/README.md
@@ -1015,6 +1015,7 @@
1059|[All Paths from Source Lead to Destination](./solutions/1059-all-paths-from-source-lead-to-destination.js)|Medium|
1060|[Missing Element in Sorted Array](./solutions/1060-missing-element-in-sorted-array.js)|Medium|
1061|[Lexicographically Smallest Equivalent String](./solutions/1061-lexicographically-smallest-equivalent-string.js)|Medium|
+1062|[Longest Repeating Substring](./solutions/1062-longest-repeating-substring.js)|Medium|
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
1073|[Adding Two Negabinary Numbers](./solutions/1073-adding-two-negabinary-numbers.js)|Medium|
diff --git a/solutions/1062-longest-repeating-substring.js b/solutions/1062-longest-repeating-substring.js
new file mode 100644
index 00000000..68c7232c
--- /dev/null
+++ b/solutions/1062-longest-repeating-substring.js
@@ -0,0 +1,29 @@
+/**
+ * 1062. Longest Repeating Substring
+ * https://leetcode.com/problems/longest-repeating-substring/
+ * Difficulty: Medium
+ *
+ * Given a string s, return the length of the longest repeating substrings. If no repeating
+ * substring exists, return 0.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var longestRepeatingSubstring = function(s) {
+ const n = s.length;
+ const dp = new Array(n + 1).fill(null).map(() => new Array(n + 1).fill(0));
+ let result = 0;
+
+ for (let i = 1; i <= n; i++) {
+ for (let j = 1; j <= n; j++) {
+ if (i !== j && s[i - 1] === s[j - 1]) {
+ dp[i][j] = dp[i - 1][j - 1] + 1;
+ result = Math.max(result, dp[i][j]);
+ }
+ }
+ }
+
+ return result;
+};
From ebfece58e1b674133c297fda1be8a565636f011c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 23:31:32 -0500
Subject: [PATCH 573/994] Add solution #1063
---
README.md | 1 +
solutions/1063-number-of-valid-subarrays.js | 35 +++++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/1063-number-of-valid-subarrays.js
diff --git a/README.md b/README.md
index a494a2e8..dedf3d8b 100644
--- a/README.md
+++ b/README.md
@@ -1016,6 +1016,7 @@
1060|[Missing Element in Sorted Array](./solutions/1060-missing-element-in-sorted-array.js)|Medium|
1061|[Lexicographically Smallest Equivalent String](./solutions/1061-lexicographically-smallest-equivalent-string.js)|Medium|
1062|[Longest Repeating Substring](./solutions/1062-longest-repeating-substring.js)|Medium|
+1063|[Number of Valid Subarrays](./solutions/1063-number-of-valid-subarrays.js)|Hard|
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
1073|[Adding Two Negabinary Numbers](./solutions/1073-adding-two-negabinary-numbers.js)|Medium|
diff --git a/solutions/1063-number-of-valid-subarrays.js b/solutions/1063-number-of-valid-subarrays.js
new file mode 100644
index 00000000..075c69b5
--- /dev/null
+++ b/solutions/1063-number-of-valid-subarrays.js
@@ -0,0 +1,35 @@
+/**
+ * 1063. Number of Valid Subarrays
+ * https://leetcode.com/problems/number-of-valid-subarrays/
+ * Difficulty: Hard
+ *
+ * Given an integer array nums, return the number of non-empty subarrays with the leftmost
+ * element of the subarray not larger than other elements in the subarray.
+ *
+ * A subarray is a contiguous part of an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var validSubarrays = function(nums) {
+ const n = nums.length;
+ const stack = [];
+ let result = 0;
+
+ for (let i = 0; i < n; i++) {
+ while (stack.length && nums[stack[stack.length - 1]] > nums[i]) {
+ const index = stack.pop();
+ result += i - index;
+ }
+ stack.push(i);
+ }
+
+ while (stack.length) {
+ const index = stack.pop();
+ result += n - index;
+ }
+
+ return result;
+};
From 4a91982de559bef6a3746175177c52dbc73fc2a9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 23:32:22 -0500
Subject: [PATCH 574/994] Add solution #1064
---
README.md | 1 +
solutions/1064-fixed-point.js | 33 +++++++++++++++++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/1064-fixed-point.js
diff --git a/README.md b/README.md
index dedf3d8b..02dcdb3e 100644
--- a/README.md
+++ b/README.md
@@ -1017,6 +1017,7 @@
1061|[Lexicographically Smallest Equivalent String](./solutions/1061-lexicographically-smallest-equivalent-string.js)|Medium|
1062|[Longest Repeating Substring](./solutions/1062-longest-repeating-substring.js)|Medium|
1063|[Number of Valid Subarrays](./solutions/1063-number-of-valid-subarrays.js)|Hard|
+1064|[Fixed Point](./solutions/1064-fixed-point.js)|Easy|
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
1073|[Adding Two Negabinary Numbers](./solutions/1073-adding-two-negabinary-numbers.js)|Medium|
diff --git a/solutions/1064-fixed-point.js b/solutions/1064-fixed-point.js
new file mode 100644
index 00000000..216af9a6
--- /dev/null
+++ b/solutions/1064-fixed-point.js
@@ -0,0 +1,33 @@
+/**
+ * 1064. Fixed Point
+ * https://leetcode.com/problems/fixed-point/
+ * Difficulty: Easy
+ *
+ * Given an array of distinct integers arr, where arr is sorted in ascending order, return
+ * the smallest index i that satisfies arr[i] == i. If there is no such index, return -1.
+ */
+
+/**
+ * @param {number[]} arr
+ * @return {number}
+ */
+var fixedPoint = function(arr) {
+ let left = 0;
+ let right = arr.length - 1;
+ let result = -1;
+
+ while (left <= right) {
+ const mid = Math.floor((left + right) / 2);
+
+ if (arr[mid] === mid) {
+ result = mid;
+ right = mid - 1;
+ } else if (arr[mid] < mid) {
+ left = mid + 1;
+ } else {
+ right = mid - 1;
+ }
+ }
+
+ return result;
+};
From fb307183de4878bf03f7617da92485a2a0f14148 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 23:33:16 -0500
Subject: [PATCH 575/994] Add solution #1065
---
README.md | 1 +
solutions/1065-index-pairs-of-a-string.js | 32 +++++++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/1065-index-pairs-of-a-string.js
diff --git a/README.md b/README.md
index 02dcdb3e..6a298642 100644
--- a/README.md
+++ b/README.md
@@ -1018,6 +1018,7 @@
1062|[Longest Repeating Substring](./solutions/1062-longest-repeating-substring.js)|Medium|
1063|[Number of Valid Subarrays](./solutions/1063-number-of-valid-subarrays.js)|Hard|
1064|[Fixed Point](./solutions/1064-fixed-point.js)|Easy|
+1065|[Index Pairs of a String](./solutions/1065-index-pairs-of-a-string.js)|Easy|
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
1073|[Adding Two Negabinary Numbers](./solutions/1073-adding-two-negabinary-numbers.js)|Medium|
diff --git a/solutions/1065-index-pairs-of-a-string.js b/solutions/1065-index-pairs-of-a-string.js
new file mode 100644
index 00000000..35aa0a54
--- /dev/null
+++ b/solutions/1065-index-pairs-of-a-string.js
@@ -0,0 +1,32 @@
+/**
+ * 1065. Index Pairs of a String
+ * https://leetcode.com/problems/index-pairs-of-a-string/
+ * Difficulty: Easy
+ *
+ * Given a string text and an array of strings words, return an array of all index
+ * pairs [i, j] so that the substring text[i...j] is in words.
+ *
+ * Return the pairs [i, j] in sorted order (i.e., sort them by their first coordinate,
+ * and in case of ties sort them by their second coordinate).
+ */
+
+/**
+ * @param {string} text
+ * @param {string[]} words
+ * @return {number[][]}
+ */
+var indexPairs = function(text, words) {
+ const result = [];
+ const wordSet = new Set(words);
+
+ for (let i = 0; i < text.length; i++) {
+ for (let j = i; j < text.length; j++) {
+ const substring = text.slice(i, j + 1);
+ if (wordSet.has(substring)) {
+ result.push([i, j]);
+ }
+ }
+ }
+
+ return result;
+};
From c4f2d555d35c6a8b1ac8cc150753e3b42a512df8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 23:35:51 -0500
Subject: [PATCH 576/994] Add solution #1066
---
README.md | 1 +
solutions/1066-campus-bikes-ii.js | 55 +++++++++++++++++++++++++++++++
2 files changed, 56 insertions(+)
create mode 100644 solutions/1066-campus-bikes-ii.js
diff --git a/README.md b/README.md
index 6a298642..847bc309 100644
--- a/README.md
+++ b/README.md
@@ -1019,6 +1019,7 @@
1063|[Number of Valid Subarrays](./solutions/1063-number-of-valid-subarrays.js)|Hard|
1064|[Fixed Point](./solutions/1064-fixed-point.js)|Easy|
1065|[Index Pairs of a String](./solutions/1065-index-pairs-of-a-string.js)|Easy|
+1066|[Campus Bikes II](./solutions/1066-campus-bikes-ii.js)|Medium|
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
1073|[Adding Two Negabinary Numbers](./solutions/1073-adding-two-negabinary-numbers.js)|Medium|
diff --git a/solutions/1066-campus-bikes-ii.js b/solutions/1066-campus-bikes-ii.js
new file mode 100644
index 00000000..8d2e0f74
--- /dev/null
+++ b/solutions/1066-campus-bikes-ii.js
@@ -0,0 +1,55 @@
+/**
+ * 1066. Campus Bikes II
+ * https://leetcode.com/problems/campus-bikes-ii/
+ * Difficulty: Medium
+ *
+ * On a campus represented as a 2D grid, there are n workers and m bikes, with n <= m.
+ * Each worker and bike is a 2D coordinate on this grid.
+ *
+ * We assign one unique bike to each worker so that the sum of the Manhattan distances
+ * between each worker and their assigned bike is minimized.
+ *
+ * Return the minimum possible sum of Manhattan distances between each worker and their
+ * assigned bike.
+ *
+ * The Manhattan distance between two points p1 and p2 is
+ * Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|.
+ */
+
+/**
+ * @param {number[][]} workers
+ * @param {number[][]} bikes
+ * @return {number}
+ */
+var assignBikes = function(workers, bikes) {
+ const n = workers.length;
+ const m = bikes.length;
+ const memo = new Map();
+
+ return dfs(0, 0);
+
+ function getDistance(worker, bike) {
+ return Math.abs(workers[worker][0] - bikes[bike][0])
+ + Math.abs(workers[worker][1] - bikes[bike][1]);
+ }
+
+ function dfs(workerIndex, usedBikes) {
+ if (workerIndex === n) return 0;
+
+ const key = `${workerIndex}-${usedBikes}`;
+ if (memo.has(key)) return memo.get(key);
+
+ let minDistance = Infinity;
+
+ for (let bikeIndex = 0; bikeIndex < m; bikeIndex++) {
+ if ((usedBikes & (1 << bikeIndex)) === 0) {
+ const distance = getDistance(workerIndex, bikeIndex)
+ + dfs(workerIndex + 1, usedBikes | (1 << bikeIndex));
+ minDistance = Math.min(minDistance, distance);
+ }
+ }
+
+ memo.set(key, minDistance);
+ return minDistance;
+ }
+};
From 8018ad66ef4a2942275f5fe290bfaf5023051429 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 23:39:03 -0500
Subject: [PATCH 577/994] Add solution #1067
---
README.md | 1 +
solutions/1067-digit-count-in-range.js | 60 ++++++++++++++++++++++++++
2 files changed, 61 insertions(+)
create mode 100644 solutions/1067-digit-count-in-range.js
diff --git a/README.md b/README.md
index 847bc309..0b3df6d8 100644
--- a/README.md
+++ b/README.md
@@ -1020,6 +1020,7 @@
1064|[Fixed Point](./solutions/1064-fixed-point.js)|Easy|
1065|[Index Pairs of a String](./solutions/1065-index-pairs-of-a-string.js)|Easy|
1066|[Campus Bikes II](./solutions/1066-campus-bikes-ii.js)|Medium|
+1067|[Digit Count in Range](./solutions/1067-digit-count-in-range.js)|Hard|
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
1073|[Adding Two Negabinary Numbers](./solutions/1073-adding-two-negabinary-numbers.js)|Medium|
diff --git a/solutions/1067-digit-count-in-range.js b/solutions/1067-digit-count-in-range.js
new file mode 100644
index 00000000..63ffbb94
--- /dev/null
+++ b/solutions/1067-digit-count-in-range.js
@@ -0,0 +1,60 @@
+/**
+ * 1067. Digit Count in Range
+ * https://leetcode.com/problems/digit-count-in-range/
+ * Difficulty: Hard
+ *
+ * Given a single-digit integer d and two integers low and high, return the number of times
+ * that d occurs as a digit in all integers in the inclusive range [low, high].
+ */
+
+/**
+ * @param {number} d
+ * @param {number} low
+ * @param {number} high
+ * @return {number}
+ */
+var digitsCount = function(d, low, high) {
+ return countDigits(high) - countDigits(low - 1);
+
+ function countDigits(num) {
+ if (num < 0) return 0;
+
+ const str = num.toString();
+ const n = str.length;
+ let count = 0;
+
+ for (let pos = 0; pos < n; pos++) {
+ const left = pos > 0 ? parseInt(str.substring(0, pos)) : 0;
+ const current = parseInt(str[pos]);
+ const right = pos < n - 1 ? parseInt(str.substring(pos + 1)) : 0;
+ const rightLength = n - pos - 1;
+ const rightPower = Math.pow(10, rightLength);
+
+ if (d === 0) {
+ if (pos === 0) {
+ continue;
+ }
+
+ if (current > d) {
+ count += (left - 1) * rightPower + rightPower;
+ } else if (current === d) {
+ count += (left - 1) * rightPower + right + 1;
+ } else {
+ if (left > 0) {
+ count += (left - 1) * rightPower + rightPower;
+ }
+ }
+ } else {
+ if (current > d) {
+ count += (left + 1) * rightPower;
+ } else if (current === d) {
+ count += left * rightPower + right + 1;
+ } else {
+ count += left * rightPower;
+ }
+ }
+ }
+
+ return count;
+ }
+};
From 96e2904264f85cff15898938bbf151548e486220 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 23:40:30 -0500
Subject: [PATCH 578/994] Add solution #1085
---
README.md | 1 +
...085-sum-of-digits-in-the-minimum-number.js | 21 +++++++++++++++++++
2 files changed, 22 insertions(+)
create mode 100644 solutions/1085-sum-of-digits-in-the-minimum-number.js
diff --git a/README.md b/README.md
index 0b3df6d8..e14d7bcf 100644
--- a/README.md
+++ b/README.md
@@ -1029,6 +1029,7 @@
1079|[Letter Tile Possibilities](./solutions/1079-letter-tile-possibilities.js)|Medium|
1080|[Insufficient Nodes in Root to Leaf Paths](./solutions/1080-insufficient-nodes-in-root-to-leaf-paths.js)|Medium|
1081|[Smallest Subsequence of Distinct Characters](./solutions/1081-smallest-subsequence-of-distinct-characters.js)|Medium|
+1085|[Sum of Digits in the Minimum Number](./solutions/1085-sum-of-digits-in-the-minimum-number.js)|Easy|
1089|[Duplicate Zeros](./solutions/1089-duplicate-zeros.js)|Easy|
1090|[Largest Values From Labels](./solutions/1090-largest-values-from-labels.js)|Medium|
1091|[Shortest Path in Binary Matrix](./solutions/1091-shortest-path-in-binary-matrix.js)|Medium|
diff --git a/solutions/1085-sum-of-digits-in-the-minimum-number.js b/solutions/1085-sum-of-digits-in-the-minimum-number.js
new file mode 100644
index 00000000..69d8735a
--- /dev/null
+++ b/solutions/1085-sum-of-digits-in-the-minimum-number.js
@@ -0,0 +1,21 @@
+/**
+ * 1085. Sum of Digits in the Minimum Number
+ * https://leetcode.com/problems/sum-of-digits-in-the-minimum-number/
+ * Difficulty: Easy
+ *
+ * Given an integer array nums, return 0 if the sum of the digits of the minimum
+ * integer in nums is odd, or 1 otherwise.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var sumOfDigits = function(nums) {
+ const digitSum = Math.min(...nums)
+ .toString()
+ .split('')
+ .reduce((sum, digit) => sum + parseInt(digit), 0);
+
+ return digitSum % 2 === 0 ? 1 : 0;
+};
From e869ee39fec83180656b25c3a9bdb2dfa16a6224 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 23:41:36 -0500
Subject: [PATCH 579/994] Add solution #1086
---
README.md | 1 +
solutions/1086-high-five.js | 42 +++++++++++++++++++++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/1086-high-five.js
diff --git a/README.md b/README.md
index e14d7bcf..2d945526 100644
--- a/README.md
+++ b/README.md
@@ -1030,6 +1030,7 @@
1080|[Insufficient Nodes in Root to Leaf Paths](./solutions/1080-insufficient-nodes-in-root-to-leaf-paths.js)|Medium|
1081|[Smallest Subsequence of Distinct Characters](./solutions/1081-smallest-subsequence-of-distinct-characters.js)|Medium|
1085|[Sum of Digits in the Minimum Number](./solutions/1085-sum-of-digits-in-the-minimum-number.js)|Easy|
+1086|[High Five](./solutions/1086-high-five.js)|Easy|
1089|[Duplicate Zeros](./solutions/1089-duplicate-zeros.js)|Easy|
1090|[Largest Values From Labels](./solutions/1090-largest-values-from-labels.js)|Medium|
1091|[Shortest Path in Binary Matrix](./solutions/1091-shortest-path-in-binary-matrix.js)|Medium|
diff --git a/solutions/1086-high-five.js b/solutions/1086-high-five.js
new file mode 100644
index 00000000..e7f379ba
--- /dev/null
+++ b/solutions/1086-high-five.js
@@ -0,0 +1,42 @@
+/**
+ * 1086. High Five
+ * https://leetcode.com/problems/high-five/
+ * Difficulty: Easy
+ *
+ * Given a list of the scores of different students, items, where items[i] = [IDi, scorei]
+ * represents one score from a student with IDi, calculate each student's top five average.
+ *
+ * Return the answer as an array of pairs result, where result[j] = [IDj, topFiveAveragej]
+ * represents the student with IDj and their top five average. Sort result by IDj in
+ * increasing order.
+ *
+ * A student's top five average is calculated by taking the sum of their top five scores
+ * and dividing it by 5 using integer division.
+ */
+
+/**
+ * @param {number[][]} items
+ * @return {number[][]}
+ */
+var highFive = function(items) {
+ const studentScores = new Map();
+
+ for (const [id, score] of items) {
+ if (!studentScores.has(id)) {
+ studentScores.set(id, []);
+ }
+ studentScores.get(id).push(score);
+ }
+
+ const result = [];
+ for (const [id, scores] of studentScores) {
+ scores.sort((a, b) => b - a);
+ const topFiveSum = scores.slice(0, 5).reduce((sum, score) => sum + score, 0);
+ const average = Math.floor(topFiveSum / 5);
+ result.push([id, average]);
+ }
+
+ result.sort((a, b) => a[0] - b[0]);
+
+ return result;
+};
From e40c57ac808d0603f49ff54af77a89ce492662cc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 23:43:09 -0500
Subject: [PATCH 580/994] Add solution #1087
---
README.md | 1 +
solutions/1087-brace-expansion.js | 55 +++++++++++++++++++++++++++++++
2 files changed, 56 insertions(+)
create mode 100644 solutions/1087-brace-expansion.js
diff --git a/README.md b/README.md
index 2d945526..ff1f64a1 100644
--- a/README.md
+++ b/README.md
@@ -1031,6 +1031,7 @@
1081|[Smallest Subsequence of Distinct Characters](./solutions/1081-smallest-subsequence-of-distinct-characters.js)|Medium|
1085|[Sum of Digits in the Minimum Number](./solutions/1085-sum-of-digits-in-the-minimum-number.js)|Easy|
1086|[High Five](./solutions/1086-high-five.js)|Easy|
+1087|[Brace Expansion](./solutions/1087-brace-expansion.js)|Medium|
1089|[Duplicate Zeros](./solutions/1089-duplicate-zeros.js)|Easy|
1090|[Largest Values From Labels](./solutions/1090-largest-values-from-labels.js)|Medium|
1091|[Shortest Path in Binary Matrix](./solutions/1091-shortest-path-in-binary-matrix.js)|Medium|
diff --git a/solutions/1087-brace-expansion.js b/solutions/1087-brace-expansion.js
new file mode 100644
index 00000000..95571310
--- /dev/null
+++ b/solutions/1087-brace-expansion.js
@@ -0,0 +1,55 @@
+/**
+ * 1087. Brace Expansion
+ * https://leetcode.com/problems/brace-expansion/
+ * Difficulty: Medium
+ *
+ * You are given a string s representing a list of words. Each letter in the word has
+ * one or more options.
+ * - If there is one option, the letter is represented as is.
+ * - If there is more than one option, then curly braces delimit the options.
+ * For example, "{a,b,c}" represents options ["a", "b", "c"].
+ *
+ * For example, if s = "a{b,c}", the first character is always 'a', but the second
+ * character can be 'b' or 'c'. The original list is ["ab", "ac"].
+ *
+ * Return all words that can be formed in this manner, sorted in lexicographical order.
+ */
+
+/**
+ * @param {string} s
+ * @return {string[]}
+ */
+var expand = function(s) {
+ const groups = [];
+ let i = 0;
+
+ while (i < s.length) {
+ if (s[i] === '{') {
+ const start = i + 1;
+ while (s[i] !== '}') i++;
+ const options = s.substring(start, i).split(',');
+ groups.push(options);
+ i++;
+ } else {
+ groups.push([s[i]]);
+ i++;
+ }
+ }
+
+ const result = [];
+
+ backtrack(0, '');
+
+ return result.sort();
+
+ function backtrack(index, current) {
+ if (index === groups.length) {
+ result.push(current);
+ return;
+ }
+
+ for (const option of groups[index]) {
+ backtrack(index + 1, current + option);
+ }
+ }
+};
From 39c20697bb974a5fc001beca5c351561139155f7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 23:56:05 -0500
Subject: [PATCH 581/994] Add solution #1088
---
README.md | 1 +
solutions/1088-confusing-number-ii.js | 64 +++++++++++++++++++++++++++
2 files changed, 65 insertions(+)
create mode 100644 solutions/1088-confusing-number-ii.js
diff --git a/README.md b/README.md
index ff1f64a1..74d8673a 100644
--- a/README.md
+++ b/README.md
@@ -1032,6 +1032,7 @@
1085|[Sum of Digits in the Minimum Number](./solutions/1085-sum-of-digits-in-the-minimum-number.js)|Easy|
1086|[High Five](./solutions/1086-high-five.js)|Easy|
1087|[Brace Expansion](./solutions/1087-brace-expansion.js)|Medium|
+1088|[Confusing Number II](./solutions/1088-confusing-number-ii.js)|Hard|
1089|[Duplicate Zeros](./solutions/1089-duplicate-zeros.js)|Easy|
1090|[Largest Values From Labels](./solutions/1090-largest-values-from-labels.js)|Medium|
1091|[Shortest Path in Binary Matrix](./solutions/1091-shortest-path-in-binary-matrix.js)|Medium|
diff --git a/solutions/1088-confusing-number-ii.js b/solutions/1088-confusing-number-ii.js
new file mode 100644
index 00000000..dc5c8f51
--- /dev/null
+++ b/solutions/1088-confusing-number-ii.js
@@ -0,0 +1,64 @@
+/**
+ * 1088. Confusing Number II
+ * https://leetcode.com/problems/confusing-number-ii/
+ * Difficulty: Hard
+ *
+ * A confusing number is a number that when rotated 180 degrees becomes a different number
+ * with each digit valid.
+ *
+ * We can rotate digits of a number by 180 degrees to form new digits.
+ * - When 0, 1, 6, 8, and 9 are rotated 180 degrees, they become 0, 1, 9, 8, and 6 respectively.
+ * - When 2, 3, 4, 5, and 7 are rotated 180 degrees, they become invalid.
+ *
+ * Note that after rotating a number, we can ignore leading zeros.
+ * - For example, after rotating 8000, we have 0008 which is considered as just 8.
+ *
+ * Given an integer n, return the number of confusing numbers in the inclusive range [1, n].
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var confusingNumberII = function(n) {
+ const validDigits = [0, 1, 6, 8, 9];
+ const rotationMap = { 0: 0, 1: 1, 6: 9, 8: 8, 9: 6 };
+ let count = 0;
+
+ const maxLength = n.toString().length;
+
+ for (let len = 1; len <= maxLength; len++) {
+ dfs(0, 0, len);
+ }
+
+ return count;
+
+ function isConfusing(num) {
+ const original = num;
+ let rotated = 0;
+
+ while (num > 0) {
+ const digit = num % 10;
+ rotated = rotated * 10 + rotationMap[digit];
+ num = Math.floor(num / 10);
+ }
+
+ return original !== rotated;
+ }
+
+ function dfs(current, length, targetLength) {
+ if (length === targetLength) {
+ if (current <= n && current > 0 && isConfusing(current)) {
+ count++;
+ }
+ return;
+ }
+
+ for (const digit of validDigits) {
+ if (current === 0 && digit === 0) continue;
+ const next = current * 10 + digit;
+ if (next > n) break;
+ dfs(next, length + 1, targetLength);
+ }
+ }
+};
From 7f0b28f35079be77fa1d6634e5be5b3258720e75 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 23:57:23 -0500
Subject: [PATCH 582/994] Add solution #1099
---
README.md | 1 +
solutions/1099-two-sum-less-than-k.js | 34 +++++++++++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/1099-two-sum-less-than-k.js
diff --git a/README.md b/README.md
index 74d8673a..fb7744db 100644
--- a/README.md
+++ b/README.md
@@ -1041,6 +1041,7 @@
1094|[Car Pooling](./solutions/1094-car-pooling.js)|Medium|
1095|[Find in Mountain Array](./solutions/1095-find-in-mountain-array.js)|Hard|
1096|[Brace Expansion II](./solutions/1096-brace-expansion-ii.js)|Hard|
+1099|[Two Sum Less Than K](./solutions/1099-two-sum-less-than-k.js)|Easy|
1103|[Distribute Candies to People](./solutions/1103-distribute-candies-to-people.js)|Easy|
1104|[Path In Zigzag Labelled Binary Tree](./solutions/1104-path-in-zigzag-labelled-binary-tree.js)|Medium|
1105|[Filling Bookcase Shelves](./solutions/1105-filling-bookcase-shelves.js)|Medium|
diff --git a/solutions/1099-two-sum-less-than-k.js b/solutions/1099-two-sum-less-than-k.js
new file mode 100644
index 00000000..9041f0c2
--- /dev/null
+++ b/solutions/1099-two-sum-less-than-k.js
@@ -0,0 +1,34 @@
+/**
+ * 1099. Two Sum Less Than K
+ * https://leetcode.com/problems/two-sum-less-than-k/
+ * Difficulty: Easy
+ *
+ * Given an array nums of integers and integer k, return the maximum sum such that there
+ * exists i < j with nums[i] + nums[j] = sum and sum < k. If no i, j exist satisfying
+ * this equation, return -1.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var twoSumLessThanK = function(nums, k) {
+ nums.sort((a, b) => a - b);
+ let left = 0;
+ let right = nums.length - 1;
+ let result = -1;
+
+ while (left < right) {
+ const sum = nums[left] + nums[right];
+
+ if (sum < k) {
+ result = Math.max(result, sum);
+ left++;
+ } else {
+ right--;
+ }
+ }
+
+ return result;
+};
From e76a15fce29a095043887ef984ef555d7d5735d9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 23:58:20 -0500
Subject: [PATCH 583/994] Add solution #1100
---
README.md | 1 +
...-substrings-with-no-repeated-characters.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/1100-find-k-length-substrings-with-no-repeated-characters.js
diff --git a/README.md b/README.md
index fb7744db..c3f2fbf8 100644
--- a/README.md
+++ b/README.md
@@ -1042,6 +1042,7 @@
1095|[Find in Mountain Array](./solutions/1095-find-in-mountain-array.js)|Hard|
1096|[Brace Expansion II](./solutions/1096-brace-expansion-ii.js)|Hard|
1099|[Two Sum Less Than K](./solutions/1099-two-sum-less-than-k.js)|Easy|
+1100|[Find K-Length Substrings With No Repeated Characters](./solutions/1100-find-k-length-substrings-with-no-repeated-characters.js)|Medium|
1103|[Distribute Candies to People](./solutions/1103-distribute-candies-to-people.js)|Easy|
1104|[Path In Zigzag Labelled Binary Tree](./solutions/1104-path-in-zigzag-labelled-binary-tree.js)|Medium|
1105|[Filling Bookcase Shelves](./solutions/1105-filling-bookcase-shelves.js)|Medium|
diff --git a/solutions/1100-find-k-length-substrings-with-no-repeated-characters.js b/solutions/1100-find-k-length-substrings-with-no-repeated-characters.js
new file mode 100644
index 00000000..bcbd2814
--- /dev/null
+++ b/solutions/1100-find-k-length-substrings-with-no-repeated-characters.js
@@ -0,0 +1,42 @@
+/**
+ * 1100. Find K-Length Substrings With No Repeated Characters
+ * https://leetcode.com/problems/find-k-length-substrings-with-no-repeated-characters/
+ * Difficulty: Medium
+ *
+ * Given a string s and an integer k, return the number of substrings in s of length k
+ * with no repeated characters.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} k
+ * @return {number}
+ */
+var numKLenSubstrNoRepeats = function(s, k) {
+ if (k > s.length) return 0;
+
+ const charCount = new Map();
+ let count = 0;
+
+ for (let i = 0; i < k; i++) {
+ charCount.set(s[i], (charCount.get(s[i]) || 0) + 1);
+ }
+
+ if (charCount.size === k) count++;
+
+ for (let i = k; i < s.length; i++) {
+ const leftChar = s[i - k];
+ const rightChar = s[i];
+
+ charCount.set(leftChar, charCount.get(leftChar) - 1);
+ if (charCount.get(leftChar) === 0) {
+ charCount.delete(leftChar);
+ }
+
+ charCount.set(rightChar, (charCount.get(rightChar) || 0) + 1);
+
+ if (charCount.size === k) count++;
+ }
+
+ return count;
+};
From fd34678523fd4871fc31601760c7c6520b423b57 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 26 Jun 2025 23:59:59 -0500
Subject: [PATCH 584/994] Add solution #1101
---
README.md | 1 +
...est-moment-when-everyone-become-friends.js | 62 +++++++++++++++++++
2 files changed, 63 insertions(+)
create mode 100644 solutions/1101-the-earliest-moment-when-everyone-become-friends.js
diff --git a/README.md b/README.md
index c3f2fbf8..7235f443 100644
--- a/README.md
+++ b/README.md
@@ -1043,6 +1043,7 @@
1096|[Brace Expansion II](./solutions/1096-brace-expansion-ii.js)|Hard|
1099|[Two Sum Less Than K](./solutions/1099-two-sum-less-than-k.js)|Easy|
1100|[Find K-Length Substrings With No Repeated Characters](./solutions/1100-find-k-length-substrings-with-no-repeated-characters.js)|Medium|
+1101|[The Earliest Moment When Everyone Become Friends](./solutions/1101-the-earliest-moment-when-everyone-become-friends.js)|Medium|
1103|[Distribute Candies to People](./solutions/1103-distribute-candies-to-people.js)|Easy|
1104|[Path In Zigzag Labelled Binary Tree](./solutions/1104-path-in-zigzag-labelled-binary-tree.js)|Medium|
1105|[Filling Bookcase Shelves](./solutions/1105-filling-bookcase-shelves.js)|Medium|
diff --git a/solutions/1101-the-earliest-moment-when-everyone-become-friends.js b/solutions/1101-the-earliest-moment-when-everyone-become-friends.js
new file mode 100644
index 00000000..cc6cf1a9
--- /dev/null
+++ b/solutions/1101-the-earliest-moment-when-everyone-become-friends.js
@@ -0,0 +1,62 @@
+/**
+ * 1101. The Earliest Moment When Everyone Become Friends
+ * https://leetcode.com/problems/the-earliest-moment-when-everyone-become-friends/
+ * Difficulty: Medium
+ *
+ * There are n people in a social group labeled from 0 to n - 1. You are given an array logs
+ * where logs[i] = [timestampi, xi, yi] indicates that xi and yi will be friends at the time
+ * timestampi.
+ *
+ * Friendship is symmetric. That means if a is friends with b, then b is friends with a.
+ * Also, person a is acquainted with a person b if a is friends with b, or a is a friend
+ * of someone acquainted with b.
+ *
+ * Return the earliest time for which every person became acquainted with every other person.
+ * If there is no such earliest time, return -1.
+ */
+
+/**
+ * @param {number[][]} logs
+ * @param {number} n
+ * @return {number}
+ */
+var earliestAcq = function(logs, n) {
+ logs.sort((a, b) => a[0] - b[0]);
+
+ const parent = Array.from({ length: n }, (_, i) => i);
+ const rank = new Array(n).fill(0);
+ let components = n;
+ for (const [timestamp, x, y] of logs) {
+ if (union(x, y) && components === 1) {
+ return timestamp;
+ }
+ }
+
+ return -1;
+
+ function find(x) {
+ if (parent[x] !== x) {
+ parent[x] = find(parent[x]);
+ }
+ return parent[x];
+ }
+
+ function union(x, y) {
+ const rootX = find(x);
+ const rootY = find(y);
+
+ if (rootX === rootY) return false;
+
+ if (rank[rootX] < rank[rootY]) {
+ parent[rootX] = rootY;
+ } else if (rank[rootX] > rank[rootY]) {
+ parent[rootY] = rootX;
+ } else {
+ parent[rootY] = rootX;
+ rank[rootX]++;
+ }
+
+ components--;
+ return true;
+ }
+};
From 2b6b1736b2f9aa41957f027473fedc3737ada180 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 00:08:10 -0500
Subject: [PATCH 585/994] Add solution #1102
---
README.md | 1 +
.../1102-path-with-maximum-minimum-value.js | 47 +++++++++++++++++++
2 files changed, 48 insertions(+)
create mode 100644 solutions/1102-path-with-maximum-minimum-value.js
diff --git a/README.md b/README.md
index 7235f443..927b7621 100644
--- a/README.md
+++ b/README.md
@@ -1044,6 +1044,7 @@
1099|[Two Sum Less Than K](./solutions/1099-two-sum-less-than-k.js)|Easy|
1100|[Find K-Length Substrings With No Repeated Characters](./solutions/1100-find-k-length-substrings-with-no-repeated-characters.js)|Medium|
1101|[The Earliest Moment When Everyone Become Friends](./solutions/1101-the-earliest-moment-when-everyone-become-friends.js)|Medium|
+1102|[Path With Maximum Minimum Value](./solutions/1102-path-with-maximum-minimum-value.js)|Medium|
1103|[Distribute Candies to People](./solutions/1103-distribute-candies-to-people.js)|Easy|
1104|[Path In Zigzag Labelled Binary Tree](./solutions/1104-path-in-zigzag-labelled-binary-tree.js)|Medium|
1105|[Filling Bookcase Shelves](./solutions/1105-filling-bookcase-shelves.js)|Medium|
diff --git a/solutions/1102-path-with-maximum-minimum-value.js b/solutions/1102-path-with-maximum-minimum-value.js
new file mode 100644
index 00000000..37536848
--- /dev/null
+++ b/solutions/1102-path-with-maximum-minimum-value.js
@@ -0,0 +1,47 @@
+/**
+ * 1102. Path With Maximum Minimum Value
+ * https://leetcode.com/problems/path-with-maximum-minimum-value/
+ * Difficulty: Medium
+ *
+ * Given an m x n integer matrix grid, return the maximum score of a path starting
+ * at (0, 0) and ending at (m - 1, n - 1) moving in the 4 cardinal directions.
+ *
+ * The score of a path is the minimum value in that path.
+ * - For example, the score of the path 8 → 4 → 5 → 9 is 4.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var maximumMinimumPath = function(grid) {
+ const m = grid.length;
+ const n = grid[0].length;
+ const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
+ const visited = new Array(m).fill(null).map(() => new Array(n).fill(false));
+
+ const maxHeap = new PriorityQueue((a, b) => b[0] - a[0]);
+ maxHeap.enqueue([grid[0][0], 0, 0]);
+ visited[0][0] = true;
+
+ while (!maxHeap.isEmpty()) {
+ const [currentScore, row, col] = maxHeap.dequeue();
+
+ if (row === m - 1 && col === n - 1) {
+ return currentScore;
+ }
+
+ for (const [dr, dc] of directions) {
+ const newRow = row + dr;
+ const newCol = col + dc;
+
+ if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n && !visited[newRow][newCol]) {
+ visited[newRow][newCol] = true;
+ const newScore = Math.min(currentScore, grid[newRow][newCol]);
+ maxHeap.enqueue([newScore, newRow, newCol]);
+ }
+ }
+ }
+
+ return -1;
+};
From eb5ab7bb307b6d355ec9a994bb6167fa37524717 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 23:25:50 -0500
Subject: [PATCH 586/994] Add solution #1118
---
README.md | 1 +
solutions/1118-number-of-days-in-a-month.js | 16 ++++++++++++++++
2 files changed, 17 insertions(+)
create mode 100644 solutions/1118-number-of-days-in-a-month.js
diff --git a/README.md b/README.md
index 927b7621..994b4edc 100644
--- a/README.md
+++ b/README.md
@@ -1053,6 +1053,7 @@
1109|[Corporate Flight Bookings](./solutions/1109-corporate-flight-bookings.js)|Medium|
1110|[Delete Nodes And Return Forest](./solutions/1110-delete-nodes-and-return-forest.js)|Medium|
1111|[Maximum Nesting Depth of Two Valid Parentheses Strings](./solutions/1111-maximum-nesting-depth-of-two-valid-parentheses-strings.js)|Medium|
+1118|[Number of Days in a Month](./solutions/1118-number-of-days-in-a-month.js)|Easy|
1122|[Relative Sort Array](./solutions/1122-relative-sort-array.js)|Easy|
1123|[Lowest Common Ancestor of Deepest Leaves](./solutions/1123-lowest-common-ancestor-of-deepest-leaves.js)|Medium|
1124|[Longest Well-Performing Interval](./solutions/1124-longest-well-performing-interval.js)|Medium|
diff --git a/solutions/1118-number-of-days-in-a-month.js b/solutions/1118-number-of-days-in-a-month.js
new file mode 100644
index 00000000..d201f255
--- /dev/null
+++ b/solutions/1118-number-of-days-in-a-month.js
@@ -0,0 +1,16 @@
+/**
+ * 1118. Number of Days in a Month
+ * https://leetcode.com/problems/number-of-days-in-a-month/
+ * Difficulty: Easy
+ *
+ * Given a year year and a month month, return the number of days of that month.
+ */
+
+/**
+ * @param {number} year
+ * @param {number} month
+ * @return {number}
+ */
+var numberOfDays = function(year, month) {
+ return new Date(year, month, 0).getDate();
+};
From f9bf0ba3fd1e12a3c79545a91475f7ea08f85676 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 23:26:54 -0500
Subject: [PATCH 587/994] Add solution #1119
---
README.md | 1 +
solutions/1119-remove-vowels-from-a-string.js | 16 ++++++++++++++++
2 files changed, 17 insertions(+)
create mode 100644 solutions/1119-remove-vowels-from-a-string.js
diff --git a/README.md b/README.md
index 994b4edc..b4d868f7 100644
--- a/README.md
+++ b/README.md
@@ -1054,6 +1054,7 @@
1110|[Delete Nodes And Return Forest](./solutions/1110-delete-nodes-and-return-forest.js)|Medium|
1111|[Maximum Nesting Depth of Two Valid Parentheses Strings](./solutions/1111-maximum-nesting-depth-of-two-valid-parentheses-strings.js)|Medium|
1118|[Number of Days in a Month](./solutions/1118-number-of-days-in-a-month.js)|Easy|
+1119|[Remove Vowels from a String](./solutions/1119-remove-vowels-from-a-string.js)|Easy|
1122|[Relative Sort Array](./solutions/1122-relative-sort-array.js)|Easy|
1123|[Lowest Common Ancestor of Deepest Leaves](./solutions/1123-lowest-common-ancestor-of-deepest-leaves.js)|Medium|
1124|[Longest Well-Performing Interval](./solutions/1124-longest-well-performing-interval.js)|Medium|
diff --git a/solutions/1119-remove-vowels-from-a-string.js b/solutions/1119-remove-vowels-from-a-string.js
new file mode 100644
index 00000000..df679c98
--- /dev/null
+++ b/solutions/1119-remove-vowels-from-a-string.js
@@ -0,0 +1,16 @@
+/**
+ * 1119. Remove Vowels from a String
+ * https://leetcode.com/problems/remove-vowels-from-a-string/
+ * Difficulty: Easy
+ *
+ * Given a string s, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and
+ * return the new string.
+ */
+
+/**
+ * @param {string} s
+ * @return {string}
+ */
+var removeVowels = function(s) {
+ return s.replace(/[aeiou]/g, '');
+};
From 96bbb08691100a49acccd5f154b8fee323f19380 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 23:28:04 -0500
Subject: [PATCH 588/994] Add solution #1120
---
README.md | 1 +
solutions/1120-maximum-average-subtree.js | 44 +++++++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/1120-maximum-average-subtree.js
diff --git a/README.md b/README.md
index b4d868f7..101836fe 100644
--- a/README.md
+++ b/README.md
@@ -1055,6 +1055,7 @@
1111|[Maximum Nesting Depth of Two Valid Parentheses Strings](./solutions/1111-maximum-nesting-depth-of-two-valid-parentheses-strings.js)|Medium|
1118|[Number of Days in a Month](./solutions/1118-number-of-days-in-a-month.js)|Easy|
1119|[Remove Vowels from a String](./solutions/1119-remove-vowels-from-a-string.js)|Easy|
+1120|[Maximum Average Subtree](./solutions/1120-maximum-average-subtree.js)|Medium|
1122|[Relative Sort Array](./solutions/1122-relative-sort-array.js)|Easy|
1123|[Lowest Common Ancestor of Deepest Leaves](./solutions/1123-lowest-common-ancestor-of-deepest-leaves.js)|Medium|
1124|[Longest Well-Performing Interval](./solutions/1124-longest-well-performing-interval.js)|Medium|
diff --git a/solutions/1120-maximum-average-subtree.js b/solutions/1120-maximum-average-subtree.js
new file mode 100644
index 00000000..2052a8f2
--- /dev/null
+++ b/solutions/1120-maximum-average-subtree.js
@@ -0,0 +1,44 @@
+/**
+ * 1120. Maximum Average Subtree
+ * https://leetcode.com/problems/maximum-average-subtree/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree, return the maximum average value of a subtree of that tree.
+ * Answers within 10-5 of the actual answer will be accepted.
+ *
+ * A subtree of a tree is any node of that tree plus all its descendants.
+ *
+ * The average value of a tree is the sum of its values, divided by the number of nodes.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @return {number}
+ */
+var maximumAverageSubtree = function(root) {
+ let maxAverage = 0;
+ calculateSubtree(root);
+ return maxAverage;
+
+ function calculateSubtree(node) {
+ if (!node) return [0, 0];
+
+ const [leftSum, leftCount] = calculateSubtree(node.left);
+ const [rightSum, rightCount] = calculateSubtree(node.right);
+ const totalSum = leftSum + rightSum + node.val;
+ const totalCount = leftCount + rightCount + 1;
+ const currentAverage = totalSum / totalCount;
+
+ maxAverage = Math.max(maxAverage, currentAverage);
+
+ return [totalSum, totalCount];
+ }
+};
From 69e9aa1780708c186befe425926890c18a94797a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 23:36:13 -0500
Subject: [PATCH 589/994] Add solution #1121
---
README.md | 1 +
...-divide-array-into-increasing-sequences.js | 26 +++++++++++++++++++
2 files changed, 27 insertions(+)
create mode 100644 solutions/1121-divide-array-into-increasing-sequences.js
diff --git a/README.md b/README.md
index 101836fe..ab502ff8 100644
--- a/README.md
+++ b/README.md
@@ -1056,6 +1056,7 @@
1118|[Number of Days in a Month](./solutions/1118-number-of-days-in-a-month.js)|Easy|
1119|[Remove Vowels from a String](./solutions/1119-remove-vowels-from-a-string.js)|Easy|
1120|[Maximum Average Subtree](./solutions/1120-maximum-average-subtree.js)|Medium|
+1121|[Divide Array Into Increasing Sequences](./solutions/1121-divide-array-into-increasing-sequences.js)|Hard|
1122|[Relative Sort Array](./solutions/1122-relative-sort-array.js)|Easy|
1123|[Lowest Common Ancestor of Deepest Leaves](./solutions/1123-lowest-common-ancestor-of-deepest-leaves.js)|Medium|
1124|[Longest Well-Performing Interval](./solutions/1124-longest-well-performing-interval.js)|Medium|
diff --git a/solutions/1121-divide-array-into-increasing-sequences.js b/solutions/1121-divide-array-into-increasing-sequences.js
new file mode 100644
index 00000000..e36de1ad
--- /dev/null
+++ b/solutions/1121-divide-array-into-increasing-sequences.js
@@ -0,0 +1,26 @@
+/**
+ * 1121. Divide Array Into Increasing Sequences
+ * https://leetcode.com/problems/divide-array-into-increasing-sequences/
+ * Difficulty: Hard
+ *
+ * Given an integer array nums sorted in non-decreasing order and an integer k, return true
+ * if this array can be divided into one or more disjoint increasing subsequences of length
+ * at least k, or false otherwise.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {boolean}
+ */
+var canDivideIntoSubsequences = function(nums, k) {
+ let maxFrequency = 0;
+ let currentFrequency = 1;
+
+ for (let i = 1; i < nums.length; i++) {
+ currentFrequency = nums[i] === nums[i - 1] ? currentFrequency + 1 : 1;
+ maxFrequency = Math.max(maxFrequency, currentFrequency);
+ }
+
+ return k * maxFrequency <= nums.length;
+};
From 9bf4ed32d2696208a8d50d8ff2d3ce3bd3cb8aeb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 23:37:35 -0500
Subject: [PATCH 590/994] Add solution #1133
---
README.md | 1 +
solutions/1133-largest-unique-number.js | 29 +++++++++++++++++++++++++
2 files changed, 30 insertions(+)
create mode 100644 solutions/1133-largest-unique-number.js
diff --git a/README.md b/README.md
index ab502ff8..ad50fc72 100644
--- a/README.md
+++ b/README.md
@@ -1065,6 +1065,7 @@
1129|[Shortest Path with Alternating Colors](./solutions/1129-shortest-path-with-alternating-colors.js)|Medium|
1130|[Minimum Cost Tree From Leaf Values](./solutions/1130-minimum-cost-tree-from-leaf-values.js)|Medium|
1131|[Maximum of Absolute Value Expression](./solutions/1131-maximum-of-absolute-value-expression.js)|Medium|
+1133|[Largest Unique Number](./solutions/1133-largest-unique-number.js)|Easy|
1137|[N-th Tribonacci Number](./solutions/1137-n-th-tribonacci-number.js)|Easy|
1138|[Alphabet Board Path](./solutions/1138-alphabet-board-path.js)|Medium|
1139|[Largest 1-Bordered Square](./solutions/1139-largest-1-bordered-square.js)|Medium|
diff --git a/solutions/1133-largest-unique-number.js b/solutions/1133-largest-unique-number.js
new file mode 100644
index 00000000..7e731d63
--- /dev/null
+++ b/solutions/1133-largest-unique-number.js
@@ -0,0 +1,29 @@
+/**
+ * 1133. Largest Unique Number
+ * https://leetcode.com/problems/largest-unique-number/
+ * Difficulty: Easy
+ *
+ * Given an integer array nums, return the largest integer that only occurs once.
+ * If no integer occurs once, return -1.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var largestUniqueNumber = function(nums) {
+ const map = new Map();
+
+ for (const num of nums) {
+ map.set(num, (map.get(num) || 0) + 1);
+ }
+
+ let result = -1;
+ for (const [num, frequency] of map) {
+ if (frequency === 1) {
+ result = Math.max(result, num);
+ }
+ }
+
+ return result;
+};
From aed3ff3fd4e6bcfa3ed70aa43d8265a37ce0ee01 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 23:38:46 -0500
Subject: [PATCH 591/994] Add solution #1134
---
README.md | 1 +
solutions/1134-armstrong-number.js | 23 +++++++++++++++++++++++
2 files changed, 24 insertions(+)
create mode 100644 solutions/1134-armstrong-number.js
diff --git a/README.md b/README.md
index ad50fc72..8a2f6258 100644
--- a/README.md
+++ b/README.md
@@ -1066,6 +1066,7 @@
1130|[Minimum Cost Tree From Leaf Values](./solutions/1130-minimum-cost-tree-from-leaf-values.js)|Medium|
1131|[Maximum of Absolute Value Expression](./solutions/1131-maximum-of-absolute-value-expression.js)|Medium|
1133|[Largest Unique Number](./solutions/1133-largest-unique-number.js)|Easy|
+1134|[Armstrong Number](./solutions/1134-armstrong-number.js)|Easy|
1137|[N-th Tribonacci Number](./solutions/1137-n-th-tribonacci-number.js)|Easy|
1138|[Alphabet Board Path](./solutions/1138-alphabet-board-path.js)|Medium|
1139|[Largest 1-Bordered Square](./solutions/1139-largest-1-bordered-square.js)|Medium|
diff --git a/solutions/1134-armstrong-number.js b/solutions/1134-armstrong-number.js
new file mode 100644
index 00000000..cd4f9e33
--- /dev/null
+++ b/solutions/1134-armstrong-number.js
@@ -0,0 +1,23 @@
+/**
+ * 1134. Armstrong Number
+ * https://leetcode.com/problems/armstrong-number/
+ * Difficulty: Easy
+ *
+ * Given an integer n, return true if and only if it is an Armstrong number.
+ *
+ * The k-digit number n is an Armstrong number if and only if the kth power of each digit sums to n.
+ */
+
+/**
+ * @param {number} n
+ * @return {boolean}
+ */
+var isArmstrong = function(n) {
+ const digits = n.toString();
+ const digitCount = digits.length;
+ const digitSum = digits
+ .split('')
+ .reduce((sum, digit) => sum + Math.pow(parseInt(digit, 10), digitCount), 0);
+
+ return digitSum === n;
+};
From 59e49902205a4c0773602d5cd56e0fcf20bc693d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 23:39:58 -0500
Subject: [PATCH 592/994] Add solution #1135
---
README.md | 1 +
...135-connecting-cities-with-minimum-cost.js | 59 +++++++++++++++++++
2 files changed, 60 insertions(+)
create mode 100644 solutions/1135-connecting-cities-with-minimum-cost.js
diff --git a/README.md b/README.md
index 8a2f6258..ff65e8a1 100644
--- a/README.md
+++ b/README.md
@@ -1067,6 +1067,7 @@
1131|[Maximum of Absolute Value Expression](./solutions/1131-maximum-of-absolute-value-expression.js)|Medium|
1133|[Largest Unique Number](./solutions/1133-largest-unique-number.js)|Easy|
1134|[Armstrong Number](./solutions/1134-armstrong-number.js)|Easy|
+1135|[Connecting Cities With Minimum Cost](./solutions/1135-connecting-cities-with-minimum-cost.js)|Medium|
1137|[N-th Tribonacci Number](./solutions/1137-n-th-tribonacci-number.js)|Easy|
1138|[Alphabet Board Path](./solutions/1138-alphabet-board-path.js)|Medium|
1139|[Largest 1-Bordered Square](./solutions/1139-largest-1-bordered-square.js)|Medium|
diff --git a/solutions/1135-connecting-cities-with-minimum-cost.js b/solutions/1135-connecting-cities-with-minimum-cost.js
new file mode 100644
index 00000000..94f9062d
--- /dev/null
+++ b/solutions/1135-connecting-cities-with-minimum-cost.js
@@ -0,0 +1,59 @@
+/**
+ * 1135. Connecting Cities With Minimum Cost
+ * https://leetcode.com/problems/connecting-cities-with-minimum-cost/
+ * Difficulty: Medium
+ *
+ * There are n cities labeled from 1 to n. You are given the integer n and an array
+ * connections where connections[i] = [xi, yi, costi] indicates that the cost of connecting
+ * city xi and city yi (bidirectional connection) is costi.
+ *
+ * Return the minimum cost to connect all the n cities such that there is at least one path
+ * between each pair of cities. If it is impossible to connect all the n cities, return -1,
+ *
+ * The cost is the sum of the connections' costs used.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} connections
+ * @return {number}
+ */
+var minimumCost = function(n, connections) {
+ const parent = Array.from({ length: n + 1 }, (_, i) => i);
+
+ connections.sort((a, b) => a[2] - b[2]);
+
+ let totalCost = 0;
+ let edgesUsed = 0;
+
+ for (const [city1, city2, cost] of connections) {
+ if (union(city1, city2)) {
+ totalCost += cost;
+ edgesUsed++;
+
+ if (edgesUsed === n - 1) {
+ return totalCost;
+ }
+ }
+ }
+
+ return -1;
+
+ function findParent(x) {
+ if (parent[x] !== x) {
+ parent[x] = findParent(parent[x]);
+ }
+ return parent[x];
+ }
+
+ function union(x, y) {
+ const rootX = findParent(x);
+ const rootY = findParent(y);
+
+ if (rootX !== rootY) {
+ parent[rootX] = rootY;
+ return true;
+ }
+ return false;
+ }
+};
From 006d38603614b7d9b35b40bfaba99306bfcdd411 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 23:40:59 -0500
Subject: [PATCH 593/994] Add solution #1136
---
README.md | 1 +
solutions/1136-parallel-courses.js | 64 ++++++++++++++++++++++++++++++
2 files changed, 65 insertions(+)
create mode 100644 solutions/1136-parallel-courses.js
diff --git a/README.md b/README.md
index ff65e8a1..9d8920be 100644
--- a/README.md
+++ b/README.md
@@ -1068,6 +1068,7 @@
1133|[Largest Unique Number](./solutions/1133-largest-unique-number.js)|Easy|
1134|[Armstrong Number](./solutions/1134-armstrong-number.js)|Easy|
1135|[Connecting Cities With Minimum Cost](./solutions/1135-connecting-cities-with-minimum-cost.js)|Medium|
+1136|[Parallel Courses](./solutions/1136-parallel-courses.js)|Medium|
1137|[N-th Tribonacci Number](./solutions/1137-n-th-tribonacci-number.js)|Easy|
1138|[Alphabet Board Path](./solutions/1138-alphabet-board-path.js)|Medium|
1139|[Largest 1-Bordered Square](./solutions/1139-largest-1-bordered-square.js)|Medium|
diff --git a/solutions/1136-parallel-courses.js b/solutions/1136-parallel-courses.js
new file mode 100644
index 00000000..121eaf3f
--- /dev/null
+++ b/solutions/1136-parallel-courses.js
@@ -0,0 +1,64 @@
+/**
+ * 1136. Parallel Courses
+ * https://leetcode.com/problems/parallel-courses/
+ * Difficulty: Medium
+ *
+ * You are given an integer n, which indicates that there are n courses labeled from 1 to n.
+ * You are also given an array relations where relations[i] = [prevCoursei, nextCoursei],
+ * representing a prerequisite relationship between course prevCoursei and course
+ * nextCoursei: course prevCoursei has to be taken before course nextCoursei.
+ *
+ * In one semester, you can take any number of courses as long as you have taken all the
+ * prerequisites in the previous semester for the courses you are taking.
+ *
+ * Return the minimum number of semesters needed to take all courses. If there is no way to
+ * take all the courses, return -1.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} relations
+ * @return {number}
+ */
+var minimumSemesters = function(n, relations) {
+ const graph = new Map();
+ const indegree = new Array(n + 1).fill(0);
+
+ for (let i = 1; i <= n; i++) {
+ graph.set(i, []);
+ }
+
+ for (const [prev, next] of relations) {
+ graph.get(prev).push(next);
+ indegree[next]++;
+ }
+
+ const queue = [];
+ for (let i = 1; i <= n; i++) {
+ if (indegree[i] === 0) {
+ queue.push(i);
+ }
+ }
+
+ let semesters = 0;
+ let coursesCompleted = 0;
+
+ while (queue.length > 0) {
+ const currentSemesterSize = queue.length;
+ semesters++;
+
+ for (let i = 0; i < currentSemesterSize; i++) {
+ const course = queue.shift();
+ coursesCompleted++;
+
+ for (const nextCourse of graph.get(course)) {
+ indegree[nextCourse]--;
+ if (indegree[nextCourse] === 0) {
+ queue.push(nextCourse);
+ }
+ }
+ }
+ }
+
+ return coursesCompleted === n ? semesters : -1;
+};
From 8517758bc7f9cbb73879e816f450f50be9e12bd3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 23:42:27 -0500
Subject: [PATCH 594/994] Add solution #1150
---
README.md | 1 +
...r-is-majority-element-in-a-sorted-array.js | 56 +++++++++++++++++++
2 files changed, 57 insertions(+)
create mode 100644 solutions/1150-check-if-a-number-is-majority-element-in-a-sorted-array.js
diff --git a/README.md b/README.md
index 9d8920be..4c2b716d 100644
--- a/README.md
+++ b/README.md
@@ -1078,6 +1078,7 @@
1145|[Binary Tree Coloring Game](./solutions/1145-binary-tree-coloring-game.js)|Medium|
1146|[Snapshot Array](./solutions/1146-snapshot-array.js)|Medium|
1147|[Longest Chunked Palindrome Decomposition](./solutions/1147-longest-chunked-palindrome-decomposition.js)|Hard|
+1150|[Check If a Number Is Majority Element in a Sorted Array](./solutions/1150-check-if-a-number-is-majority-element-in-a-sorted-array.js)|Easy|
1154|[Day of the Year](./solutions/1154-day-of-the-year.js)|Easy|
1155|[Number of Dice Rolls With Target Sum](./solutions/1155-number-of-dice-rolls-with-target-sum.js)|Medium|
1156|[Swap For Longest Repeated Character Substring](./solutions/1156-swap-for-longest-repeated-character-substring.js)|Medium|
diff --git a/solutions/1150-check-if-a-number-is-majority-element-in-a-sorted-array.js b/solutions/1150-check-if-a-number-is-majority-element-in-a-sorted-array.js
new file mode 100644
index 00000000..87414163
--- /dev/null
+++ b/solutions/1150-check-if-a-number-is-majority-element-in-a-sorted-array.js
@@ -0,0 +1,56 @@
+/**
+ * 1150. Check If a Number Is Majority Element in a Sorted Array
+ * https://leetcode.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array/
+ * Difficulty: Easy
+ *
+ * Given an integer array nums sorted in non-decreasing order and an integer target, return true
+ * if target is a majority element, or false otherwise.
+ *
+ * A majority element in an array nums is an element that appears more than nums.length / 2 times
+ * in the array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} target
+ * @return {boolean}
+ */
+var isMajorityElement = function(nums, target) {
+ const firstIndex = findFirstIndex(target);
+ if (firstIndex >= nums.length || nums[firstIndex] !== target) {
+ return false;
+ }
+
+ const lastIndex = findLastIndex(target);
+ const frequency = lastIndex - firstIndex + 1;
+
+ return frequency > nums.length / 2;
+
+ function findFirstIndex(target) {
+ let left = 0;
+ let right = nums.length;
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (nums[mid] < target) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+ return left;
+ }
+
+ function findLastIndex(target) {
+ let left = 0;
+ let right = nums.length;
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (nums[mid] <= target) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+ return left - 1;
+ }
+};
From cf9a05e8490f27b93aded930b46d71037c874c2c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 23:43:21 -0500
Subject: [PATCH 595/994] Add solution #1151
---
README.md | 1 +
...-minimum-swaps-to-group-all-1s-together.js | 32 +++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/1151-minimum-swaps-to-group-all-1s-together.js
diff --git a/README.md b/README.md
index 4c2b716d..0fc5cf93 100644
--- a/README.md
+++ b/README.md
@@ -1079,6 +1079,7 @@
1146|[Snapshot Array](./solutions/1146-snapshot-array.js)|Medium|
1147|[Longest Chunked Palindrome Decomposition](./solutions/1147-longest-chunked-palindrome-decomposition.js)|Hard|
1150|[Check If a Number Is Majority Element in a Sorted Array](./solutions/1150-check-if-a-number-is-majority-element-in-a-sorted-array.js)|Easy|
+1151|[Minimum Swaps to Group All 1's Together](./solutions/1151-minimum-swaps-to-group-all-1s-together.js)|Medium|
1154|[Day of the Year](./solutions/1154-day-of-the-year.js)|Easy|
1155|[Number of Dice Rolls With Target Sum](./solutions/1155-number-of-dice-rolls-with-target-sum.js)|Medium|
1156|[Swap For Longest Repeated Character Substring](./solutions/1156-swap-for-longest-repeated-character-substring.js)|Medium|
diff --git a/solutions/1151-minimum-swaps-to-group-all-1s-together.js b/solutions/1151-minimum-swaps-to-group-all-1s-together.js
new file mode 100644
index 00000000..5e923a94
--- /dev/null
+++ b/solutions/1151-minimum-swaps-to-group-all-1s-together.js
@@ -0,0 +1,32 @@
+/**
+ * 1151. Minimum Swaps to Group All 1's Together
+ * https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together/
+ * Difficulty: Medium
+ *
+ * Given a binary array data, return the minimum number of swaps required to group all
+ * 1’s present in the array together in any place in the array.
+ */
+
+/**
+ * @param {number[]} data
+ * @return {number}
+ */
+var minSwaps = function(data) {
+ const totalOnes = data.reduce((sum, val) => sum + val, 0);
+
+ if (totalOnes <= 1) return 0;
+
+ let currentOnes = 0;
+ for (let i = 0; i < totalOnes; i++) {
+ currentOnes += data[i];
+ }
+
+ let maxOnes = currentOnes;
+
+ for (let i = totalOnes; i < data.length; i++) {
+ currentOnes = currentOnes - data[i - totalOnes] + data[i];
+ maxOnes = Math.max(maxOnes, currentOnes);
+ }
+
+ return totalOnes - maxOnes;
+};
From a02ddc1d18ec5c7ee39570950245b109472bb009 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 23:53:30 -0500
Subject: [PATCH 596/994] Add solution #1152
---
README.md | 1 +
...1152-analyze-user-website-visit-pattern.js | 88 +++++++++++++++++++
2 files changed, 89 insertions(+)
create mode 100644 solutions/1152-analyze-user-website-visit-pattern.js
diff --git a/README.md b/README.md
index 0fc5cf93..70bdf127 100644
--- a/README.md
+++ b/README.md
@@ -1080,6 +1080,7 @@
1147|[Longest Chunked Palindrome Decomposition](./solutions/1147-longest-chunked-palindrome-decomposition.js)|Hard|
1150|[Check If a Number Is Majority Element in a Sorted Array](./solutions/1150-check-if-a-number-is-majority-element-in-a-sorted-array.js)|Easy|
1151|[Minimum Swaps to Group All 1's Together](./solutions/1151-minimum-swaps-to-group-all-1s-together.js)|Medium|
+1152|[Analyze User Website Visit Pattern](./solutions/1152-analyze-user-website-visit-pattern.js)|Medium|
1154|[Day of the Year](./solutions/1154-day-of-the-year.js)|Easy|
1155|[Number of Dice Rolls With Target Sum](./solutions/1155-number-of-dice-rolls-with-target-sum.js)|Medium|
1156|[Swap For Longest Repeated Character Substring](./solutions/1156-swap-for-longest-repeated-character-substring.js)|Medium|
diff --git a/solutions/1152-analyze-user-website-visit-pattern.js b/solutions/1152-analyze-user-website-visit-pattern.js
new file mode 100644
index 00000000..fae12ef7
--- /dev/null
+++ b/solutions/1152-analyze-user-website-visit-pattern.js
@@ -0,0 +1,88 @@
+/**
+ * 1152. Analyze User Website Visit Pattern
+ * https://leetcode.com/problems/analyze-user-website-visit-pattern/
+ * Difficulty: Medium
+ *
+ * You are given two string arrays username and website and an integer array timestamp.
+ * All the given arrays are of the same length and the tuple [username[i], website[i],
+ * timestamp[i]] indicates that the user username[i] visited the website website[i] at
+ * time timestamp[i].
+ *
+ * A pattern is a list of three websites (not necessarily distinct).
+ * - For example, ["home", "away", "love"], ["leetcode", "love", "leetcode"],
+ * and ["luffy", "luffy", "luffy"] are all patterns.
+ *
+ * The score of a pattern is the number of users that visited all the websites in the
+ * pattern in the same order they appeared in the pattern.
+ * - For example, if the pattern is ["home", "away", "love"], the score is the number of
+ * users x such that x visited "home" then visited "away" and visited "love" after that.
+ * - Similarly, if the pattern is ["leetcode", "love", "leetcode"], the score is the number
+ * of users x such that x visited "leetcode" then visited "love" and visited "leetcode"
+ * one more time after that.
+ * - Also, if the pattern is ["luffy", "luffy", "luffy"], the score is the number of users
+ * x such that x visited "luffy" three different times at different timestamps.
+ *
+ * Return the pattern with the largest score. If there is more than one pattern with the
+ * same largest score, return the lexicographically smallest such pattern.
+ *
+ * Note that the websites in a pattern do not need to be visited contiguously, they only
+ * need to be visited in the order they appeared in the pattern.
+ */
+
+/**
+ * @param {string[]} username
+ * @param {number[]} timestamp
+ * @param {string[]} website
+ * @return {string[]}
+ */
+var mostVisitedPattern = function(username, timestamp, website) {
+ const visitData = username.map((user, i) => ({
+ user,
+ time: timestamp[i],
+ site: website[i]
+ }));
+
+ visitData.sort((a, b) => a.time - b.time);
+
+ const userVisits = new Map();
+
+ for (const visit of visitData) {
+ if (!userVisits.has(visit.user)) {
+ userVisits.set(visit.user, []);
+ }
+ userVisits.get(visit.user).push(visit.site);
+ }
+
+ const patternCounts = new Map();
+
+ for (const [user, sites] of userVisits) {
+ if (sites.length < 3) continue;
+
+ const userPatterns = new Set();
+
+ for (let i = 0; i < sites.length - 2; i++) {
+ for (let j = i + 1; j < sites.length - 1; j++) {
+ for (let k = j + 1; k < sites.length; k++) {
+ const pattern = [sites[i], sites[j], sites[k]].join(',');
+ userPatterns.add(pattern);
+ }
+ }
+ }
+
+ for (const pattern of userPatterns) {
+ patternCounts.set(pattern, (patternCounts.get(pattern) || 0) + 1);
+ }
+ }
+
+ let maxCount = 0;
+ let bestPattern = '';
+
+ for (const [pattern, count] of patternCounts) {
+ if (count > maxCount || (count === maxCount && pattern < bestPattern)) {
+ maxCount = count;
+ bestPattern = pattern;
+ }
+ }
+
+ return bestPattern.split(',');
+};
From eafee234e70577eb4818ae566bf09ca2cf1dc8d1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 23:54:43 -0500
Subject: [PATCH 597/994] Add solution #1153
---
README.md | 1 +
...3-string-transforms-into-another-string.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/1153-string-transforms-into-another-string.js
diff --git a/README.md b/README.md
index 70bdf127..4208bf31 100644
--- a/README.md
+++ b/README.md
@@ -1081,6 +1081,7 @@
1150|[Check If a Number Is Majority Element in a Sorted Array](./solutions/1150-check-if-a-number-is-majority-element-in-a-sorted-array.js)|Easy|
1151|[Minimum Swaps to Group All 1's Together](./solutions/1151-minimum-swaps-to-group-all-1s-together.js)|Medium|
1152|[Analyze User Website Visit Pattern](./solutions/1152-analyze-user-website-visit-pattern.js)|Medium|
+1153|[String Transforms Into Another String](./solutions/1153-string-transforms-into-another-string.js)|Hard|
1154|[Day of the Year](./solutions/1154-day-of-the-year.js)|Easy|
1155|[Number of Dice Rolls With Target Sum](./solutions/1155-number-of-dice-rolls-with-target-sum.js)|Medium|
1156|[Swap For Longest Repeated Character Substring](./solutions/1156-swap-for-longest-repeated-character-substring.js)|Medium|
diff --git a/solutions/1153-string-transforms-into-another-string.js b/solutions/1153-string-transforms-into-another-string.js
new file mode 100644
index 00000000..e677e77e
--- /dev/null
+++ b/solutions/1153-string-transforms-into-another-string.js
@@ -0,0 +1,41 @@
+/**
+ * 1153. String Transforms Into Another String
+ * https://leetcode.com/problems/string-transforms-into-another-string/
+ * Difficulty: Hard
+ *
+ * Given two strings str1 and str2 of the same length, determine whether you can transform
+ * str1 into str2 by doing zero or more conversions.
+ *
+ * In one conversion you can convert all occurrences of one character in str1 to any other
+ * lowercase English character.
+ *
+ * Return true if and only if you can transform str1 into str2.
+ */
+
+/**
+ * @param {string} str1
+ * @param {string} str2
+ * @return {boolean}
+ */
+var canConvert = function(str1, str2) {
+ if (str1 === str2) return true;
+
+ const mapping = new Map();
+ const uniqueCharsInStr2 = new Set();
+ for (let i = 0; i < str1.length; i++) {
+ const char1 = str1[i];
+ const char2 = str2[i];
+
+ if (mapping.has(char1)) {
+ if (mapping.get(char1) !== char2) {
+ return false;
+ }
+ } else {
+ mapping.set(char1, char2);
+ }
+
+ uniqueCharsInStr2.add(char2);
+ }
+
+ return uniqueCharsInStr2.size < 26;
+};
From a57b9702c1fa6b8f759f13849a7b4c5960db7684 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 23:56:00 -0500
Subject: [PATCH 598/994] Add solution #1165
---
README.md | 1 +
solutions/1165-single-row-keyboard.js | 39 +++++++++++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/1165-single-row-keyboard.js
diff --git a/README.md b/README.md
index 4208bf31..f9bdf040 100644
--- a/README.md
+++ b/README.md
@@ -1090,6 +1090,7 @@
1161|[Maximum Level Sum of a Binary Tree](./solutions/1161-maximum-level-sum-of-a-binary-tree.js)|Medium|
1162|[As Far from Land as Possible](./solutions/1162-as-far-from-land-as-possible.js)|Medium|
1163|[Last Substring in Lexicographical Order](./solutions/1163-last-substring-in-lexicographical-order.js)|Hard|
+1165|[Single-Row Keyboard](./solutions/1165-single-row-keyboard.js)|Easy|
1169|[Invalid Transactions](./solutions/1169-invalid-transactions.js)|Medium|
1170|[Compare Strings by Frequency of the Smallest Character](./solutions/1170-compare-strings-by-frequency-of-the-smallest-character.js)|Medium|
1171|[Remove Zero Sum Consecutive Nodes from Linked List](./solutions/1171-remove-zero-sum-consecutive-nodes-from-linked-list.js)|Medium|
diff --git a/solutions/1165-single-row-keyboard.js b/solutions/1165-single-row-keyboard.js
new file mode 100644
index 00000000..58c34abc
--- /dev/null
+++ b/solutions/1165-single-row-keyboard.js
@@ -0,0 +1,39 @@
+/**
+ * 1165. Single-Row Keyboard
+ * https://leetcode.com/problems/single-row-keyboard/
+ * Difficulty: Easy
+ *
+ * There is a special keyboard with all keys in a single row.
+ *
+ * Given a string keyboard of length 26 indicating the layout of the keyboard (indexed
+ * from 0 to 25). Initially, your finger is at index 0. To type a character, you have
+ * to move your finger to the index of the desired character. The time taken to move
+ * your finger from index i to index j is |i - j|.
+ *
+ * You want to type a string word. Write a function to calculate how much time it takes
+ * to type it with one finger.
+ */
+
+/**
+ * @param {string} keyboard
+ * @param {string} word
+ * @return {number}
+ */
+var calculateTime = function(keyboard, word) {
+ const map = new Map();
+
+ for (let i = 0; i < keyboard.length; i++) {
+ map.set(keyboard[i], i);
+ }
+
+ let currentPosition = 0;
+ let result = 0;
+
+ for (const char of word) {
+ const targetPosition = map.get(char);
+ result += Math.abs(currentPosition - targetPosition);
+ currentPosition = targetPosition;
+ }
+
+ return result;
+};
From d9a3afc6e82f3d75c9ac007587c0b926b50f9551 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 23:57:55 -0500
Subject: [PATCH 599/994] Add solution #1166
---
README.md | 1 +
solutions/1166-design-file-system.js | 52 ++++++++++++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 solutions/1166-design-file-system.js
diff --git a/README.md b/README.md
index f9bdf040..82d6c98b 100644
--- a/README.md
+++ b/README.md
@@ -1091,6 +1091,7 @@
1162|[As Far from Land as Possible](./solutions/1162-as-far-from-land-as-possible.js)|Medium|
1163|[Last Substring in Lexicographical Order](./solutions/1163-last-substring-in-lexicographical-order.js)|Hard|
1165|[Single-Row Keyboard](./solutions/1165-single-row-keyboard.js)|Easy|
+1166|[Design File System](./solutions/1166-design-file-system.js)|Medium|
1169|[Invalid Transactions](./solutions/1169-invalid-transactions.js)|Medium|
1170|[Compare Strings by Frequency of the Smallest Character](./solutions/1170-compare-strings-by-frequency-of-the-smallest-character.js)|Medium|
1171|[Remove Zero Sum Consecutive Nodes from Linked List](./solutions/1171-remove-zero-sum-consecutive-nodes-from-linked-list.js)|Medium|
diff --git a/solutions/1166-design-file-system.js b/solutions/1166-design-file-system.js
new file mode 100644
index 00000000..71af7964
--- /dev/null
+++ b/solutions/1166-design-file-system.js
@@ -0,0 +1,52 @@
+/**
+ * 1166. Design File System
+ * https://leetcode.com/problems/design-file-system/
+ * Difficulty: Medium
+ *
+ * You are asked to design a file system that allows you to create new paths and associate
+ * them with different values.
+ *
+ * The format of a path is one or more concatenated strings of the form: / followed by one
+ * or more lowercase English letters. For example, "/leetcode" and "/leetcode/problems" are
+ * valid paths while an empty string "" and "/" are not.
+ *
+ * Implement the FileSystem class:
+ * - bool createPath(string path, int value) Creates a new path and associates a value to it
+ * if possible and returns true. Returns false if the path already exists or its parent path
+ * doesn't exist.
+ * - int get(string path) Returns the value associated with path or returns -1 if the path
+ * doesn't exist.
+ */
+
+var FileSystem = function() {
+ this.pathMap = new Map();
+};
+
+/**
+ * @param {string} path
+ * @param {number} value
+ * @return {boolean}
+ */
+FileSystem.prototype.createPath = function(path, value) {
+ if (this.pathMap.has(path)) {
+ return false;
+ }
+
+ const lastSlashIndex = path.lastIndexOf('/');
+ const parentPath = path.substring(0, lastSlashIndex);
+
+ if (parentPath.length > 0 && !this.pathMap.has(parentPath)) {
+ return false;
+ }
+
+ this.pathMap.set(path, value);
+ return true;
+};
+
+/**
+ * @param {string} path
+ * @return {number}
+ */
+FileSystem.prototype.get = function(path) {
+ return this.pathMap.get(path) ?? -1;
+};
From 65ef1ec3312182190c088dd0256f6cad47fe973e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 27 Jun 2025 23:59:10 -0500
Subject: [PATCH 600/994] Add solution #1167
---
README.md | 1 +
.../1167-minimum-cost-to-connect-sticks.js | 38 +++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/1167-minimum-cost-to-connect-sticks.js
diff --git a/README.md b/README.md
index 82d6c98b..3cddb2e4 100644
--- a/README.md
+++ b/README.md
@@ -1092,6 +1092,7 @@
1163|[Last Substring in Lexicographical Order](./solutions/1163-last-substring-in-lexicographical-order.js)|Hard|
1165|[Single-Row Keyboard](./solutions/1165-single-row-keyboard.js)|Easy|
1166|[Design File System](./solutions/1166-design-file-system.js)|Medium|
+1167|[Minimum Cost to Connect Sticks](./solutions/1167-minimum-cost-to-connect-sticks.js)|Medium|
1169|[Invalid Transactions](./solutions/1169-invalid-transactions.js)|Medium|
1170|[Compare Strings by Frequency of the Smallest Character](./solutions/1170-compare-strings-by-frequency-of-the-smallest-character.js)|Medium|
1171|[Remove Zero Sum Consecutive Nodes from Linked List](./solutions/1171-remove-zero-sum-consecutive-nodes-from-linked-list.js)|Medium|
diff --git a/solutions/1167-minimum-cost-to-connect-sticks.js b/solutions/1167-minimum-cost-to-connect-sticks.js
new file mode 100644
index 00000000..db2ee2b4
--- /dev/null
+++ b/solutions/1167-minimum-cost-to-connect-sticks.js
@@ -0,0 +1,38 @@
+/**
+ * 1167. Minimum Cost to Connect Sticks
+ * https://leetcode.com/problems/minimum-cost-to-connect-sticks/
+ * Difficulty: Medium
+ *
+ * You have some number of sticks with positive integer lengths. These lengths are given as
+ * an array sticks, where sticks[i] is the length of the ith stick.
+ *
+ * You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y.
+ * You must connect all the sticks until there is only one stick remaining.
+ *
+ * Return the minimum cost of connecting all the given sticks into one stick in this way.
+ */
+
+/**
+ * @param {number[]} sticks
+ * @return {number}
+ */
+var connectSticks = function(sticks) {
+ const minHeap = [...sticks].sort((a, b) => a - b);
+ let result = 0;
+
+ while (minHeap.length > 1) {
+ const first = minHeap.shift();
+ const second = minHeap.shift();
+ const combinedCost = first + second;
+
+ result += combinedCost;
+
+ let insertIndex = 0;
+ while (insertIndex < minHeap.length && minHeap[insertIndex] < combinedCost) {
+ insertIndex++;
+ }
+ minHeap.splice(insertIndex, 0, combinedCost);
+ }
+
+ return result;
+};
From 9446c8c2c89235320c47cbe5b9868567fff6acb3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 00:12:16 -0500
Subject: [PATCH 601/994] Add solution #1168
---
README.md | 1 +
...ptimize-water-distribution-in-a-village.js | 68 +++++++++++++++++++
2 files changed, 69 insertions(+)
create mode 100644 solutions/1168-optimize-water-distribution-in-a-village.js
diff --git a/README.md b/README.md
index 3cddb2e4..8111aa92 100644
--- a/README.md
+++ b/README.md
@@ -1093,6 +1093,7 @@
1165|[Single-Row Keyboard](./solutions/1165-single-row-keyboard.js)|Easy|
1166|[Design File System](./solutions/1166-design-file-system.js)|Medium|
1167|[Minimum Cost to Connect Sticks](./solutions/1167-minimum-cost-to-connect-sticks.js)|Medium|
+1168|[Optimize Water Distribution in a Village](./solutions/1168-optimize-water-distribution-in-a-village.js)|Hard|
1169|[Invalid Transactions](./solutions/1169-invalid-transactions.js)|Medium|
1170|[Compare Strings by Frequency of the Smallest Character](./solutions/1170-compare-strings-by-frequency-of-the-smallest-character.js)|Medium|
1171|[Remove Zero Sum Consecutive Nodes from Linked List](./solutions/1171-remove-zero-sum-consecutive-nodes-from-linked-list.js)|Medium|
diff --git a/solutions/1168-optimize-water-distribution-in-a-village.js b/solutions/1168-optimize-water-distribution-in-a-village.js
new file mode 100644
index 00000000..74be1b50
--- /dev/null
+++ b/solutions/1168-optimize-water-distribution-in-a-village.js
@@ -0,0 +1,68 @@
+/**
+ * 1168. Optimize Water Distribution in a Village
+ * https://leetcode.com/problems/optimize-water-distribution-in-a-village/
+ * Difficulty: Hard
+ *
+ * There are n houses in a village. We want to supply water for all the houses by building
+ * wells and laying pipes.
+ *
+ * For each house i, we can either build a well inside it directly with cost wells[i - 1]
+ * (note the -1 due to 0-indexing), or pipe in water from another well to it. The costs
+ * to lay pipes between houses are given by the array pipes where each
+ * pipes[j] = [house1j, house2j, costj] represents the cost to connect house1j and house2j
+ * together using a pipe. Connections are bidirectional, and there could be multiple valid
+ * connections between the same two houses with different costs.
+ *
+ * Return the minimum total cost to supply water to all houses.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[]} wells
+ * @param {number[][]} pipes
+ * @return {number}
+ */
+var minCostToSupplyWater = function(n, wells, pipes) {
+ const edges = [];
+
+ for (let i = 0; i < n; i++) {
+ edges.push([0, i + 1, wells[i]]);
+ }
+
+ for (const [house1, house2, cost] of pipes) {
+ edges.push([house1, house2, cost]);
+ }
+
+ edges.sort((a, b) => a[2] - b[2]);
+
+ const parent = Array.from({ length: n + 1 }, (_, i) => i);
+ let result = 0;
+ let edgesUsed = 0;
+
+ for (const [from, to, cost] of edges) {
+ if (union(from, to)) {
+ result += cost;
+ edgesUsed++;
+ if (edgesUsed === n) break;
+ }
+ }
+
+ return result;
+
+ function find(x) {
+ if (parent[x] !== x) {
+ parent[x] = find(parent[x]);
+ }
+ return parent[x];
+ }
+
+ function union(x, y) {
+ const rootX = find(x);
+ const rootY = find(y);
+ if (rootX !== rootY) {
+ parent[rootX] = rootY;
+ return true;
+ }
+ return false;
+ }
+};
From 57cb06417eb0b11f7c2d5f949259ac1cf13a85e9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 00:13:29 -0500
Subject: [PATCH 602/994] Add solution #1176
---
README.md | 1 +
solutions/1176-diet-plan-performance.js | 48 +++++++++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/1176-diet-plan-performance.js
diff --git a/README.md b/README.md
index 8111aa92..50b4fa09 100644
--- a/README.md
+++ b/README.md
@@ -1099,6 +1099,7 @@
1171|[Remove Zero Sum Consecutive Nodes from Linked List](./solutions/1171-remove-zero-sum-consecutive-nodes-from-linked-list.js)|Medium|
1172|[Dinner Plate Stacks](./solutions/1172-dinner-plate-stacks.js)|Hard|
1175|[Prime Arrangements](./solutions/1175-prime-arrangements.js)|Easy|
+1176|[Diet Plan Performance](./solutions/1176-diet-plan-performance.js)|Easy|
1177|[Can Make Palindrome from Substring](./solutions/1177-can-make-palindrome-from-substring.js)|Medium|
1178|[Number of Valid Words for Each Puzzle](./solutions/1178-number-of-valid-words-for-each-puzzle.js)|Hard|
1184|[Distance Between Bus Stops](./solutions/1184-distance-between-bus-stops.js)|Easy|
diff --git a/solutions/1176-diet-plan-performance.js b/solutions/1176-diet-plan-performance.js
new file mode 100644
index 00000000..4bb18c83
--- /dev/null
+++ b/solutions/1176-diet-plan-performance.js
@@ -0,0 +1,48 @@
+/**
+ * 1176. Diet Plan Performance
+ * https://leetcode.com/problems/diet-plan-performance/
+ * Difficulty: Easy
+ *
+ * A dieter consumes calories[i] calories on the i-th day.
+ *
+ * Given an integer k, for every consecutive sequence of k days
+ * (calories[i], calories[i+1], ..., calories[i+k-1] for all 0 <= i <= n-k),
+ * they look at T, the total calories consumed during that sequence of k days
+ * (calories[i] + calories[i+1] + ... + calories[i+k-1]):
+ * - If T < lower, they performed poorly on their diet and lose 1 point;
+ * - If T > upper, they performed well on their diet and gain 1 point;
+ * - Otherwise, they performed normally and there is no change in points.
+ *
+ * Initially, the dieter has zero points. Return the total number of points the dieter
+ * has after dieting for calories.length days.
+ *
+ * Note that the total points can be negative.
+ */
+
+/**
+ * @param {number[]} calories
+ * @param {number} k
+ * @param {number} lower
+ * @param {number} upper
+ * @return {number}
+ */
+var dietPlanPerformance = function(calories, k, lower, upper) {
+ let windowSum = 0;
+ let points = 0;
+
+ for (let i = 0; i < k; i++) {
+ windowSum += calories[i];
+ }
+
+ if (windowSum < lower) points--;
+ else if (windowSum > upper) points++;
+
+ for (let i = k; i < calories.length; i++) {
+ windowSum = windowSum - calories[i - k] + calories[i];
+
+ if (windowSum < lower) points--;
+ else if (windowSum > upper) points++;
+ }
+
+ return points;
+};
From c1d104efa13a780b4a21a1e0bc6bad57a2264cd8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 00:14:17 -0500
Subject: [PATCH 603/994] Add solution #1180
---
README.md | 1 +
...ubstrings-with-only-one-distinct-letter.js | 29 +++++++++++++++++++
2 files changed, 30 insertions(+)
create mode 100644 solutions/1180-count-substrings-with-only-one-distinct-letter.js
diff --git a/README.md b/README.md
index 50b4fa09..a064f496 100644
--- a/README.md
+++ b/README.md
@@ -1102,6 +1102,7 @@
1176|[Diet Plan Performance](./solutions/1176-diet-plan-performance.js)|Easy|
1177|[Can Make Palindrome from Substring](./solutions/1177-can-make-palindrome-from-substring.js)|Medium|
1178|[Number of Valid Words for Each Puzzle](./solutions/1178-number-of-valid-words-for-each-puzzle.js)|Hard|
+1180|[Count Substrings with Only One Distinct Letter](./solutions/1180-count-substrings-with-only-one-distinct-letter.js)|Easy|
1184|[Distance Between Bus Stops](./solutions/1184-distance-between-bus-stops.js)|Easy|
1185|[Day of the Week](./solutions/1185-day-of-the-week.js)|Easy|
1186|[Maximum Subarray Sum with One Deletion](./solutions/1186-maximum-subarray-sum-with-one-deletion.js)|Medium|
diff --git a/solutions/1180-count-substrings-with-only-one-distinct-letter.js b/solutions/1180-count-substrings-with-only-one-distinct-letter.js
new file mode 100644
index 00000000..4d61be97
--- /dev/null
+++ b/solutions/1180-count-substrings-with-only-one-distinct-letter.js
@@ -0,0 +1,29 @@
+/**
+ * 1180. Count Substrings with Only One Distinct Letter
+ * https://leetcode.com/problems/count-substrings-with-only-one-distinct-letter/
+ * Difficulty: Easy
+ *
+ * Given a string s, return the number of substrings that have only one distinct letter.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var countLetters = function(s) {
+ let result = 0;
+ let consecutiveCount = 1;
+
+ for (let i = 1; i < s.length; i++) {
+ if (s[i] === s[i - 1]) {
+ consecutiveCount++;
+ } else {
+ result += (consecutiveCount * (consecutiveCount + 1)) / 2;
+ consecutiveCount = 1;
+ }
+ }
+
+ result += (consecutiveCount * (consecutiveCount + 1)) / 2;
+
+ return result;
+};
From fe908fc84c55d92fe71673b97e7bbab26ba672df Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 00:15:31 -0500
Subject: [PATCH 604/994] Add solution #1181
---
README.md | 1 +
solutions/1181-before-and-after-puzzle.js | 46 +++++++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/1181-before-and-after-puzzle.js
diff --git a/README.md b/README.md
index a064f496..5d652fc2 100644
--- a/README.md
+++ b/README.md
@@ -1103,6 +1103,7 @@
1177|[Can Make Palindrome from Substring](./solutions/1177-can-make-palindrome-from-substring.js)|Medium|
1178|[Number of Valid Words for Each Puzzle](./solutions/1178-number-of-valid-words-for-each-puzzle.js)|Hard|
1180|[Count Substrings with Only One Distinct Letter](./solutions/1180-count-substrings-with-only-one-distinct-letter.js)|Easy|
+1181|[Before and After Puzzle](./solutions/1181-before-and-after-puzzle.js)|Medium|
1184|[Distance Between Bus Stops](./solutions/1184-distance-between-bus-stops.js)|Easy|
1185|[Day of the Week](./solutions/1185-day-of-the-week.js)|Easy|
1186|[Maximum Subarray Sum with One Deletion](./solutions/1186-maximum-subarray-sum-with-one-deletion.js)|Medium|
diff --git a/solutions/1181-before-and-after-puzzle.js b/solutions/1181-before-and-after-puzzle.js
new file mode 100644
index 00000000..9aa544b9
--- /dev/null
+++ b/solutions/1181-before-and-after-puzzle.js
@@ -0,0 +1,46 @@
+/**
+ * 1181. Before and After Puzzle
+ * https://leetcode.com/problems/before-and-after-puzzle/
+ * Difficulty: Medium
+ *
+ * Given a list of phrases, generate a list of Before and After puzzles.
+ *
+ * A phrase is a string that consists of lowercase English letters and spaces only. No
+ * space appears in the start or the end of a phrase. There are no consecutive spaces
+ * in a phrase.
+ *
+ * Before and After puzzles are phrases that are formed by merging two phrases where the
+ * last word of the first phrase is the same as the first word of the second phrase.
+ *
+ * Return the Before and After puzzles that can be formed by every two phrases phrases[i]
+ * and phrases[j] where i != j. Note that the order of matching two phrases matters, we
+ * want to consider both orders.
+ *
+ * You should return a list of distinct strings sorted lexicographically.
+ */
+
+/**
+ * @param {string[]} phrases
+ * @return {string[]}
+ */
+var beforeAndAfterPuzzles = function(phrases) {
+ const set = new Set();
+
+ for (let i = 0; i < phrases.length; i++) {
+ for (let j = 0; j < phrases.length; j++) {
+ if (i !== j) {
+ const firstWords = phrases[i].split(' ');
+ const secondWords = phrases[j].split(' ');
+
+ const lastWordFirst = firstWords[firstWords.length - 1];
+ const firstWordSecond = secondWords[0];
+ if (lastWordFirst === firstWordSecond) {
+ const merged = firstWords.concat(secondWords.slice(1)).join(' ');
+ set.add(merged);
+ }
+ }
+ }
+ }
+
+ return Array.from(set).sort();
+};
From 879c945af7b4a18deea5f2e846967e5230ddede7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 00:16:46 -0500
Subject: [PATCH 605/994] Add solution #1182
---
README.md | 1 +
.../1182-shortest-distance-to-target-color.js | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/1182-shortest-distance-to-target-color.js
diff --git a/README.md b/README.md
index 5d652fc2..206327f6 100644
--- a/README.md
+++ b/README.md
@@ -1104,6 +1104,7 @@
1178|[Number of Valid Words for Each Puzzle](./solutions/1178-number-of-valid-words-for-each-puzzle.js)|Hard|
1180|[Count Substrings with Only One Distinct Letter](./solutions/1180-count-substrings-with-only-one-distinct-letter.js)|Easy|
1181|[Before and After Puzzle](./solutions/1181-before-and-after-puzzle.js)|Medium|
+1182|[Shortest Distance to Target Color](./solutions/1182-shortest-distance-to-target-color.js)|Medium|
1184|[Distance Between Bus Stops](./solutions/1184-distance-between-bus-stops.js)|Easy|
1185|[Day of the Week](./solutions/1185-day-of-the-week.js)|Easy|
1186|[Maximum Subarray Sum with One Deletion](./solutions/1186-maximum-subarray-sum-with-one-deletion.js)|Medium|
diff --git a/solutions/1182-shortest-distance-to-target-color.js b/solutions/1182-shortest-distance-to-target-color.js
new file mode 100644
index 00000000..469c8aab
--- /dev/null
+++ b/solutions/1182-shortest-distance-to-target-color.js
@@ -0,0 +1,50 @@
+/**
+ * 1182. Shortest Distance to Target Color
+ * https://leetcode.com/problems/shortest-distance-to-target-color/
+ * Difficulty: Medium
+ *
+ * You are given an array colors, in which there are three colors: 1, 2 and 3.
+ *
+ * You are also given some queries. Each query consists of two integers i and c,
+ * return the shortest distance between the given index i and the target color c.
+ * If there is no solution return -1.
+ */
+
+/**
+ * @param {number[]} colors
+ * @param {number[][]} queries
+ * @return {number[]}
+ */
+var shortestDistanceColor = function(colors, queries) {
+ const colorIndices = { 1: [], 2: [], 3: [] };
+
+ for (let i = 0; i < colors.length; i++) {
+ colorIndices[colors[i]].push(i);
+ }
+
+ return queries.map(([index, color]) =>
+ findClosestDistance(index, colorIndices[color])
+ );
+
+ function findClosestDistance(targetIndex, colorArray) {
+ if (colorArray.length === 0) return -1;
+
+ let left = 0;
+ let right = colorArray.length - 1;
+ let closestDistance = Infinity;
+
+ while (left <= right) {
+ const mid = Math.floor((left + right) / 2);
+ const distance = Math.abs(colorArray[mid] - targetIndex);
+ closestDistance = Math.min(closestDistance, distance);
+
+ if (colorArray[mid] < targetIndex) {
+ left = mid + 1;
+ } else {
+ right = mid - 1;
+ }
+ }
+
+ return closestDistance;
+ }
+};
From bb263cc37da7c18bfd6d7deea67b9116acb05b77 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 00:26:10 -0500
Subject: [PATCH 606/994] Add solution #1183
---
README.md | 1 +
solutions/1183-maximum-number-of-ones.js | 38 ++++++++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/1183-maximum-number-of-ones.js
diff --git a/README.md b/README.md
index 206327f6..d63495ed 100644
--- a/README.md
+++ b/README.md
@@ -1105,6 +1105,7 @@
1180|[Count Substrings with Only One Distinct Letter](./solutions/1180-count-substrings-with-only-one-distinct-letter.js)|Easy|
1181|[Before and After Puzzle](./solutions/1181-before-and-after-puzzle.js)|Medium|
1182|[Shortest Distance to Target Color](./solutions/1182-shortest-distance-to-target-color.js)|Medium|
+1183|[Maximum Number of Ones](./solutions/1183-maximum-number-of-ones.js)|Hard|
1184|[Distance Between Bus Stops](./solutions/1184-distance-between-bus-stops.js)|Easy|
1185|[Day of the Week](./solutions/1185-day-of-the-week.js)|Easy|
1186|[Maximum Subarray Sum with One Deletion](./solutions/1186-maximum-subarray-sum-with-one-deletion.js)|Medium|
diff --git a/solutions/1183-maximum-number-of-ones.js b/solutions/1183-maximum-number-of-ones.js
new file mode 100644
index 00000000..1e50b44b
--- /dev/null
+++ b/solutions/1183-maximum-number-of-ones.js
@@ -0,0 +1,38 @@
+/**
+ * 1183. Maximum Number of Ones
+ * https://leetcode.com/problems/maximum-number-of-ones/
+ * Difficulty: Hard
+ *
+ * Consider a matrix M with dimensions width * height, such that every cell has value 0 or 1,
+ * and any square sub-matrix of M of size sideLength * sideLength has at most maxOnes ones.
+ *
+ * Return the maximum possible number of ones that the matrix M can have.
+ */
+
+/**
+ * @param {number} width
+ * @param {number} height
+ * @param {number} sideLength
+ * @param {number} maxOnes
+ * @return {number}
+ */
+var maximumNumberOfOnes = function(width, height, sideLength, maxOnes) {
+ const frequencies = [];
+
+ for (let i = 0; i < sideLength; i++) {
+ for (let j = 0; j < sideLength; j++) {
+ const rowCount = Math.ceil((height - i) / sideLength);
+ const colCount = Math.ceil((width - j) / sideLength);
+ frequencies.push(rowCount * colCount);
+ }
+ }
+
+ frequencies.sort((a, b) => b - a);
+
+ let result = 0;
+ for (let i = 0; i < maxOnes; i++) {
+ result += frequencies[i];
+ }
+
+ return result;
+};
From 8632959500bf85c79236ca933f580bef26a9d1e3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 00:27:07 -0500
Subject: [PATCH 607/994] Add solution #1196
---
README.md | 1 +
...many-apples-can-you-put-into-the-basket.js | 32 +++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/1196-how-many-apples-can-you-put-into-the-basket.js
diff --git a/README.md b/README.md
index d63495ed..70a79569 100644
--- a/README.md
+++ b/README.md
@@ -1114,6 +1114,7 @@
1190|[Reverse Substrings Between Each Pair of Parentheses](./solutions/1190-reverse-substrings-between-each-pair-of-parentheses.js)|Medium|
1191|[K-Concatenation Maximum Sum](./solutions/1191-k-concatenation-maximum-sum.js)|Medium|
1192|[Critical Connections in a Network](./solutions/1192-critical-connections-in-a-network.js)|Hard|
+1196|[How Many Apples Can You Put into the Basket](./solutions/1196-how-many-apples-can-you-put-into-the-basket.js)|Easy|
1200|[Minimum Absolute Difference](./solutions/1200-minimum-absolute-difference.js)|Easy|
1201|[Ugly Number III](./solutions/1201-ugly-number-iii.js)|Medium|
1202|[Smallest String With Swaps](./solutions/1202-smallest-string-with-swaps.js)|Medium|
diff --git a/solutions/1196-how-many-apples-can-you-put-into-the-basket.js b/solutions/1196-how-many-apples-can-you-put-into-the-basket.js
new file mode 100644
index 00000000..8d7a4531
--- /dev/null
+++ b/solutions/1196-how-many-apples-can-you-put-into-the-basket.js
@@ -0,0 +1,32 @@
+/**
+ * 1196. How Many Apples Can You Put into the Basket
+ * https://leetcode.com/problems/how-many-apples-can-you-put-into-the-basket/
+ * Difficulty: Easy
+ *
+ * You have some apples and a basket that can carry up to 5000 units of weight.
+ *
+ * Given an integer array weight where weight[i] is the weight of the ith apple,
+ * return the maximum number of apples you can put in the basket.
+ */
+
+/**
+ * @param {number[]} weight
+ * @return {number}
+ */
+var maxNumberOfApples = function(weight) {
+ weight.sort((a, b) => a - b);
+
+ let totalWeight = 0;
+ let result = 0;
+
+ for (const appleWeight of weight) {
+ if (totalWeight + appleWeight <= 5000) {
+ totalWeight += appleWeight;
+ result++;
+ } else {
+ break;
+ }
+ }
+
+ return result;
+};
From cdafadaa5f3e8c66d404fceec0e12e66f4304a26 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 00:28:45 -0500
Subject: [PATCH 608/994] Add solution #1197
---
README.md | 1 +
solutions/1197-minimum-knight-moves.js | 43 ++++++++++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/1197-minimum-knight-moves.js
diff --git a/README.md b/README.md
index 70a79569..4cf943cb 100644
--- a/README.md
+++ b/README.md
@@ -1115,6 +1115,7 @@
1191|[K-Concatenation Maximum Sum](./solutions/1191-k-concatenation-maximum-sum.js)|Medium|
1192|[Critical Connections in a Network](./solutions/1192-critical-connections-in-a-network.js)|Hard|
1196|[How Many Apples Can You Put into the Basket](./solutions/1196-how-many-apples-can-you-put-into-the-basket.js)|Easy|
+1197|[Minimum Knight Moves](./solutions/1197-minimum-knight-moves.js)|Medium|
1200|[Minimum Absolute Difference](./solutions/1200-minimum-absolute-difference.js)|Easy|
1201|[Ugly Number III](./solutions/1201-ugly-number-iii.js)|Medium|
1202|[Smallest String With Swaps](./solutions/1202-smallest-string-with-swaps.js)|Medium|
diff --git a/solutions/1197-minimum-knight-moves.js b/solutions/1197-minimum-knight-moves.js
new file mode 100644
index 00000000..7c1b59e7
--- /dev/null
+++ b/solutions/1197-minimum-knight-moves.js
@@ -0,0 +1,43 @@
+/**
+ * 1197. Minimum Knight Moves
+ * https://leetcode.com/problems/minimum-knight-moves/
+ * Difficulty: Medium
+ *
+ * In an infinite chess board with coordinates from -infinity to +infinity, you have
+ * a knight at square [0, 0].
+ *
+ * A knight has 8 possible moves it can make, as illustrated below. Each move is two
+ * squares in a cardinal direction, then one square in an orthogonal direction.
+ *
+ * Return the minimum number of steps needed to move the knight to the square [x, y].
+ * It is guaranteed the answer exists.
+ */
+
+/**
+ * @param {number} x
+ * @param {number} y
+ * @return {number}
+ */
+var minKnightMoves = function(x, y) {
+ x = Math.abs(x);
+ y = Math.abs(y);
+
+ const memo = new Map();
+ return dfs(x, y);
+
+ function dfs(currX, currY) {
+ if (currX + currY === 0) return 0;
+ if (currX + currY === 2) return 2;
+
+ const key = `${currX},${currY}`;
+ if (memo.has(key)) return memo.get(key);
+
+ const result = Math.min(
+ dfs(Math.abs(currX - 1), Math.abs(currY - 2)),
+ dfs(Math.abs(currX - 2), Math.abs(currY - 1))
+ ) + 1;
+
+ memo.set(key, result);
+ return result;
+ }
+};
From 146e2fad805e65994b75f4a838070b371e13359b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 00:29:45 -0500
Subject: [PATCH 609/994] Add solution #1198
---
README.md | 1 +
...ind-smallest-common-element-in-all-rows.js | 31 +++++++++++++++++++
2 files changed, 32 insertions(+)
create mode 100644 solutions/1198-find-smallest-common-element-in-all-rows.js
diff --git a/README.md b/README.md
index 4cf943cb..7c524d4f 100644
--- a/README.md
+++ b/README.md
@@ -1116,6 +1116,7 @@
1192|[Critical Connections in a Network](./solutions/1192-critical-connections-in-a-network.js)|Hard|
1196|[How Many Apples Can You Put into the Basket](./solutions/1196-how-many-apples-can-you-put-into-the-basket.js)|Easy|
1197|[Minimum Knight Moves](./solutions/1197-minimum-knight-moves.js)|Medium|
+1198|[Find Smallest Common Element in All Rows](./solutions/1198-find-smallest-common-element-in-all-rows.js)|Medium|
1200|[Minimum Absolute Difference](./solutions/1200-minimum-absolute-difference.js)|Easy|
1201|[Ugly Number III](./solutions/1201-ugly-number-iii.js)|Medium|
1202|[Smallest String With Swaps](./solutions/1202-smallest-string-with-swaps.js)|Medium|
diff --git a/solutions/1198-find-smallest-common-element-in-all-rows.js b/solutions/1198-find-smallest-common-element-in-all-rows.js
new file mode 100644
index 00000000..9f777b33
--- /dev/null
+++ b/solutions/1198-find-smallest-common-element-in-all-rows.js
@@ -0,0 +1,31 @@
+/**
+ * 1198. Find Smallest Common Element in All Rows
+ * https://leetcode.com/problems/find-smallest-common-element-in-all-rows/
+ * Difficulty: Medium
+ *
+ * Given an m x n matrix mat where every row is sorted in strictly increasing order,
+ * return the smallest common element in all rows.
+ *
+ * If there is no common element, return -1.
+ */
+
+/**
+ * @param {number[][]} mat
+ * @return {number}
+ */
+var smallestCommonElement = function(mat) {
+ const map = new Map();
+ const rows = mat.length;
+
+ for (let i = 0; i < rows; i++) {
+ for (const element of mat[i]) {
+ map.set(element, (map.get(element) || 0) + 1);
+
+ if (map.get(element) === rows) {
+ return element;
+ }
+ }
+ }
+
+ return -1;
+};
From 79c9a2db8f9060eb7b4dcb3d70e03add82d52cbf Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 00:31:36 -0500
Subject: [PATCH 610/994] Add solution #1199
---
README.md | 1 +
.../1199-minimum-time-to-build-blocks.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/1199-minimum-time-to-build-blocks.js
diff --git a/README.md b/README.md
index 7c524d4f..f3db7954 100644
--- a/README.md
+++ b/README.md
@@ -1117,6 +1117,7 @@
1196|[How Many Apples Can You Put into the Basket](./solutions/1196-how-many-apples-can-you-put-into-the-basket.js)|Easy|
1197|[Minimum Knight Moves](./solutions/1197-minimum-knight-moves.js)|Medium|
1198|[Find Smallest Common Element in All Rows](./solutions/1198-find-smallest-common-element-in-all-rows.js)|Medium|
+1199|[Minimum Time to Build Blocks](./solutions/1199-minimum-time-to-build-blocks.js)|Hard|
1200|[Minimum Absolute Difference](./solutions/1200-minimum-absolute-difference.js)|Easy|
1201|[Ugly Number III](./solutions/1201-ugly-number-iii.js)|Medium|
1202|[Smallest String With Swaps](./solutions/1202-smallest-string-with-swaps.js)|Medium|
diff --git a/solutions/1199-minimum-time-to-build-blocks.js b/solutions/1199-minimum-time-to-build-blocks.js
new file mode 100644
index 00000000..76cd4a45
--- /dev/null
+++ b/solutions/1199-minimum-time-to-build-blocks.js
@@ -0,0 +1,42 @@
+/**
+ * 1199. Minimum Time to Build Blocks
+ * https://leetcode.com/problems/minimum-time-to-build-blocks/
+ * Difficulty: Hard
+ *
+ * You are given a list of blocks, where blocks[i] = t means that the i-th block needs
+ * t units of time to be built. A block can only be built by exactly one worker.
+ *
+ * A worker can either split into two workers (number of workers increases by one) or
+ * build a block then go home. Both decisions cost some time.
+ *
+ * The time cost of spliting one worker into two workers is given as an integer split.
+ * Note that if two workers split at the same time, they split in parallel so the cost
+ * would be split.
+ *
+ * Output the minimum time needed to build all blocks.
+ *
+ * Initially, there is only one worker.
+ */
+
+/**
+ * @param {number[]} blocks
+ * @param {number} split
+ * @return {number}
+ */
+var minBuildTime = function(blocks, split) {
+ const minHeap = new PriorityQueue((a, b) => a - b);
+
+ for (const block of blocks) {
+ minHeap.enqueue(block);
+ }
+
+ while (minHeap.size() > 1) {
+ const first = minHeap.dequeue();
+ const second = minHeap.dequeue();
+
+ const mergedTime = split + Math.max(first, second);
+ minHeap.enqueue(mergedTime);
+ }
+
+ return minHeap.dequeue();
+};
From 2085b6012c412882c58645c0cbe6f4df273b9afe Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 00:33:21 -0500
Subject: [PATCH 611/994] Add solution #1213
---
README.md | 1 +
...213-intersection-of-three-sorted-arrays.js | 37 +++++++++++++++++++
2 files changed, 38 insertions(+)
create mode 100644 solutions/1213-intersection-of-three-sorted-arrays.js
diff --git a/README.md b/README.md
index f3db7954..4d78bcf6 100644
--- a/README.md
+++ b/README.md
@@ -1127,6 +1127,7 @@
1208|[Get Equal Substrings Within Budget](./solutions/1208-get-equal-substrings-within-budget.js)|Medium|
1209|[Remove All Adjacent Duplicates in String II](./solutions/1209-remove-all-adjacent-duplicates-in-string-ii.js)|Medium|
1210|[Minimum Moves to Reach Target with Rotations](./solutions/1210-minimum-moves-to-reach-target-with-rotations.js)|Hard|
+1213|[Intersection of Three Sorted Arrays](./solutions/1213-intersection-of-three-sorted-arrays.js)|Easy|
1217|[Minimum Cost to Move Chips to The Same Position](./solutions/1217-minimum-cost-to-move-chips-to-the-same-position.js)|Easy|
1218|[Longest Arithmetic Subsequence of Given Difference](./solutions/1218-longest-arithmetic-subsequence-of-given-difference.js)|Medium|
1219|[Path with Maximum Gold](./solutions/1219-path-with-maximum-gold.js)|Medium|
diff --git a/solutions/1213-intersection-of-three-sorted-arrays.js b/solutions/1213-intersection-of-three-sorted-arrays.js
new file mode 100644
index 00000000..86bddea1
--- /dev/null
+++ b/solutions/1213-intersection-of-three-sorted-arrays.js
@@ -0,0 +1,37 @@
+/**
+ * 1213. Intersection of Three Sorted Arrays
+ * https://leetcode.com/problems/intersection-of-three-sorted-arrays/
+ * Difficulty: Easy
+ *
+ * Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order,
+ * return a sorted array of only the integers that appeared in all three arrays.
+ */
+
+/**
+ * @param {number[]} arr1
+ * @param {number[]} arr2
+ * @param {number[]} arr3
+ * @return {number[]}
+ */
+var arraysIntersection = function(arr1, arr2, arr3) {
+ let i = 0;
+ let j = 0;
+ let k = 0;
+ const result = [];
+
+ while (i < arr1.length && j < arr2.length && k < arr3.length) {
+ if (arr1[i] === arr2[j] && arr2[j] === arr3[k]) {
+ result.push(arr1[i]);
+ i++;
+ j++;
+ k++;
+ } else {
+ const minValue = Math.min(arr1[i], arr2[j], arr3[k]);
+ if (arr1[i] === minValue) i++;
+ if (arr2[j] === minValue) j++;
+ if (arr3[k] === minValue) k++;
+ }
+ }
+
+ return result;
+};
From 7e17bccf98394bcae25cbd89ffff9505d6508d82 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 00:34:26 -0500
Subject: [PATCH 612/994] Add solution #1214
---
README.md | 1 +
solutions/1214-two-sum-bsts.js | 45 ++++++++++++++++++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/1214-two-sum-bsts.js
diff --git a/README.md b/README.md
index 4d78bcf6..bc799c9e 100644
--- a/README.md
+++ b/README.md
@@ -1128,6 +1128,7 @@
1209|[Remove All Adjacent Duplicates in String II](./solutions/1209-remove-all-adjacent-duplicates-in-string-ii.js)|Medium|
1210|[Minimum Moves to Reach Target with Rotations](./solutions/1210-minimum-moves-to-reach-target-with-rotations.js)|Hard|
1213|[Intersection of Three Sorted Arrays](./solutions/1213-intersection-of-three-sorted-arrays.js)|Easy|
+1214|[Two Sum BSTs](./solutions/1214-two-sum-bsts.js)|Medium|
1217|[Minimum Cost to Move Chips to The Same Position](./solutions/1217-minimum-cost-to-move-chips-to-the-same-position.js)|Easy|
1218|[Longest Arithmetic Subsequence of Given Difference](./solutions/1218-longest-arithmetic-subsequence-of-given-difference.js)|Medium|
1219|[Path with Maximum Gold](./solutions/1219-path-with-maximum-gold.js)|Medium|
diff --git a/solutions/1214-two-sum-bsts.js b/solutions/1214-two-sum-bsts.js
new file mode 100644
index 00000000..c8452c8d
--- /dev/null
+++ b/solutions/1214-two-sum-bsts.js
@@ -0,0 +1,45 @@
+/**
+ * 1214. Two Sum BSTs
+ * https://leetcode.com/problems/two-sum-bsts/
+ * Difficulty: Medium
+ *
+ * Given the roots of two binary search trees, root1 and root2, return true if and only if
+ * there is a node in the first tree and a node in the second tree whose values sum up to
+ * a given integer target.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root1
+ * @param {TreeNode} root2
+ * @param {number} target
+ * @return {boolean}
+ */
+var twoSumBSTs = function(root1, root2, target) {
+ const valuesSet = new Set();
+ collectValues(root1);
+ return searchForComplement(root2);
+
+ function collectValues(node) {
+ if (!node) return;
+ valuesSet.add(node.val);
+ collectValues(node.left);
+ collectValues(node.right);
+ }
+
+ function searchForComplement(node) {
+ if (!node) return false;
+
+ const complement = target - node.val;
+ if (valuesSet.has(complement)) return true;
+
+ return searchForComplement(node.left) || searchForComplement(node.right);
+ }
+};
From 2f71966c68a232adbf82163084899566cbaa7327 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 00:35:34 -0500
Subject: [PATCH 613/994] Add solution #1215
---
README.md | 1 +
solutions/1215-stepping-numbers.js | 53 ++++++++++++++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/1215-stepping-numbers.js
diff --git a/README.md b/README.md
index bc799c9e..316809f2 100644
--- a/README.md
+++ b/README.md
@@ -1129,6 +1129,7 @@
1210|[Minimum Moves to Reach Target with Rotations](./solutions/1210-minimum-moves-to-reach-target-with-rotations.js)|Hard|
1213|[Intersection of Three Sorted Arrays](./solutions/1213-intersection-of-three-sorted-arrays.js)|Easy|
1214|[Two Sum BSTs](./solutions/1214-two-sum-bsts.js)|Medium|
+1215|[Stepping Numbers](./solutions/1215-stepping-numbers.js)|Medium|
1217|[Minimum Cost to Move Chips to The Same Position](./solutions/1217-minimum-cost-to-move-chips-to-the-same-position.js)|Easy|
1218|[Longest Arithmetic Subsequence of Given Difference](./solutions/1218-longest-arithmetic-subsequence-of-given-difference.js)|Medium|
1219|[Path with Maximum Gold](./solutions/1219-path-with-maximum-gold.js)|Medium|
diff --git a/solutions/1215-stepping-numbers.js b/solutions/1215-stepping-numbers.js
new file mode 100644
index 00000000..3051bc98
--- /dev/null
+++ b/solutions/1215-stepping-numbers.js
@@ -0,0 +1,53 @@
+/**
+ * 1215. Stepping Numbers
+ * https://leetcode.com/problems/stepping-numbers/
+ * Difficulty: Medium
+ *
+ * A stepping number is an integer such that all of its adjacent digits have an absolute
+ * difference of exactly 1.
+ * - For example, 321 is a stepping number while 421 is not.
+ *
+ * Given two integers low and high, return a sorted list of all the stepping numbers in the
+ * inclusive range [low, high].
+ */
+
+/**
+ * @param {number} low
+ * @param {number} high
+ * @return {number[]}
+ */
+var countSteppingNumbers = function(low, high) {
+ const result = [];
+
+ if (low === 0) result.push(0);
+
+ const minLength = low.toString().length;
+ const maxLength = high.toString().length;
+
+ for (let length = minLength; length <= maxLength; length++) {
+ for (let start = 1; start <= 9; start++) {
+ dfs(start.toString(), length);
+ }
+ }
+
+ return result.sort((a, b) => a - b);
+
+ function dfs(current, targetLength) {
+ if (current.length === targetLength) {
+ const num = parseInt(current);
+ if (num >= low && num <= high) {
+ result.push(num);
+ }
+ return;
+ }
+
+ const lastDigit = parseInt(current[current.length - 1]);
+
+ if (lastDigit > 0) {
+ dfs(current + (lastDigit - 1), targetLength);
+ }
+ if (lastDigit < 9) {
+ dfs(current + (lastDigit + 1), targetLength);
+ }
+ }
+};
From 5d5d0588845b8555857bd0b0ebecafd4d964b1e9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 00:36:42 -0500
Subject: [PATCH 614/994] Add solution #1216
---
README.md | 1 +
solutions/1216-valid-palindrome-iii.js | 42 ++++++++++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/1216-valid-palindrome-iii.js
diff --git a/README.md b/README.md
index 316809f2..d6a5faf2 100644
--- a/README.md
+++ b/README.md
@@ -1130,6 +1130,7 @@
1213|[Intersection of Three Sorted Arrays](./solutions/1213-intersection-of-three-sorted-arrays.js)|Easy|
1214|[Two Sum BSTs](./solutions/1214-two-sum-bsts.js)|Medium|
1215|[Stepping Numbers](./solutions/1215-stepping-numbers.js)|Medium|
+1216|[Valid Palindrome III](./solutions/1216-valid-palindrome-iii.js)|Hard|
1217|[Minimum Cost to Move Chips to The Same Position](./solutions/1217-minimum-cost-to-move-chips-to-the-same-position.js)|Easy|
1218|[Longest Arithmetic Subsequence of Given Difference](./solutions/1218-longest-arithmetic-subsequence-of-given-difference.js)|Medium|
1219|[Path with Maximum Gold](./solutions/1219-path-with-maximum-gold.js)|Medium|
diff --git a/solutions/1216-valid-palindrome-iii.js b/solutions/1216-valid-palindrome-iii.js
new file mode 100644
index 00000000..2371169f
--- /dev/null
+++ b/solutions/1216-valid-palindrome-iii.js
@@ -0,0 +1,42 @@
+/**
+ * 1216. Valid Palindrome III
+ * https://leetcode.com/problems/valid-palindrome-iii/
+ * Difficulty: Hard
+ *
+ * Given a string s and an integer k, return true if s is a k-palindrome.
+ *
+ * A string is k-palindrome if it can be transformed into a palindrome by removing
+ * at most k characters from it.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} k
+ * @return {boolean}
+ */
+var isValidPalindrome = function(s, k) {
+ const n = s.length;
+ const memo = new Array(n).fill().map(() => new Array(n).fill(-1));
+ const longestPalindrome = longestPalindromeSubseq(0, n - 1);
+ const deletions = n - longestPalindrome;
+
+ return deletions <= k;
+
+ function longestPalindromeSubseq(left, right) {
+ if (left > right) return 0;
+ if (left === right) return 1;
+
+ if (memo[left][right] !== -1) return memo[left][right];
+
+ if (s[left] === s[right]) {
+ memo[left][right] = 2 + longestPalindromeSubseq(left + 1, right - 1);
+ } else {
+ memo[left][right] = Math.max(
+ longestPalindromeSubseq(left + 1, right),
+ longestPalindromeSubseq(left, right - 1)
+ );
+ }
+
+ return memo[left][right];
+ }
+};
From 3919851e238d04adf742320ad795ec25d49666fa Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 00:37:47 -0500
Subject: [PATCH 615/994] Add solution #1228
---
README.md | 3 +-
...issing-number-in-arithmetic-progression.js | 30 +++++++++++++++++++
2 files changed, 32 insertions(+), 1 deletion(-)
create mode 100644 solutions/1228-missing-number-in-arithmetic-progression.js
diff --git a/README.md b/README.md
index d6a5faf2..c1de904f 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 2,350+ LeetCode solutions in JavaScript
+# 2,400+ LeetCode solutions in JavaScript
[https://leetcodejavascript.com](https://leetcodejavascript.com)
@@ -1140,6 +1140,7 @@
1223|[Dice Roll Simulation](./solutions/1223-dice-roll-simulation.js)|Hard|
1224|[Maximum Equal Frequency](./solutions/1224-maximum-equal-frequency.js)|Hard|
1227|[Airplane Seat Assignment Probability](./solutions/1227-airplane-seat-assignment-probability.js)|Medium|
+1228|[Missing Number In Arithmetic Progression](./solutions/1228-missing-number-in-arithmetic-progression.js)|Easy|
1232|[Check If It Is a Straight Line](./solutions/1232-check-if-it-is-a-straight-line.js)|Easy|
1233|[Remove Sub-Folders from the Filesystem](./solutions/1233-remove-sub-folders-from-the-filesystem.js)|Medium|
1234|[Replace the Substring for Balanced String](./solutions/1234-replace-the-substring-for-balanced-string.js)|Medium|
diff --git a/solutions/1228-missing-number-in-arithmetic-progression.js b/solutions/1228-missing-number-in-arithmetic-progression.js
new file mode 100644
index 00000000..67fff03e
--- /dev/null
+++ b/solutions/1228-missing-number-in-arithmetic-progression.js
@@ -0,0 +1,30 @@
+/**
+ * 1228. Missing Number In Arithmetic Progression
+ * https://leetcode.com/problems/missing-number-in-arithmetic-progression/
+ * Difficulty: Easy
+ *
+ * In some array arr, the values were in arithmetic progression: the values
+ * arr[i + 1] - arr[i] are all equal for every 0 <= i < arr.length - 1.
+ *
+ * A value from arr was removed that was not the first or last value in the array.
+ *
+ * Given arr, return the removed value.
+ */
+
+/**
+ * @param {number[]} arr
+ * @return {number}
+ */
+var missingNumber = function(arr) {
+ const n = arr.length;
+ const totalDiff = arr[n - 1] - arr[0];
+ const expectedDiff = totalDiff / n;
+
+ for (let i = 1; i < n; i++) {
+ if (arr[i] - arr[i - 1] !== expectedDiff) {
+ return arr[i - 1] + expectedDiff;
+ }
+ }
+
+ return arr[0] + expectedDiff;
+};
From 67d6aa2ef3afa0202a3b2541ed152314ddeb95f5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 28 Jun 2025 23:45:05 -0500
Subject: [PATCH 616/994] Add solution #1229
---
README.md | 1 +
solutions/1229-meeting-scheduler.js | 49 +++++++++++++++++++++++++++++
2 files changed, 50 insertions(+)
create mode 100644 solutions/1229-meeting-scheduler.js
diff --git a/README.md b/README.md
index c1de904f..8c5d8e40 100644
--- a/README.md
+++ b/README.md
@@ -1141,6 +1141,7 @@
1224|[Maximum Equal Frequency](./solutions/1224-maximum-equal-frequency.js)|Hard|
1227|[Airplane Seat Assignment Probability](./solutions/1227-airplane-seat-assignment-probability.js)|Medium|
1228|[Missing Number In Arithmetic Progression](./solutions/1228-missing-number-in-arithmetic-progression.js)|Easy|
+1229|[Meeting Scheduler](./solutions/1229-meeting-scheduler.js)|Medium|
1232|[Check If It Is a Straight Line](./solutions/1232-check-if-it-is-a-straight-line.js)|Easy|
1233|[Remove Sub-Folders from the Filesystem](./solutions/1233-remove-sub-folders-from-the-filesystem.js)|Medium|
1234|[Replace the Substring for Balanced String](./solutions/1234-replace-the-substring-for-balanced-string.js)|Medium|
diff --git a/solutions/1229-meeting-scheduler.js b/solutions/1229-meeting-scheduler.js
new file mode 100644
index 00000000..c0f8f772
--- /dev/null
+++ b/solutions/1229-meeting-scheduler.js
@@ -0,0 +1,49 @@
+/**
+ * 1229. Meeting Scheduler
+ * https://leetcode.com/problems/meeting-scheduler/
+ * Difficulty: Medium
+ *
+ * Given the availability time slots arrays slots1 and slots2 of two people and a meeting
+ * duration duration, return the earliest time slot that works for both of them and is of
+ * duration duration.
+ *
+ * If there is no common time slot that satisfies the requirements, return an empty array.
+ *
+ * The format of a time slot is an array of two elements [start, end] representing an
+ * inclusive time range from start to end.
+ *
+ * It is guaranteed that no two availability slots of the same person intersect with each
+ * other. That is, for any two time slots [start1, end1] and [start2, end2] of the same
+ * person, either start1 > end2 or start2 > end1.
+ */
+
+/**
+ * @param {number[][]} slots1
+ * @param {number[][]} slots2
+ * @param {number} duration
+ * @return {number[]}
+ */
+var minAvailableDuration = function(slots1, slots2, duration) {
+ slots1.sort((a, b) => a[0] - b[0]);
+ slots2.sort((a, b) => a[0] - b[0]);
+
+ let i = 0;
+ let j = 0;
+
+ while (i < slots1.length && j < slots2.length) {
+ const overlapStart = Math.max(slots1[i][0], slots2[j][0]);
+ const overlapEnd = Math.min(slots1[i][1], slots2[j][1]);
+
+ if (overlapEnd - overlapStart >= duration) {
+ return [overlapStart, overlapStart + duration];
+ }
+
+ if (slots1[i][1] < slots2[j][1]) {
+ i++;
+ } else {
+ j++;
+ }
+ }
+
+ return [];
+};
From fa30b8487c13c6351c76ce76685d0c8c1eb319f4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 29 Jun 2025 22:41:59 -0500
Subject: [PATCH 617/994] Add solution #1230
---
README.md | 1 +
solutions/1230-toss-strange-coins.js | 30 ++++++++++++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 solutions/1230-toss-strange-coins.js
diff --git a/README.md b/README.md
index 8c5d8e40..6865bf3c 100644
--- a/README.md
+++ b/README.md
@@ -1142,6 +1142,7 @@
1227|[Airplane Seat Assignment Probability](./solutions/1227-airplane-seat-assignment-probability.js)|Medium|
1228|[Missing Number In Arithmetic Progression](./solutions/1228-missing-number-in-arithmetic-progression.js)|Easy|
1229|[Meeting Scheduler](./solutions/1229-meeting-scheduler.js)|Medium|
+1230|[Toss Strange Coins](./solutions/1230-toss-strange-coins.js)|Medium|
1232|[Check If It Is a Straight Line](./solutions/1232-check-if-it-is-a-straight-line.js)|Easy|
1233|[Remove Sub-Folders from the Filesystem](./solutions/1233-remove-sub-folders-from-the-filesystem.js)|Medium|
1234|[Replace the Substring for Balanced String](./solutions/1234-replace-the-substring-for-balanced-string.js)|Medium|
diff --git a/solutions/1230-toss-strange-coins.js b/solutions/1230-toss-strange-coins.js
new file mode 100644
index 00000000..b78575e7
--- /dev/null
+++ b/solutions/1230-toss-strange-coins.js
@@ -0,0 +1,30 @@
+/**
+ * 1230. Toss Strange Coins
+ * https://leetcode.com/problems/toss-strange-coins/
+ * Difficulty: Medium
+ *
+ * You have some coins. The i-th coin has a probability prob[i] of facing heads when tossed.
+ *
+ * Return the probability that the number of coins facing heads equals target if you toss every
+ * coin exactly once.
+ */
+
+/**
+ * @param {number[]} prob
+ * @param {number} target
+ * @return {number}
+ */
+var probabilityOfHeads = function(prob, target) {
+ const n = prob.length;
+ const dp = new Array(target + 1).fill(0);
+ dp[0] = 1;
+
+ for (let i = 0; i < n; i++) {
+ for (let j = Math.min(i + 1, target); j >= 1; j--) {
+ dp[j] = dp[j] * (1 - prob[i]) + dp[j - 1] * prob[i];
+ }
+ dp[0] *= (1 - prob[i]);
+ }
+
+ return dp[target];
+};
From 2f9dc07917c44bc8e2cd6ce6b6009407c7a2d7b6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 29 Jun 2025 22:44:11 -0500
Subject: [PATCH 618/994] Add solution #1231
---
README.md | 1 +
solutions/1231-divide-chocolate.js | 55 ++++++++++++++++++++++++++++++
2 files changed, 56 insertions(+)
create mode 100644 solutions/1231-divide-chocolate.js
diff --git a/README.md b/README.md
index 6865bf3c..62507bf9 100644
--- a/README.md
+++ b/README.md
@@ -1143,6 +1143,7 @@
1228|[Missing Number In Arithmetic Progression](./solutions/1228-missing-number-in-arithmetic-progression.js)|Easy|
1229|[Meeting Scheduler](./solutions/1229-meeting-scheduler.js)|Medium|
1230|[Toss Strange Coins](./solutions/1230-toss-strange-coins.js)|Medium|
+1231|[Divide Chocolate](./solutions/1231-divide-chocolate.js)|Hard|
1232|[Check If It Is a Straight Line](./solutions/1232-check-if-it-is-a-straight-line.js)|Easy|
1233|[Remove Sub-Folders from the Filesystem](./solutions/1233-remove-sub-folders-from-the-filesystem.js)|Medium|
1234|[Replace the Substring for Balanced String](./solutions/1234-replace-the-substring-for-balanced-string.js)|Medium|
diff --git a/solutions/1231-divide-chocolate.js b/solutions/1231-divide-chocolate.js
new file mode 100644
index 00000000..cbb25425
--- /dev/null
+++ b/solutions/1231-divide-chocolate.js
@@ -0,0 +1,55 @@
+/**
+ * 1231. Divide Chocolate
+ * https://leetcode.com/problems/divide-chocolate/
+ * Difficulty: Hard
+ *
+ * You have one chocolate bar that consists of some chunks. Each chunk has its own sweetness
+ * given by the array sweetness.
+ *
+ * You want to share the chocolate with your k friends so you start cutting the chocolate bar
+ * into k + 1 pieces using k cuts, each piece consists of some consecutive chunks.
+ *
+ * Being generous, you will eat the piece with the minimum total sweetness and give the other
+ * pieces to your friends.
+ *
+ * Find the maximum total sweetness of the piece you can get by cutting the chocolate bar optimally.
+ */
+
+/**
+ * @param {number[]} sweetness
+ * @param {number} k
+ * @return {number}
+ */
+var maximizeSweetness = function(sweetness, k) {
+ let left = Math.min(...sweetness);
+ let right = sweetness.reduce((sum, val) => sum + val, 0);
+ let result = left;
+
+ while (left <= right) {
+ const mid = Math.floor((left + right) / 2);
+
+ if (canDivide(mid)) {
+ result = mid;
+ left = mid + 1;
+ } else {
+ right = mid - 1;
+ }
+ }
+
+ return result;
+
+ function canDivide(minSweetness) {
+ let pieces = 0;
+ let currentSum = 0;
+
+ for (const chunk of sweetness) {
+ currentSum += chunk;
+ if (currentSum >= minSweetness) {
+ pieces++;
+ currentSum = 0;
+ }
+ }
+
+ return pieces >= k + 1;
+ }
+};
From a1e845110078c262be5882b5ed9b4813852d3f0f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 29 Jun 2025 22:46:21 -0500
Subject: [PATCH 619/994] Add solution #1236
---
README.md | 1 +
solutions/1236-web-crawler.js | 69 +++++++++++++++++++++++++++++++++++
2 files changed, 70 insertions(+)
create mode 100644 solutions/1236-web-crawler.js
diff --git a/README.md b/README.md
index 62507bf9..604fb764 100644
--- a/README.md
+++ b/README.md
@@ -1148,6 +1148,7 @@
1233|[Remove Sub-Folders from the Filesystem](./solutions/1233-remove-sub-folders-from-the-filesystem.js)|Medium|
1234|[Replace the Substring for Balanced String](./solutions/1234-replace-the-substring-for-balanced-string.js)|Medium|
1235|[Maximum Profit in Job Scheduling](./solutions/1235-maximum-profit-in-job-scheduling.js)|Hard|
+1236|[Web Crawler](./solutions/1236-web-crawler.js)|Medium|
1237|[Find Positive Integer Solution for a Given Equation](./solutions/1237-find-positive-integer-solution-for-a-given-equation.js)|Medium|
1238|[Circular Permutation in Binary Representation](./solutions/1238-circular-permutation-in-binary-representation.js)|Medium|
1239|[Maximum Length of a Concatenated String with Unique Characters](./solutions/1239-maximum-length-of-a-concatenated-string-with-unique-characters.js)|Medium|
diff --git a/solutions/1236-web-crawler.js b/solutions/1236-web-crawler.js
new file mode 100644
index 00000000..b5d4a40c
--- /dev/null
+++ b/solutions/1236-web-crawler.js
@@ -0,0 +1,69 @@
+/**
+ * 1236. Web Crawler
+ * https://leetcode.com/problems/web-crawler/
+ * Difficulty: Medium
+ *
+ * Given a url startUrl and an interface HtmlParser, implement a web crawler to crawl all
+ * links that are under the same hostname as startUrl.
+ *
+ * Return all urls obtained by your web crawler in any order.
+ *
+ * Your crawler should:
+ * - Start from the page: startUrl
+ * - Call HtmlParser.getUrls(url) to get all urls from a webpage of given url.
+ * - Do not crawl the same link twice.
+ * - Explore only the links that are under the same hostname as startUrl.
+ *
+ * As shown in the example url above, the hostname is example.org. For simplicity sake, you may
+ * assume all urls use http protocol without any port specified. For example, the urls
+ * http://leetcode.com/problems and http://leetcode.com/contest are under the same hostname,
+ * while urls http://example.org/test and http://example.com/abc are not under the same hostname.
+ *
+ * The HtmlParser interface is defined as such:
+ * interface HtmlParser {
+ * // Return a list of all urls from a webpage of given url.
+ * public List getUrls(String url);
+ * }
+ *
+ * Below are two examples explaining the functionality of the problem, for custom testing purposes
+ * you'll have three variables urls, edges and startUrl. Notice that you will only have access to
+ * startUrl in your code, while urls and edges are not directly accessible to you in code.
+ *
+ * Note: Consider the same URL with the trailing slash "/" as a different URL. For example,
+ * "http://news.yahoo.com", and "http://news.yahoo.com/" are different urls.
+ */
+
+/**
+ * @param {string} startUrl
+ * @param {HtmlParser} htmlParser
+ * @return {string[]}
+*/
+var crawl = function(startUrl, htmlParser) {
+ const targetHostname = getHostname(startUrl);
+ const visited = new Set();
+ const queue = [startUrl];
+ const result = [];
+
+ while (queue.length > 0) {
+ const currentUrl = queue.shift();
+
+ if (visited.has(currentUrl)) continue;
+
+ visited.add(currentUrl);
+ result.push(currentUrl);
+
+ const urls = htmlParser.getUrls(currentUrl);
+
+ for (const url of urls) {
+ if (!visited.has(url) && getHostname(url) === targetHostname) {
+ queue.push(url);
+ }
+ }
+ }
+
+ return result;
+
+ function getHostname(url) {
+ return url.split('/')[2];
+ }
+};
From 30e6fb05b171f98ed1bd4c9c3c2c8e2775db854b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 29 Jun 2025 22:47:37 -0500
Subject: [PATCH 620/994] Add solution #1243
---
README.md | 1 +
solutions/1243-array-transformation.js | 47 ++++++++++++++++++++++++++
2 files changed, 48 insertions(+)
create mode 100644 solutions/1243-array-transformation.js
diff --git a/README.md b/README.md
index 604fb764..3173458f 100644
--- a/README.md
+++ b/README.md
@@ -1153,6 +1153,7 @@
1238|[Circular Permutation in Binary Representation](./solutions/1238-circular-permutation-in-binary-representation.js)|Medium|
1239|[Maximum Length of a Concatenated String with Unique Characters](./solutions/1239-maximum-length-of-a-concatenated-string-with-unique-characters.js)|Medium|
1240|[Tiling a Rectangle with the Fewest Squares](./solutions/1240-tiling-a-rectangle-with-the-fewest-squares.js)|Hard|
+1243|[Array Transformation](./solutions/1243-array-transformation.js)|Easy|
1247|[Minimum Swaps to Make Strings Equal](./solutions/1247-minimum-swaps-to-make-strings-equal.js)|Medium|
1248|[Count Number of Nice Subarrays](./solutions/1248-count-number-of-nice-subarrays.js)|Medium|
1249|[Minimum Remove to Make Valid Parentheses](./solutions/1249-minimum-remove-to-make-valid-parentheses.js)|Medium|
diff --git a/solutions/1243-array-transformation.js b/solutions/1243-array-transformation.js
new file mode 100644
index 00000000..43bd2c30
--- /dev/null
+++ b/solutions/1243-array-transformation.js
@@ -0,0 +1,47 @@
+/**
+ * 1243. Array Transformation
+ * https://leetcode.com/problems/array-transformation/
+ * Difficulty: Easy
+ *
+ * Given an initial array arr, every day you produce a new array using the array of the
+ * previous day.
+ *
+ * On the i-th day, you do the following operations on the array of day i-1 to produce
+ * the array of day i:
+ * - If an element is smaller than both its left neighbor and its right neighbor, then this
+ * element is incremented.
+ * - If an element is bigger than both its left neighbor and its right neighbor, then this
+ * element is decremented.
+ *
+ * The first and last elements never change.
+ *
+ * After some days, the array does not change. Return that final array.
+ */
+
+/**
+ * @param {number[]} arr
+ * @return {number[]}
+ */
+var transformArray = function(arr) {
+ let current = [...arr];
+
+ while (true) {
+ const next = [...current];
+ let changed = false;
+
+ for (let i = 1; i < current.length - 1; i++) {
+ if (current[i] < current[i - 1] && current[i] < current[i + 1]) {
+ next[i]++;
+ changed = true;
+ } else if (current[i] > current[i - 1] && current[i] > current[i + 1]) {
+ next[i]--;
+ changed = true;
+ }
+ }
+
+ if (!changed) break;
+ current = next;
+ }
+
+ return current;
+};
From 8f413cdf29e6af035b96ce9b46c3ea4af99e4ffb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 29 Jun 2025 23:13:35 -0500
Subject: [PATCH 621/994] Add solution #1244
---
README.md | 1 +
solutions/1244-design-a-leaderboard.js | 47 ++++++++++++++++++++++++++
2 files changed, 48 insertions(+)
create mode 100644 solutions/1244-design-a-leaderboard.js
diff --git a/README.md b/README.md
index 3173458f..1efe83d6 100644
--- a/README.md
+++ b/README.md
@@ -1154,6 +1154,7 @@
1239|[Maximum Length of a Concatenated String with Unique Characters](./solutions/1239-maximum-length-of-a-concatenated-string-with-unique-characters.js)|Medium|
1240|[Tiling a Rectangle with the Fewest Squares](./solutions/1240-tiling-a-rectangle-with-the-fewest-squares.js)|Hard|
1243|[Array Transformation](./solutions/1243-array-transformation.js)|Easy|
+1244|[Design A Leaderboard](./solutions/1244-design-a-leaderboard.js)|Medium|
1247|[Minimum Swaps to Make Strings Equal](./solutions/1247-minimum-swaps-to-make-strings-equal.js)|Medium|
1248|[Count Number of Nice Subarrays](./solutions/1248-count-number-of-nice-subarrays.js)|Medium|
1249|[Minimum Remove to Make Valid Parentheses](./solutions/1249-minimum-remove-to-make-valid-parentheses.js)|Medium|
diff --git a/solutions/1244-design-a-leaderboard.js b/solutions/1244-design-a-leaderboard.js
new file mode 100644
index 00000000..0b1fe9f7
--- /dev/null
+++ b/solutions/1244-design-a-leaderboard.js
@@ -0,0 +1,47 @@
+/**
+ * 1244. Design A Leaderboard
+ * https://leetcode.com/problems/design-a-leaderboard/
+ * Difficulty: Medium
+ *
+ * Design a Leaderboard class, which has 3 functions:
+ * - addScore(playerId, score): Update the leaderboard by adding score to the given player's
+ * score. If there is no player with such id in the leaderboard, add him to the leaderboard
+ * with the given score.
+ * - top(K): Return the score sum of the top K players.
+ * - reset(playerId): Reset the score of the player with the given id to 0 (in other words
+ * erase it from the leaderboard). It is guaranteed that the player was added to the leaderboard
+ * before calling this function.
+ *
+ * Initially, the leaderboard is empty.
+ */
+
+
+var Leaderboard = function() {
+ this.scores = new Map();
+};
+
+/**
+ * @param {number} playerId
+ * @param {number} score
+ * @return {void}
+ */
+Leaderboard.prototype.addScore = function(playerId, score) {
+ this.scores.set(playerId, (this.scores.get(playerId) || 0) + score);
+};
+
+/**
+ * @param {number} K
+ * @return {number}
+ */
+Leaderboard.prototype.top = function(K) {
+ const sortedScores = Array.from(this.scores.values()).sort((a, b) => b - a);
+ return sortedScores.slice(0, K).reduce((sum, score) => sum + score, 0);
+};
+
+/**
+ * @param {number} playerId
+ * @return {void}
+ */
+Leaderboard.prototype.reset = function(playerId) {
+ this.scores.delete(playerId);
+};
From 0faee229c1ecbd1a114b934242d96cb04cdc1a11 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 29 Jun 2025 23:14:51 -0500
Subject: [PATCH 622/994] Add solution #1245
---
README.md | 1 +
solutions/1245-tree-diameter.js | 60 +++++++++++++++++++++++++++++++++
2 files changed, 61 insertions(+)
create mode 100644 solutions/1245-tree-diameter.js
diff --git a/README.md b/README.md
index 1efe83d6..ca2453ce 100644
--- a/README.md
+++ b/README.md
@@ -1155,6 +1155,7 @@
1240|[Tiling a Rectangle with the Fewest Squares](./solutions/1240-tiling-a-rectangle-with-the-fewest-squares.js)|Hard|
1243|[Array Transformation](./solutions/1243-array-transformation.js)|Easy|
1244|[Design A Leaderboard](./solutions/1244-design-a-leaderboard.js)|Medium|
+1245|[Tree Diameter](./solutions/1245-tree-diameter.js)|Medium|
1247|[Minimum Swaps to Make Strings Equal](./solutions/1247-minimum-swaps-to-make-strings-equal.js)|Medium|
1248|[Count Number of Nice Subarrays](./solutions/1248-count-number-of-nice-subarrays.js)|Medium|
1249|[Minimum Remove to Make Valid Parentheses](./solutions/1249-minimum-remove-to-make-valid-parentheses.js)|Medium|
diff --git a/solutions/1245-tree-diameter.js b/solutions/1245-tree-diameter.js
new file mode 100644
index 00000000..b086c2b5
--- /dev/null
+++ b/solutions/1245-tree-diameter.js
@@ -0,0 +1,60 @@
+/**
+ * 1245. Tree Diameter
+ * https://leetcode.com/problems/tree-diameter/
+ * Difficulty: Medium
+ *
+ * The diameter of a tree is the number of edges in the longest path in that tree.
+ *
+ * There is an undirected tree of n nodes labeled from 0 to n - 1. You are given a 2D array
+ * edges where edges.length == n - 1 and edges[i] = [ai, bi] indicates that there is an
+ * undirected edge between nodes ai and bi in the tree.
+ *
+ * Return the diameter of the tree.
+ */
+
+/**
+ * @param {number[][]} edges
+ * @return {number}
+ */
+var treeDiameter = function(edges) {
+ if (edges.length === 0) return 0;
+
+ const graph = new Map();
+ for (const [a, b] of edges) {
+ if (!graph.has(a)) graph.set(a, []);
+ if (!graph.has(b)) graph.set(b, []);
+ graph.get(a).push(b);
+ graph.get(b).push(a);
+ }
+
+ const [farthestFromStart] = bfs(0);
+ const [, diameter] = bfs(farthestFromStart);
+
+ return diameter;
+
+ function bfs(start) {
+ const visited = new Set();
+ const queue = [[start, 0]];
+ visited.add(start);
+ let farthestNode = start;
+ let maxDistance = 0;
+
+ while (queue.length > 0) {
+ const [node, distance] = queue.shift();
+
+ if (distance > maxDistance) {
+ maxDistance = distance;
+ farthestNode = node;
+ }
+
+ for (const neighbor of graph.get(node) || []) {
+ if (!visited.has(neighbor)) {
+ visited.add(neighbor);
+ queue.push([neighbor, distance + 1]);
+ }
+ }
+ }
+
+ return [farthestNode, maxDistance];
+ }
+};
From 116ad1a7404cdfcbf7ea4fb4654334586ef8d59c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 29 Jun 2025 23:17:40 -0500
Subject: [PATCH 623/994] Add solution #1246
---
README.md | 1 +
solutions/1246-palindrome-removal.js | 47 ++++++++++++++++++++++++++++
2 files changed, 48 insertions(+)
create mode 100644 solutions/1246-palindrome-removal.js
diff --git a/README.md b/README.md
index ca2453ce..3d625fb8 100644
--- a/README.md
+++ b/README.md
@@ -1156,6 +1156,7 @@
1243|[Array Transformation](./solutions/1243-array-transformation.js)|Easy|
1244|[Design A Leaderboard](./solutions/1244-design-a-leaderboard.js)|Medium|
1245|[Tree Diameter](./solutions/1245-tree-diameter.js)|Medium|
+1246|[Palindrome Removal](./solutions/1246-palindrome-removal.js)|Hard|
1247|[Minimum Swaps to Make Strings Equal](./solutions/1247-minimum-swaps-to-make-strings-equal.js)|Medium|
1248|[Count Number of Nice Subarrays](./solutions/1248-count-number-of-nice-subarrays.js)|Medium|
1249|[Minimum Remove to Make Valid Parentheses](./solutions/1249-minimum-remove-to-make-valid-parentheses.js)|Medium|
diff --git a/solutions/1246-palindrome-removal.js b/solutions/1246-palindrome-removal.js
new file mode 100644
index 00000000..32810863
--- /dev/null
+++ b/solutions/1246-palindrome-removal.js
@@ -0,0 +1,47 @@
+/**
+ * 1246. Palindrome Removal
+ * https://leetcode.com/problems/palindrome-removal/
+ * Difficulty: Hard
+ *
+ * You are given an integer array arr.
+ *
+ * In one move, you can select a palindromic subarray arr[i], arr[i + 1], ..., arr[j]
+ * where i <= j, and remove that subarray from the given array. Note that after removing
+ * a subarray, the elements on the left and on the right of that subarray move to fill
+ * the gap left by the removal.
+ *
+ * Return the minimum number of moves needed to remove all numbers from the array.
+ */
+
+/**
+ * @param {number[]} arr
+ * @return {number}
+ */
+var minimumMoves = function(arr) {
+ const n = arr.length;
+ const dp = new Array(n).fill().map(() => new Array(n).fill(Infinity));
+
+ for (let i = 0; i < n; i++) {
+ dp[i][i] = 1;
+ }
+
+ for (let length = 2; length <= n; length++) {
+ for (let i = 0; i <= n - length; i++) {
+ const j = i + length - 1;
+
+ if (arr[i] === arr[j]) {
+ if (length === 2) {
+ dp[i][j] = 1;
+ } else {
+ dp[i][j] = dp[i + 1][j - 1];
+ }
+ }
+
+ for (let k = i; k < j; k++) {
+ dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j]);
+ }
+ }
+ }
+
+ return dp[0][n - 1];
+};
From 60f1489bf174fe300da03bcd8098a40584d407c1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 29 Jun 2025 23:18:33 -0500
Subject: [PATCH 624/994] Add solution #1256
---
README.md | 1 +
solutions/1256-encode-number.js | 18 ++++++++++++++++++
2 files changed, 19 insertions(+)
create mode 100644 solutions/1256-encode-number.js
diff --git a/README.md b/README.md
index 3d625fb8..d77b4056 100644
--- a/README.md
+++ b/README.md
@@ -1165,6 +1165,7 @@
1253|[Reconstruct a 2-Row Binary Matrix](./solutions/1253-reconstruct-a-2-row-binary-matrix.js)|Medium|
1254|[Number of Closed Islands](./solutions/1254-number-of-closed-islands.js)|Medium|
1255|[Maximum Score Words Formed by Letters](./solutions/1255-maximum-score-words-formed-by-letters.js)|Hard|
+1256|[Encode Number](./solutions/1256-encode-number.js)|Medium|
1260|[Shift 2D Grid](./solutions/1260-shift-2d-grid.js)|Easy|
1261|[Find Elements in a Contaminated Binary Tree](./solutions/1261-find-elements-in-a-contaminated-binary-tree.js)|Medium|
1262|[Greatest Sum Divisible by Three](./solutions/1262-greatest-sum-divisible-by-three.js)|Medium|
diff --git a/solutions/1256-encode-number.js b/solutions/1256-encode-number.js
new file mode 100644
index 00000000..0b334dfc
--- /dev/null
+++ b/solutions/1256-encode-number.js
@@ -0,0 +1,18 @@
+/**
+ * 1256. Encode Number
+ * https://leetcode.com/problems/encode-number/
+ * Difficulty: Medium
+ *
+ * Given a non-negative integer num, Return its encoding string.
+ *
+ * The encoding is done by converting the integer to a string using a secret function that
+ * you should deduce from the following table:
+ */
+
+/**
+ * @param {number} num
+ * @return {string}
+ */
+var encode = function(num) {
+ return (num + 1).toString(2).slice(1);
+};
From 3c3ed98dacd2bd52c7c0fa859ab38d500afd2b12 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 29 Jun 2025 23:20:28 -0500
Subject: [PATCH 625/994] Add solution #1257
---
README.md | 1 +
solutions/1257-smallest-common-region.js | 56 ++++++++++++++++++++++++
2 files changed, 57 insertions(+)
create mode 100644 solutions/1257-smallest-common-region.js
diff --git a/README.md b/README.md
index d77b4056..8fd28ff3 100644
--- a/README.md
+++ b/README.md
@@ -1166,6 +1166,7 @@
1254|[Number of Closed Islands](./solutions/1254-number-of-closed-islands.js)|Medium|
1255|[Maximum Score Words Formed by Letters](./solutions/1255-maximum-score-words-formed-by-letters.js)|Hard|
1256|[Encode Number](./solutions/1256-encode-number.js)|Medium|
+1257|[Smallest Common Region](./solutions/1257-smallest-common-region.js)|Medium|
1260|[Shift 2D Grid](./solutions/1260-shift-2d-grid.js)|Easy|
1261|[Find Elements in a Contaminated Binary Tree](./solutions/1261-find-elements-in-a-contaminated-binary-tree.js)|Medium|
1262|[Greatest Sum Divisible by Three](./solutions/1262-greatest-sum-divisible-by-three.js)|Medium|
diff --git a/solutions/1257-smallest-common-region.js b/solutions/1257-smallest-common-region.js
new file mode 100644
index 00000000..c40af77a
--- /dev/null
+++ b/solutions/1257-smallest-common-region.js
@@ -0,0 +1,56 @@
+/**
+ * 1257. Smallest Common Region
+ * https://leetcode.com/problems/smallest-common-region/
+ * Difficulty: Medium
+ *
+ * You are given some lists of regions where the first region of each list directly contains
+ * all other regions in that list.
+ *
+ * If a region x contains a region y directly, and region y contains region z directly, then
+ * region x is said to contain region z indirectly. Note that region x also indirectly contains
+ * all regions indirectly containd in y.
+ *
+ * Naturally, if a region x contains (either directly or indirectly) another region y, then x
+ * is bigger than or equal to y in size. Also, by definition, a region x contains itself.
+ *
+ * Given two regions: region1 and region2, return the smallest region that contains both of them.
+ *
+ * It is guaranteed the smallest region exists.
+ */
+
+/**
+ * @param {string[][]} regions
+ * @param {string} region1
+ * @param {string} region2
+ * @return {string}
+ */
+var findSmallestRegion = function(regions, region1, region2) {
+ const map = new Map();
+
+ for (const region of regions) {
+ const parent = region[0];
+ for (let i = 1; i < region.length; i++) {
+ map.set(region[i], parent);
+ }
+ }
+
+ const path1 = getPath(region1);
+ const path2 = getPath(region2);
+ const set = new Set(path1);
+
+ for (const ancestor of path2) {
+ if (set.has(ancestor)) {
+ return ancestor;
+ }
+ }
+
+ function getPath(region) {
+ const path = [];
+ let current = region;
+ while (current) {
+ path.push(current);
+ current = map.get(current);
+ }
+ return path;
+ }
+};
From 0f23fd605e7283284f2a2a5e322f29acf240b5a7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 30 Jun 2025 23:37:18 -0500
Subject: [PATCH 626/994] Add solution #3330
---
README.md | 1 +
.../3330-find-the-original-typed-string-i.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/3330-find-the-original-typed-string-i.js
diff --git a/README.md b/README.md
index 8fd28ff3..9878c374 100644
--- a/README.md
+++ b/README.md
@@ -2389,6 +2389,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|
+3330|[Find the Original Typed String I](./solutions/3330-find-the-original-typed-string-i.js)|Easy|
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|
diff --git a/solutions/3330-find-the-original-typed-string-i.js b/solutions/3330-find-the-original-typed-string-i.js
new file mode 100644
index 00000000..4613a000
--- /dev/null
+++ b/solutions/3330-find-the-original-typed-string-i.js
@@ -0,0 +1,41 @@
+/**
+ * 3330. Find the Original Typed String I
+ * https://leetcode.com/problems/find-the-original-typed-string-i/
+ * Difficulty: Easy
+ *
+ * Alice is attempting to type a specific string on her computer. However, she tends to be
+ * clumsy and may press a key for too long, resulting in a character being typed multiple times.
+ *
+ * Although Alice tried to focus on her typing, she is aware that she may still have done this
+ * at most once.
+ *
+ * You are given a string word, which represents the final output displayed on Alice's screen.
+ *
+ * Return the total number of possible original strings that Alice might have intended to type.
+ */
+
+/**
+ * @param {string} word
+ * @return {number}
+ */
+var possibleStringCount = function(word) {
+ let result = 1;
+ let consecutiveCount = 1;
+
+ for (let i = 1; i < word.length; i++) {
+ if (word[i] === word[i - 1]) {
+ consecutiveCount++;
+ } else {
+ if (consecutiveCount > 1) {
+ result += consecutiveCount - 1;
+ }
+ consecutiveCount = 1;
+ }
+ }
+
+ if (consecutiveCount > 1) {
+ result += consecutiveCount - 1;
+ }
+
+ return result;
+};
From 2b0fd3ac794cf4ebe840bb977a84c55f84d53dbf Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 30 Jun 2025 23:39:34 -0500
Subject: [PATCH 627/994] Add solution #1258
---
README.md | 1 +
solutions/1258-synonymous-sentences.js | 69 ++++++++++++++++++++++++++
2 files changed, 70 insertions(+)
create mode 100644 solutions/1258-synonymous-sentences.js
diff --git a/README.md b/README.md
index 9878c374..31512291 100644
--- a/README.md
+++ b/README.md
@@ -1167,6 +1167,7 @@
1255|[Maximum Score Words Formed by Letters](./solutions/1255-maximum-score-words-formed-by-letters.js)|Hard|
1256|[Encode Number](./solutions/1256-encode-number.js)|Medium|
1257|[Smallest Common Region](./solutions/1257-smallest-common-region.js)|Medium|
+1258|[Synonymous Sentences](./solutions/1258-synonymous-sentences.js)|Medium|
1260|[Shift 2D Grid](./solutions/1260-shift-2d-grid.js)|Easy|
1261|[Find Elements in a Contaminated Binary Tree](./solutions/1261-find-elements-in-a-contaminated-binary-tree.js)|Medium|
1262|[Greatest Sum Divisible by Three](./solutions/1262-greatest-sum-divisible-by-three.js)|Medium|
diff --git a/solutions/1258-synonymous-sentences.js b/solutions/1258-synonymous-sentences.js
new file mode 100644
index 00000000..125d1bf9
--- /dev/null
+++ b/solutions/1258-synonymous-sentences.js
@@ -0,0 +1,69 @@
+/**
+ * 1258. Synonymous Sentences
+ * https://leetcode.com/problems/synonymous-sentences/
+ * Difficulty: Medium
+ *
+ * You are given a list of equivalent string pairs synonyms where synonyms[i] = [si, ti]
+ * indicates that si and ti are equivalent strings. You are also given a sentence text.
+ *
+ * Return all possible synonymous sentences sorted lexicographically.
+ */
+
+/**
+ * @param {string[][]} synonyms
+ * @param {string} text
+ * @return {string[]}
+ */
+var generateSentences = function(synonyms, text) {
+ const graph = new Map();
+
+ for (const [word1, word2] of synonyms) {
+ if (!graph.has(word1)) graph.set(word1, []);
+ if (!graph.has(word2)) graph.set(word2, []);
+ graph.get(word1).push(word2);
+ graph.get(word2).push(word1);
+ }
+
+ const words = text.split(' ');
+ const allCombinations = [];
+ backtrack(0, []);
+ return allCombinations.sort();
+
+ function findSynonyms(word) {
+ if (!graph.has(word)) return [word];
+
+ const visited = new Set();
+ const queue = [word];
+ const synonymGroup = [];
+
+ while (queue.length > 0) {
+ const current = queue.shift();
+ if (visited.has(current)) continue;
+
+ visited.add(current);
+ synonymGroup.push(current);
+
+ for (const neighbor of graph.get(current)) {
+ if (!visited.has(neighbor)) {
+ queue.push(neighbor);
+ }
+ }
+ }
+
+ return synonymGroup.sort();
+ }
+
+ function backtrack(index, currentSentence) {
+ if (index === words.length) {
+ allCombinations.push(currentSentence.join(' '));
+ return;
+ }
+
+ const synonyms = findSynonyms(words[index]);
+ for (const synonym of synonyms) {
+ currentSentence.push(synonym);
+ backtrack(index + 1, currentSentence);
+ currentSentence.pop();
+ }
+ }
+};
From 51ff4b566f368ec446251f2949dd3e03cd6891d4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 30 Jun 2025 23:41:21 -0500
Subject: [PATCH 628/994] Add solution #1259
---
README.md | 1 +
solutions/1259-handshakes-that-dont-cross.js | 31 ++++++++++++++++++++
2 files changed, 32 insertions(+)
create mode 100644 solutions/1259-handshakes-that-dont-cross.js
diff --git a/README.md b/README.md
index 31512291..c7374d86 100644
--- a/README.md
+++ b/README.md
@@ -1168,6 +1168,7 @@
1256|[Encode Number](./solutions/1256-encode-number.js)|Medium|
1257|[Smallest Common Region](./solutions/1257-smallest-common-region.js)|Medium|
1258|[Synonymous Sentences](./solutions/1258-synonymous-sentences.js)|Medium|
+1259|[Handshakes That Don't Cross](./solutions/1259-handshakes-that-dont-cross.js)|Hard|
1260|[Shift 2D Grid](./solutions/1260-shift-2d-grid.js)|Easy|
1261|[Find Elements in a Contaminated Binary Tree](./solutions/1261-find-elements-in-a-contaminated-binary-tree.js)|Medium|
1262|[Greatest Sum Divisible by Three](./solutions/1262-greatest-sum-divisible-by-three.js)|Medium|
diff --git a/solutions/1259-handshakes-that-dont-cross.js b/solutions/1259-handshakes-that-dont-cross.js
new file mode 100644
index 00000000..28006d83
--- /dev/null
+++ b/solutions/1259-handshakes-that-dont-cross.js
@@ -0,0 +1,31 @@
+/**
+ * 1259. Handshakes That Don't Cross
+ * https://leetcode.com/problems/handshakes-that-dont-cross/
+ * Difficulty: Hard
+ *
+ * You are given an even number of people numPeople that stand around a circle and each
+ * person shakes hands with someone else so that there are numPeople / 2 handshakes total.
+ *
+ * Return the number of ways these handshakes could occur such that none of the handshakes cross.
+ *
+ * Since the answer could be very large, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {number} numPeople
+ * @return {number}
+ */
+var numberOfWays = function(numPeople) {
+ const MOD = 1e9 + 7;
+ const n = numPeople / 2;
+ const dp = new Array(n + 1).fill(0n);
+ dp[0] = 1n;
+
+ for (let i = 1; i <= n; i++) {
+ for (let j = 0; j < i; j++) {
+ dp[i] = (dp[i] + dp[j] * dp[i - 1 - j]) % BigInt(MOD);
+ }
+ }
+
+ return Number(dp[n]);
+};
From 8b2d730d60e13e594ae5c048ca9dd346a37d7c4a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 30 Jun 2025 23:42:57 -0500
Subject: [PATCH 629/994] Add solution #1265
---
README.md | 1 +
...-print-immutable-linked-list-in-reverse.js | 28 +++++++++++++++++++
2 files changed, 29 insertions(+)
create mode 100644 solutions/1265-print-immutable-linked-list-in-reverse.js
diff --git a/README.md b/README.md
index c7374d86..efd89767 100644
--- a/README.md
+++ b/README.md
@@ -1173,6 +1173,7 @@
1261|[Find Elements in a Contaminated Binary Tree](./solutions/1261-find-elements-in-a-contaminated-binary-tree.js)|Medium|
1262|[Greatest Sum Divisible by Three](./solutions/1262-greatest-sum-divisible-by-three.js)|Medium|
1263|[Minimum Moves to Move a Box to Their Target Location](./solutions/1263-minimum-moves-to-move-a-box-to-their-target-location.js)|Hard|
+1265|[Print Immutable Linked List in Reverse](./solutions/1265-print-immutable-linked-list-in-reverse.js)|Medium|
1266|[Minimum Time Visiting All Points](./solutions/1266-minimum-time-visiting-all-points.js)|Easy|
1267|[Count Servers that Communicate](./solutions/1267-count-servers-that-communicate.js)|Medium|
1268|[Search Suggestions System](./solutions/1268-search-suggestions-system.js)|Medium|
diff --git a/solutions/1265-print-immutable-linked-list-in-reverse.js b/solutions/1265-print-immutable-linked-list-in-reverse.js
new file mode 100644
index 00000000..6435844d
--- /dev/null
+++ b/solutions/1265-print-immutable-linked-list-in-reverse.js
@@ -0,0 +1,28 @@
+/**
+ * 1265. Print Immutable Linked List in Reverse
+ * https://leetcode.com/problems/print-immutable-linked-list-in-reverse/
+ * Difficulty: Medium
+ *
+ * You are given an immutable linked list, print out all values of each node in reverse
+ * with the help of the following interface:
+ * - ImmutableListNode: An interface of immutable linked list, you are given the head of the list.
+ *
+ * You need to use the following functions to access the linked list (you can't access the
+ * ImmutableListNode directly):
+ * - ImmutableListNode.printValue(): Print value of the current node.
+ * - ImmutableListNode.getNext(): Return the next node.
+ *
+ * The input is only given to initialize the linked list internally. You must solve this problem
+ * without modifying the linked list. In other words, you must operate the linked list using
+ * only the mentioned APIs.
+ */
+
+/**
+ * @param {ImmutableListNode} head
+ * @return {void}
+ */
+var printLinkedListInReverse = function(head) {
+ if (!head) return;
+ printLinkedListInReverse(head.getNext());
+ head.printValue();
+};
From cb56b13175452ca2765a5ccbc0e7d8d40cbf55f1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 30 Jun 2025 23:44:00 -0500
Subject: [PATCH 630/994] Add solution #1271
---
README.md | 1 +
solutions/1271-hexspeak.js | 30 ++++++++++++++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 solutions/1271-hexspeak.js
diff --git a/README.md b/README.md
index efd89767..5a621d99 100644
--- a/README.md
+++ b/README.md
@@ -1178,6 +1178,7 @@
1267|[Count Servers that Communicate](./solutions/1267-count-servers-that-communicate.js)|Medium|
1268|[Search Suggestions System](./solutions/1268-search-suggestions-system.js)|Medium|
1269|[Number of Ways to Stay in the Same Place After Some Steps](./solutions/1269-number-of-ways-to-stay-in-the-same-place-after-some-steps.js)|Hard|
+1271|[Hexspeak](./solutions/1271-hexspeak.js)|Easy|
1275|[Find Winner on a Tic Tac Toe Game](./solutions/1275-find-winner-on-a-tic-tac-toe-game.js)|Easy|
1276|[Number of Burgers with No Waste of Ingredients](./solutions/1276-number-of-burgers-with-no-waste-of-ingredients.js)|Medium|
1277|[Count Square Submatrices with All Ones](./solutions/1277-count-square-submatrices-with-all-ones.js)|Medium|
diff --git a/solutions/1271-hexspeak.js b/solutions/1271-hexspeak.js
new file mode 100644
index 00000000..4a5714f3
--- /dev/null
+++ b/solutions/1271-hexspeak.js
@@ -0,0 +1,30 @@
+/**
+ * 1271. Hexspeak
+ * https://leetcode.com/problems/hexspeak/
+ * Difficulty: Easy
+ *
+ * A decimal number can be converted to its Hexspeak representation by first converting it to
+ * an uppercase hexadecimal string, then replacing all occurrences of the digit '0' with the
+ * letter 'O', and the digit '1' with the letter 'I'. Such a representation is valid if and
+ * only if it consists only of the letters in the set {'A', 'B', 'C', 'D', 'E', 'F', 'I', 'O'}.
+ *
+ * Given a string num representing a decimal integer n, return the Hexspeak representation of
+ * n if it is valid, otherwise return "ERROR".
+ */
+
+/**
+ * @param {string} num
+ * @return {string}
+ */
+var toHexspeak = function(num) {
+ const hex = BigInt(num).toString(16).toUpperCase();
+ const validChars = new Set(['0', '1', 'A', 'B', 'C', 'D', 'E', 'F']);
+
+ for (const char of hex) {
+ if (!validChars.has(char)) {
+ return 'ERROR';
+ }
+ }
+
+ return hex.replace(/0/g, 'O').replace(/1/g, 'I');
+};
From eb73a581f9bfc91562d74a8097ef300fa39b697b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 30 Jun 2025 23:47:43 -0500
Subject: [PATCH 631/994] Add solution #1272
---
README.md | 1 +
solutions/1272-remove-interval.js | 43 +++++++++++++++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/1272-remove-interval.js
diff --git a/README.md b/README.md
index 5a621d99..e4f2f7f1 100644
--- a/README.md
+++ b/README.md
@@ -1179,6 +1179,7 @@
1268|[Search Suggestions System](./solutions/1268-search-suggestions-system.js)|Medium|
1269|[Number of Ways to Stay in the Same Place After Some Steps](./solutions/1269-number-of-ways-to-stay-in-the-same-place-after-some-steps.js)|Hard|
1271|[Hexspeak](./solutions/1271-hexspeak.js)|Easy|
+1272|[Remove Interval](./solutions/1272-remove-interval.js)|Medium|
1275|[Find Winner on a Tic Tac Toe Game](./solutions/1275-find-winner-on-a-tic-tac-toe-game.js)|Easy|
1276|[Number of Burgers with No Waste of Ingredients](./solutions/1276-number-of-burgers-with-no-waste-of-ingredients.js)|Medium|
1277|[Count Square Submatrices with All Ones](./solutions/1277-count-square-submatrices-with-all-ones.js)|Medium|
diff --git a/solutions/1272-remove-interval.js b/solutions/1272-remove-interval.js
new file mode 100644
index 00000000..ef3b2157
--- /dev/null
+++ b/solutions/1272-remove-interval.js
@@ -0,0 +1,43 @@
+/**
+ * 1272. Remove Interval
+ * https://leetcode.com/problems/remove-interval/
+ * Difficulty: Medium
+ *
+ * A set of real numbers can be represented as the union of several disjoint intervals,
+ * where each interval is in the form [a, b). A real number x is in the set if one of
+ * its intervals [a, b) contains x (i.e. a <= x < b).
+ *
+ * You are given a sorted list of disjoint intervals intervals representing a set of
+ * real numbers as described above, where intervals[i] = [ai, bi] represents the interval
+ * [ai, bi). You are also given another interval toBeRemoved.
+ *
+ * Return the set of real numbers with the interval toBeRemoved removed from intervals.
+ * In other words, return the set of real numbers such that every x in the set is in
+ * intervals but not in toBeRemoved. Your answer should be a sorted list of disjoint
+ * intervals as described above.
+ */
+
+/**
+ * @param {number[][]} intervals
+ * @param {number[]} toBeRemoved
+ * @return {number[][]}
+ */
+var removeInterval = function(intervals, toBeRemoved) {
+ const result = [];
+ const [removeStart, removeEnd] = toBeRemoved;
+
+ for (const [start, end] of intervals) {
+ if (end <= removeStart || start >= removeEnd) {
+ result.push([start, end]);
+ } else {
+ if (start < removeStart) {
+ result.push([start, removeStart]);
+ }
+ if (end > removeEnd) {
+ result.push([removeEnd, end]);
+ }
+ }
+ }
+
+ return result;
+};
From c299f2a8b600cee5e7bc5fe6ca8672ed8b9c4886 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 30 Jun 2025 23:49:01 -0500
Subject: [PATCH 632/994] Add solution #1273
---
README.md | 1 +
solutions/1273-delete-tree-nodes.js | 47 +++++++++++++++++++++++++++++
2 files changed, 48 insertions(+)
create mode 100644 solutions/1273-delete-tree-nodes.js
diff --git a/README.md b/README.md
index e4f2f7f1..06b2c173 100644
--- a/README.md
+++ b/README.md
@@ -1180,6 +1180,7 @@
1269|[Number of Ways to Stay in the Same Place After Some Steps](./solutions/1269-number-of-ways-to-stay-in-the-same-place-after-some-steps.js)|Hard|
1271|[Hexspeak](./solutions/1271-hexspeak.js)|Easy|
1272|[Remove Interval](./solutions/1272-remove-interval.js)|Medium|
+1273|[Delete Tree Nodes](./solutions/1273-delete-tree-nodes.js)|Medium|
1275|[Find Winner on a Tic Tac Toe Game](./solutions/1275-find-winner-on-a-tic-tac-toe-game.js)|Easy|
1276|[Number of Burgers with No Waste of Ingredients](./solutions/1276-number-of-burgers-with-no-waste-of-ingredients.js)|Medium|
1277|[Count Square Submatrices with All Ones](./solutions/1277-count-square-submatrices-with-all-ones.js)|Medium|
diff --git a/solutions/1273-delete-tree-nodes.js b/solutions/1273-delete-tree-nodes.js
new file mode 100644
index 00000000..5b9d250c
--- /dev/null
+++ b/solutions/1273-delete-tree-nodes.js
@@ -0,0 +1,47 @@
+/**
+ * 1273. Delete Tree Nodes
+ * https://leetcode.com/problems/delete-tree-nodes/
+ * Difficulty: Medium
+ *
+ * A tree rooted at node 0 is given as follows:
+ * - The number of nodes is nodes;
+ * - The value of the ith node is value[i];
+ * - The parent of the ith node is parent[i].
+ *
+ * Remove every subtree whose sum of values of nodes is zero.
+ *
+ * Return the number of the remaining nodes in the tree.
+ */
+
+/**
+ * @param {number} nodes
+ * @param {number[]} parent
+ * @param {number[]} value
+ * @return {number}
+ */
+var deleteTreeNodes = function(nodes, parent, value) {
+ const children = new Array(nodes).fill().map(() => []);
+
+ for (let i = 1; i < nodes; i++) {
+ children[parent[i]].push(i);
+ }
+
+ return dfs(0)[1];
+
+ function dfs(node) {
+ let subtreeSum = value[node];
+ let subtreeCount = 1;
+
+ for (const child of children[node]) {
+ const [childSum, childCount] = dfs(child);
+ subtreeSum += childSum;
+ subtreeCount += childCount;
+ }
+
+ if (subtreeSum === 0) {
+ return [0, 0];
+ }
+
+ return [subtreeSum, subtreeCount];
+ }
+};
From 42282637573c532bf31c169cbf05b05a9e6e2bac Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 30 Jun 2025 23:50:35 -0500
Subject: [PATCH 633/994] Add solution #1274
---
README.md | 1 +
.../1274-number-of-ships-in-a-rectangle.js | 46 +++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/1274-number-of-ships-in-a-rectangle.js
diff --git a/README.md b/README.md
index 06b2c173..9bc483c8 100644
--- a/README.md
+++ b/README.md
@@ -1181,6 +1181,7 @@
1271|[Hexspeak](./solutions/1271-hexspeak.js)|Easy|
1272|[Remove Interval](./solutions/1272-remove-interval.js)|Medium|
1273|[Delete Tree Nodes](./solutions/1273-delete-tree-nodes.js)|Medium|
+1274|[Number of Ships in a Rectangle](./solutions/1274-number-of-ships-in-a-rectangle.js)|Hard|
1275|[Find Winner on a Tic Tac Toe Game](./solutions/1275-find-winner-on-a-tic-tac-toe-game.js)|Easy|
1276|[Number of Burgers with No Waste of Ingredients](./solutions/1276-number-of-burgers-with-no-waste-of-ingredients.js)|Medium|
1277|[Count Square Submatrices with All Ones](./solutions/1277-count-square-submatrices-with-all-ones.js)|Medium|
diff --git a/solutions/1274-number-of-ships-in-a-rectangle.js b/solutions/1274-number-of-ships-in-a-rectangle.js
new file mode 100644
index 00000000..2093511a
--- /dev/null
+++ b/solutions/1274-number-of-ships-in-a-rectangle.js
@@ -0,0 +1,46 @@
+/**
+ * 1274. Number of Ships in a Rectangle
+ * https://leetcode.com/problems/number-of-ships-in-a-rectangle/
+ * Difficulty: Hard
+ *
+ * Each ship is located at an integer point on the sea represented by a cartesian plane, and
+ * each integer point may contain at most 1 ship.
+ *
+ * You have a function Sea.hasShips(topRight, bottomLeft) which takes two points as arguments
+ * and returns true If there is at least one ship in the rectangle represented by the two
+ * points, including on the boundary.
+ *
+ * Given two points: the top right and bottom left corners of a rectangle, return the number
+ * of ships present in that rectangle. It is guaranteed that there are at most 10 ships in
+ * that rectangle.
+ *
+ * Submissions making more than 400 calls to hasShips will be judged Wrong Answer. Also, any
+ * solutions that attempt to circumvent the judge will result in disqualification.
+ */
+
+/**
+ * @param {Sea} sea
+ * @param {integer[]} topRight
+ * @param {integer[]} bottomLeft
+ * @return {integer}
+ */
+var countShips = function(sea, topRight, bottomLeft) {
+ const [x2, y2] = topRight;
+ const [x1, y1] = bottomLeft;
+
+ if (x1 > x2 || y1 > y2 || !sea.hasShips(topRight, bottomLeft)) {
+ return 0;
+ }
+
+ if (x1 === x2 && y1 === y2) {
+ return 1;
+ }
+
+ const midX = Math.floor((x1 + x2) / 2);
+ const midY = Math.floor((y1 + y2) / 2);
+
+ return countShips(sea, [midX, midY], [x1, y1])
+ + countShips(sea, [x2, midY], [midX + 1, y1])
+ + countShips(sea, [midX, y2], [x1, midY + 1])
+ + countShips(sea, [x2, y2], [midX + 1, midY + 1]);
+};
From 202e0f0c246de0c571206f6317ecc4febc3c6856 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 30 Jun 2025 23:52:27 -0500
Subject: [PATCH 634/994] Add solution #1426
---
README.md | 1 +
solutions/1426-counting-elements.js | 17 +++++++++++++++++
2 files changed, 18 insertions(+)
create mode 100644 solutions/1426-counting-elements.js
diff --git a/README.md b/README.md
index 9bc483c8..88da8c90 100644
--- a/README.md
+++ b/README.md
@@ -1311,6 +1311,7 @@
1423|[Maximum Points You Can Obtain from Cards](./solutions/1423-maximum-points-you-can-obtain-from-cards.js)|Medium|
1424|[Diagonal Traverse II](./solutions/1424-diagonal-traverse-ii.js)|Medium|
1425|[Constrained Subsequence Sum](./solutions/1425-constrained-subsequence-sum.js)|Hard|
+1426|[Counting Elements](./solutions/1426-counting-elements.js)|Easy|
1431|[Kids With the Greatest Number of Candies](./solutions/1431-kids-with-the-greatest-number-of-candies.js)|Easy|
1432|[Max Difference You Can Get From Changing an Integer](./solutions/1432-max-difference-you-can-get-from-changing-an-integer.js)|Medium|
1433|[Check If a String Can Break Another String](./solutions/1433-check-if-a-string-can-break-another-string.js)|Medium|
diff --git a/solutions/1426-counting-elements.js b/solutions/1426-counting-elements.js
new file mode 100644
index 00000000..1784bdef
--- /dev/null
+++ b/solutions/1426-counting-elements.js
@@ -0,0 +1,17 @@
+/**
+ * 1426. Counting Elements
+ * https://leetcode.com/problems/counting-elements/
+ * Difficulty: Easy
+ *
+ * Given an integer array arr, count how many elements x there are, such that x + 1 is also
+ * in arr. If there are duplicates in arr, count them separately.
+ */
+
+/**
+ * @param {number[]} arr
+ * @return {number}
+ */
+var countElements = function(arr) {
+ const set = new Set(arr);
+ return arr.filter(num => set.has(num + 1)).length;
+};
From 43190688fb72473d3f140dc7662e34f77f4b0e93 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 30 Jun 2025 23:53:30 -0500
Subject: [PATCH 635/994] Add solution #1427
---
README.md | 1 +
solutions/1427-perform-string-shifts.js | 32 +++++++++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/1427-perform-string-shifts.js
diff --git a/README.md b/README.md
index 88da8c90..cbb21614 100644
--- a/README.md
+++ b/README.md
@@ -1312,6 +1312,7 @@
1424|[Diagonal Traverse II](./solutions/1424-diagonal-traverse-ii.js)|Medium|
1425|[Constrained Subsequence Sum](./solutions/1425-constrained-subsequence-sum.js)|Hard|
1426|[Counting Elements](./solutions/1426-counting-elements.js)|Easy|
+1427|[Perform String Shifts](./solutions/1427-perform-string-shifts.js)|Easy|
1431|[Kids With the Greatest Number of Candies](./solutions/1431-kids-with-the-greatest-number-of-candies.js)|Easy|
1432|[Max Difference You Can Get From Changing an Integer](./solutions/1432-max-difference-you-can-get-from-changing-an-integer.js)|Medium|
1433|[Check If a String Can Break Another String](./solutions/1433-check-if-a-string-can-break-another-string.js)|Medium|
diff --git a/solutions/1427-perform-string-shifts.js b/solutions/1427-perform-string-shifts.js
new file mode 100644
index 00000000..751826e5
--- /dev/null
+++ b/solutions/1427-perform-string-shifts.js
@@ -0,0 +1,32 @@
+/**
+ * 1427. Perform String Shifts
+ * https://leetcode.com/problems/perform-string-shifts/
+ * Difficulty: Easy
+ *
+ * You are given a string s containing lowercase English letters, and a matrix shift,
+ * where shift[i] = [directioni, amounti]:
+ * - directioni can be 0 (for left shift) or 1 (for right shift).
+ * - amounti is the amount by which string s is to be shifted.
+ * - A left shift by 1 means remove the first character of s and append it to the end.
+ * - Similarly, a right shift by 1 means remove the last character of s and add it to the beginning.
+ *
+ * Return the final string after all operations.
+ */
+
+/**
+ * @param {string} s
+ * @param {number[][]} shift
+ * @return {string}
+ */
+var stringShift = function(s, shift) {
+ let netShift = 0;
+
+ for (const [direction, amount] of shift) {
+ netShift += direction === 0 ? -amount : amount;
+ }
+
+ const n = s.length;
+ netShift = ((netShift % n) + n) % n;
+
+ return s.slice(-netShift) + s.slice(0, -netShift);
+};
From 33cebff37009f88b9fcd0fe40d8deee9c24a445c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 1 Jul 2025 23:59:40 -0500
Subject: [PATCH 636/994] Add solution #3333
---
README.md | 1 +
.../3333-find-the-original-typed-string-ii.js | 78 +++++++++++++++++++
2 files changed, 79 insertions(+)
create mode 100644 solutions/3333-find-the-original-typed-string-ii.js
diff --git a/README.md b/README.md
index cbb21614..2aa96c71 100644
--- a/README.md
+++ b/README.md
@@ -2399,6 +2399,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|
3330|[Find the Original Typed String I](./solutions/3330-find-the-original-typed-string-i.js)|Easy|
+3333|[Find the Original Typed String II](./solutions/3333-find-the-original-typed-string-ii.js)|Hard|
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|
diff --git a/solutions/3333-find-the-original-typed-string-ii.js b/solutions/3333-find-the-original-typed-string-ii.js
new file mode 100644
index 00000000..607bf17c
--- /dev/null
+++ b/solutions/3333-find-the-original-typed-string-ii.js
@@ -0,0 +1,78 @@
+/**
+ * 3333. Find the Original Typed String II
+ * https://leetcode.com/problems/find-the-original-typed-string-ii/
+ * Difficulty: Hard
+ *
+ * Alice is attempting to type a specific string on her computer. However, she tends to be
+ * clumsy and may press a key for too long, resulting in a character being typed multiple times.
+ *
+ * You are given a string word, which represents the final output displayed on Alice's screen.
+ * You are also given a positive integer k.
+ *
+ * Return the total number of possible original strings that Alice might have intended to type,
+ * if she was trying to type a string of size at least k.
+ *
+ * Since the answer may be very large, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {string} word
+ * @param {number} k
+ * @return {number}
+ */
+var possibleStringCount = function(word, k) {
+ const MOD = 1e9 + 7;
+ const groups = [];
+ let count = 1;
+
+ for (let i = 1; i < word.length; i++) {
+ if (word[i] === word[i - 1]) {
+ count++;
+ } else {
+ groups.push(count);
+ count = 1;
+ }
+ }
+ groups.push(count);
+
+ const n = groups.length;
+
+ let totalWays = 1;
+ for (const groupSize of groups) {
+ totalWays = (totalWays * groupSize) % MOD;
+ }
+
+ if (k <= n) {
+ return totalWays;
+ }
+
+ let dp = new Array(k).fill(0);
+ dp[0] = 1;
+
+ for (let i = 0; i < n; i++) {
+ const newDp = new Array(k).fill(0);
+ const groupSize = groups[i];
+
+ let sum = 0;
+ for (let j = 0; j < Math.min(groupSize, k); j++) {
+ sum = (sum + dp[j]) % MOD;
+ newDp[j + 1] = sum;
+ }
+
+ for (let j = groupSize; j < k; j++) {
+ sum = (sum + dp[j] - dp[j - groupSize] + MOD) % MOD;
+ if (j + 1 < k) {
+ newDp[j + 1] = sum;
+ }
+ }
+
+ dp = newDp;
+ }
+
+ let invalidWays = 0;
+ for (let j = 0; j < k; j++) {
+ invalidWays = (invalidWays + dp[j]) % MOD;
+ }
+
+ return (totalWays - invalidWays + MOD) % MOD;
+};
From 8c70c00799c1213982b7008e8998389b07dfd60b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 2 Jul 2025 22:54:16 -0500
Subject: [PATCH 637/994] Add solution #3304
---
README.md | 1 +
...ind-the-k-th-character-in-string-game-i.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/3304-find-the-k-th-character-in-string-game-i.js
diff --git a/README.md b/README.md
index 2aa96c71..04caf47f 100644
--- a/README.md
+++ b/README.md
@@ -2397,6 +2397,7 @@
3208|[Alternating Groups II](./solutions/3208-alternating-groups-ii.js)|Medium|
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|
+3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
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|
3330|[Find the Original Typed String I](./solutions/3330-find-the-original-typed-string-i.js)|Easy|
3333|[Find the Original Typed String II](./solutions/3333-find-the-original-typed-string-ii.js)|Hard|
diff --git a/solutions/3304-find-the-k-th-character-in-string-game-i.js b/solutions/3304-find-the-k-th-character-in-string-game-i.js
new file mode 100644
index 00000000..7c192745
--- /dev/null
+++ b/solutions/3304-find-the-k-th-character-in-string-game-i.js
@@ -0,0 +1,39 @@
+/**
+ * 3304. Find the K-th Character in String Game I
+ * https://leetcode.com/problems/find-the-k-th-character-in-string-game-i/
+ * Difficulty: Easy
+ *
+ * Alice and Bob are playing a game. Initially, Alice has a string word = "a".
+ *
+ * You are given a positive integer k.
+ *
+ * Now Bob will ask Alice to perform the following operation forever:
+ * - Generate a new string by changing each character in word to its next character in the
+ * English alphabet, and append it to the original word.
+ *
+ * For example, performing the operation on "c" generates "cd" and performing the operation
+ * on "zb" generates "zbac".
+ *
+ * Return the value of the kth character in word, after enough operations have been done for
+ * word to have at least k characters.
+ *
+ * Note that the character 'z' can be changed to 'a' in the operation.
+ */
+
+/**
+ * @param {number} k
+ * @return {character}
+ */
+var kthCharacter = function(k) {
+ let word = 'a';
+
+ while (word.length < k) {
+ let nextPart = '';
+ for (const char of word) {
+ nextPart += String.fromCharCode(((char.charCodeAt(0) - 97 + 1) % 26) + 97);
+ }
+ word += nextPart;
+ }
+
+ return word[k - 1];
+};
From 4133a1891d899726f11c3b0ce60faefb1ab43458 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 2 Jul 2025 22:57:14 -0500
Subject: [PATCH 638/994] Add solution #1428
---
README.md | 1 +
...428-leftmost-column-with-at-least-a-one.js | 45 +++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/1428-leftmost-column-with-at-least-a-one.js
diff --git a/README.md b/README.md
index 04caf47f..6ccd1c3e 100644
--- a/README.md
+++ b/README.md
@@ -1313,6 +1313,7 @@
1425|[Constrained Subsequence Sum](./solutions/1425-constrained-subsequence-sum.js)|Hard|
1426|[Counting Elements](./solutions/1426-counting-elements.js)|Easy|
1427|[Perform String Shifts](./solutions/1427-perform-string-shifts.js)|Easy|
+1428|[Leftmost Column with at Least a One](./solutions/1428-leftmost-column-with-at-least-a-one.js)|Medium|
1431|[Kids With the Greatest Number of Candies](./solutions/1431-kids-with-the-greatest-number-of-candies.js)|Easy|
1432|[Max Difference You Can Get From Changing an Integer](./solutions/1432-max-difference-you-can-get-from-changing-an-integer.js)|Medium|
1433|[Check If a String Can Break Another String](./solutions/1433-check-if-a-string-can-break-another-string.js)|Medium|
diff --git a/solutions/1428-leftmost-column-with-at-least-a-one.js b/solutions/1428-leftmost-column-with-at-least-a-one.js
new file mode 100644
index 00000000..004ae054
--- /dev/null
+++ b/solutions/1428-leftmost-column-with-at-least-a-one.js
@@ -0,0 +1,45 @@
+/**
+ * 1428. Leftmost Column with at Least a One
+ * https://leetcode.com/problems/leftmost-column-with-at-least-a-one/
+ * Difficulty: Medium
+ *
+ * A row-sorted binary matrix means that all elements are 0 or 1 and each row of the matrix
+ * is sorted in non-decreasing order.
+ *
+ * Given a row-sorted binary matrix binaryMatrix, return the index (0-indexed) of the leftmost
+ * column with a 1 in it. If such an index does not exist, return -1.
+ *
+ * You can't access the Binary Matrix directly. You may only access the matrix using a
+ * BinaryMatrix interface:
+ * - BinaryMatrix.get(row, col) returns the element of the matrix at index (row, col) (0-indexed).
+ * - BinaryMatrix.dimensions() returns the dimensions of the matrix as a list of 2
+ * elements [rows, cols], which means the matrix is rows x cols.
+ *
+ * Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer.
+ * Also, any solutions that attempt to circumvent the judge will result in disqualification.
+ *
+ * For custom testing purposes, the input will be the entire binary matrix mat. You will not
+ * have access to the binary matrix directly.
+ */
+
+/**
+ * @param {BinaryMatrix} binaryMatrix
+ * @return {number}
+ */
+var leftMostColumnWithOne = function(binaryMatrix) {
+ const [rows, cols] = binaryMatrix.dimensions();
+ let result = -1;
+ let row = 0;
+ let col = cols - 1;
+
+ while (row < rows && col >= 0) {
+ if (binaryMatrix.get(row, col) === 1) {
+ result = col;
+ col--;
+ } else {
+ row++;
+ }
+ }
+
+ return result;
+};
From 3a5957eeb9400be02d50bf00212f0302c447905b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 2 Jul 2025 22:58:36 -0500
Subject: [PATCH 639/994] Add solution #1429
---
README.md | 1 +
solutions/1429-first-unique-number.js | 52 +++++++++++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 solutions/1429-first-unique-number.js
diff --git a/README.md b/README.md
index 6ccd1c3e..6971c9aa 100644
--- a/README.md
+++ b/README.md
@@ -1314,6 +1314,7 @@
1426|[Counting Elements](./solutions/1426-counting-elements.js)|Easy|
1427|[Perform String Shifts](./solutions/1427-perform-string-shifts.js)|Easy|
1428|[Leftmost Column with at Least a One](./solutions/1428-leftmost-column-with-at-least-a-one.js)|Medium|
+1429|[First Unique Number](./solutions/1429-first-unique-number.js)|Medium|
1431|[Kids With the Greatest Number of Candies](./solutions/1431-kids-with-the-greatest-number-of-candies.js)|Easy|
1432|[Max Difference You Can Get From Changing an Integer](./solutions/1432-max-difference-you-can-get-from-changing-an-integer.js)|Medium|
1433|[Check If a String Can Break Another String](./solutions/1433-check-if-a-string-can-break-another-string.js)|Medium|
diff --git a/solutions/1429-first-unique-number.js b/solutions/1429-first-unique-number.js
new file mode 100644
index 00000000..de330ddf
--- /dev/null
+++ b/solutions/1429-first-unique-number.js
@@ -0,0 +1,52 @@
+/**
+ * 1429. First Unique Number
+ * https://leetcode.com/problems/first-unique-number/
+ * Difficulty: Medium
+ *
+ * You have a queue of integers, you need to retrieve the first unique integer in the queue.
+ *
+ * Implement the FirstUnique class:
+ * - FirstUnique(int[] nums) Initializes the object with the numbers in the queue.
+ * - int showFirstUnique() returns the value of the first unique integer of the queue, and
+ * returns -1 if there is no such integer.
+ * - void add(int value) insert value to the queue.
+ */
+
+/**
+* @param {number[]} nums
+*/
+var FirstUnique = function(nums) {
+ this.queue = [];
+ this.counts = new Map();
+ this.uniqueSet = new Set();
+
+ for (const num of nums) {
+ this.add(num);
+ }
+};
+
+/**
+* @return {number}
+*/
+FirstUnique.prototype.showFirstUnique = function() {
+ while (this.queue.length > 0 && !this.uniqueSet.has(this.queue[0])) {
+ this.queue.shift();
+ }
+ return this.queue.length > 0 ? this.queue[0] : -1;
+};
+
+/**
+* @param {number} value
+* @return {void}
+*/
+FirstUnique.prototype.add = function(value) {
+ const count = this.counts.get(value) || 0;
+ this.counts.set(value, count + 1);
+
+ if (count === 0) {
+ this.queue.push(value);
+ this.uniqueSet.add(value);
+ } else if (count === 1) {
+ this.uniqueSet.delete(value);
+ }
+};
From e7093120c38399ab1491a9123cb16f2dc79d1235 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 2 Jul 2025 22:59:51 -0500
Subject: [PATCH 640/994] Add solution #1430
---
README.md | 1 +
...om-root-to-leaves-path-in-a-binary-tree.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/1430-check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree.js
diff --git a/README.md b/README.md
index 6971c9aa..85a4e963 100644
--- a/README.md
+++ b/README.md
@@ -1315,6 +1315,7 @@
1427|[Perform String Shifts](./solutions/1427-perform-string-shifts.js)|Easy|
1428|[Leftmost Column with at Least a One](./solutions/1428-leftmost-column-with-at-least-a-one.js)|Medium|
1429|[First Unique Number](./solutions/1429-first-unique-number.js)|Medium|
+1430|[Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree](./solutions/1430-check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree.js)|Medium|
1431|[Kids With the Greatest Number of Candies](./solutions/1431-kids-with-the-greatest-number-of-candies.js)|Easy|
1432|[Max Difference You Can Get From Changing an Integer](./solutions/1432-max-difference-you-can-get-from-changing-an-integer.js)|Medium|
1433|[Check If a String Can Break Another String](./solutions/1433-check-if-a-string-can-break-another-string.js)|Medium|
diff --git a/solutions/1430-check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree.js b/solutions/1430-check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree.js
new file mode 100644
index 00000000..7fcc855b
--- /dev/null
+++ b/solutions/1430-check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree.js
@@ -0,0 +1,41 @@
+/**
+ * 1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree
+ * https://leetcode.com/problems/check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree/
+ * Difficulty: Medium
+ *
+ * Given a binary tree where each path going from the root to any leaf form a valid
+ * sequence, check if a given string is a valid sequence in such binary tree.
+ *
+ * We get the given string from the concatenation of an array of integers arr and the
+ * concatenation of all values of the nodes along a path results in a sequence in the
+ * given binary tree.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @param {number[]} arr
+ * @return {boolean}
+ */
+var isValidSequence = function(root, arr) {
+ return dfs(root, 0);
+
+ function dfs(node, index) {
+ if (!node || index >= arr.length || node.val !== arr[index]) {
+ return false;
+ }
+
+ if (index === arr.length - 1) {
+ return !node.left && !node.right;
+ }
+
+ return dfs(node.left, index + 1) || dfs(node.right, index + 1);
+ }
+};
From 00972f21f6bb53d926adb3b63dda9894eb57fcad Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 2 Jul 2025 23:01:23 -0500
Subject: [PATCH 641/994] Add solution #1469
---
README.md | 1 +
solutions/1469-find-all-the-lonely-nodes.js | 44 +++++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/1469-find-all-the-lonely-nodes.js
diff --git a/README.md b/README.md
index 85a4e963..10b7017f 100644
--- a/README.md
+++ b/README.md
@@ -1348,6 +1348,7 @@
1465|[Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts](./solutions/1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts.js)|Medium|
1466|[Reorder Routes to Make All Paths Lead to the City Zero](./solutions/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js)|Medium|
1467|[Probability of a Two Boxes Having The Same Number of Distinct Balls](./solutions/1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls.js)|Hard|
+1469|[Find All The Lonely Nodes](./solutions/1469-find-all-the-lonely-nodes.js)|Easy|
1470|[Shuffle the Array](./solutions/1470-shuffle-the-array.js)|Easy|
1471|[The k Strongest Values in an Array](./solutions/1471-the-k-strongest-values-in-an-array.js)|Medium|
1472|[Design Browser History](./solutions/1472-design-browser-history.js)|Medium|
diff --git a/solutions/1469-find-all-the-lonely-nodes.js b/solutions/1469-find-all-the-lonely-nodes.js
new file mode 100644
index 00000000..91aa1167
--- /dev/null
+++ b/solutions/1469-find-all-the-lonely-nodes.js
@@ -0,0 +1,44 @@
+/**
+ * 1469. Find All The Lonely Nodes
+ * https://leetcode.com/problems/find-all-the-lonely-nodes/
+ * Difficulty: Easy
+ *
+ * In a binary tree, a lonely node is a node that is the only child of its parent node.
+ * The root of the tree is not lonely because it does not have a parent node.
+ *
+ * Given the root of a binary tree, return an array containing the values of all lonely
+ * nodes in the tree. Return the list in any order.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @return {number[]}
+ */
+var getLonelyNodes = function(root) {
+ const result = [];
+ dfs(root);
+ return result;
+
+ function dfs(node) {
+ if (!node) return;
+
+ if (node.left && !node.right) {
+ result.push(node.left.val);
+ }
+
+ if (!node.left && node.right) {
+ result.push(node.right.val);
+ }
+
+ dfs(node.left);
+ dfs(node.right);
+ }
+};
From 2341e08eb63f7da30fe65a8926832130842d265f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 2 Jul 2025 23:04:41 -0500
Subject: [PATCH 642/994] Add solution #1474
---
README.md | 1 +
...-n-nodes-after-m-nodes-of-a-linked-list.js | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/1474-delete-n-nodes-after-m-nodes-of-a-linked-list.js
diff --git a/README.md b/README.md
index 10b7017f..f42616aa 100644
--- a/README.md
+++ b/README.md
@@ -1353,6 +1353,7 @@
1471|[The k Strongest Values in an Array](./solutions/1471-the-k-strongest-values-in-an-array.js)|Medium|
1472|[Design Browser History](./solutions/1472-design-browser-history.js)|Medium|
1473|[Paint House III](./solutions/1473-paint-house-iii.js)|Hard|
+1474|[Delete N Nodes After M Nodes of a Linked List](./solutions/1474-delete-n-nodes-after-m-nodes-of-a-linked-list.js)|Easy|
1475|[Final Prices With a Special Discount in a Shop](./solutions/1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy|
1476|[Subrectangle Queries](./solutions/1476-subrectangle-queries.js)|Medium|
1477|[Find Two Non-overlapping Sub-arrays Each With Target Sum](./solutions/1477-find-two-non-overlapping-sub-arrays-each-with-target-sum.js)|Medium|
diff --git a/solutions/1474-delete-n-nodes-after-m-nodes-of-a-linked-list.js b/solutions/1474-delete-n-nodes-after-m-nodes-of-a-linked-list.js
new file mode 100644
index 00000000..8fd296ca
--- /dev/null
+++ b/solutions/1474-delete-n-nodes-after-m-nodes-of-a-linked-list.js
@@ -0,0 +1,50 @@
+/**
+ * 1474. Delete N Nodes After M Nodes of a Linked List
+ * https://leetcode.com/problems/delete-n-nodes-after-m-nodes-of-a-linked-list/
+ * Difficulty: Easy
+ *
+ * You are given the head of a linked list and two integers m and n.
+ *
+ * Traverse the linked list and remove some nodes in the following way:
+ * - Start with the head as the current node.
+ * - Keep the first m nodes starting with the current node.
+ * - Remove the next n nodes
+ * - Keep repeating steps 2 and 3 until you reach the end of the list.
+ *
+ * Return the head of the modified list after removing the mentioned nodes.
+ */
+
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val, next) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.next = (next===undefined ? null : next)
+ * }
+ */
+/**
+ * @param {ListNode} head
+ * @param {number} m
+ * @param {number} n
+ * @return {ListNode}
+ */
+var deleteNodes = function(head, m, n) {
+ let current = head;
+
+ while (current) {
+ for (let i = 1; i < m && current; i++) {
+ current = current.next;
+ }
+
+ if (!current) break;
+
+ let nodeToDelete = current.next;
+ for (let i = 0; i < n && nodeToDelete; i++) {
+ nodeToDelete = nodeToDelete.next;
+ }
+
+ current.next = nodeToDelete;
+ current = nodeToDelete;
+ }
+
+ return head;
+};
From a3621ab80823d56daea20ba2309f82753c5589e9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 2 Jul 2025 23:06:50 -0500
Subject: [PATCH 643/994] Add solution #1485
---
README.md | 1 +
...5-clone-binary-tree-with-random-pointer.js | 53 +++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/1485-clone-binary-tree-with-random-pointer.js
diff --git a/README.md b/README.md
index f42616aa..bf98d5d9 100644
--- a/README.md
+++ b/README.md
@@ -1362,6 +1362,7 @@
1481|[Least Number of Unique Integers after K Removals](./solutions/1481-least-number-of-unique-integers-after-k-removals.js)|Medium|
1482|[Minimum Number of Days to Make m Bouquets](./solutions/1482-minimum-number-of-days-to-make-m-bouquets.js)|Medium|
1483|[Kth Ancestor of a Tree Node](./solutions/1483-kth-ancestor-of-a-tree-node.js)|Hard|
+1485|[Clone Binary Tree With Random Pointer](./solutions/1485-clone-binary-tree-with-random-pointer.js)|Medium|
1486|[XOR Operation in an Array](./solutions/1486-xor-operation-in-an-array.js)|Easy|
1487|[Making File Names Unique](./solutions/1487-making-file-names-unique.js)|Medium|
1488|[Avoid Flood in The City](./solutions/1488-avoid-flood-in-the-city.js)|Medium|
diff --git a/solutions/1485-clone-binary-tree-with-random-pointer.js b/solutions/1485-clone-binary-tree-with-random-pointer.js
new file mode 100644
index 00000000..36dab6d7
--- /dev/null
+++ b/solutions/1485-clone-binary-tree-with-random-pointer.js
@@ -0,0 +1,53 @@
+/**
+ * 1485. Clone Binary Tree With Random Pointer
+ * https://leetcode.com/problems/clone-binary-tree-with-random-pointer/
+ * Difficulty: Medium
+ *
+ * A binary tree is given such that each node contains an additional random pointer which
+ * could point to any node in the tree or null.
+ *
+ * Return a deep copy of the tree.
+ *
+ * The tree is represented in the same input/output way as normal binary trees where each
+ * node is represented as a pair of [val, random_index] where:
+ * - val: an integer representing Node.val
+ * - random_index: the index of the node (in the input) where the random pointer points to,
+ * or null if it does not point to any node.
+ *
+ * You will be given the tree in class Node and you should return the cloned tree in class
+ * NodeCopy. NodeCopy class is just a clone of Node class with the same attributes and constructors.
+ */
+
+/**
+ * // Definition for a _Node.
+ * function _Node(val, left, right, random) {
+ * this.val = val === undefined ? null : val;
+ * this.left = left === undefined ? null : left;
+ * this.right = right === undefined ? null : right;
+ * this.random = random === undefined ? null : random;
+ * };
+ */
+
+/**
+ * @param {_Node} root
+ * @return {NodeCopy}
+ */
+var copyRandomBinaryTree = function(root) {
+ if (!root) return null;
+ const nodeMap = new Map();
+ return createCopy(root);
+
+ function createCopy(node) {
+ if (!node) return null;
+ if (nodeMap.has(node)) return nodeMap.get(node);
+
+ const copy = new NodeCopy(node.val);
+ nodeMap.set(node, copy);
+
+ copy.left = createCopy(node.left);
+ copy.right = createCopy(node.right);
+ copy.random = createCopy(node.random);
+
+ return copy;
+ }
+};
From 5e766fd8dc096f3cb5e22556a79b03c03ee21742 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 2 Jul 2025 23:08:05 -0500
Subject: [PATCH 644/994] Add solution #1490
---
README.md | 1 +
solutions/1490-clone-n-ary-tree.js | 38 ++++++++++++++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/1490-clone-n-ary-tree.js
diff --git a/README.md b/README.md
index bf98d5d9..2f1c0a59 100644
--- a/README.md
+++ b/README.md
@@ -1367,6 +1367,7 @@
1487|[Making File Names Unique](./solutions/1487-making-file-names-unique.js)|Medium|
1488|[Avoid Flood in The City](./solutions/1488-avoid-flood-in-the-city.js)|Medium|
1489|[Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree](./solutions/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.js)|Hard|
+1490|[Clone N-ary Tree](./solutions/1490-clone-n-ary-tree.js)|Medium|
1491|[Average Salary Excluding the Minimum and Maximum Salary](./solutions/1491-average-salary-excluding-the-minimum-and-maximum-salary.js)|Easy|
1492|[The kth Factor of n](./solutions/1492-the-kth-factor-of-n.js)|Medium|
1493|[Longest Subarray of 1's After Deleting One Element](./solutions/1493-longest-subarray-of-1s-after-deleting-one-element.js)|Medium|
diff --git a/solutions/1490-clone-n-ary-tree.js b/solutions/1490-clone-n-ary-tree.js
new file mode 100644
index 00000000..46d589f0
--- /dev/null
+++ b/solutions/1490-clone-n-ary-tree.js
@@ -0,0 +1,38 @@
+/**
+ * 1490. Clone N-ary Tree
+ * https://leetcode.com/problems/clone-n-ary-tree/
+ * Difficulty: Medium
+ *
+ * Given a root of an N-ary tree, return a deep copy (clone) of the tree.
+ *
+ * Each node in the n-ary tree contains a val (int) and a list (List[Node]) of its children.
+ *
+ * class Node {
+ * public int val;
+ * public List children;
+ * }
+ *
+ * Nary-Tree input serialization is represented in their level order traversal, each group
+ * of children is separated by the null value (See examples).
+ */
+
+/**
+ * // Definition for a _Node.
+ * function _Node(val, children) {
+ * this.val = val === undefined ? 0 : val;
+ * this.children = children === undefined ? [] : children;
+ * };
+ */
+
+/**
+ * @param {_Node|null} node
+ * @return {_Node|null}
+ */
+var cloneTree = function(root) {
+ if (!root) return null;
+
+ const clonedNode = new _Node(root.val);
+ clonedNode.children = root.children.map(child => cloneTree(child));
+
+ return clonedNode;
+};
From f3dd2eb10a92346972576b99aba8165c6d1cb292 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 2 Jul 2025 23:12:03 -0500
Subject: [PATCH 645/994] Add solution #1500
---
README.md | 1 +
.../1500-design-a-file-sharing-system.js | 89 +++++++++++++++++++
2 files changed, 90 insertions(+)
create mode 100644 solutions/1500-design-a-file-sharing-system.js
diff --git a/README.md b/README.md
index 2f1c0a59..dafd332f 100644
--- a/README.md
+++ b/README.md
@@ -1376,6 +1376,7 @@
1497|[Check If Array Pairs Are Divisible by k](./solutions/1497-check-if-array-pairs-are-divisible-by-k.js)|Medium|
1498|[Number of Subsequences That Satisfy the Given Sum Condition](./solutions/1498-number-of-subsequences-that-satisfy-the-given-sum-condition.js)|Medium|
1499|[Max Value of Equation](./solutions/1499-max-value-of-equation.js)|Hard|
+1500|[Design a File Sharing System](./solutions/1500-design-a-file-sharing-system.js)|Medium|
1502|[Can Make Arithmetic Progression From Sequence](./solutions/1502-can-make-arithmetic-progression-from-sequence.js)|Easy|
1503|[Last Moment Before All Ants Fall Out of a Plank](./solutions/1503-last-moment-before-all-ants-fall-out-of-a-plank.js)|Medium|
1504|[Count Submatrices With All Ones](./solutions/1504-count-submatrices-with-all-ones.js)|Medium|
diff --git a/solutions/1500-design-a-file-sharing-system.js b/solutions/1500-design-a-file-sharing-system.js
new file mode 100644
index 00000000..f32f210a
--- /dev/null
+++ b/solutions/1500-design-a-file-sharing-system.js
@@ -0,0 +1,89 @@
+/**
+ * 1500. Design a File Sharing System
+ * https://leetcode.com/problems/design-a-file-sharing-system/
+ * Difficulty: Medium
+ *
+ * We will use a file-sharing system to share a very large file which consists of m small
+ * chunks with IDs from 1 to m.
+ *
+ * When users join the system, the system should assign a unique ID to them. The unique ID
+ * should be used once for each user, but when a user leaves the system, the ID can be reused again.
+ *
+ * Users can request a certain chunk of the file, the system should return a list of IDs of
+ * all the users who own this chunk. If the user receives a non-empty list of IDs, they receive
+ * the requested chunk successfully.
+ *
+ * Implement the FileSharing class:
+ * - FileSharing(int m) Initializes the object with a file of m chunks.
+ * - int join(int[] ownedChunks): A new user joined the system owning some chunks of the file,
+ * the system should assign an id to the user which is the smallest positive integer not
+ * taken by any other user. Return the assigned id.
+ * - void leave(int userID): The user with userID will leave the system, you cannot take file
+ * chunks from them anymore.
+ * - int[] request(int userID, int chunkID): The user userID requested the file chunk with chunkID.
+ * Return a list of the IDs of all users that own this chunk sorted in ascending order.
+ */
+
+/**
+* @param {number} m
+*/
+var FileSharing = function(m) {
+ this.chunkToUsers = new Array(m + 1).fill().map(() => new Set());
+ this.userToChunks = new Map();
+ this.availableIds = [];
+ this.nextId = 1;
+};
+
+/**
+* @param {number[]} ownedChunks
+* @return {number}
+*/
+FileSharing.prototype.join = function(ownedChunks) {
+ let userId;
+
+ if (this.availableIds.length > 0) {
+ userId = this.availableIds.sort((a, b) => a - b).shift();
+ } else {
+ userId = this.nextId++;
+ }
+
+ this.userToChunks.set(userId, new Set(ownedChunks));
+
+ for (const chunk of ownedChunks) {
+ this.chunkToUsers[chunk].add(userId);
+ }
+
+ return userId;
+};
+
+/**
+* @param {number} userID
+* @return {void}
+*/
+FileSharing.prototype.leave = function(userID) {
+ const userChunks = this.userToChunks.get(userID);
+
+ if (userChunks) {
+ for (const chunk of userChunks) {
+ this.chunkToUsers[chunk].delete(userID);
+ }
+ this.userToChunks.delete(userID);
+ this.availableIds.push(userID);
+ }
+};
+
+/**
+* @param {number} userID
+* @param {number} chunkID
+* @return {number[]}
+*/
+FileSharing.prototype.request = function(userID, chunkID) {
+ const usersWithChunk = Array.from(this.chunkToUsers[chunkID]).sort((a, b) => a - b);
+
+ if (usersWithChunk.length > 0) {
+ this.userToChunks.get(userID).add(chunkID);
+ this.chunkToUsers[chunkID].add(userID);
+ }
+
+ return usersWithChunk;
+};
From 26f7037e4d6adc6577e39df6e63503f65c7affcc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 2 Jul 2025 23:19:54 -0500
Subject: [PATCH 646/994] Add solution #1506
---
README.md | 1 +
solutions/1506-find-root-of-n-ary-tree.js | 42 +++++++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/1506-find-root-of-n-ary-tree.js
diff --git a/README.md b/README.md
index dafd332f..e9375067 100644
--- a/README.md
+++ b/README.md
@@ -1381,6 +1381,7 @@
1503|[Last Moment Before All Ants Fall Out of a Plank](./solutions/1503-last-moment-before-all-ants-fall-out-of-a-plank.js)|Medium|
1504|[Count Submatrices With All Ones](./solutions/1504-count-submatrices-with-all-ones.js)|Medium|
1505|[Minimum Possible Integer After at Most K Adjacent Swaps On Digits](./solutions/1505-minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits.js)|Hard|
+1506|[Find Root of N-Ary Tree](./solutions/1506-find-root-of-n-ary-tree.js)|Medium|
1507|[Reformat Date](./solutions/1507-reformat-date.js)|Easy|
1508|[Range Sum of Sorted Subarray Sums](./solutions/1508-range-sum-of-sorted-subarray-sums.js)|Medium|
1509|[Minimum Difference Between Largest and Smallest Value in Three Moves](./solutions/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves.js)|Medium|
diff --git a/solutions/1506-find-root-of-n-ary-tree.js b/solutions/1506-find-root-of-n-ary-tree.js
new file mode 100644
index 00000000..22e1105b
--- /dev/null
+++ b/solutions/1506-find-root-of-n-ary-tree.js
@@ -0,0 +1,42 @@
+/**
+ * 1506. Find Root of N-Ary Tree
+ * https://leetcode.com/problems/find-root-of-n-ary-tree/
+ * Difficulty: Medium
+ *
+ * You are given all the nodes of an N-ary tree as an array of Node objects, where each
+ * node has a unique value.
+ *
+ * Return the root of the N-ary tree.
+ *
+ * Custom testing:
+ * - An N-ary tree can be serialized as represented in its level order traversal where each
+ * group of children is separated by the null value (see examples).
+ */
+
+/**
+ * // Definition for a _Node.
+ * function _Node(val, children) {
+ * this.val = val === undefined ? 0 : val;
+ * this.children = children === undefined ? [] : children;
+ * };
+ */
+
+/**
+ * @param {_Node[]} tree
+ * @return {_Node}
+ */
+var findRoot = function(tree) {
+ const set = new Set();
+
+ for (const node of tree) {
+ for (const child of node.children) {
+ set.add(child.val);
+ }
+ }
+
+ for (const node of tree) {
+ if (!set.has(node.val)) {
+ return node;
+ }
+ }
+};
From b95e21a5b07c92a810c54ceee01f69e36bb4f552 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 2 Jul 2025 23:31:13 -0500
Subject: [PATCH 647/994] Add solution #1516
---
README.md | 1 +
solutions/1516-move-sub-tree-of-n-ary-tree.js | 76 +++++++++++++++++++
2 files changed, 77 insertions(+)
create mode 100644 solutions/1516-move-sub-tree-of-n-ary-tree.js
diff --git a/README.md b/README.md
index e9375067..05208d8d 100644
--- a/README.md
+++ b/README.md
@@ -1390,6 +1390,7 @@
1513|[Number of Substrings With Only 1s](./solutions/1513-number-of-substrings-with-only-1s.js)|Medium|
1514|[Path with Maximum Probability](./solutions/1514-path-with-maximum-probability.js)|Medium|
1515|[Best Position for a Service Centre](./solutions/1515-best-position-for-a-service-centre.js)|Hard|
+1516|[Move Sub-Tree of N-Ary Tree](./solutions/1516-move-sub-tree-of-n-ary-tree.js)|Hard|
1518|[Water Bottles](./solutions/1518-water-bottles.js)|Easy|
1519|[Number of Nodes in the Sub-Tree With the Same Label](./solutions/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js)|Medium|
1520|[Maximum Number of Non-Overlapping Substrings](./solutions/1520-maximum-number-of-non-overlapping-substrings.js)|Hard|
diff --git a/solutions/1516-move-sub-tree-of-n-ary-tree.js b/solutions/1516-move-sub-tree-of-n-ary-tree.js
new file mode 100644
index 00000000..09b8cade
--- /dev/null
+++ b/solutions/1516-move-sub-tree-of-n-ary-tree.js
@@ -0,0 +1,76 @@
+/**
+ * 1516. Move Sub-Tree of N-Ary Tree
+ * https://leetcode.com/problems/move-sub-tree-of-n-ary-tree/
+ * Difficulty: Hard
+ *
+ * Given the root of an N-ary tree of unique values, and two nodes of the tree p and q.
+ *
+ * You should move the subtree of the node p to become a direct child of node q. If p is
+ * already a direct child of q, do not change anything. Node p must be the last child in
+ * the children list of node q.
+ *
+ * Return the root of the tree after adjusting it.
+ *
+ * There are 3 cases for nodes p and q:
+ * 1. Node q is in the sub-tree of node p.
+ * 2. Node p is in the sub-tree of node q.
+ * 3. Neither node p is in the sub-tree of node q nor node q is in the sub-tree of node p.
+ *
+ * In cases 2 and 3, you just need to move p (with its sub-tree) to be a child of q, but in
+ * case 1 the tree may be disconnected, thus you need to reconnect the tree again. Please
+ * read the examples carefully before solving this problem.
+ *
+ * Nary-Tree input serialization is represented in their level order traversal, each group
+ * of children is separated by the null value (See examples).
+ */
+
+/**
+ * // Definition for a Node.
+ * function Node(val, children) {
+ * this.val = val === undefined ? 0 : val;
+ * this.children = children === undefined ? [] : children;
+ * };
+ */
+
+/**
+ * @param {Node} root
+ * @param {Node} p
+ * @param {Node} q
+ * @return {Node}
+ */
+var moveSubTree = function(root, p, q) {
+ if (q.children.includes(p)) return root;
+
+ const pParent = findParent(root, p);
+ const qParent = findParent(root, q);
+
+ if (isDescendant(q, p)) {
+ qParent.children = qParent.children.filter(child => child !== q);
+ q.children.push(p);
+
+ if (!pParent) return q;
+
+ pParent.children[pParent.children.indexOf(p)] = q;
+ } else {
+ q.children.push(p);
+ pParent.children = pParent.children.filter(child => child !== p);
+ }
+
+ return root;
+
+ function findParent(node, target) {
+ if (!node) return null;
+ for (const child of node.children) {
+ if (child === target) return node;
+ const parent = findParent(child, target);
+ if (parent) return parent;
+ }
+ return null;
+ }
+
+ function isDescendant(target, node) {
+ if (!node) return false;
+ if (node === target) return true;
+ return node.children.some(child => isDescendant(target, child));
+ }
+};
From 6ec0e3243cd239de8041e509e2e94b37c88badf0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 2 Jul 2025 23:32:39 -0500
Subject: [PATCH 648/994] Add solution #1522
---
README.md | 1 +
solutions/1522-diameter-of-n-ary-tree.js | 42 ++++++++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/1522-diameter-of-n-ary-tree.js
diff --git a/README.md b/README.md
index 05208d8d..2ecc347b 100644
--- a/README.md
+++ b/README.md
@@ -1395,6 +1395,7 @@
1519|[Number of Nodes in the Sub-Tree With the Same Label](./solutions/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js)|Medium|
1520|[Maximum Number of Non-Overlapping Substrings](./solutions/1520-maximum-number-of-non-overlapping-substrings.js)|Hard|
1521|[Find a Value of a Mysterious Function Closest to Target](./solutions/1521-find-a-value-of-a-mysterious-function-closest-to-target.js)|Hard|
+1522|[Diameter of N-Ary Tree](./solutions/1522-diameter-of-n-ary-tree.js)|Medium|
1523|[Count Odd Numbers in an Interval Range](./solutions/1523-count-odd-numbers-in-an-interval-range.js)|Easy|
1524|[Number of Sub-arrays With Odd Sum](./solutions/1524-number-of-sub-arrays-with-odd-sum.js)|Medium|
1525|[Number of Good Ways to Split a String](./solutions/1525-number-of-good-ways-to-split-a-string.js)|Medium|
diff --git a/solutions/1522-diameter-of-n-ary-tree.js b/solutions/1522-diameter-of-n-ary-tree.js
new file mode 100644
index 00000000..d953888d
--- /dev/null
+++ b/solutions/1522-diameter-of-n-ary-tree.js
@@ -0,0 +1,42 @@
+/**
+ * 1522. Diameter of N-Ary Tree
+ * https://leetcode.com/problems/diameter-of-n-ary-tree/
+ * Difficulty: Medium
+ *
+ * Given a root of an N-ary tree, you need to compute the length of the diameter of the tree.
+ *
+ * The diameter of an N-ary tree is the length of the longest path between any two nodes in
+ * the tree. This path may or may not pass through the root.
+ *
+ * (Nary-Tree input serialization is represented in their level order traversal, each group
+ * of children is separated by the null value.)
+ */
+
+/**
+ * // Definition for a _Node.
+ * function _Node(val, children) {
+ * this.val = val === undefined ? 0 : val;
+ * this.children = children === undefined ? [] : children;
+ * };
+ */
+
+/**
+ * @param {_Node} root
+ * @return {number}
+ */
+var diameter = function(root) {
+ let maxDiameter = 0;
+ dfs(root);
+ return maxDiameter;
+
+ function dfs(node) {
+ if (!node) return 0;
+
+ const depths = node.children.map(child => dfs(child)).sort((a, b) => b - a);
+
+ const currentDiameter = depths.length >= 2 ? depths[0] + depths[1] : depths[0] || 0;
+ maxDiameter = Math.max(maxDiameter, currentDiameter);
+
+ return (depths[0] || 0) + 1;
+ }
+};
From 8e53467296ea9941e6ba0c8e03f7c22c3e5af6b2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 2 Jul 2025 23:34:27 -0500
Subject: [PATCH 649/994] Add solution #1533
---
README.md | 1 +
...533-find-the-index-of-the-large-integer.js | 56 +++++++++++++++++++
2 files changed, 57 insertions(+)
create mode 100644 solutions/1533-find-the-index-of-the-large-integer.js
diff --git a/README.md b/README.md
index 2ecc347b..4b7ff793 100644
--- a/README.md
+++ b/README.md
@@ -1404,6 +1404,7 @@
1529|[Minimum Suffix Flips](./solutions/1529-minimum-suffix-flips.js)|Medium|
1530|[Number of Good Leaf Nodes Pairs](./solutions/1530-number-of-good-leaf-nodes-pairs.js)|Medium|
1531|[String Compression II](./solutions/1531-string-compression-ii.js)|Hard|
+1533|[Find the Index of the Large Integer](./solutions/1533-find-the-index-of-the-large-integer.js)|Medium|
1534|[Count Good Triplets](./solutions/1534-count-good-triplets.js)|Easy|
1535|[Find the Winner of an Array Game](./solutions/1535-find-the-winner-of-an-array-game.js)|Medium|
1536|[Minimum Swaps to Arrange a Binary Grid](./solutions/1536-minimum-swaps-to-arrange-a-binary-grid.js)|Medium|
diff --git a/solutions/1533-find-the-index-of-the-large-integer.js b/solutions/1533-find-the-index-of-the-large-integer.js
new file mode 100644
index 00000000..74decece
--- /dev/null
+++ b/solutions/1533-find-the-index-of-the-large-integer.js
@@ -0,0 +1,56 @@
+/**
+ * 1533. Find the Index of the Large Integer
+ * https://leetcode.com/problems/find-the-index-of-the-large-integer/
+ * Difficulty: Medium
+ *
+ * We have an integer array arr, where all the integers in arr are equal except for one integer
+ * which is larger than the rest of the integers. You will not be given direct access to the
+ * array, instead, you will have an API ArrayReader which have the following functions:
+ * - int compareSub(int l, int r, int x, int y): where 0 <= l, r, x, y < ArrayReader.length(),
+ * l <= r and x <= y. The function compares the sum of sub-array arr[l..r] with the sum of
+ * the sub-array arr[x..y] and returns:
+ * - 1 if arr[l]+arr[l+1]+...+arr[r] > arr[x]+arr[x+1]+...+arr[y].
+ * - 0 if arr[l]+arr[l+1]+...+arr[r] == arr[x]+arr[x+1]+...+arr[y].
+ * - -1 if arr[l]+arr[l+1]+...+arr[r] < arr[x]+arr[x+1]+...+arr[y].
+ * - int length(): Returns the size of the array.
+ *
+ * You are allowed to call compareSub() 20 times at most. You can assume both functions work
+ * in O(1) time.
+ *
+ * Return the index of the array arr which has the largest integer.
+ */
+
+/**
+ * @param {ArrayReader} reader
+ * @return {number}
+ */
+var getIndex = function(reader) {
+ const n = reader.length();
+ let left = 0;
+ let right = n - 1;
+
+ while (left < right) {
+ const length = right - left + 1;
+ const mid = Math.floor((left + right) / 2);
+
+ if (length % 2 === 1) {
+ const comparison = reader.compareSub(left, mid - 1, mid + 1, right);
+ if (comparison === 0) {
+ return mid;
+ } else if (comparison === 1) {
+ right = mid - 1;
+ } else {
+ left = mid + 1;
+ }
+ } else {
+ const comparison = reader.compareSub(left, mid, mid + 1, right);
+ if (comparison === 1) {
+ right = mid;
+ } else {
+ left = mid + 1;
+ }
+ }
+ }
+
+ return left;
+};
From f5ddbfb5a178648a4adff37063a5c516fc53a20d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 2 Jul 2025 23:50:22 -0500
Subject: [PATCH 650/994] Add solution #1538
---
README.md | 1 +
...38-guess-the-majority-in-a-hidden-array.js | 86 +++++++++++++++++++
2 files changed, 87 insertions(+)
create mode 100644 solutions/1538-guess-the-majority-in-a-hidden-array.js
diff --git a/README.md b/README.md
index 4b7ff793..fb66ab50 100644
--- a/README.md
+++ b/README.md
@@ -1409,6 +1409,7 @@
1535|[Find the Winner of an Array Game](./solutions/1535-find-the-winner-of-an-array-game.js)|Medium|
1536|[Minimum Swaps to Arrange a Binary Grid](./solutions/1536-minimum-swaps-to-arrange-a-binary-grid.js)|Medium|
1537|[Get the Maximum Score](./solutions/1537-get-the-maximum-score.js)|Hard|
+1538|[Guess the Majority in a Hidden Array](./solutions/1538-guess-the-majority-in-a-hidden-array.js)|Medium|
1539|[Kth Missing Positive Number](./solutions/1539-kth-missing-positive-number.js)|Easy|
1540|[Can Convert String in K Moves](./solutions/1540-can-convert-string-in-k-moves.js)|Medium|
1541|[Minimum Insertions to Balance a Parentheses String](./solutions/1541-minimum-insertions-to-balance-a-parentheses-string.js)|Medium|
diff --git a/solutions/1538-guess-the-majority-in-a-hidden-array.js b/solutions/1538-guess-the-majority-in-a-hidden-array.js
new file mode 100644
index 00000000..d1f1dbc6
--- /dev/null
+++ b/solutions/1538-guess-the-majority-in-a-hidden-array.js
@@ -0,0 +1,86 @@
+/**
+ * 1538. Guess the Majority in a Hidden Array
+ * https://leetcode.com/problems/guess-the-majority-in-a-hidden-array/
+ * Difficulty: Medium
+ *
+ * We have an integer array nums, where all the integers in nums are 0 or 1. You will not
+ * be given direct access to the array, instead, you will have an API ArrayReader which
+ * have the following functions:
+ * - int query(int a, int b, int c, int d): where 0 <= a < b < c < d < ArrayReader.length().
+ * The function returns the distribution of the value of the 4 elements and returns:
+ * - 4 : if the values of the 4 elements are the same (0 or 1).
+ * - 2 : if three elements have a value equal to 0 and one element has value equal to 1 or
+ * vice versa.
+ * - 0 : if two element have a value equal to 0 and two elements have a value equal to 1.
+ * - int length(): Returns the size of the array.
+ *
+ * You are allowed to call query() 2 * n times at most where n is equal to ArrayReader.length().
+ *
+ * Return any index of the most frequent value in nums, in case of tie, return -1.
+ */
+
+/**
+ * // This is the ArrayReader's API interface.
+ * // You should not implement it, or speculate about its implementation
+ * function ArrayReader() {
+ * // Compares 4 different elements in the array
+ * // return 4 if the values of the 4 elements are the same (0 or 1).
+ * // return 2 if three elements have a value equal to 0 and one element has value equal
+ * // to 1 or vice versa.
+ * // return 0 : if two element have a value equal to 0 and two elements have a value
+ * // equal to 1.
+ * @param {number} a, b, c, d
+ * @return {number}
+ * this.query = function(a, b, c, d) {
+ * ...
+ * };
+ *
+ * // Returns the length of the array
+ * @return {number}
+ * this.length = function() {
+ * ...
+ * };
+ * };
+ */
+
+/**
+ * @param {ArrayReader} reader
+ * @return {number}
+ */
+var guessMajority = function(reader) {
+ const baseQuery = reader.query(0, 1, 2, 3);
+ const n = reader.length();
+ let sameAsZeroCount = 1;
+ let differentIndex = -1;
+
+ for (let i = 4; i < n; i++) {
+ const currentQuery = reader.query(1, 2, 3, i);
+ if (baseQuery === currentQuery) {
+ sameAsZeroCount++;
+ } else {
+ differentIndex = i;
+ }
+ }
+
+ const referenceQuery = reader.query(1, 2, 3, 4);
+ checkElement([0, 2, 3, 4], 1);
+ checkElement([0, 1, 3, 4], 2);
+ checkElement([0, 1, 2, 4], 3);
+
+ const differentCount = n - sameAsZeroCount;
+ if (sameAsZeroCount > differentCount) {
+ return 0;
+ } else if (sameAsZeroCount === differentCount) {
+ return -1;
+ } else {
+ return differentIndex;
+ }
+
+ function checkElement(indices, elementIndex) {
+ if (referenceQuery === reader.query(...indices)) {
+ sameAsZeroCount++;
+ } else {
+ differentIndex = elementIndex;
+ }
+ }
+};
From fa905a22fb3884a813a2c061a9d014556d6c3966 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 3 Jul 2025 23:31:17 -0500
Subject: [PATCH 651/994] Add solution #3307
---
README.md | 1 +
...nd-the-k-th-character-in-string-game-ii.js | 54 +++++++++++++++++++
2 files changed, 55 insertions(+)
create mode 100644 solutions/3307-find-the-k-th-character-in-string-game-ii.js
diff --git a/README.md b/README.md
index fb66ab50..812587d8 100644
--- a/README.md
+++ b/README.md
@@ -2412,6 +2412,7 @@
3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard|
3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
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|
+3307|[Find the K-th Character in String Game II](./solutions/3307-find-the-k-th-character-in-string-game-ii.js)|Hard|
3330|[Find the Original Typed String I](./solutions/3330-find-the-original-typed-string-i.js)|Easy|
3333|[Find the Original Typed String II](./solutions/3333-find-the-original-typed-string-ii.js)|Hard|
3335|[Total Characters in String After Transformations I](./solutions/3335-total-characters-in-string-after-transformations-i.js)|Medium|
diff --git a/solutions/3307-find-the-k-th-character-in-string-game-ii.js b/solutions/3307-find-the-k-th-character-in-string-game-ii.js
new file mode 100644
index 00000000..33329c8c
--- /dev/null
+++ b/solutions/3307-find-the-k-th-character-in-string-game-ii.js
@@ -0,0 +1,54 @@
+/**
+ * 3307. Find the K-th Character in String Game II
+ * https://leetcode.com/problems/find-the-k-th-character-in-string-game-ii/
+ * Difficulty: Hard
+ *
+ * Alice and Bob are playing a game. Initially, Alice has a string word = "a".
+ *
+ * You are given a positive integer k. You are also given an integer array operations,
+ * where operations[i] represents the type of the ith operation.
+ *
+ * Now Bob will ask Alice to perform all operations in sequence:
+ * - If operations[i] == 0, append a copy of word to itself.
+ * - If operations[i] == 1, generate a new string by changing each character in word to
+ * its next character in the English alphabet, and append it to the original word.
+ * For example, performing the operation on "c" generates "cd" and performing the
+ * operation on "zb" generates "zbac".
+ *
+ * Return the value of the kth character in word after performing all the operations.
+ *
+ * Note that the character 'z' can be changed to 'a' in the second type of operation.
+ */
+
+/**
+ * @param {number} k
+ * @param {number[]} operations
+ * @return {character}
+ */
+var kthCharacter = function(k, operations) {
+ const validOperations = [];
+ let length = 1;
+
+ for (const op of operations) {
+ if (length >= k) break;
+ validOperations.push(op);
+ length *= 2;
+ }
+
+ return findCharacter(k, validOperations.length - 1, 0);
+
+ function findCharacter(position, operationIndex, shifts) {
+ if (operationIndex < 0) {
+ return String.fromCharCode(97 + (shifts % 26));
+ }
+
+ const halfLength = Math.pow(2, operationIndex);
+
+ if (position <= halfLength) {
+ return findCharacter(position, operationIndex - 1, shifts);
+ } else {
+ const newShifts = shifts + validOperations[operationIndex];
+ return findCharacter(position - halfLength, operationIndex - 1, newShifts);
+ }
+ }
+};
From 5aa010e3eb799c10e81a21738160c9c06402e421 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 3 Jul 2025 23:36:10 -0500
Subject: [PATCH 652/994] Add solution #1548
---
README.md | 1 +
.../1548-the-most-similar-path-in-a-graph.js | 71 +++++++++++++++++++
2 files changed, 72 insertions(+)
create mode 100644 solutions/1548-the-most-similar-path-in-a-graph.js
diff --git a/README.md b/README.md
index 812587d8..bcb55207 100644
--- a/README.md
+++ b/README.md
@@ -1418,6 +1418,7 @@
1545|[Find Kth Bit in Nth Binary String](./solutions/1545-find-kth-bit-in-nth-binary-string.js)|Medium|
1546|[Maximum Number of Non-Overlapping Subarrays With Sum Equals Target](./solutions/1546-maximum-number-of-non-overlapping-subarrays-with-sum-equals-target.js)|Medium|
1547|[Minimum Cost to Cut a Stick](./solutions/1547-minimum-cost-to-cut-a-stick.js)|Hard|
+1548|[The Most Similar Path in a Graph](./solutions/1548-the-most-similar-path-in-a-graph.js)|Hard|
1550|[Three Consecutive Odds](./solutions/1550-three-consecutive-odds.js)|Easy|
1551|[Minimum Operations to Make Array Equal](./solutions/1551-minimum-operations-to-make-array-equal.js)|Medium|
1552|[Magnetic Force Between Two Balls](./solutions/1552-magnetic-force-between-two-balls.js)|Medium|
diff --git a/solutions/1548-the-most-similar-path-in-a-graph.js b/solutions/1548-the-most-similar-path-in-a-graph.js
new file mode 100644
index 00000000..6de39220
--- /dev/null
+++ b/solutions/1548-the-most-similar-path-in-a-graph.js
@@ -0,0 +1,71 @@
+/**
+ * 1548. The Most Similar Path in a Graph
+ * https://leetcode.com/problems/the-most-similar-path-in-a-graph/
+ * Difficulty: Hard
+ *
+ * We have n cities and m bi-directional roads where roads[i] = [ai, bi] connects city ai
+ * with city bi. Each city has a name consisting of exactly three upper-case English letters
+ * given in the string array names. Starting at any city x, you can reach any city y where
+ * y != x (i.e., the cities and the roads are forming an undirected connected graph).
+ *
+ * You will be given a string array targetPath. You should find a path in the graph of the
+ * same length and with the minimum edit distance to targetPath.
+ *
+ * You need to return the order of the nodes in the path with the minimum edit distance.
+ * The path should be of the same length of targetPath and should be valid (i.e., there
+ * should be a direct road between ans[i] and ans[i + 1]). If there are multiple answers
+ * return any one of them.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} roads
+ * @param {string[]} names
+ * @param {string[]} targetPath
+ * @return {number[]}
+ */
+var mostSimilar = function(n, roads, names, targetPath) {
+ const graph = new Array(n).fill().map(() => []);
+ for (const [a, b] of roads) {
+ graph[a].push(b);
+ graph[b].push(a);
+ }
+
+ const m = targetPath.length;
+ const dp = new Array(m).fill().map(() => new Array(n).fill(Infinity));
+ const parent = new Array(m).fill().map(() => new Array(n).fill(-1));
+
+ for (let city = 0; city < n; city++) {
+ dp[0][city] = names[city] === targetPath[0] ? 0 : 1;
+ }
+
+ for (let step = 1; step < m; step++) {
+ for (let city = 0; city < n; city++) {
+ for (const neighbor of graph[city]) {
+ const cost = dp[step - 1][neighbor] + (names[city] === targetPath[step] ? 0 : 1);
+ if (cost < dp[step][city]) {
+ dp[step][city] = cost;
+ parent[step][city] = neighbor;
+ }
+ }
+ }
+ }
+
+ let minCost = Infinity;
+ let lastCity = -1;
+ for (let city = 0; city < n; city++) {
+ if (dp[m - 1][city] < minCost) {
+ minCost = dp[m - 1][city];
+ lastCity = city;
+ }
+ }
+
+ const result = [];
+ let currentCity = lastCity;
+ for (let step = m - 1; step >= 0; step--) {
+ result.unshift(currentCity);
+ currentCity = parent[step][currentCity];
+ }
+
+ return result;
+};
From 1f0634cf5a17855e6ab73f9a5a33b2553d645c66 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 3 Jul 2025 23:40:44 -0500
Subject: [PATCH 653/994] Add solution #1554
---
README.md | 1 +
.../1554-strings-differ-by-one-character.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/1554-strings-differ-by-one-character.js
diff --git a/README.md b/README.md
index bcb55207..fd565716 100644
--- a/README.md
+++ b/README.md
@@ -1423,6 +1423,7 @@
1551|[Minimum Operations to Make Array Equal](./solutions/1551-minimum-operations-to-make-array-equal.js)|Medium|
1552|[Magnetic Force Between Two Balls](./solutions/1552-magnetic-force-between-two-balls.js)|Medium|
1553|[Minimum Number of Days to Eat N Oranges](./solutions/1553-minimum-number-of-days-to-eat-n-oranges.js)|Hard|
+1554|[Strings Differ by One Character](./solutions/1554-strings-differ-by-one-character.js)|Medium|
1556|[Thousand Separator](./solutions/1556-thousand-separator.js)|Easy|
1557|[Minimum Number of Vertices to Reach All Nodes](./solutions/1557-minimum-number-of-vertices-to-reach-all-nodes.js)|Medium|
1558|[Minimum Numbers of Function Calls to Make Target Array](./solutions/1558-minimum-numbers-of-function-calls-to-make-target-array.js)|Medium|
diff --git a/solutions/1554-strings-differ-by-one-character.js b/solutions/1554-strings-differ-by-one-character.js
new file mode 100644
index 00000000..52fb2b70
--- /dev/null
+++ b/solutions/1554-strings-differ-by-one-character.js
@@ -0,0 +1,34 @@
+/**
+ * 1554. Strings Differ by One Character
+ * https://leetcode.com/problems/strings-differ-by-one-character/
+ * Difficulty: Medium
+ *
+ * Given a list of strings dict where all the strings are of the same length.
+ *
+ * Return true if there are 2 strings that only differ by 1 character in the same index,
+ * otherwise return false.
+ */
+
+/**
+ * @param {string[]} dict
+ * @return {boolean}
+ */
+var differByOne = function(dict) {
+ const m = dict[0].length;
+
+ for (let pos = 0; pos < m; pos++) {
+ const patterns = new Set();
+
+ for (const word of dict) {
+ const pattern = word.slice(0, pos) + '*' + word.slice(pos + 1);
+
+ if (patterns.has(pattern)) {
+ return true;
+ }
+
+ patterns.add(pattern);
+ }
+ }
+
+ return false;
+};
From 82a52973f8de9ff3f435654a290a4c038ea46826 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 3 Jul 2025 23:58:25 -0500
Subject: [PATCH 654/994] Add solution #1564
---
README.md | 1 +
.../1564-put-boxes-into-the-warehouse-i.js | 46 +++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/1564-put-boxes-into-the-warehouse-i.js
diff --git a/README.md b/README.md
index fd565716..adb02e93 100644
--- a/README.md
+++ b/README.md
@@ -1432,6 +1432,7 @@
1561|[Maximum Number of Coins You Can Get](./solutions/1561-maximum-number-of-coins-you-can-get.js)|Medium|
1562|[Find Latest Group of Size M](./solutions/1562-find-latest-group-of-size-m.js)|Medium|
1563|[Stone Game V](./solutions/1563-stone-game-v.js)|Hard|
+1564|[Put Boxes Into the Warehouse I](./solutions/1564-put-boxes-into-the-warehouse-i.js)|Medium|
1566|[Detect Pattern of Length M Repeated K or More Times](./solutions/1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy|
1567|[Maximum Length of Subarray With Positive Product](./solutions/1567-maximum-length-of-subarray-with-positive-product.js)|Medium|
1568|[Minimum Number of Days to Disconnect Island](./solutions/1568-minimum-number-of-days-to-disconnect-island.js)|Hard|
diff --git a/solutions/1564-put-boxes-into-the-warehouse-i.js b/solutions/1564-put-boxes-into-the-warehouse-i.js
new file mode 100644
index 00000000..dbd787e4
--- /dev/null
+++ b/solutions/1564-put-boxes-into-the-warehouse-i.js
@@ -0,0 +1,46 @@
+/**
+ * 1564. Put Boxes Into the Warehouse I
+ * https://leetcode.com/problems/put-boxes-into-the-warehouse-i/
+ * Difficulty: Medium
+ *
+ * You are given two arrays of positive integers, boxes and warehouse, representing the
+ * heights of some boxes of unit width and the heights of n rooms in a warehouse respectively.
+ * The warehouse's rooms are labelled from 0 to n - 1 from left to right where warehouse[i]
+ * (0-indexed) is the height of the ith room.
+ *
+ * Boxes are put into the warehouse by the following rules:
+ * - Boxes cannot be stacked.
+ * - You can rearrange the insertion order of the boxes.
+ * - Boxes can only be pushed into the warehouse from left to right only.
+ * - If the height of some room in the warehouse is less than the height of a box, then that
+ * box and all other boxes behind it will be stopped before that room.
+ *
+ * Return the maximum number of boxes you can put into the warehouse.
+ */
+
+/**
+ * @param {number[]} boxes
+ * @param {number[]} warehouse
+ * @return {number}
+ */
+var maxBoxesInWarehouse = function(boxes, warehouse) {
+ const effectiveHeights = new Array(warehouse.length);
+ effectiveHeights[0] = warehouse[0];
+
+ for (let i = 1; i < warehouse.length; i++) {
+ effectiveHeights[i] = Math.min(effectiveHeights[i - 1], warehouse[i]);
+ }
+
+ boxes.sort((a, b) => a - b);
+
+ let boxIndex = 0;
+ let count = 0;
+ for (let i = effectiveHeights.length - 1; i >= 0; i--) {
+ if (boxIndex < boxes.length && boxes[boxIndex] <= effectiveHeights[i]) {
+ count++;
+ boxIndex++;
+ }
+ }
+
+ return count;
+};
From 9878007fe77ed558678d7d3ca5d0f3fa343e2b1f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 4 Jul 2025 00:01:21 -0500
Subject: [PATCH 655/994] Add solution #1570
---
README.md | 1 +
.../1570-dot-product-of-two-sparse-vectors.js | 45 +++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/1570-dot-product-of-two-sparse-vectors.js
diff --git a/README.md b/README.md
index adb02e93..3ffa730b 100644
--- a/README.md
+++ b/README.md
@@ -1437,6 +1437,7 @@
1567|[Maximum Length of Subarray With Positive Product](./solutions/1567-maximum-length-of-subarray-with-positive-product.js)|Medium|
1568|[Minimum Number of Days to Disconnect Island](./solutions/1568-minimum-number-of-days-to-disconnect-island.js)|Hard|
1569|[Number of Ways to Reorder Array to Get Same BST](./solutions/1569-number-of-ways-to-reorder-array-to-get-same-bst.js)|Hard|
+1570|[Dot Product of Two Sparse Vectors](./solutions/1570-dot-product-of-two-sparse-vectors.js)|Medium|
1572|[Matrix Diagonal Sum](./solutions/1572-matrix-diagonal-sum.js)|Easy|
1573|[Number of Ways to Split a String](./solutions/1573-number-of-ways-to-split-a-string.js)|Medium|
1574|[Shortest Subarray to be Removed to Make Array Sorted](./solutions/1574-shortest-subarray-to-be-removed-to-make-array-sorted.js)|Medium|
diff --git a/solutions/1570-dot-product-of-two-sparse-vectors.js b/solutions/1570-dot-product-of-two-sparse-vectors.js
new file mode 100644
index 00000000..3fa6bb2b
--- /dev/null
+++ b/solutions/1570-dot-product-of-two-sparse-vectors.js
@@ -0,0 +1,45 @@
+/**
+ * 1570. Dot Product of Two Sparse Vectors
+ * https://leetcode.com/problems/dot-product-of-two-sparse-vectors/
+ * Difficulty: Medium
+ *
+ * Given two sparse vectors, compute their dot product.
+ *
+ * Implement class SparseVector:
+ * - SparseVector(nums) Initializes the object with the vector nums
+ * - dotProduct(vec) Compute the dot product between the instance of SparseVector and vec
+ *
+ * A sparse vector is a vector that has mostly zero values, you should store the sparse vector
+ * efficiently and compute the dot product between two SparseVector.
+ *
+ * Follow up: What if only one of the vectors is sparse?
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {SparseVector}
+ */
+var SparseVector = function(nums) {
+ this.nonZeroElements = new Map();
+ for (let i = 0; i < nums.length; i++) {
+ if (nums[i] !== 0) {
+ this.nonZeroElements.set(i, nums[i]);
+ }
+ }
+};
+
+/**
+ * @param {SparseVector} vec
+ * @return {number}
+ */
+SparseVector.prototype.dotProduct = function(vec) {
+ let result = 0;
+
+ for (const [index, value] of this.nonZeroElements) {
+ if (vec.nonZeroElements.has(index)) {
+ result += value * vec.nonZeroElements.get(index);
+ }
+ }
+
+ return result;
+};
From 82d1cc7b73c8ddf3dc0b74b80aa8ca22344579a3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 4 Jul 2025 21:27:25 -0500
Subject: [PATCH 656/994] Add solution #1580
---
README.md | 1 +
.../1580-put-boxes-into-the-warehouse-ii.js | 66 +++++++++++++++++++
2 files changed, 67 insertions(+)
create mode 100644 solutions/1580-put-boxes-into-the-warehouse-ii.js
diff --git a/README.md b/README.md
index 3ffa730b..7d3e27f1 100644
--- a/README.md
+++ b/README.md
@@ -1446,6 +1446,7 @@
1577|[Number of Ways Where Square of Number Is Equal to Product of Two Numbers](./solutions/1577-number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers.js)|Medium|
1578|[Minimum Time to Make Rope Colorful](./solutions/1578-minimum-time-to-make-rope-colorful.js)|Medium|
1579|[Remove Max Number of Edges to Keep Graph Fully Traversable](./solutions/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.js)|Hard|
+1580|[Put Boxes Into the Warehouse II](./solutions/1580-put-boxes-into-the-warehouse-ii.js)|Medium|
1582|[Special Positions in a Binary Matrix](./solutions/1582-special-positions-in-a-binary-matrix.js)|Easy|
1583|[Count Unhappy Friends](./solutions/1583-count-unhappy-friends.js)|Medium|
1584|[Min Cost to Connect All Points](./solutions/1584-min-cost-to-connect-all-points.js)|Medium|
diff --git a/solutions/1580-put-boxes-into-the-warehouse-ii.js b/solutions/1580-put-boxes-into-the-warehouse-ii.js
new file mode 100644
index 00000000..66c86ba8
--- /dev/null
+++ b/solutions/1580-put-boxes-into-the-warehouse-ii.js
@@ -0,0 +1,66 @@
+/**
+ * 1580. Put Boxes Into the Warehouse II
+ * https://leetcode.com/problems/put-boxes-into-the-warehouse-ii/
+ * Difficulty: Medium
+ *
+ * You are given two arrays of positive integers, boxes and warehouse, representing the heights
+ * of some boxes of unit width and the heights of n rooms in a warehouse respectively. The
+ * warehouse's rooms are labeled from 0 to n - 1 from left to right where warehouse[i] (0-indexed)
+ * is the height of the ith room.
+ *
+ * Boxes are put into the warehouse by the following rules:
+ * - Boxes cannot be stacked.
+ * - You can rearrange the insertion order of the boxes.
+ * - Boxes can be pushed into the warehouse from either side (left or right)
+ * - If the height of some room in the warehouse is less than the height of a box, then that box
+ * and all other boxes behind it will be stopped before that room.
+ *
+ * Return the maximum number of boxes you can put into the warehouse.
+ */
+
+/**
+ * @param {number[]} boxes
+ * @param {number[]} warehouse
+ * @return {number}
+ */
+var maxBoxesInWarehouse = function(boxes, warehouse) {
+ boxes.sort((a, b) => a - b);
+
+ let leftPointer = 0;
+ let rightPointer = warehouse.length - 1;
+ let leftMaxHeight = warehouse[0];
+ let rightMaxHeight = warehouse[warehouse.length - 1];
+ let result = 0;
+
+ while (result < warehouse.length && leftPointer <= rightPointer && boxes.length > 0) {
+ while (boxes.length > 0 && boxes[boxes.length - 1] > leftMaxHeight
+ && boxes[boxes.length - 1] > rightMaxHeight) {
+ boxes.pop();
+ }
+
+ if (boxes.length === 0) break;
+
+ const canFitLeft = boxes[boxes.length - 1] <= leftMaxHeight;
+ const canFitRight = boxes[boxes.length - 1] <= rightMaxHeight;
+
+ if (canFitLeft && (!canFitRight || leftMaxHeight <= rightMaxHeight)) {
+ boxes.pop();
+ leftPointer++;
+ result++;
+ if (leftPointer < warehouse.length) {
+ leftMaxHeight = Math.min(warehouse[leftPointer], leftMaxHeight);
+ }
+ } else if (canFitRight) {
+ boxes.pop();
+ rightPointer--;
+ result++;
+ if (rightPointer >= 0) {
+ rightMaxHeight = Math.min(warehouse[rightPointer], rightMaxHeight);
+ }
+ } else {
+ break;
+ }
+ }
+
+ return result;
+};
From 1be04464b41da3a60f1798919c8b3481bfc0f64f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 4 Jul 2025 21:33:42 -0500
Subject: [PATCH 657/994] Add solution #1586
---
README.md | 1 +
.../1586-binary-search-tree-iterator-ii.js | 72 +++++++++++++++++++
2 files changed, 73 insertions(+)
create mode 100644 solutions/1586-binary-search-tree-iterator-ii.js
diff --git a/README.md b/README.md
index 7d3e27f1..b7025b1f 100644
--- a/README.md
+++ b/README.md
@@ -1451,6 +1451,7 @@
1583|[Count Unhappy Friends](./solutions/1583-count-unhappy-friends.js)|Medium|
1584|[Min Cost to Connect All Points](./solutions/1584-min-cost-to-connect-all-points.js)|Medium|
1585|[Check If String Is Transformable With Substring Sort Operations](./solutions/1585-check-if-string-is-transformable-with-substring-sort-operations.js)|Hard|
+1586|[Binary Search Tree Iterator II](./solutions/1586-binary-search-tree-iterator-ii.js)|Medium|
1588|[Sum of All Odd Length Subarrays](./solutions/1588-sum-of-all-odd-length-subarrays.js)|Easy|
1589|[Maximum Sum Obtained of Any Permutation](./solutions/1589-maximum-sum-obtained-of-any-permutation.js)|Medium|
1590|[Make Sum Divisible by P](./solutions/1590-make-sum-divisible-by-p.js)|Medium|
diff --git a/solutions/1586-binary-search-tree-iterator-ii.js b/solutions/1586-binary-search-tree-iterator-ii.js
new file mode 100644
index 00000000..b343697a
--- /dev/null
+++ b/solutions/1586-binary-search-tree-iterator-ii.js
@@ -0,0 +1,72 @@
+/**
+ * 1586. Binary Search Tree Iterator II
+ * https://leetcode.com/problems/binary-search-tree-iterator-ii/
+ * Difficulty: Medium
+ *
+ * Implement the BSTIterator class that represents an iterator over the in-order traversal
+ * of a binary search tree (BST):
+ * - BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the
+ * BST is given as part of the constructor. The pointer should be initialized to a non-existent
+ * number smaller than any element in the BST.
+ * - boolean hasNext() Returns true if there exists a number in the traversal to the right of the
+ * pointer, otherwise returns false.
+ * - int next() Moves the pointer to the right, then returns the number at the pointer.
+ * - boolean hasPrev() Returns true if there exists a number in the traversal to the left of the
+ * pointer, otherwise returns false.
+ * - int prev() Moves the pointer to the left, then returns the number at the pointer.
+ *
+ * Notice that by initializing the pointer to a non-existent smallest number, the first call to
+ * next() will return the smallest element in the BST.
+ *
+ * You may assume that next() and prev() calls will always be valid. That is, there will be at
+ * least a next/previous number in the in-order traversal when next()/prev() is called.
+ */
+
+/**
+ * @param {TreeNode} root
+ */
+var BSTIterator = function(root) {
+ this.inorderValues = [];
+ this.currentIndex = -1;
+ this.inorderTraversal(root);
+};
+
+/**
+ * @param {TreeNode} node
+ */
+BSTIterator.prototype.inorderTraversal = function(node) {
+ if (!node) return;
+ this.inorderTraversal(node.left);
+ this.inorderValues.push(node.val);
+ this.inorderTraversal(node.right);
+};
+
+/**
+ * @return {boolean}
+ */
+BSTIterator.prototype.hasNext = function() {
+ return this.currentIndex + 1 < this.inorderValues.length;
+};
+
+/**
+ * @return {number}
+ */
+BSTIterator.prototype.next = function() {
+ this.currentIndex++;
+ return this.inorderValues[this.currentIndex];
+};
+
+/**
+ * @return {boolean}
+ */
+BSTIterator.prototype.hasPrev = function() {
+ return this.currentIndex > 0;
+};
+
+/**
+ * @return {number}
+ */
+BSTIterator.prototype.prev = function() {
+ this.currentIndex--;
+ return this.inorderValues[this.currentIndex];
+};
From 9cdf28317a0f9ecbcd08ba0aa5f9c58db06917b5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 4 Jul 2025 22:46:24 -0500
Subject: [PATCH 658/994] Add solution #1597
---
README.md | 1 +
...y-expression-tree-from-infix-expression.js | 85 +++++++++++++++++++
2 files changed, 86 insertions(+)
create mode 100644 solutions/1597-build-binary-expression-tree-from-infix-expression.js
diff --git a/README.md b/README.md
index b7025b1f..578a8d09 100644
--- a/README.md
+++ b/README.md
@@ -1460,6 +1460,7 @@
1593|[Split a String Into the Max Number of Unique Substrings](./solutions/1593-split-a-string-into-the-max-number-of-unique-substrings.js)|Medium|
1594|[Maximum Non Negative Product in a Matrix](./solutions/1594-maximum-non-negative-product-in-a-matrix.js)|Medium|
1595|[Minimum Cost to Connect Two Groups of Points](./solutions/1595-minimum-cost-to-connect-two-groups-of-points.js)|Hard|
+1597|[Build Binary Expression Tree From Infix Expression](./solutions/1597-build-binary-expression-tree-from-infix-expression.js)|Hard|
1598|[Crawler Log Folder](./solutions/1598-crawler-log-folder.js)|Easy|
1599|[Maximum Profit of Operating a Centennial Wheel](./solutions/1599-maximum-profit-of-operating-a-centennial-wheel.js)|Medium|
1600|[Throne Inheritance](./solutions/1600-throne-inheritance.js)|Medium|
diff --git a/solutions/1597-build-binary-expression-tree-from-infix-expression.js b/solutions/1597-build-binary-expression-tree-from-infix-expression.js
new file mode 100644
index 00000000..50fbd593
--- /dev/null
+++ b/solutions/1597-build-binary-expression-tree-from-infix-expression.js
@@ -0,0 +1,85 @@
+/**
+ * 1597. Build Binary Expression Tree From Infix Expression
+ * https://leetcode.com/problems/build-binary-expression-tree-from-infix-expression/
+ * Difficulty: Hard
+ *
+ * A binary expression tree is a kind of binary tree used to represent arithmetic expressions.
+ * Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes
+ * with 0 children) correspond to operands (numbers), and internal nodes (nodes with 2 children)
+ * correspond to the operators '+' (addition), '-' (subtraction), '*' (multiplication), and
+ * '/' (division).
+ *
+ * For each internal node with operator o, the infix expression it represents is (A o B),
+ * where A is the expression the left subtree represents and B is the expression the right
+ * subtree represents.
+ *
+ * You are given a string s, an infix expression containing operands, the operators described
+ * above, and parentheses '(' and ')'.
+ *
+ * Return any valid binary expression tree, whose in-order traversal reproduces s after omitting
+ * the parenthesis from it.
+ *
+ * Please note that order of operations applies in s. That is, expressions in parentheses are
+ * evaluated first, and multiplication and division happen before addition and subtraction.
+ *
+ * Operands must also appear in the same order in both s and the in-order traversal of the tree.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function Node(val, left, right) {
+ * this.val = (val===undefined ? " " : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {string} s
+ * @return {Node}
+ */
+var expTree = function(s) {
+ const operators = new Map([['+', 1], ['-', 1], ['*', 2], ['/', 2]]);
+ const operatorStack = [];
+ const operandStack = [];
+
+ for (let i = 0; i < s.length; i++) {
+ const char = s[i];
+
+ if (char >= '0' && char <= '9') {
+ operandStack.push(createNode(char));
+ } else if (char === '(') {
+ operatorStack.push(char);
+ } else if (char === ')') {
+ while (operatorStack.length > 0 && operatorStack[operatorStack.length - 1] !== '(') {
+ processOperator();
+ }
+ operatorStack.pop();
+ } else if (operators.has(char)) {
+ while (operatorStack.length > 0 && operatorStack[operatorStack.length - 1] !== '('
+ && operators.get(operatorStack[operatorStack.length - 1]) >= operators.get(char)) {
+ processOperator();
+ }
+ operatorStack.push(char);
+ }
+ }
+
+ while (operatorStack.length > 0) {
+ processOperator();
+ }
+
+ return operandStack[0];
+
+ function processOperator() {
+ const operator = operatorStack.pop();
+ const right = operandStack.pop();
+ const left = operandStack.pop();
+ const node = createNode(operator);
+ node.left = left;
+ node.right = right;
+ operandStack.push(node);
+ }
+
+ function createNode(val) {
+ return new Node(val);
+ }
+};
From f961a9f7e76c663f221dff747096eaacfd19f02a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 4 Jul 2025 22:47:16 -0500
Subject: [PATCH 659/994] Add solution #1602
---
README.md | 1 +
...-find-nearest-right-node-in-binary-tree.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/1602-find-nearest-right-node-in-binary-tree.js
diff --git a/README.md b/README.md
index 578a8d09..f6719bbd 100644
--- a/README.md
+++ b/README.md
@@ -1465,6 +1465,7 @@
1599|[Maximum Profit of Operating a Centennial Wheel](./solutions/1599-maximum-profit-of-operating-a-centennial-wheel.js)|Medium|
1600|[Throne Inheritance](./solutions/1600-throne-inheritance.js)|Medium|
1601|[Maximum Number of Achievable Transfer Requests](./solutions/1601-maximum-number-of-achievable-transfer-requests.js)|Hard|
+1602|[Find Nearest Right Node in Binary Tree](./solutions/1602-find-nearest-right-node-in-binary-tree.js)|Medium|
1603|[Design Parking System](./solutions/1603-design-parking-system.js)|Easy|
1604|[Alert Using Same Key-Card Three or More Times in a One Hour Period](./solutions/1604-alert-using-same-key-card-three-or-more-times-in-a-one-hour-period.js)|Medium|
1605|[Find Valid Matrix Given Row and Column Sums](./solutions/1605-find-valid-matrix-given-row-and-column-sums.js)|Medium|
diff --git a/solutions/1602-find-nearest-right-node-in-binary-tree.js b/solutions/1602-find-nearest-right-node-in-binary-tree.js
new file mode 100644
index 00000000..626f0a0b
--- /dev/null
+++ b/solutions/1602-find-nearest-right-node-in-binary-tree.js
@@ -0,0 +1,42 @@
+/**
+ * 1602. Find Nearest Right Node in Binary Tree
+ * https://leetcode.com/problems/find-nearest-right-node-in-binary-tree/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree and a node u in the tree, return the nearest node on the
+ * same level that is to the right of u, or return null if u is the rightmost node in its level.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @param {TreeNode} u
+ * @return {TreeNode}
+ */
+var findNearestRightNode = function(root, u) {
+ const queue = [root];
+
+ while (queue.length > 0) {
+ const levelSize = queue.length;
+
+ for (let i = 0; i < levelSize; i++) {
+ const currentNode = queue.shift();
+
+ if (currentNode === u) {
+ return i === levelSize - 1 ? null : queue.shift();
+ }
+
+ if (currentNode.left) queue.push(currentNode.left);
+ if (currentNode.right) queue.push(currentNode.right);
+ }
+ }
+
+ return null;
+};
From afa73bb3d72134066dd1c4472a041fb509116140 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 4 Jul 2025 22:50:05 -0500
Subject: [PATCH 660/994] Add solution #1612
---
README.md | 1 +
...-if-two-expression-trees-are-equivalent.js | 64 +++++++++++++++++++
2 files changed, 65 insertions(+)
create mode 100644 solutions/1612-check-if-two-expression-trees-are-equivalent.js
diff --git a/README.md b/README.md
index f6719bbd..85805add 100644
--- a/README.md
+++ b/README.md
@@ -1474,6 +1474,7 @@
1609|[Even Odd Tree](./solutions/1609-even-odd-tree.js)|Medium|
1610|[Maximum Number of Visible Points](./solutions/1610-maximum-number-of-visible-points.js)|Hard|
1611|[Minimum One Bit Operations to Make Integers Zero](./solutions/1611-minimum-one-bit-operations-to-make-integers-zero.js)|Hard|
+1612|[Check If Two Expression Trees are Equivalent](./solutions/1612-check-if-two-expression-trees-are-equivalent.js)|Medium|
1614|[Maximum Nesting Depth of the Parentheses](./solutions/1614-maximum-nesting-depth-of-the-parentheses.js)|Easy|
1615|[Maximal Network Rank](./solutions/1615-maximal-network-rank.js)|Medium|
1616|[Split Two Strings to Make Palindrome](./solutions/1616-split-two-strings-to-make-palindrome.js)|Medium|
diff --git a/solutions/1612-check-if-two-expression-trees-are-equivalent.js b/solutions/1612-check-if-two-expression-trees-are-equivalent.js
new file mode 100644
index 00000000..a0c1970f
--- /dev/null
+++ b/solutions/1612-check-if-two-expression-trees-are-equivalent.js
@@ -0,0 +1,64 @@
+/**
+ * 1612. Check If Two Expression Trees are Equivalent
+ * https://leetcode.com/problems/check-if-two-expression-trees-are-equivalent/
+ * Difficulty: Medium
+ *
+ * A binary expression tree is a kind of binary tree used to represent arithmetic expressions.
+ * Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes
+ * with 0 children) correspond to operands (variables), and internal nodes (nodes with two
+ * children) correspond to the operators. In this problem, we only consider the '+' operator
+ * (i.e. addition).
+ *
+ * You are given the roots of two binary expression trees, root1 and root2. Return true if
+ * the two binary expression trees are equivalent. Otherwise, return false.
+ *
+ * Two binary expression trees are equivalent if they evaluate to the same value regardless
+ * of what the variables are set to.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function Node(val, left, right) {
+ * this.val = (val===undefined ? " " : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {Node} root1
+ * @param {Node} root2
+ * @return {boolean}
+ */
+var checkEquivalence = function(root1, root2) {
+ const count1 = getVariableCount(root1);
+ const count2 = getVariableCount(root2);
+ const variables1 = Object.keys(count1);
+ const variables2 = Object.keys(count2);
+
+ if (variables1.length !== variables2.length) return false;
+
+ for (const variable of variables1) {
+ if (count1[variable] !== count2[variable]) return false;
+ }
+
+ return true;
+
+ function getVariableCount(node) {
+ if (!node) return {};
+
+ if (node.val !== '+') {
+ return { [node.val]: 1 };
+ }
+
+ const leftCount = getVariableCount(node.left);
+ const rightCount = getVariableCount(node.right);
+ const mergedCount = { ...leftCount };
+ for (const variable in rightCount) {
+ if (rightCount.hasOwnProperty(variable)) {
+ mergedCount[variable] = (mergedCount[variable] || 0) + rightCount[variable];
+ }
+ }
+
+ return mergedCount;
+ }
+};
From 51b14a2d9fc6fb8db3fa9ec02248432089dfe5dc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 4 Jul 2025 23:37:38 -0500
Subject: [PATCH 661/994] Add solution #1618
---
README.md | 1 +
...imum-font-to-fit-a-sentence-in-a-screen.js | 96 +++++++++++++++++++
2 files changed, 97 insertions(+)
create mode 100644 solutions/1618-maximum-font-to-fit-a-sentence-in-a-screen.js
diff --git a/README.md b/README.md
index 85805add..3a4c9607 100644
--- a/README.md
+++ b/README.md
@@ -1479,6 +1479,7 @@
1615|[Maximal Network Rank](./solutions/1615-maximal-network-rank.js)|Medium|
1616|[Split Two Strings to Make Palindrome](./solutions/1616-split-two-strings-to-make-palindrome.js)|Medium|
1617|[Count Subtrees With Max Distance Between Cities](./solutions/1617-count-subtrees-with-max-distance-between-cities.js)|Hard|
+1618|[Maximum Font to Fit a Sentence in a Screen](./solutions/1618-maximum-font-to-fit-a-sentence-in-a-screen.js)|Medium|
1619|[Mean of Array After Removing Some Elements](./solutions/1619-mean-of-array-after-removing-some-elements.js)|Easy|
1620|[Coordinate With Maximum Network Quality](./solutions/1620-coordinate-with-maximum-network-quality.js)|Medium|
1621|[Number of Sets of K Non-Overlapping Line Segments](./solutions/1621-number-of-sets-of-k-non-overlapping-line-segments.js)|Medium|
diff --git a/solutions/1618-maximum-font-to-fit-a-sentence-in-a-screen.js b/solutions/1618-maximum-font-to-fit-a-sentence-in-a-screen.js
new file mode 100644
index 00000000..2300f043
--- /dev/null
+++ b/solutions/1618-maximum-font-to-fit-a-sentence-in-a-screen.js
@@ -0,0 +1,96 @@
+/**
+ * 1618. Maximum Font to Fit a Sentence in a Screen
+ * https://leetcode.com/problems/maximum-font-to-fit-a-sentence-in-a-screen/
+ * Difficulty: Medium
+ *
+ * You are given a string text. We want to display text on a screen of width w and height h.
+ * You can choose any font size from array fonts, which contains the available font sizes in
+ * ascending order.
+ *
+ * You can use the FontInfo interface to get the width and height of any character at any
+ * available font size.
+ *
+ * The FontInfo interface is defined as such:
+ * interface FontInfo {
+ * // Returns the width of character ch on the screen using font size fontSize.
+ * // O(1) per call
+ * public int getWidth(int fontSize, char ch);
+ *
+ * // Returns the height of any character on the screen using font size fontSize.
+ * // O(1) per call
+ * public int getHeight(int fontSize);
+ * }
+ *
+ * The calculated width of text for some fontSize is the sum of every
+ * getWidth(fontSize, text[i]) call for each 0 <= i < text.length (0-indexed).
+ * The calculated height of text for some fontSize is getHeight(fontSize). Note
+ * that text is displayed on a single line.
+ *
+ * It is guaranteed that FontInfo will return the same value if you call getHeight
+ * or getWidth with the same parameters.
+ *
+ * It is also guaranteed that for any font size fontSize and any character ch:
+ * - getHeight(fontSize) <= getHeight(fontSize+1)
+ * - getWidth(fontSize, ch) <= getWidth(fontSize+1, ch)
+ *
+ * Return the maximum font size you can use to display text on the screen. If text cannot
+ * fit on the display with any font size, return -1.
+ */
+
+/**
+ * // This is the FontInfo's API interface.
+ * // You should not implement it, or speculate about its implementation
+ * function FontInfo() {
+ *
+ * @param {number} fontSize
+ * @param {char} ch
+ * @return {number}
+ * this.getWidth = function(fontSize, ch) {
+ * ...
+ * };
+ *
+ * @param {number} fontSize
+ * @return {number}
+ * this.getHeight = function(fontSize) {
+ * ...
+ * };
+ * };
+ */
+/**
+ * @param {string} text
+ * @param {number} w
+ * @param {number} h
+ * @param {number[]} fonts
+ * @param {FontInfo} fontInfo
+ * @return {number}
+ */
+var maxFont = function(text, w, h, fonts, fontInfo) {
+ let left = 0;
+ let right = fonts.length - 1;
+ let maxFontSize = -1;
+
+ while (left <= right) {
+ const mid = Math.floor((left + right) / 2);
+ const fontSize = fonts[mid];
+
+ if (canFit(fontSize)) {
+ maxFontSize = fontSize;
+ left = mid + 1;
+ } else {
+ right = mid - 1;
+ }
+ }
+
+ return maxFontSize;
+
+ function canFit(fontSize) {
+ if (fontInfo.getHeight(fontSize) > h) return false;
+
+ let totalWidth = 0;
+ for (const char of text) {
+ totalWidth += fontInfo.getWidth(fontSize, char);
+ if (totalWidth > w) return false;
+ }
+ return true;
+ }
+};
From c80f419d15a3372e88c7f4fddf8fa4403c24a449 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 4 Jul 2025 23:41:25 -0500
Subject: [PATCH 662/994] Add solution #1628
---
README.md | 1 +
...-expression-tree-with-evaluate-function.js | 106 ++++++++++++++++++
2 files changed, 107 insertions(+)
create mode 100644 solutions/1628-design-an-expression-tree-with-evaluate-function.js
diff --git a/README.md b/README.md
index 3a4c9607..c7deb743 100644
--- a/README.md
+++ b/README.md
@@ -1488,6 +1488,7 @@
1625|[Lexicographically Smallest String After Applying Operations](./solutions/1625-lexicographically-smallest-string-after-applying-operations.js)|Medium|
1626|[Best Team With No Conflicts](./solutions/1626-best-team-with-no-conflicts.js)|Medium|
1627|[Graph Connectivity With Threshold](./solutions/1627-graph-connectivity-with-threshold.js)|Hard|
+1628|[Design an Expression Tree With Evaluate Function](./solutions/1628-design-an-expression-tree-with-evaluate-function.js)|Medium|
1629|[Slowest Key](./solutions/1629-slowest-key.js)|Easy|
1630|[Arithmetic Subarrays](./solutions/1630-arithmetic-subarrays.js)|Medium|
1631|[Path With Minimum Effort](./solutions/1631-path-with-minimum-effort.js)|Medium|
diff --git a/solutions/1628-design-an-expression-tree-with-evaluate-function.js b/solutions/1628-design-an-expression-tree-with-evaluate-function.js
new file mode 100644
index 00000000..649aab3a
--- /dev/null
+++ b/solutions/1628-design-an-expression-tree-with-evaluate-function.js
@@ -0,0 +1,106 @@
+/**
+ * 1628. Design an Expression Tree With Evaluate Function
+ * https://leetcode.com/problems/design-an-expression-tree-with-evaluate-function/
+ * Difficulty: Medium
+ *
+ * Given the postfix tokens of an arithmetic expression, build and return the binary expression
+ * tree that represents this expression.
+ *
+ * Postfix notation is a notation for writing arithmetic expressions in which the operands
+ * (numbers) appear before their operators. For example, the postfix tokens of the expression
+ * 4*(5-(7+2)) are represented in the array postfix = ["4","5","7","2","+","-","*"].
+ *
+ * The class Node is an interface you should use to implement the binary expression tree.
+ * The returned tree will be tested using the evaluate function, which is supposed to evaluate
+ * the tree's value. You should not remove the Node class; however, you can modify it as you
+ * wish, and you can define other classes to implement it if needed.
+ *
+ * A binary expression tree is a kind of binary tree used to represent arithmetic expressions.
+ * Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes
+ * with 0 children) correspond to operands (numbers), and internal nodes (nodes with two
+ * children) correspond to the operators '+' (addition), '-' (subtraction), '*'
+ * (multiplication), and '/' (division).
+ *
+ * It's guaranteed that no subtree will yield a value that exceeds 109 in absolute value,
+ * and all the operations are valid (i.e., no division by zero).
+ *
+ * Follow up: Could you design the expression tree such that it is more modular? For example,
+ * is your design able to support additional operators without making changes to your existing
+ * evaluate implementation?
+ */
+
+/**
+ * This is the interface for the expression tree Node.
+ * You should not remove it, and you can define some classes to implement it.
+ */
+var Node = function() {
+ if (this.constructor === Node) {
+ throw new Error('Cannot instanciate abstract class');
+ }
+};
+
+Node.prototype.evaluate = function() {
+ throw new Error('Cannot call abstract method');
+};
+
+class NumberNode extends Node {
+ constructor(value) {
+ super();
+ this.value = parseInt(value);
+ }
+
+ evaluate() {
+ return this.value;
+ }
+}
+
+class OperatorNode extends Node {
+ constructor(operator, left, right) {
+ super();
+ this.operator = operator;
+ this.left = left;
+ this.right = right;
+ }
+
+ evaluate() {
+ const leftValue = this.left.evaluate();
+ const rightValue = this.right.evaluate();
+
+ switch (this.operator) {
+ case '+':
+ return leftValue + rightValue;
+ case '-':
+ return leftValue - rightValue;
+ case '*':
+ return leftValue * rightValue;
+ case '/':
+ return Math.floor(leftValue / rightValue);
+ default:
+ throw new Error('Unknown operator');
+ }
+ }
+}
+
+/**
+ * This is the TreeBuilder class.
+ * You can treat it as the driver code that takes the postinfix input
+ * and returns the expression tree representing it as a Node.
+ */
+class TreeBuilder {
+ buildTree(postfix) {
+ const stack = [];
+ const operators = new Set(['+', '-', '*', '/']);
+
+ for (const token of postfix) {
+ if (operators.has(token)) {
+ const right = stack.pop();
+ const left = stack.pop();
+ stack.push(new OperatorNode(token, left, right));
+ } else {
+ stack.push(new NumberNode(token));
+ }
+ }
+
+ return stack[0];
+ }
+}
From 777bd79689be0fea4d618a59ec6c604bff7a848e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 4 Jul 2025 23:43:45 -0500
Subject: [PATCH 663/994] Add solution #1634
---
README.md | 1 +
...polynomials-represented-as-linked-lists.js | 84 +++++++++++++++++++
2 files changed, 85 insertions(+)
create mode 100644 solutions/1634-add-two-polynomials-represented-as-linked-lists.js
diff --git a/README.md b/README.md
index c7deb743..110c4f44 100644
--- a/README.md
+++ b/README.md
@@ -1493,6 +1493,7 @@
1630|[Arithmetic Subarrays](./solutions/1630-arithmetic-subarrays.js)|Medium|
1631|[Path With Minimum Effort](./solutions/1631-path-with-minimum-effort.js)|Medium|
1632|[Rank Transform of a Matrix](./solutions/1632-rank-transform-of-a-matrix.js)|Hard|
+1634|[Add Two Polynomials Represented as Linked Lists](./solutions/1634-add-two-polynomials-represented-as-linked-lists.js)|Medium|
1636|[Sort Array by Increasing Frequency](./solutions/1636-sort-array-by-increasing-frequency.js)|Easy|
1637|[Widest Vertical Area Between Two Points Containing No Points](./solutions/1637-widest-vertical-area-between-two-points-containing-no-points.js)|Easy|
1638|[Count Substrings That Differ by One Character](./solutions/1638-count-substrings-that-differ-by-one-character.js)|Medium|
diff --git a/solutions/1634-add-two-polynomials-represented-as-linked-lists.js b/solutions/1634-add-two-polynomials-represented-as-linked-lists.js
new file mode 100644
index 00000000..d8bc467f
--- /dev/null
+++ b/solutions/1634-add-two-polynomials-represented-as-linked-lists.js
@@ -0,0 +1,84 @@
+/**
+ * 1634. Add Two Polynomials Represented as Linked Lists
+ * https://leetcode.com/problems/add-two-polynomials-represented-as-linked-lists/
+ * Difficulty: Medium
+ *
+ * A polynomial linked list is a special type of linked list where every node represents a
+ * term in a polynomial expression.
+ *
+ * Each node has three attributes:
+ * - coefficient: an integer representing the number multiplier of the term. The coefficient
+ * of the term 9x4 is 9.
+ * - power: an integer representing the exponent. The power of the term 9x4 is 4.
+ * - next: a pointer to the next node in the list, or null if it is the last node of the list.
+ *
+ * For example, the polynomial 5x3 + 4x - 7 is represented by the polynomial linked list
+ * illustrated below:
+ *
+ * The polynomial linked list must be in its standard form: the polynomial must be in strictly
+ * descending order by its power value. Also, terms with a coefficient of 0 are omitted.
+ *
+ * Given two polynomial linked list heads, poly1 and poly2, add the polynomials together
+ * and return the head of the sum of the polynomials.
+ *
+ * PolyNode format:
+ * The input/output format is as a list of n nodes, where each node is represented as
+ * its [coefficient, power]. For example, the polynomial 5x3 + 4x - 7 would be represented
+ * as: [[5,3],[4,1],[-7,0]].
+ */
+
+/**
+ * Definition for polynomial singly-linked list.
+ * function PolyNode(x=0, y=0, next=null) {
+ * this.coefficient = x;
+ * this.power = y;
+ * this.next = next;
+ * }
+ */
+
+/**
+ * @param {PolyNode} poly1
+ * @param {PolyNode} poly2
+ * @return {PolyNode}
+ */
+var addPoly = function(poly1, poly2) {
+ const dummyHead = new PolyNode();
+ let current = dummyHead;
+ let pointer1 = poly1;
+ let pointer2 = poly2;
+
+ while (pointer1 || pointer2) {
+ let coefficient = 0;
+ let power = 0;
+
+ if (!pointer1) {
+ coefficient = pointer2.coefficient;
+ power = pointer2.power;
+ pointer2 = pointer2.next;
+ } else if (!pointer2) {
+ coefficient = pointer1.coefficient;
+ power = pointer1.power;
+ pointer1 = pointer1.next;
+ } else if (pointer1.power > pointer2.power) {
+ coefficient = pointer1.coefficient;
+ power = pointer1.power;
+ pointer1 = pointer1.next;
+ } else if (pointer2.power > pointer1.power) {
+ coefficient = pointer2.coefficient;
+ power = pointer2.power;
+ pointer2 = pointer2.next;
+ } else {
+ coefficient = pointer1.coefficient + pointer2.coefficient;
+ power = pointer1.power;
+ pointer1 = pointer1.next;
+ pointer2 = pointer2.next;
+ }
+
+ if (coefficient !== 0) {
+ current.next = new PolyNode(coefficient, power);
+ current = current.next;
+ }
+ }
+
+ return dummyHead.next;
+};
From a8746671451ce73ed6810f0912211a037b7e4f91 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 4 Jul 2025 23:47:40 -0500
Subject: [PATCH 664/994] Add solution #1644
---
README.md | 1 +
...est-common-ancestor-of-a-binary-tree-ii.js | 63 +++++++++++++++++++
2 files changed, 64 insertions(+)
create mode 100644 solutions/1644-lowest-common-ancestor-of-a-binary-tree-ii.js
diff --git a/README.md b/README.md
index 110c4f44..cd60fd9c 100644
--- a/README.md
+++ b/README.md
@@ -1502,6 +1502,7 @@
1641|[Count Sorted Vowel Strings](./solutions/1641-count-sorted-vowel-strings.js)|Medium|
1642|[Furthest Building You Can Reach](./solutions/1642-furthest-building-you-can-reach.js)|Medium|
1643|[Kth Smallest Instructions](./solutions/1643-kth-smallest-instructions.js)|Hard|
+1644|[Lowest Common Ancestor of a Binary Tree II](./solutions/1644-lowest-common-ancestor-of-a-binary-tree-ii.js)|Medium|
1646|[Get Maximum in Generated Array](./solutions/1646-get-maximum-in-generated-array.js)|Easy|
1647|[Minimum Deletions to Make Character Frequencies Unique](./solutions/1647-minimum-deletions-to-make-character-frequencies-unique.js)|Medium|
1648|[Sell Diminishing-Valued Colored Balls](./solutions/1648-sell-diminishing-valued-colored-balls.js)|Medium|
diff --git a/solutions/1644-lowest-common-ancestor-of-a-binary-tree-ii.js b/solutions/1644-lowest-common-ancestor-of-a-binary-tree-ii.js
new file mode 100644
index 00000000..07762f25
--- /dev/null
+++ b/solutions/1644-lowest-common-ancestor-of-a-binary-tree-ii.js
@@ -0,0 +1,63 @@
+/**
+ * 1644. Lowest Common Ancestor of a Binary Tree II
+ * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-ii/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree, return the lowest common ancestor (LCA) of two given
+ * nodes, p and q. If either node p or q does not exist in the tree, return null. All
+ * values of the nodes in the tree are unique.
+ *
+ * According to the definition of LCA on Wikipedia: "The lowest common ancestor of two
+ * nodes p and q in a binary tree T is the lowest node that has both p and q as descendants
+ * (where we allow a node to be a descendant of itself)". A descendant of a node x is a
+ * node y that is on the path from node x to some leaf node.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val) {
+ * this.val = val;
+ * this.left = this.right = null;
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @param {TreeNode} p
+ * @param {TreeNode} q
+ * @return {TreeNode}
+ */
+var lowestCommonAncestor = function(root, p, q) {
+ let foundP = false;
+ let foundQ = false;
+
+ const lca = findLCA(root);
+ return foundP && foundQ ? lca : null;
+
+ function findLCA(node) {
+ if (!node) return null;
+
+ const leftResult = findLCA(node.left);
+ const rightResult = findLCA(node.right);
+
+ let currentMatch = false;
+ if (node === p) {
+ foundP = true;
+ currentMatch = true;
+ }
+
+ if (node === q) {
+ foundQ = true;
+ currentMatch = true;
+ }
+
+ if (leftResult && rightResult) {
+ return node;
+ }
+
+ if (currentMatch && (leftResult || rightResult)) {
+ return node;
+ }
+
+ return leftResult || rightResult || (currentMatch ? node : null);
+ }
+};
From 4b2c38e4be592fcdaa7bf9e145f1909de71f60b8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 4 Jul 2025 23:49:43 -0500
Subject: [PATCH 665/994] Add solution #1650
---
README.md | 3 +-
...st-common-ancestor-of-a-binary-tree-iii.js | 54 +++++++++++++++++++
2 files changed, 56 insertions(+), 1 deletion(-)
create mode 100644 solutions/1650-lowest-common-ancestor-of-a-binary-tree-iii.js
diff --git a/README.md b/README.md
index cd60fd9c..7eb0e55b 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 2,400+ LeetCode solutions in JavaScript
+# 2,450+ LeetCode solutions in JavaScript
[https://leetcodejavascript.com](https://leetcodejavascript.com)
@@ -1507,6 +1507,7 @@
1647|[Minimum Deletions to Make Character Frequencies Unique](./solutions/1647-minimum-deletions-to-make-character-frequencies-unique.js)|Medium|
1648|[Sell Diminishing-Valued Colored Balls](./solutions/1648-sell-diminishing-valued-colored-balls.js)|Medium|
1649|[Create Sorted Array through Instructions](./solutions/1649-create-sorted-array-through-instructions.js)|Hard|
+1650|[Lowest Common Ancestor of a Binary Tree III](./solutions/1650-lowest-common-ancestor-of-a-binary-tree-iii.js)|Medium|
1652|[Defuse the Bomb](./solutions/1652-defuse-the-bomb.js)|Easy|
1653|[Minimum Deletions to Make String Balanced](./solutions/1653-minimum-deletions-to-make-string-balanced.js)|Medium|
1654|[Minimum Jumps to Reach Home](./solutions/1654-minimum-jumps-to-reach-home.js)|Medium|
diff --git a/solutions/1650-lowest-common-ancestor-of-a-binary-tree-iii.js b/solutions/1650-lowest-common-ancestor-of-a-binary-tree-iii.js
new file mode 100644
index 00000000..78a6cc1e
--- /dev/null
+++ b/solutions/1650-lowest-common-ancestor-of-a-binary-tree-iii.js
@@ -0,0 +1,54 @@
+/**
+ * 1650. Lowest Common Ancestor of a Binary Tree III
+ * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-iii/
+ * Difficulty: Medium
+ *
+ * Given two nodes of a binary tree p and q, return their lowest common ancestor (LCA).
+ *
+ * Each node will have a reference to its parent node. The definition for Node is below:
+ * class Node {
+ * public int val;
+ * public Node left;
+ * public Node right;
+ * public Node parent;
+ * }
+ *
+ * According to the definition of LCA on Wikipedia: "The lowest common ancestor of two
+ * nodes p and q in a tree T is the lowest node that has both p and q as descendants
+ * (where we allow a node to be a descendant of itself)."
+ */
+
+/**
+ * // Definition for a _Node.
+ * function _Node(val) {
+ * this.val = val;
+ * this.left = null;
+ * this.right = null;
+ * this.parent = null;
+ * };
+ */
+
+/**
+ * @param {_Node} p
+ * @param {_Node} q
+ * @return {_Node}
+ */
+var lowestCommonAncestor = function(p, q) {
+ const set = new Set();
+
+ let current = p;
+ while (current) {
+ set.add(current);
+ current = current.parent;
+ }
+
+ current = q;
+ while (current) {
+ if (set.has(current)) {
+ return current;
+ }
+ current = current.parent;
+ }
+
+ return null;
+};
From 3d51b267b594701406812718f69cca9c2a6d62c6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 15:40:40 -0500
Subject: [PATCH 666/994] Add solution #1660
---
README.md | 1 +
solutions/1660-correct-a-binary-tree.js | 63 +++++++++++++++++++++++++
2 files changed, 64 insertions(+)
create mode 100644 solutions/1660-correct-a-binary-tree.js
diff --git a/README.md b/README.md
index 7eb0e55b..6df9a778 100644
--- a/README.md
+++ b/README.md
@@ -1516,6 +1516,7 @@
1657|[Determine if Two Strings Are Close](./solutions/1657-determine-if-two-strings-are-close.js)|Medium|
1658|[Minimum Operations to Reduce X to Zero](./solutions/1658-minimum-operations-to-reduce-x-to-zero.js)|Medium|
1659|[Maximize Grid Happiness](./solutions/1659-maximize-grid-happiness.js)|Hard|
+1660|[Correct a Binary Tree](./solutions/1660-correct-a-binary-tree.js)|Medium|
1662|[Check If Two String Arrays are Equivalent](./solutions/1662-check-if-two-string-arrays-are-equivalent.js)|Easy|
1663|[Smallest String With A Given Numeric Value](./solutions/1663-smallest-string-with-a-given-numeric-value.js)|Medium|
1664|[Ways to Make a Fair Array](./solutions/1664-ways-to-make-a-fair-array.js)|Medium|
diff --git a/solutions/1660-correct-a-binary-tree.js b/solutions/1660-correct-a-binary-tree.js
new file mode 100644
index 00000000..c5ab98cd
--- /dev/null
+++ b/solutions/1660-correct-a-binary-tree.js
@@ -0,0 +1,63 @@
+/**
+ * 1660. Correct a Binary Tree
+ * https://leetcode.com/problems/correct-a-binary-tree/
+ * Difficulty: Medium
+ *
+ * You have a binary tree with a small defect. There is exactly one invalid node where its right
+ * child incorrectly points to another node at the same depth but to the invalid node's right.
+ *
+ * Given the root of the binary tree with this defect, root, return the root of the binary tree
+ * after removing this invalid node and every node underneath it (minus the node it incorrectly
+ * points to).
+ *
+ * Custom testing:
+ * The test input is read as 3 lines:
+ * - TreeNode root
+ * - int fromNode (not available to correctBinaryTree)
+ * - int toNode (not available to correctBinaryTree)
+ *
+ * After the binary tree rooted at root is parsed, the TreeNode with value of fromNode will have
+ * its right child pointer pointing to the TreeNode with a value of toNode. Then, root is passed
+ * to correctBinaryTree.
+ */
+
+/**
+ * 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} from
+ * @param {number} to
+ * @return {TreeNode}
+ */
+var correctBinaryTree = function(root) {
+ const set = new Set();
+ return traverse(root, null, false);
+
+ function traverse(node, parent, isLeft) {
+ if (!node) return null;
+
+ if (node.right && set.has(node.right)) {
+ if (parent) {
+ if (isLeft) {
+ parent.left = null;
+ } else {
+ parent.right = null;
+ }
+ }
+ return null;
+ }
+
+ set.add(node);
+
+ node.right = traverse(node.right, node, false);
+ node.left = traverse(node.left, node, true);
+
+ return node;
+ }
+};
From 4f986750e35875e68442fb4670deebad1a44ae53 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 15:47:57 -0500
Subject: [PATCH 667/994] Add solution #1666
---
README.md | 1 +
.../1666-change-the-root-of-a-binary-tree.js | 55 +++++++++++++++++++
2 files changed, 56 insertions(+)
create mode 100644 solutions/1666-change-the-root-of-a-binary-tree.js
diff --git a/README.md b/README.md
index 6df9a778..08959e49 100644
--- a/README.md
+++ b/README.md
@@ -1521,6 +1521,7 @@
1663|[Smallest String With A Given Numeric Value](./solutions/1663-smallest-string-with-a-given-numeric-value.js)|Medium|
1664|[Ways to Make a Fair Array](./solutions/1664-ways-to-make-a-fair-array.js)|Medium|
1665|[Minimum Initial Energy to Finish Tasks](./solutions/1665-minimum-initial-energy-to-finish-tasks.js)|Hard|
+1666|[Change the Root of a Binary Tree](./solutions/1666-change-the-root-of-a-binary-tree.js)|Medium|
1668|[Maximum Repeating Substring](./solutions/1668-maximum-repeating-substring.js)|Easy|
1669|[Merge In Between Linked Lists](./solutions/1669-merge-in-between-linked-lists.js)|Medium|
1670|[Design Front Middle Back Queue](./solutions/1670-design-front-middle-back-queue.js)|Medium|
diff --git a/solutions/1666-change-the-root-of-a-binary-tree.js b/solutions/1666-change-the-root-of-a-binary-tree.js
new file mode 100644
index 00000000..b27b8773
--- /dev/null
+++ b/solutions/1666-change-the-root-of-a-binary-tree.js
@@ -0,0 +1,55 @@
+/**
+ * 1666. Change the Root of a Binary Tree
+ * https://leetcode.com/problems/change-the-root-of-a-binary-tree/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree and a leaf node, reroot the tree so that the leaf is the
+ * new root.
+ *
+ * You can reroot the tree with the following steps for each node cur on the path starting
+ * from the leaf up to the root excluding the root:
+ * 1. If cur has a left child, then that child becomes cur's right child.
+ * 2. cur's original parent becomes cur's left child. Note that in this process the original
+ * parent's pointer to cur becomes null, making it have at most one child.
+ *
+ * Return the new root of the rerooted tree.
+ *
+ * Note: Ensure that your solution sets the Node.parent pointers correctly after rerooting or
+ * you will receive "Wrong Answer".
+ */
+
+/**
+ * // Definition for a Node.
+ * function Node(val) {
+ * this.val = val;
+ * this.left = null;
+ * this.right = null;
+ * this.parent = null;
+ * };
+ */
+
+/**
+ * @param {Node} node
+ * @return {Node}
+ */
+var flipBinaryTree = function(root, leaf) {
+ helper(leaf, null);
+ return leaf;
+
+ function helper(node, newParent) {
+ const originalParent = node.parent;
+ node.parent = newParent;
+ if (!originalParent) return;
+
+ if (node.left) node.right = node.left;
+ node.left = originalParent;
+
+ if (originalParent.left === node) {
+ originalParent.left = null;
+ } else {
+ originalParent.right = null;
+ }
+
+ helper(originalParent, node);
+ }
+};
From d16346b35647e6ec091245081050e1573c245f9e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 15:49:21 -0500
Subject: [PATCH 668/994] Add solution #1676
---
README.md | 1 +
...est-common-ancestor-of-a-binary-tree-iv.js | 44 +++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/1676-lowest-common-ancestor-of-a-binary-tree-iv.js
diff --git a/README.md b/README.md
index 08959e49..1ca99063 100644
--- a/README.md
+++ b/README.md
@@ -1530,6 +1530,7 @@
1673|[Find the Most Competitive Subsequence](./solutions/1673-find-the-most-competitive-subsequence.js)|Medium|
1674|[Minimum Moves to Make Array Complementary](./solutions/1674-minimum-moves-to-make-array-complementary.js)|Medium|
1675|[Minimize Deviation in Array](./solutions/1675-minimize-deviation-in-array.js)|Hard|
+1676|[Lowest Common Ancestor of a Binary Tree IV](./solutions/1676-lowest-common-ancestor-of-a-binary-tree-iv.js)|Medium|
1678|[Goal Parser Interpretation](./solutions/1678-goal-parser-interpretation.js)|Easy|
1679|[Max Number of K-Sum Pairs](./solutions/1679-max-number-of-k-sum-pairs.js)|Medium|
1680|[Concatenation of Consecutive Binary Numbers](./solutions/1680-concatenation-of-consecutive-binary-numbers.js)|Medium|
diff --git a/solutions/1676-lowest-common-ancestor-of-a-binary-tree-iv.js b/solutions/1676-lowest-common-ancestor-of-a-binary-tree-iv.js
new file mode 100644
index 00000000..f9690335
--- /dev/null
+++ b/solutions/1676-lowest-common-ancestor-of-a-binary-tree-iv.js
@@ -0,0 +1,44 @@
+/**
+ * 1676. Lowest Common Ancestor of a Binary Tree IV
+ * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-iv/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree and an array of TreeNode objects nodes, return the lowest common
+ * ancestor (LCA) of all the nodes in nodes. All the nodes will exist in the tree, and all values
+ * of the tree's nodes are unique.
+ *
+ * Extending the definition of LCA on Wikipedia: "The lowest common ancestor of n nodes p1,
+ * p2, ..., pn in a binary tree T is the lowest node that has every pi as a descendant (where we
+ * allow a node to be a descendant of itself) for every valid i". A descendant of a node x is a
+ * node y that is on the path from node x to some leaf node.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val) {
+ * this.val = val;
+ * this.left = this.right = null;
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @param {TreeNode[]} nodes
+ * @return {TreeNode}
+ */
+var lowestCommonAncestor = function(root, nodes) {
+ const targetSet = new Set(nodes);
+ return helper(root);
+
+ function helper(node) {
+ if (!node) return null;
+
+ if (targetSet.has(node)) return node;
+
+ const leftResult = helper(node.left);
+ const rightResult = helper(node.right);
+
+ if (leftResult && rightResult) return node;
+
+ return leftResult || rightResult;
+ }
+};
From 997c0bf66cb35d3edca8993d1df29b1f4304db99 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 16:00:08 -0500
Subject: [PATCH 669/994] Add solution #1682
---
README.md | 1 +
...1682-longest-palindromic-subsequence-ii.js | 60 +++++++++++++++++++
2 files changed, 61 insertions(+)
create mode 100644 solutions/1682-longest-palindromic-subsequence-ii.js
diff --git a/README.md b/README.md
index 1ca99063..717d76a2 100644
--- a/README.md
+++ b/README.md
@@ -1535,6 +1535,7 @@
1679|[Max Number of K-Sum Pairs](./solutions/1679-max-number-of-k-sum-pairs.js)|Medium|
1680|[Concatenation of Consecutive Binary Numbers](./solutions/1680-concatenation-of-consecutive-binary-numbers.js)|Medium|
1681|[Minimum Incompatibility](./solutions/1681-minimum-incompatibility.js)|Hard|
+1682|[Longest Palindromic Subsequence II](./solutions/1682-longest-palindromic-subsequence-ii.js)|Medium|
1684|[Count the Number of Consistent Strings](./solutions/1684-count-the-number-of-consistent-strings.js)|Easy|
1685|[Sum of Absolute Differences in a Sorted Array](./solutions/1685-sum-of-absolute-differences-in-a-sorted-array.js)|Medium|
1686|[Stone Game VI](./solutions/1686-stone-game-vi.js)|Medium|
diff --git a/solutions/1682-longest-palindromic-subsequence-ii.js b/solutions/1682-longest-palindromic-subsequence-ii.js
new file mode 100644
index 00000000..2a10e561
--- /dev/null
+++ b/solutions/1682-longest-palindromic-subsequence-ii.js
@@ -0,0 +1,60 @@
+/**
+ * 1682. Longest Palindromic Subsequence II
+ * https://leetcode.com/problems/longest-palindromic-subsequence-ii/
+ * Difficulty: Medium
+ *
+ * A subsequence of a string s is considered a good palindromic subsequence if:
+ * - It is a subsequence of s.
+ * - It is a palindrome (has the same value if reversed).
+ * - It has an even length.
+ * - No two consecutive characters are equal, except the two middle ones.
+ *
+ * For example, if s = "abcabcabb", then "abba" is considered a good palindromic subsequence,
+ * while "bcb" (not even length) and "bbbb" (has equal consecutive characters) are not.
+ *
+ * Given a string s, return the length of the longest good palindromic subsequence in s.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var longestPalindromeSubseq = function(s) {
+ const stringLength = s.length;
+ const alphabetSize = 26;
+ const baseCharCode = 97;
+
+ const memoTable = new Array(alphabetSize + 1);
+ for (let i = 0; i <= alphabetSize; i++) {
+ const matrix = memoTable[i] = new Array(stringLength);
+ for (let j = 0; j < stringLength; j++) {
+ matrix[j] = new Array(stringLength);
+ }
+ }
+
+ return findLongestPalindrome(alphabetSize, 0, stringLength - 1);
+
+ function findLongestPalindrome(previousChar, leftIndex, rightIndex) {
+ if (leftIndex >= rightIndex) return 0;
+
+ const cachedResult = memoTable[previousChar][leftIndex][rightIndex];
+ if (cachedResult !== undefined) return cachedResult;
+
+ let maxLength = 0;
+ const leftChar = s.charCodeAt(leftIndex) - baseCharCode;
+ const rightChar = s.charCodeAt(rightIndex) - baseCharCode;
+
+ if (leftChar === rightChar) {
+ if (leftChar !== previousChar) {
+ maxLength += 2;
+ }
+ maxLength += findLongestPalindrome(leftChar, leftIndex + 1, rightIndex - 1);
+ } else {
+ const skipLeftResult = findLongestPalindrome(previousChar, leftIndex + 1, rightIndex);
+ const skipRightResult = findLongestPalindrome(previousChar, leftIndex, rightIndex - 1);
+ maxLength += Math.max(skipLeftResult, skipRightResult);
+ }
+
+ return memoTable[previousChar][leftIndex][rightIndex] = maxLength;
+ }
+};
From 322e69a5db5317d1526ad5af03118cd9cc253066 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 16:01:31 -0500
Subject: [PATCH 670/994] Add solution #1692
---
README.md | 1 +
.../1692-count-ways-to-distribute-candies.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/1692-count-ways-to-distribute-candies.js
diff --git a/README.md b/README.md
index 717d76a2..f73f3a47 100644
--- a/README.md
+++ b/README.md
@@ -1544,6 +1544,7 @@
1689|[Partitioning Into Minimum Number Of Deci-Binary Numbers](./solutions/1689-partitioning-into-minimum-number-of-deci-binary-numbers.js)|Medium|
1690|[Stone Game VII](./solutions/1690-stone-game-vii.js)|Medium|
1691|[Maximum Height by Stacking Cuboids](./solutions/1691-maximum-height-by-stacking-cuboids.js)|Hard|
+1692|[Count Ways to Distribute Candies](./solutions/1692-count-ways-to-distribute-candies.js)|Hard|
1694|[Reformat Phone Number](./solutions/1694-reformat-phone-number.js)|Easy|
1695|[Maximum Erasure Value](./solutions/1695-maximum-erasure-value.js)|Medium|
1696|[Jump Game VI](./solutions/1696-jump-game-vi.js)|Medium|
diff --git a/solutions/1692-count-ways-to-distribute-candies.js b/solutions/1692-count-ways-to-distribute-candies.js
new file mode 100644
index 00000000..3288cbd6
--- /dev/null
+++ b/solutions/1692-count-ways-to-distribute-candies.js
@@ -0,0 +1,42 @@
+/**
+ * 1692. Count Ways to Distribute Candies
+ * https://leetcode.com/problems/count-ways-to-distribute-candies/
+ * Difficulty: Hard
+ *
+ * There are n unique candies (labeled 1 through n) and k bags. You are asked to distribute all
+ * the candies into the bags such that every bag has at least one candy.
+ *
+ * There can be multiple ways to distribute the candies. Two ways are considered different if
+ * the candies in one bag in the first way are not all in the same bag in the second way. The
+ * order of the bags and the order of the candies within each bag do not matter.
+ *
+ * For example, (1), (2,3) and (2), (1,3) are considered different because candies 2 and 3 in
+ * the bag (2,3) in the first way are not in the same bag in the second way (they are split
+ * between the bags (2) and (1,3)). However, (1), (2,3) and (3,2), (1) are considered the same
+ * because the candies in each bag are all in the same bags in both ways.
+ *
+ * Given two integers, n and k, return the number of different ways to distribute the candies.
+ * As the answer may be too large, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} k
+ * @return {number}
+ */
+var waysToDistribute = function(n, k) {
+ const MOD = 1e9 + 7;
+ const dp = new Array(n + 1).fill(0).map(() => new Array(k + 1).fill(0));
+
+ for (let i = 1; i <= n; i++) {
+ dp[i][1] = 1;
+ }
+
+ for (let candies = 2; candies <= n; candies++) {
+ for (let bags = 2; bags <= Math.min(candies, k); bags++) {
+ dp[candies][bags] = (dp[candies - 1][bags - 1] + (bags * dp[candies - 1][bags]) % MOD) % MOD;
+ }
+ }
+
+ return dp[n][k];
+};
From cee22414107be6c0f939dc95f2bfa069221b10f2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 16:22:58 -0500
Subject: [PATCH 671/994] Add solution #1698
---
README.md | 1 +
...mber-of-distinct-substrings-in-a-string.js | 27 +++++++++++++++++++
2 files changed, 28 insertions(+)
create mode 100644 solutions/1698-number-of-distinct-substrings-in-a-string.js
diff --git a/README.md b/README.md
index f73f3a47..43f557bb 100644
--- a/README.md
+++ b/README.md
@@ -1549,6 +1549,7 @@
1695|[Maximum Erasure Value](./solutions/1695-maximum-erasure-value.js)|Medium|
1696|[Jump Game VI](./solutions/1696-jump-game-vi.js)|Medium|
1697|[Checking Existence of Edge Length Limited Paths](./solutions/1697-checking-existence-of-edge-length-limited-paths.js)|Hard|
+1698|[Number of Distinct Substrings in a String](./solutions/1698-number-of-distinct-substrings-in-a-string.js)|Medium|
1700|[Number of Students Unable to Eat Lunch](./solutions/1700-number-of-students-unable-to-eat-lunch.js)|Easy|
1701|[Average Waiting Time](./solutions/1701-average-waiting-time.js)|Medium|
1702|[Maximum Binary String After Change](./solutions/1702-maximum-binary-string-after-change.js)|Medium|
diff --git a/solutions/1698-number-of-distinct-substrings-in-a-string.js b/solutions/1698-number-of-distinct-substrings-in-a-string.js
new file mode 100644
index 00000000..d7700654
--- /dev/null
+++ b/solutions/1698-number-of-distinct-substrings-in-a-string.js
@@ -0,0 +1,27 @@
+/**
+ * 1698. Number of Distinct Substrings in a String
+ * https://leetcode.com/problems/number-of-distinct-substrings-in-a-string/
+ * Difficulty: Medium
+ *
+ * Given a string s, return the number of distinct substrings of s.
+ *
+ * A substring of a string is obtained by deleting any number of characters (possibly zero)
+ * from the front of the string and any number (possibly zero) from the back of the string.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var countDistinct = function(s) {
+ const set = new Set();
+ const length = s.length;
+
+ for (let start = 0; start < length; start++) {
+ for (let end = start; end < length; end++) {
+ set.add(s.substring(start, end + 1));
+ }
+ }
+
+ return set.size;
+};
From 1b8b8f338a1d175375cf3a1e687fc1e88fa72544 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 16:24:08 -0500
Subject: [PATCH 672/994] Add solution #1708
---
README.md | 1 +
solutions/1708-largest-subarray-length-k.js | 33 +++++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/1708-largest-subarray-length-k.js
diff --git a/README.md b/README.md
index 43f557bb..f44d44a1 100644
--- a/README.md
+++ b/README.md
@@ -1558,6 +1558,7 @@
1705|[Maximum Number of Eaten Apples](./solutions/1705-maximum-number-of-eaten-apples.js)|Medium|
1706|[Where Will the Ball Fall](./solutions/1706-where-will-the-ball-fall.js)|Medium|
1707|[Maximum XOR With an Element From Array](./solutions/1707-maximum-xor-with-an-element-from-array.js)|Hard|
+1708|[Largest Subarray Length K](./solutions/1708-largest-subarray-length-k.js)|Easy|
1710|[Maximum Units on a Truck](./solutions/1710-maximum-units-on-a-truck.js)|Easy|
1711|[Count Good Meals](./solutions/1711-count-good-meals.js)|Medium|
1712|[Ways to Split Array Into Three Subarrays](./solutions/1712-ways-to-split-array-into-three-subarrays.js)|Medium|
diff --git a/solutions/1708-largest-subarray-length-k.js b/solutions/1708-largest-subarray-length-k.js
new file mode 100644
index 00000000..bf6490d1
--- /dev/null
+++ b/solutions/1708-largest-subarray-length-k.js
@@ -0,0 +1,33 @@
+/**
+ * 1708. Largest Subarray Length K
+ * https://leetcode.com/problems/largest-subarray-length-k/
+ * Difficulty: Easy
+ *
+ * An array A is larger than some array B if for the first index i where A[i] != B[i], A[i] > B[i].
+ *
+ * For example, consider 0-indexing:
+ * - [1,3,2,4] > [1,2,2,4], since at index 1, 3 > 2.
+ * - [1,4,4,4] < [2,1,1,1], since at index 0, 1 < 2.
+ *
+ * A subarray is a contiguous subsequence of the array.
+ *
+ * Given an integer array nums of distinct integers, return the largest subarray of nums of
+ * length k.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number[]}
+ */
+var largestSubarray = function(nums, k) {
+ let maxStartIndex = 0;
+
+ for (let i = 1; i <= nums.length - k; i++) {
+ if (nums[i] > nums[maxStartIndex]) {
+ maxStartIndex = i;
+ }
+ }
+
+ return nums.slice(maxStartIndex, maxStartIndex + k);
+};
From 99d42cc6084e93d9c11f7c53b7f04e06dd53307d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 16:25:47 -0500
Subject: [PATCH 673/994] Add solution #1714
---
README.md | 1 +
...special-evenly-spaced-elements-in-array.js | 53 +++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/1714-sum-of-special-evenly-spaced-elements-in-array.js
diff --git a/README.md b/README.md
index f44d44a1..06e30ba3 100644
--- a/README.md
+++ b/README.md
@@ -1563,6 +1563,7 @@
1711|[Count Good Meals](./solutions/1711-count-good-meals.js)|Medium|
1712|[Ways to Split Array Into Three Subarrays](./solutions/1712-ways-to-split-array-into-three-subarrays.js)|Medium|
1713|[Minimum Operations to Make a Subsequence](./solutions/1713-minimum-operations-to-make-a-subsequence.js)|Hard|
+1714|[Sum Of Special Evenly-Spaced Elements In Array](./solutions/1714-sum-of-special-evenly-spaced-elements-in-array.js)|Hard|
1716|[Calculate Money in Leetcode Bank](./solutions/1716-calculate-money-in-leetcode-bank.js)|Easy|
1717|[Maximum Score From Removing Substrings](./solutions/1717-maximum-score-from-removing-substrings.js)|Medium|
1718|[Construct the Lexicographically Largest Valid Sequence](./solutions/1718-construct-the-lexicographically-largest-valid-sequence.js)|Medium|
diff --git a/solutions/1714-sum-of-special-evenly-spaced-elements-in-array.js b/solutions/1714-sum-of-special-evenly-spaced-elements-in-array.js
new file mode 100644
index 00000000..de256870
--- /dev/null
+++ b/solutions/1714-sum-of-special-evenly-spaced-elements-in-array.js
@@ -0,0 +1,53 @@
+/**
+ * 1714. Sum Of Special Evenly-Spaced Elements In Array
+ * https://leetcode.com/problems/sum-of-special-evenly-spaced-elements-in-array/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed integer array nums consisting of n non-negative integers.
+ *
+ * You are also given an array queries, where queries[i] = [xi, yi]. The answer to the ith
+ * query is the sum of all nums[j] where xi <= j < n and (j - xi) is divisible by yi.
+ *
+ * Return an array answer where answer.length == queries.length and answer[i] is the answer
+ * to the ith query modulo 109 + 7.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[][]} queries
+ * @return {number[]}
+ */
+var solve = function(nums, queries) {
+ const MOD = 1e9 + 7;
+ const n = nums.length;
+ const threshold = Math.sqrt(n);
+ const precomputed = new Map();
+
+ for (let step = 1; step <= threshold; step++) {
+ const suffixSums = new Array(n).fill(0);
+ for (let start = n - 1; start >= 0; start--) {
+ if (start + step < n) {
+ suffixSums[start] = (nums[start] + suffixSums[start + step]) % MOD;
+ } else {
+ suffixSums[start] = nums[start];
+ }
+ }
+ precomputed.set(step, suffixSums);
+ }
+
+ const result = [];
+
+ for (const [startIndex, step] of queries) {
+ if (step <= threshold) {
+ result.push(precomputed.get(step)[startIndex] || 0);
+ } else {
+ let sum = 0;
+ for (let i = startIndex; i < n; i += step) {
+ sum = (sum + nums[i]) % MOD;
+ }
+ result.push(sum);
+ }
+ }
+
+ return result;
+};
From f8f3c9a5f288333f3aad00f58f42cd58f374efff Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 16:32:00 -0500
Subject: [PATCH 674/994] Add solution #1724
---
README.md | 1 +
...istence-of-edge-length-limited-paths-ii.js | 83 +++++++++++++++++++
2 files changed, 84 insertions(+)
create mode 100644 solutions/1724-checking-existence-of-edge-length-limited-paths-ii.js
diff --git a/README.md b/README.md
index 06e30ba3..f39be7d6 100644
--- a/README.md
+++ b/README.md
@@ -1572,6 +1572,7 @@
1721|[Swapping Nodes in a Linked List](./solutions/1721-swapping-nodes-in-a-linked-list.js)|Medium|
1722|[Minimize Hamming Distance After Swap Operations](./solutions/1722-minimize-hamming-distance-after-swap-operations.js)|Medium|
1723|[Find Minimum Time to Finish All Jobs](./solutions/1723-find-minimum-time-to-finish-all-jobs.js)|Hard|
+1724|[Checking Existence of Edge Length Limited Paths II](./solutions/1724-checking-existence-of-edge-length-limited-paths-ii.js)|Hard|
1725|[Number Of Rectangles That Can Form The Largest Square](./solutions/1725-number-of-rectangles-that-can-form-the-largest-square.js)|Easy|
1726|[Tuple with Same Product](./solutions/1726-tuple-with-same-product.js)|Medium|
1727|[Largest Submatrix With Rearrangements](./solutions/1727-largest-submatrix-with-rearrangements.js)|Medium|
diff --git a/solutions/1724-checking-existence-of-edge-length-limited-paths-ii.js b/solutions/1724-checking-existence-of-edge-length-limited-paths-ii.js
new file mode 100644
index 00000000..401bcc62
--- /dev/null
+++ b/solutions/1724-checking-existence-of-edge-length-limited-paths-ii.js
@@ -0,0 +1,83 @@
+/**
+ * 1724. Checking Existence of Edge Length Limited Paths II
+ * https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths-ii/
+ * Difficulty: Hard
+ *
+ * An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi]
+ * denotes an edge between nodes ui and vi with distance disi. Note that there may be multiple
+ * edges between two nodes, and the graph may not be connected.
+ *
+ * Implement the DistanceLimitedPathsExist class:
+ * - DistanceLimitedPathsExist(int n, int[][] edgeList) Initializes the class with an
+ * undirected graph.
+ * - boolean query(int p, int q, int limit) Returns true if there exists a path from p to q
+ * such that each edge on the path has a distance strictly less than limit, and otherwise
+ * false.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edgeList
+ */
+var DistanceLimitedPathsExist = function(n, edgeList) {
+ this.nodeCount = n;
+ this.sortedEdges = edgeList.slice().sort((a, b) => a[2] - b[2]);
+ this.unionFindByLimit = new Map();
+ this.processedLimits = new Set();
+};
+
+/**
+ * @param {number} p
+ * @param {number} q
+ * @param {number} limit
+ * @return {boolean}
+ */
+DistanceLimitedPathsExist.prototype.query = function(p, q, limit) {
+ if (!this.processedLimits.has(limit)) {
+ const unionFind = new UnionFind(this.nodeCount);
+
+ for (const [u, v, weight] of this.sortedEdges) {
+ if (weight >= limit) break;
+ unionFind.union(u, v);
+ }
+
+ this.unionFindByLimit.set(limit, unionFind);
+ this.processedLimits.add(limit);
+ }
+
+ return this.unionFindByLimit.get(limit).connected(p, q);
+};
+
+class UnionFind {
+ constructor(n) {
+ this.parent = Array.from({ length: n }, (_, i) => i);
+ this.rank = new Array(n).fill(0);
+ }
+
+ 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) {
+ if (this.rank[rootX] < this.rank[rootY]) {
+ this.parent[rootX] = rootY;
+ } else if (this.rank[rootX] > this.rank[rootY]) {
+ this.parent[rootY] = rootX;
+ } else {
+ this.parent[rootY] = rootX;
+ this.rank[rootX]++;
+ }
+ }
+ }
+
+ connected(x, y) {
+ return this.find(x) === this.find(y);
+ }
+}
From fbc95e31d66a373c3bba9cd50c1773b91f2b3819 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 16:33:35 -0500
Subject: [PATCH 675/994] Add solution #1730
---
README.md | 1 +
solutions/1730-shortest-path-to-get-food.js | 68 +++++++++++++++++++++
2 files changed, 69 insertions(+)
create mode 100644 solutions/1730-shortest-path-to-get-food.js
diff --git a/README.md b/README.md
index f39be7d6..aff01d16 100644
--- a/README.md
+++ b/README.md
@@ -1577,6 +1577,7 @@
1726|[Tuple with Same Product](./solutions/1726-tuple-with-same-product.js)|Medium|
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|
+1730|[Shortest Path to Get Food](./solutions/1730-shortest-path-to-get-food.js)|Medium|
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|
diff --git a/solutions/1730-shortest-path-to-get-food.js b/solutions/1730-shortest-path-to-get-food.js
new file mode 100644
index 00000000..beb22796
--- /dev/null
+++ b/solutions/1730-shortest-path-to-get-food.js
@@ -0,0 +1,68 @@
+/**
+ * 1730. Shortest Path to Get Food
+ * https://leetcode.com/problems/shortest-path-to-get-food/
+ * Difficulty: Medium
+ *
+ * You are starving and you want to eat food as quickly as possible. You want to find the
+ * shortest path to arrive at any food cell.
+ *
+ * You are given an m x n character matrix, grid, of these different types of cells:
+ * - '*' is your location. There is exactly one '*' cell.
+ * - '#' is a food cell. There may be multiple food cells.
+ * - 'O' is free space, and you can travel through these cells.
+ * - 'X' is an obstacle, and you cannot travel through these cells.
+ *
+ * You can travel to any adjacent cell north, east, south, or west of your current location
+ * if there is not an obstacle.
+ *
+ * Return the length of the shortest path for you to reach any food cell. If there is no
+ * path for you to reach food, return -1.
+ */
+
+/**
+ * @param {character[][]} grid
+ * @return {number}
+ */
+var getFood = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
+ let startRow = 0;
+ let startCol = 0;
+
+ for (let i = 0; i < rows; i++) {
+ for (let j = 0; j < cols; j++) {
+ if (grid[i][j] === '*') {
+ startRow = i;
+ startCol = j;
+ break;
+ }
+ }
+ }
+
+ const queue = [[startRow, startCol, 0]];
+ const visited = new Set();
+ visited.add(`${startRow},${startCol}`);
+
+ while (queue.length > 0) {
+ const [currentRow, currentCol, steps] = queue.shift();
+
+ if (grid[currentRow][currentCol] === '#') {
+ return steps;
+ }
+
+ for (const [deltaRow, deltaCol] of directions) {
+ const newRow = currentRow + deltaRow;
+ const newCol = currentCol + deltaCol;
+ const key = `${newRow},${newCol}`;
+
+ if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && !visited.has(key)
+ && grid[newRow][newCol] !== 'X') {
+ visited.add(key);
+ queue.push([newRow, newCol, steps + 1]);
+ }
+ }
+ }
+
+ return -1;
+};
From b195caa1cba1f28596cbbb7d0fc9d8e11f56ada9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 17:27:19 -0500
Subject: [PATCH 676/994] Add solution #1740
---
README.md | 1 +
.../1740-find-distance-in-a-binary-tree.js | 54 +++++++++++++++++++
2 files changed, 55 insertions(+)
create mode 100644 solutions/1740-find-distance-in-a-binary-tree.js
diff --git a/README.md b/README.md
index aff01d16..185d29fb 100644
--- a/README.md
+++ b/README.md
@@ -1586,6 +1586,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|
+1740|[Find Distance in a Binary Tree](./solutions/1740-find-distance-in-a-binary-tree.js)|Medium|
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|
diff --git a/solutions/1740-find-distance-in-a-binary-tree.js b/solutions/1740-find-distance-in-a-binary-tree.js
new file mode 100644
index 00000000..e4bcff0a
--- /dev/null
+++ b/solutions/1740-find-distance-in-a-binary-tree.js
@@ -0,0 +1,54 @@
+/**
+ * 1740. Find Distance in a Binary Tree
+ * https://leetcode.com/problems/find-distance-in-a-binary-tree/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree and two integers p and q, return the distance between the
+ * nodes of value p and value q in the tree.
+ *
+ * The distance between two nodes is the number of edges on the path from one to the other.
+ */
+
+/**
+ * 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} p
+ * @param {number} q
+ * @return {number}
+ */
+var findDistance = function(root, p, q) {
+ if (p === q) return 0;
+
+ const lca = findLCA(root);
+ const depthP = findDepth(lca, p, 0);
+ const depthQ = findDepth(lca, q, 0);
+
+ return depthP + depthQ;
+
+ function findLCA(node) {
+ if (!node || node.val === p || node.val === q) return node;
+
+ const leftResult = findLCA(node.left);
+ const rightResult = findLCA(node.right);
+
+ if (leftResult && rightResult) return node;
+ return leftResult || rightResult;
+ }
+
+ function findDepth(node, target, depth) {
+ if (!node) return -1;
+ if (node.val === target) return depth;
+
+ const leftDepth = findDepth(node.left, target, depth + 1);
+ if (leftDepth !== -1) return leftDepth;
+
+ return findDepth(node.right, target, depth + 1);
+ }
+};
From 162e38b445380360722738ac4fadb5fd60cb629b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 17:28:44 -0500
Subject: [PATCH 677/994] Add solution #1746
---
README.md | 1 +
...aximum-subarray-sum-after-one-operation.js | 44 +++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/1746-maximum-subarray-sum-after-one-operation.js
diff --git a/README.md b/README.md
index 185d29fb..c3158876 100644
--- a/README.md
+++ b/README.md
@@ -1591,6 +1591,7 @@
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|
+1746|[Maximum Subarray Sum After One Operation](./solutions/1746-maximum-subarray-sum-after-one-operation.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|
1750|[Minimum Length of String After Deleting Similar Ends](./solutions/1750-minimum-length-of-string-after-deleting-similar-ends.js)|Medium|
diff --git a/solutions/1746-maximum-subarray-sum-after-one-operation.js b/solutions/1746-maximum-subarray-sum-after-one-operation.js
new file mode 100644
index 00000000..57f9dd8c
--- /dev/null
+++ b/solutions/1746-maximum-subarray-sum-after-one-operation.js
@@ -0,0 +1,44 @@
+/**
+ * 1746. Maximum Subarray Sum After One Operation
+ * https://leetcode.com/problems/maximum-subarray-sum-after-one-operation/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums. You must perform exactly one operation where you can
+ * replace one element nums[i] with nums[i] * nums[i].
+ *
+ * Return the maximum possible subarray sum after exactly one operation. The subarray must
+ * be non-empty.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maxSumAfterOperation = function(nums) {
+ const n = nums.length;
+ let maxWithoutSquare = nums[0];
+ let maxWithSquare = nums[0] * nums[0];
+ let result = maxWithSquare;
+
+ for (let i = 1; i < n; i++) {
+ const currentValue = nums[i];
+ const squaredValue = currentValue * currentValue;
+
+ const newMaxWithSquare = Math.max(
+ squaredValue,
+ maxWithoutSquare + squaredValue,
+ maxWithSquare + currentValue
+ );
+
+ const newMaxWithoutSquare = Math.max(
+ currentValue,
+ maxWithoutSquare + currentValue
+ );
+
+ maxWithSquare = newMaxWithSquare;
+ maxWithoutSquare = newMaxWithoutSquare;
+ result = Math.max(result, maxWithSquare);
+ }
+
+ return result;
+};
From 22ec8eaa6e1fcf2313aa90d03b4a185802bf5971 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 17:30:02 -0500
Subject: [PATCH 678/994] Add solution #1756
---
README.md | 1 +
.../1756-design-most-recently-used-queue.js | 30 +++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 solutions/1756-design-most-recently-used-queue.js
diff --git a/README.md b/README.md
index c3158876..73921110 100644
--- a/README.md
+++ b/README.md
@@ -1600,6 +1600,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|
+1756|[Design Most Recently Used Queue](./solutions/1756-design-most-recently-used-queue.js)|Medium|
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|
diff --git a/solutions/1756-design-most-recently-used-queue.js b/solutions/1756-design-most-recently-used-queue.js
new file mode 100644
index 00000000..91ac1bb2
--- /dev/null
+++ b/solutions/1756-design-most-recently-used-queue.js
@@ -0,0 +1,30 @@
+/**
+ * 1756. Design Most Recently Used Queue
+ * https://leetcode.com/problems/design-most-recently-used-queue/
+ * Difficulty: Medium
+ *
+ * Design a queue-like data structure that moves the most recently used element to the end
+ * of the queue.
+ *
+ * Implement the MRUQueue class:
+ * - MRUQueue(int n) constructs the MRUQueue with n elements: [1,2,3,...,n].
+ * - int fetch(int k) moves the kth element (1-indexed) to the end of the queue and returns it.
+ */
+
+/**
+ * @param {number} n
+ */
+var MRUQueue = function(n) {
+ this.elements = Array.from({ length: n }, (_, i) => i + 1);
+};
+
+/**
+ * @param {number} k
+ * @return {number}
+ */
+MRUQueue.prototype.fetch = function(k) {
+ const element = this.elements[k - 1];
+ this.elements.splice(k - 1, 1);
+ this.elements.push(element);
+ return element;
+};
From 5695f0b59ae9b8a363374f9e1a3503d83e26924d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 17:31:01 -0500
Subject: [PATCH 679/994] Add solution #1762
---
README.md | 1 +
.../1762-buildings-with-an-ocean-view.js | 33 +++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/1762-buildings-with-an-ocean-view.js
diff --git a/README.md b/README.md
index 73921110..821f4a65 100644
--- a/README.md
+++ b/README.md
@@ -1605,6 +1605,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|
+1762|[Buildings With an Ocean View](./solutions/1762-buildings-with-an-ocean-view.js)|Medium|
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|
diff --git a/solutions/1762-buildings-with-an-ocean-view.js b/solutions/1762-buildings-with-an-ocean-view.js
new file mode 100644
index 00000000..34de9c3b
--- /dev/null
+++ b/solutions/1762-buildings-with-an-ocean-view.js
@@ -0,0 +1,33 @@
+/**
+ * 1762. Buildings With an Ocean View
+ * https://leetcode.com/problems/buildings-with-an-ocean-view/
+ * Difficulty: Medium
+ *
+ * There are n buildings in a line. You are given an integer array heights of size n that
+ * represents the heights of the buildings in the line.
+ *
+ * The ocean is to the right of the buildings. A building has an ocean view if the building
+ * can see the ocean without obstructions. Formally, a building has an ocean view if all the
+ * buildings to its right have a smaller height.
+ *
+ * Return a list of indices (0-indexed) of buildings that have an ocean view, sorted in
+ * increasing order.
+ */
+
+/**
+ * @param {number[]} heights
+ * @return {number[]}
+ */
+var findBuildings = function(heights) {
+ const result = [];
+ let maxHeightFromRight = 0;
+
+ for (let i = heights.length - 1; i >= 0; i--) {
+ if (heights[i] > maxHeightFromRight) {
+ result.push(i);
+ maxHeightFromRight = heights[i];
+ }
+ }
+
+ return result.reverse();
+};
From fa24b21b1e5c6d4be712cc2376dd7dc32d6233d2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 17:32:12 -0500
Subject: [PATCH 680/994] Add solution #1772
---
README.md | 1 +
solutions/1772-sort-features-by-popularity.js | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/1772-sort-features-by-popularity.js
diff --git a/README.md b/README.md
index 821f4a65..43160556 100644
--- a/README.md
+++ b/README.md
@@ -1614,6 +1614,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|
+1772|[Sort Features by Popularity](./solutions/1772-sort-features-by-popularity.js)|Medium|
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|
diff --git a/solutions/1772-sort-features-by-popularity.js b/solutions/1772-sort-features-by-popularity.js
new file mode 100644
index 00000000..66067e06
--- /dev/null
+++ b/solutions/1772-sort-features-by-popularity.js
@@ -0,0 +1,50 @@
+/**
+ * 1772. Sort Features by Popularity
+ * https://leetcode.com/problems/sort-features-by-popularity/
+ * Difficulty: Medium
+ *
+ * You are given a string array features where features[i] is a single word that represents
+ * the name of a feature of the latest product you are working on. You have made a survey
+ * where users have reported which features they like. You are given a string array responses,
+ * where each responses[i] is a string containing space-separated words.
+ *
+ * The popularity of a feature is the number of responses[i] that contain the feature. You
+ * want to sort the features in non-increasing order by their popularity. If two features
+ * have the same popularity, order them by their original index in features. Notice that
+ * one response could contain the same feature multiple times; this feature is only counted
+ * once in its popularity.
+ *
+ * Return the features in sorted order.
+ */
+
+/**
+ * @param {string[]} features
+ * @param {string[]} responses
+ * @return {string[]}
+ */
+var sortFeatures = function(features, responses) {
+ const map = new Map();
+
+ for (const feature of features) {
+ map.set(feature, 0);
+ }
+
+ for (const response of responses) {
+ const uniqueWords = new Set(response.split(' '));
+ for (const word of uniqueWords) {
+ if (map.has(word)) {
+ map.set(word, map.get(word) + 1);
+ }
+ }
+ }
+
+ return features
+ .map((feature, index) => ({ feature, popularity: map.get(feature), index }))
+ .sort((a, b) => {
+ if (a.popularity !== b.popularity) {
+ return b.popularity - a.popularity;
+ }
+ return a.index - b.index;
+ })
+ .map(item => item.feature);
+};
From 80656eb32a81a159c63c5a5a0c93fdc5232b848c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 17:36:06 -0500
Subject: [PATCH 681/994] Add solution #1778
---
README.md | 1 +
.../1778-shortest-path-in-a-hidden-grid.js | 127 ++++++++++++++++++
2 files changed, 128 insertions(+)
create mode 100644 solutions/1778-shortest-path-in-a-hidden-grid.js
diff --git a/README.md b/README.md
index 43160556..97b3ddb1 100644
--- a/README.md
+++ b/README.md
@@ -1619,6 +1619,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|
+1778|[Shortest Path in a Hidden Grid](./solutions/1778-shortest-path-in-a-hidden-grid.js)|Medium|
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|
diff --git a/solutions/1778-shortest-path-in-a-hidden-grid.js b/solutions/1778-shortest-path-in-a-hidden-grid.js
new file mode 100644
index 00000000..a205d21b
--- /dev/null
+++ b/solutions/1778-shortest-path-in-a-hidden-grid.js
@@ -0,0 +1,127 @@
+/**
+ * 1778. Shortest Path in a Hidden Grid
+ * https://leetcode.com/problems/shortest-path-in-a-hidden-grid/
+ * Difficulty: Medium
+ *
+ * This is an interactive problem.
+ *
+ * There is a robot in a hidden grid, and you are trying to get it from its starting cell to the
+ * target cell in this grid. The grid is of size m x n, and each cell in the grid is either empty
+ * or blocked. It is guaranteed that the starting cell and the target cell are different, and
+ * neither of them is blocked.
+ *
+ * You want to find the minimum distance to the target cell. However, you do not know the grid's
+ * dimensions, the starting cell, nor the target cell. You are only allowed to ask queries to the
+ * GridMaster object.
+ *
+ * The GridMaster class has the following functions:
+ * - boolean canMove(char direction) Returns true if the robot can move in that direction.
+ * Otherwise, it returns false.
+ * - void move(char direction) Moves the robot in that direction. If this move would move the
+ * robot to a blocked cell or off the grid, the move will be ignored, and the robot will
+ * remain in the same position.
+ * - boolean isTarget() Returns true if the robot is currently on the target cell. Otherwise,
+ * it returns false.
+ *
+ * Note that direction in the above functions should be a character from {'U','D','L','R'},
+ * representing the directions up, down, left, and right, respectively.
+ *
+ * Return the minimum distance between the robot's initial starting cell and the target cell.
+ * If there is no valid path between the cells, return -1.
+ *
+ * Custom testing:
+ *
+ * The test input is read as a 2D matrix grid of size m x n where:
+ * - grid[i][j] == -1 indicates that the robot is in cell (i, j) (the starting cell).
+ * - grid[i][j] == 0 indicates that the cell (i, j) is blocked.
+ * - grid[i][j] == 1 indicates that the cell (i, j) is empty.
+ * - grid[i][j] == 2 indicates that the cell (i, j) is the target cell.
+ *
+ * There is exactly one -1 and 2 in grid. Remember that you will not have this information
+ * in your code.
+ */
+
+/**
+ * // This is the GridMaster's API interface.
+ * // You should not implement it, or speculate about its implementation
+ * function GridMaster() {
+ *
+ * @param {character} direction
+ * @return {boolean}
+ * this.canMove = function(direction) {
+ * ...
+ * };
+ * @param {character} direction
+ * @return {void}
+ * this.move = function(direction) {
+ * ...
+ * };
+ * @return {boolean}
+ * this.isTarget = function() {
+ * ...
+ * };
+ * };
+ */
+
+/**
+ * @param {GridMaster} master
+ * @return {integer}
+ */
+var findShortestPath = function(master) {
+ const directions = [
+ ['U', 'D', 0, -1],
+ ['D', 'U', 0, 1],
+ ['L', 'R', -1, 0],
+ ['R', 'L', 1, 0]
+ ];
+
+ const visited = new Set();
+ let targetPosition = null;
+
+ dfs(0, 0);
+
+ if (!targetPosition) return -1;
+
+ const queue = [[0, 0, 0]];
+ const bfsVisited = new Set(['0,0']);
+
+ while (queue.length > 0) {
+ const [x, y, distance] = queue.shift();
+
+ if (x === targetPosition[0] && y === targetPosition[1]) {
+ return distance;
+ }
+
+ for (const [, , dx, dy] of directions) {
+ const newX = x + dx;
+ const newY = y + dy;
+ const key = `${newX},${newY}`;
+
+ if (!bfsVisited.has(key) && visited.has(key)) {
+ bfsVisited.add(key);
+ queue.push([newX, newY, distance + 1]);
+ }
+ }
+ }
+
+ return -1;
+
+ function dfs(x, y) {
+ const key = `${x},${y}`;
+ if (visited.has(key)) return;
+ visited.add(key);
+
+ if (master.isTarget()) {
+ targetPosition = [x, y];
+ return;
+ }
+
+ for (const [moveDir, backDir, dx, dy] of directions) {
+ if (master.canMove(moveDir)) {
+ master.move(moveDir);
+ dfs(x + dx, y + dy);
+ master.move(backDir);
+ }
+ }
+ }
+};
From c818f7f753f4df13d1307b2a52516ffc6a3edd4e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 17:37:40 -0500
Subject: [PATCH 682/994] Add solution #1788
---
README.md | 1 +
.../1788-maximize-the-beauty-of-the-garden.js | 54 +++++++++++++++++++
2 files changed, 55 insertions(+)
create mode 100644 solutions/1788-maximize-the-beauty-of-the-garden.js
diff --git a/README.md b/README.md
index 97b3ddb1..c474446d 100644
--- a/README.md
+++ b/README.md
@@ -1628,6 +1628,7 @@
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|
+1788|[Maximize the Beauty of the Garden](./solutions/1788-maximize-the-beauty-of-the-garden.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|
diff --git a/solutions/1788-maximize-the-beauty-of-the-garden.js b/solutions/1788-maximize-the-beauty-of-the-garden.js
new file mode 100644
index 00000000..bac04646
--- /dev/null
+++ b/solutions/1788-maximize-the-beauty-of-the-garden.js
@@ -0,0 +1,54 @@
+/**
+ * 1788. Maximize the Beauty of the Garden
+ * https://leetcode.com/problems/maximize-the-beauty-of-the-garden/
+ * Difficulty: Hard
+ *
+ * There is a garden of n flowers, and each flower has an integer beauty value. The flowers
+ * are arranged in a line. You are given an integer array flowers of size n and each flowers[i]
+ * represents the beauty of the ith flower.
+ *
+ * A garden is valid if it meets these conditions:
+ * - The garden has at least two flowers.
+ * - The first and the last flower of the garden have the same beauty value.
+ *
+ * As the appointed gardener, you have the ability to remove any (possibly none) flowers from
+ * the garden. You want to remove flowers in a way that makes the remaining garden valid. The
+ * beauty of the garden is the sum of the beauty of all the remaining flowers.
+ *
+ * Return the maximum possible beauty of some valid garden after you have removed any (possibly
+ * none) flowers.
+ */
+
+/**
+ * @param {number[]} flowers
+ * @return {number}
+ */
+var maximumBeauty = function(flowers) {
+ const map = new Map();
+
+ for (let i = 0; i < flowers.length; i++) {
+ if (!map.has(flowers[i])) {
+ map.set(flowers[i], []);
+ }
+ map.get(flowers[i]).push(i);
+ }
+
+ const prefixSum = new Array(flowers.length + 1).fill(0);
+ for (let i = 0; i < flowers.length; i++) {
+ prefixSum[i + 1] = prefixSum[i] + Math.max(0, flowers[i]);
+ }
+
+ let result = -Infinity;
+
+ for (const [value, indices] of map) {
+ if (indices.length >= 2) {
+ const firstIndex = indices[0];
+ const lastIndex = indices[indices.length - 1];
+ const positiveSum = prefixSum[lastIndex] - prefixSum[firstIndex + 1];
+ const beauty = 2 * value + positiveSum;
+ result = Math.max(result, beauty);
+ }
+ }
+
+ return result;
+};
From c8299cfe0c48a97d897eb1fb9754b5d62f9c6765 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 17:44:39 -0500
Subject: [PATCH 683/994] Add solution #1794
---
README.md | 1 +
...qual-substrings-with-minimum-difference.js | 52 +++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 solutions/1794-count-pairs-of-equal-substrings-with-minimum-difference.js
diff --git a/README.md b/README.md
index c474446d..2d0bf992 100644
--- a/README.md
+++ b/README.md
@@ -1633,6 +1633,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|
+1794|[Count Pairs of Equal Substrings With Minimum Difference](./solutions/1794-count-pairs-of-equal-substrings-with-minimum-difference.js)|Medium|
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|
diff --git a/solutions/1794-count-pairs-of-equal-substrings-with-minimum-difference.js b/solutions/1794-count-pairs-of-equal-substrings-with-minimum-difference.js
new file mode 100644
index 00000000..082f9188
--- /dev/null
+++ b/solutions/1794-count-pairs-of-equal-substrings-with-minimum-difference.js
@@ -0,0 +1,52 @@
+/**
+ * 1794. Count Pairs of Equal Substrings With Minimum Difference
+ * https://leetcode.com/problems/count-pairs-of-equal-substrings-with-minimum-difference/
+ * Difficulty: Medium
+ *
+ * You are given two strings firstString and secondString that are 0-indexed and consist only
+ * of lowercase English letters. Count the number of index quadruples (i,j,a,b) that satisfy
+ * the following conditions:
+ * - 0 <= i <= j < firstString.length
+ * - 0 <= a <= b < secondString.length
+ * - The substring of firstString that starts at the ith character and ends at the jth character
+ * (inclusive) is equal to the substring of secondString that starts at the ath character and
+ * ends at the bth character (inclusive).
+ * - j - a is the minimum possible value among all quadruples that satisfy the previous conditions.
+ *
+ * Return the number of such quadruples.
+ */
+
+/**
+ * @param {string} firstString
+ * @param {string} secondString
+ * @return {number}
+ */
+var countQuadruples = function(firstString, secondString) {
+ const firstPositions = new Array(26).fill(0);
+ const secondPositions = new Array(26).fill(0);
+ let minDifference = Infinity;
+ let quadrupleCount = 0;
+
+ for (let j = firstString.length - 1; j >= 0; j--) {
+ firstPositions[firstString[j].charCodeAt(0) - 97] = j + 1;
+ }
+
+ for (let a = 0; a < secondString.length; a++) {
+ secondPositions[secondString[a].charCodeAt(0) - 97] = a + 1;
+ }
+
+ for (let i = 0; i < 26; i++) {
+ if (firstPositions[i] && secondPositions[i]) {
+ const difference = firstPositions[i] - secondPositions[i];
+ if (difference < minDifference) {
+ minDifference = difference;
+ quadrupleCount = 0;
+ }
+ if (difference === minDifference) {
+ quadrupleCount++;
+ }
+ }
+ }
+
+ return quadrupleCount;
+};
From 768bd010fb7fec2137053b2c857b1e278df5da95 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 17:46:46 -0500
Subject: [PATCH 684/994] Add solution #1804
---
README.md | 1 +
.../1804-implement-trie-ii-prefix-tree.js | 81 +++++++++++++++++++
2 files changed, 82 insertions(+)
create mode 100644 solutions/1804-implement-trie-ii-prefix-tree.js
diff --git a/README.md b/README.md
index 2d0bf992..bfd0d4bf 100644
--- a/README.md
+++ b/README.md
@@ -1642,6 +1642,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|
+1804|[Implement Trie II (Prefix Tree)](./solutions/1804-implement-trie-ii-prefix-tree.js)|Medium|
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|
diff --git a/solutions/1804-implement-trie-ii-prefix-tree.js b/solutions/1804-implement-trie-ii-prefix-tree.js
new file mode 100644
index 00000000..235af683
--- /dev/null
+++ b/solutions/1804-implement-trie-ii-prefix-tree.js
@@ -0,0 +1,81 @@
+/**
+ * 1804. Implement Trie II (Prefix Tree)
+ * https://leetcode.com/problems/implement-trie-ii-prefix-tree/
+ * Difficulty: Medium
+ *
+ * A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store
+ * and retrieve keys in a dataset of strings. There are various applications of this data structure,
+ * such as autocomplete and spellchecker.
+ *
+ * Implement the Trie class:
+ * - Trie() Initializes the trie object.
+ * - void insert(String word) Inserts the string word into the trie.
+ * - int countWordsEqualTo(String word) Returns the number of instances of the string word in the
+ * trie.
+ * - int countWordsStartingWith(String prefix) Returns the number of strings in the trie that have
+ * the string prefix as a prefix.
+ * - void erase(String word) Erases the string word from the trie.
+ */
+
+var Trie = function() {
+ this.root = { children: {}, wordCount: 0, prefixCount: 0 };
+};
+
+/**
+ * @param {string} word
+ * @return {void}
+ */
+Trie.prototype.insert = function(word) {
+ let currentNode = this.root;
+ for (const char of word) {
+ if (!currentNode.children[char]) {
+ currentNode.children[char] = { children: {}, wordCount: 0, prefixCount: 0 };
+ }
+ currentNode = currentNode.children[char];
+ currentNode.prefixCount++;
+ }
+ currentNode.wordCount++;
+};
+
+/**
+ * @param {string} word
+ * @return {number}
+ */
+Trie.prototype.countWordsEqualTo = function(word) {
+ let currentNode = this.root;
+ for (const char of word) {
+ if (!currentNode.children[char]) {
+ return 0;
+ }
+ currentNode = currentNode.children[char];
+ }
+ return currentNode.wordCount;
+};
+
+/**
+ * @param {string} prefix
+ * @return {number}
+ */
+Trie.prototype.countWordsStartingWith = function(prefix) {
+ let currentNode = this.root;
+ for (const char of prefix) {
+ if (!currentNode.children[char]) {
+ return 0;
+ }
+ currentNode = currentNode.children[char];
+ }
+ return currentNode.prefixCount;
+};
+
+/**
+ * @param {string} word
+ * @return {void}
+ */
+Trie.prototype.erase = function(word) {
+ let currentNode = this.root;
+ for (const char of word) {
+ currentNode = currentNode.children[char];
+ currentNode.prefixCount--;
+ }
+ currentNode.wordCount--;
+};
From 3a93c72233a345a3ec7da988aa421950d95d4156 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 17:55:10 -0500
Subject: [PATCH 685/994] Add solution #1810
---
README.md | 1 +
...1810-minimum-path-cost-in-a-hidden-grid.js | 147 ++++++++++++++++++
2 files changed, 148 insertions(+)
create mode 100644 solutions/1810-minimum-path-cost-in-a-hidden-grid.js
diff --git a/README.md b/README.md
index bfd0d4bf..8ee1795d 100644
--- a/README.md
+++ b/README.md
@@ -1647,6 +1647,7 @@
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|
+1810|[Minimum Path Cost in a Hidden Grid](./solutions/1810-minimum-path-cost-in-a-hidden-grid.js)|Medium|
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|
diff --git a/solutions/1810-minimum-path-cost-in-a-hidden-grid.js b/solutions/1810-minimum-path-cost-in-a-hidden-grid.js
new file mode 100644
index 00000000..979de666
--- /dev/null
+++ b/solutions/1810-minimum-path-cost-in-a-hidden-grid.js
@@ -0,0 +1,147 @@
+/**
+ * 1810. Minimum Path Cost in a Hidden Grid
+ * https://leetcode.com/problems/minimum-path-cost-in-a-hidden-grid/
+ * Difficulty: Medium
+ *
+ * This is an interactive problem.
+ *
+ * There is a robot in a hidden grid, and you are trying to get it from its starting cell to the
+ * target cell in this grid. The grid is of size m x n, and each cell in the grid is either empty
+ * or blocked. It is guaranteed that the starting cell and the target cell are different, and
+ * neither of them is blocked.
+ *
+ * Each cell has a cost that you need to pay each time you move to the cell. The starting cell's
+ * cost is not applied before the robot moves.
+ *
+ * You want to find the minimum total cost to move the robot to the target cell. However, you do
+ * not know the grid's dimensions, the starting cell, nor the target cell. You are only allowed
+ * to ask queries to the GridMaster object.
+ *
+ * The GridMaster class has the following functions:
+ * - boolean canMove(char direction) Returns true if the robot can move in that direction.
+ * Otherwise, it returns false.
+ * - int move(char direction) Moves the robot in that direction and returns the cost of moving
+ * to that cell. If this move would move the robot to a blocked cell or off the grid, the move
+ * will be ignored, the robot will remain in the same position, and the function will return -1.
+ * - boolean isTarget() Returns true if the robot is currently on the target cell. Otherwise, it
+ * returns false.
+ *
+ * Note that direction in the above functions should be a character from {'U','D','L','R'},
+ * representing the directions up, down, left, and right, respectively.
+ *
+ * Return the minimum total cost to get the robot from its initial starting cell to the target
+ * cell. If there is no valid path between the cells, return -1.
+ *
+ * Custom testing:
+ *
+ * The test input is read as a 2D matrix grid of size m x n and four integers r1, c1, r2, and
+ * c2 where:
+ * - grid[i][j] == 0 indicates that the cell (i, j) is blocked.
+ * - grid[i][j] >= 1 indicates that the cell (i, j) is empty and grid[i][j] is the cost to move
+ * to that cell.
+ * - (r1, c1) is the starting cell of the robot.
+ * - (r2, c2) is the target cell of the robot.
+ *
+ * Remember that you will not have this information in your code.
+ */
+
+/**
+ * // This is the GridMaster's API interface.
+ * // You should not implement it, or speculate about its implementation
+ * function GridMaster() {
+ *
+ * @param {character} direction
+ * @return {boolean}
+ * this.canMove = function(direction) {
+ * ...
+ * };
+ * @param {character} direction
+ * @return {integer}
+ * this.move = function(direction) {
+ * ...
+ * };
+ * @return {boolean}
+ * this.isTarget = function() {
+ * ...
+ * };
+ * };
+ */
+
+/**
+ * @param {GridMaster} master
+ * @return {integer}
+ */
+var findShortestPath = function(master) {
+ const directions = ['U', 'D', 'L', 'R'];
+ const opposites = { 'U': 'D', 'D': 'U', 'L': 'R', 'R': 'L' };
+ const deltas = { 'U': [-1, 0], 'D': [1, 0], 'L': [0, -1], 'R': [0, 1] };
+ const visited = new Set();
+ const cellCosts = new Map();
+ let targetPosition = null;
+
+ cellCosts.set('0,0', 0);
+ dfs(0, 0);
+
+ if (!targetPosition) return -1;
+
+ const dijkstraVisited = new Set();
+ const priorityQueue = new PriorityQueue((a, b) => a[2] - b[2]);
+ priorityQueue.enqueue([0, 0, 0]);
+
+ while (!priorityQueue.isEmpty()) {
+ const [currentRow, currentCol, currentCost] = priorityQueue.dequeue();
+ const currentKey = `${currentRow},${currentCol}`;
+
+ if (dijkstraVisited.has(currentKey)) continue;
+ dijkstraVisited.add(currentKey);
+
+ if (currentRow === targetPosition[0] && currentCol === targetPosition[1]) {
+ return currentCost;
+ }
+
+ for (const direction of directions) {
+ const [deltaRow, deltaCol] = deltas[direction];
+ const nextRow = currentRow + deltaRow;
+ const nextCol = currentCol + deltaCol;
+ const nextKey = `${nextRow},${nextCol}`;
+
+ if (cellCosts.has(nextKey) && !dijkstraVisited.has(nextKey)) {
+ const nextCost = currentCost + cellCosts.get(nextKey);
+ priorityQueue.enqueue([nextRow, nextCol, nextCost]);
+ }
+ }
+ }
+
+ return -1;
+
+ function dfs(row, col) {
+ const key = `${row},${col}`;
+ if (visited.has(key)) return;
+
+ visited.add(key);
+
+ if (master.isTarget()) {
+ targetPosition = [row, col];
+ }
+
+ for (const direction of directions) {
+ if (master.canMove(direction)) {
+ const cost = master.move(direction);
+ if (cost !== -1) {
+ const [deltaRow, deltaCol] = deltas[direction];
+ const newRow = row + deltaRow;
+ const newCol = col + deltaCol;
+ const newKey = `${newRow},${newCol}`;
+
+ if (!cellCosts.has(newKey)) {
+ cellCosts.set(newKey, cost);
+ }
+
+ dfs(newRow, newCol);
+
+ master.move(opposites[direction]);
+ }
+ }
+ }
+ }
+};
From 69d22f70a0786ed74d9c511d4a2c7d7037427c62 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 18:02:33 -0500
Subject: [PATCH 686/994] Add solution #1820
---
README.md | 1 +
...-maximum-number-of-accepted-invitations.js | 48 +++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/1820-maximum-number-of-accepted-invitations.js
diff --git a/README.md b/README.md
index 8ee1795d..42653c0e 100644
--- a/README.md
+++ b/README.md
@@ -1656,6 +1656,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|
+1820|[Maximum Number of Accepted Invitations](./solutions/1820-maximum-number-of-accepted-invitations.js)|Medium|
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|
diff --git a/solutions/1820-maximum-number-of-accepted-invitations.js b/solutions/1820-maximum-number-of-accepted-invitations.js
new file mode 100644
index 00000000..5c6f1c11
--- /dev/null
+++ b/solutions/1820-maximum-number-of-accepted-invitations.js
@@ -0,0 +1,48 @@
+/**
+ * 1820. Maximum Number of Accepted Invitations
+ * https://leetcode.com/problems/maximum-number-of-accepted-invitations/
+ * Difficulty: Medium
+ *
+ * There are m boys and n girls in a class attending an upcoming party.
+ *
+ * You are given an m x n integer matrix grid, where grid[i][j] equals 0 or 1. If grid[i][j] == 1,
+ * then that means the ith boy can invite the jth girl to the party. A boy can invite at most one
+ * girl, and a girl can accept at most one invitation from a boy.
+ *
+ * Return the maximum possible number of accepted invitations.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var maximumInvitations = function(grid) {
+ const boyCount = grid.length;
+ const girlCount = grid[0].length;
+ const girlMatched = new Array(girlCount).fill(-1);
+
+ let result = 0;
+
+ for (let boy = 0; boy < boyCount; boy++) {
+ const visited = new Array(girlCount).fill(false);
+ if (findMatch(boy, visited)) {
+ result++;
+ }
+ }
+
+ return result;
+
+ function findMatch(boy, visited) {
+ for (let girl = 0; girl < girlCount; girl++) {
+ if (grid[boy][girl] && !visited[girl]) {
+ visited[girl] = true;
+
+ if (girlMatched[girl] === -1 || findMatch(girlMatched[girl], visited)) {
+ girlMatched[girl] = boy;
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+};
From bb758259516b19c0bac4286204bf1ae90ddf77c9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 18:07:11 -0500
Subject: [PATCH 687/994] Add solution #1826
---
README.md | 1 +
solutions/1826-faulty-sensor.js | 69 +++++++++++++++++++++++++++++++++
2 files changed, 70 insertions(+)
create mode 100644 solutions/1826-faulty-sensor.js
diff --git a/README.md b/README.md
index 42653c0e..b4e88b67 100644
--- a/README.md
+++ b/README.md
@@ -1661,6 +1661,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|
+1826|[Faulty Sensor](./solutions/1826-faulty-sensor.js)|Easy|
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|
diff --git a/solutions/1826-faulty-sensor.js b/solutions/1826-faulty-sensor.js
new file mode 100644
index 00000000..6271adf4
--- /dev/null
+++ b/solutions/1826-faulty-sensor.js
@@ -0,0 +1,69 @@
+/**
+ * 1826. Faulty Sensor
+ * https://leetcode.com/problems/faulty-sensor/
+ * Difficulty: Easy
+ *
+ * An experiment is being conducted in a lab. To ensure accuracy, there are two sensors
+ * collecting data simultaneously. You are given two arrays sensor1 and sensor2, where
+ * sensor1[i] and sensor2[i] are the ith data points collected by the two sensors.
+ *
+ * However, this type of sensor has a chance of being defective, which causes exactly one data
+ * point to be dropped. After the data is dropped, all the data points to the right of the
+ * dropped data are shifted one place to the left, and the last data point is replaced with
+ * some random value. It is guaranteed that this random value will not be equal to the dropped
+ * value.
+ * - For example, if the correct data is [1,2,3,4,5] and 3 is dropped, the sensor could
+ * return [1,2,4,5,7] (the last position can be any value, not just 7).
+ *
+ * We know that there is a defect in at most one of the sensors. Return the sensor number
+ * (1 or 2) with the defect. If there is no defect in either sensor or if it is impossible
+ * to determine the defective sensor, return -1.
+ */
+
+/**
+ * @param {number[]} sensor1
+ * @param {number[]} sensor2
+ * @return {number}
+ */
+var badSensor = function(sensor1, sensor2) {
+ const length = sensor1.length;
+ let firstDifference = -1;
+
+ for (let i = 0; i < length; i++) {
+ if (sensor1[i] !== sensor2[i]) {
+ firstDifference = i;
+ break;
+ }
+ }
+
+ if (firstDifference === -1) {
+ return -1;
+ }
+
+ let sensor1Defective = true;
+ let sensor2Defective = true;
+
+ for (let i = firstDifference; i < length - 1; i++) {
+ if (sensor1[i] !== sensor2[i + 1]) {
+ sensor1Defective = false;
+ break;
+ }
+ }
+
+ for (let i = firstDifference; i < length - 1; i++) {
+ if (sensor2[i] !== sensor1[i + 1]) {
+ sensor2Defective = false;
+ break;
+ }
+ }
+
+ if (sensor1Defective && !sensor2Defective) {
+ return 1;
+ }
+
+ if (sensor2Defective && !sensor1Defective) {
+ return 2;
+ }
+
+ return -1;
+};
From e7a5bd1ebc84046e3173198f455bf77cab62a134 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 18:15:14 -0500
Subject: [PATCH 688/994] Add solution #1836
---
README.md | 1 +
...duplicates-from-an-unsorted-linked-list.js | 47 +++++++++++++++++++
2 files changed, 48 insertions(+)
create mode 100644 solutions/1836-remove-duplicates-from-an-unsorted-linked-list.js
diff --git a/README.md b/README.md
index b4e88b67..3af0da3c 100644
--- a/README.md
+++ b/README.md
@@ -1670,6 +1670,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|
+1836|[Remove Duplicates From an Unsorted Linked List](./solutions/1836-remove-duplicates-from-an-unsorted-linked-list.js)|Medium|
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|
diff --git a/solutions/1836-remove-duplicates-from-an-unsorted-linked-list.js b/solutions/1836-remove-duplicates-from-an-unsorted-linked-list.js
new file mode 100644
index 00000000..58e17b49
--- /dev/null
+++ b/solutions/1836-remove-duplicates-from-an-unsorted-linked-list.js
@@ -0,0 +1,47 @@
+/**
+ * 1836. Remove Duplicates From an Unsorted Linked List
+ * https://leetcode.com/problems/remove-duplicates-from-an-unsorted-linked-list/
+ * Difficulty: Medium
+ *
+ * Given the head of a linked list, find all the values that appear more than once in the list
+ * and delete the nodes that have any of those values.
+ *
+ * Return the linked list after the deletions.
+ */
+
+/**
+ * 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 deleteDuplicatesUnsorted = function(head) {
+ const map = new Map();
+ let current = head;
+
+ while (current) {
+ map.set(current.val, (map.get(current.val) || 0) + 1);
+ current = current.next;
+ }
+
+ const dummy = new ListNode(0);
+ dummy.next = head;
+ let previous = dummy;
+ current = head;
+
+ while (current) {
+ if (map.get(current.val) > 1) {
+ previous.next = current.next;
+ } else {
+ previous = current;
+ }
+ current = current.next;
+ }
+
+ return dummy.next;
+};
From 96e73cc37fea96acdd78e4b70328957aaae21c7e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 18:16:50 -0500
Subject: [PATCH 689/994] Add solution #1842
---
README.md | 1 +
.../1842-next-palindrome-using-same-digits.js | 60 +++++++++++++++++++
2 files changed, 61 insertions(+)
create mode 100644 solutions/1842-next-palindrome-using-same-digits.js
diff --git a/README.md b/README.md
index 3af0da3c..91645160 100644
--- a/README.md
+++ b/README.md
@@ -1675,6 +1675,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|
+1842|[Next Palindrome Using Same Digits](./solutions/1842-next-palindrome-using-same-digits.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|
diff --git a/solutions/1842-next-palindrome-using-same-digits.js b/solutions/1842-next-palindrome-using-same-digits.js
new file mode 100644
index 00000000..906c3d29
--- /dev/null
+++ b/solutions/1842-next-palindrome-using-same-digits.js
@@ -0,0 +1,60 @@
+/**
+ * 1842. Next Palindrome Using Same Digits
+ * https://leetcode.com/problems/next-palindrome-using-same-digits/
+ * Difficulty: Hard
+ *
+ * You are given a numeric string num, representing a very large palindrome.
+ *
+ * Return the smallest palindrome larger than num that can be created by rearranging its
+ * digits. If no such palindrome exists, return an empty string "".
+ *
+ * A palindrome is a number that reads the same backward as forward.
+ */
+
+/**
+ * @param {string} num
+ * @return {string}
+ */
+var nextPalindrome = function(num) {
+ const length = num.length;
+ const halfLength = Math.floor(length / 2);
+ const leftHalf = num.slice(0, halfLength).split('');
+
+ if (!nextPermutation(leftHalf)) {
+ return '';
+ }
+
+ const rightHalf = leftHalf.slice().reverse();
+ const result = leftHalf.join('') + (length % 2 === 1 ? num[halfLength] : '') + rightHalf.join('');
+
+ return result;
+
+ function nextPermutation(digits) {
+ let pivot = -1;
+
+ for (let i = digits.length - 2; i >= 0; i--) {
+ if (digits[i] < digits[i + 1]) {
+ pivot = i;
+ break;
+ }
+ }
+
+ if (pivot === -1) return false;
+
+ for (let i = digits.length - 1; i > pivot; i--) {
+ if (digits[i] > digits[pivot]) {
+ [digits[pivot], digits[i]] = [digits[i], digits[pivot]];
+ break;
+ }
+ }
+
+ const leftPart = digits.slice(0, pivot + 1);
+ const rightPart = digits.slice(pivot + 1).reverse();
+
+ for (let i = 0; i < digits.length; i++) {
+ digits[i] = i < leftPart.length ? leftPart[i] : rightPart[i - leftPart.length];
+ }
+
+ return true;
+ }
+};
From 74fe76c720557d581e834fafa517939717af4d44 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 18:17:55 -0500
Subject: [PATCH 690/994] Add solution #1852
---
README.md | 1 +
.../1852-distinct-numbers-in-each-subarray.js | 43 +++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/1852-distinct-numbers-in-each-subarray.js
diff --git a/README.md b/README.md
index 91645160..65a5a146 100644
--- a/README.md
+++ b/README.md
@@ -1684,6 +1684,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|
+1852|[Distinct Numbers in Each Subarray](./solutions/1852-distinct-numbers-in-each-subarray.js)|Medium|
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|
diff --git a/solutions/1852-distinct-numbers-in-each-subarray.js b/solutions/1852-distinct-numbers-in-each-subarray.js
new file mode 100644
index 00000000..25cf47f2
--- /dev/null
+++ b/solutions/1852-distinct-numbers-in-each-subarray.js
@@ -0,0 +1,43 @@
+/**
+ * 1852. Distinct Numbers in Each Subarray
+ * https://leetcode.com/problems/distinct-numbers-in-each-subarray/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums of length n and an integer k. Your task is to find
+ * the number of distinct elements in every subarray of size k within nums.
+ *
+ * Return an array ans such that ans[i] is the count of distinct elements in
+ * nums[i..(i + k - 1)] for each index 0 <= i < n - k.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number[]}
+ */
+var distinctNumbers = function(nums, k) {
+ const result = [];
+ const map = new Map();
+
+ for (let i = 0; i < k; i++) {
+ map.set(nums[i], (map.get(nums[i]) || 0) + 1);
+ }
+
+ result.push(map.size);
+
+ for (let i = k; i < nums.length; i++) {
+ const leftElement = nums[i - k];
+ const rightElement = nums[i];
+
+ map.set(leftElement, map.get(leftElement) - 1);
+ if (map.get(leftElement) === 0) {
+ map.delete(leftElement);
+ }
+
+ map.set(rightElement, (map.get(rightElement) || 0) + 1);
+
+ result.push(map.size);
+ }
+
+ return result;
+};
From e4539c1294b61c0b1bef54fb50ac6dadfd978071 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 23:21:08 -0500
Subject: [PATCH 691/994] Add solution #1858
---
README.md | 1 +
.../1858-longest-word-with-all-prefixes.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/1858-longest-word-with-all-prefixes.js
diff --git a/README.md b/README.md
index 65a5a146..99844502 100644
--- a/README.md
+++ b/README.md
@@ -1689,6 +1689,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|
+1858|[Longest Word With All Prefixes](./solutions/1858-longest-word-with-all-prefixes.js)|Medium|
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|
diff --git a/solutions/1858-longest-word-with-all-prefixes.js b/solutions/1858-longest-word-with-all-prefixes.js
new file mode 100644
index 00000000..18f1c4f7
--- /dev/null
+++ b/solutions/1858-longest-word-with-all-prefixes.js
@@ -0,0 +1,41 @@
+/**
+ * 1858. Longest Word With All Prefixes
+ * https://leetcode.com/problems/longest-word-with-all-prefixes/
+ * Difficulty: Medium
+ *
+ * Given an array of strings words, find the longest string in words such that every
+ * prefix of it is also in words.
+ * - For example, let words = ["a", "app", "ap"]. The string "app" has prefixes "ap" and "a",
+ * all of which are in words.
+ *
+ * Return the string described above. If there is more than one string with the same length,
+ * return the lexicographically smallest one, and if no string exists, return "".
+ */
+
+/**
+ * @param {string[]} words
+ * @return {string}
+ */
+var longestWord = function(words) {
+ const set = new Set(words);
+ let result = '';
+
+ for (const word of words) {
+ let hasAllPrefixes = true;
+
+ for (let i = 1; i < word.length; i++) {
+ if (!set.has(word.slice(0, i))) {
+ hasAllPrefixes = false;
+ break;
+ }
+ }
+
+ if (hasAllPrefixes) {
+ if (word.length > result.length || (word.length === result.length && word < result)) {
+ result = word;
+ }
+ }
+ }
+
+ return result;
+};
From 7ec6057cf280d6f240ba2dcafb4ca292c040ba54 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 23:23:35 -0500
Subject: [PATCH 692/994] Add solution #1868
---
README.md | 1 +
...roduct-of-two-run-length-encoded-arrays.js | 66 +++++++++++++++++++
2 files changed, 67 insertions(+)
create mode 100644 solutions/1868-product-of-two-run-length-encoded-arrays.js
diff --git a/README.md b/README.md
index 99844502..acc67419 100644
--- a/README.md
+++ b/README.md
@@ -1698,6 +1698,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|
+1868|[Product of Two Run-Length Encoded Arrays](./solutions/1868-product-of-two-run-length-encoded-arrays.js)|Medium|
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|
diff --git a/solutions/1868-product-of-two-run-length-encoded-arrays.js b/solutions/1868-product-of-two-run-length-encoded-arrays.js
new file mode 100644
index 00000000..4a8d9ff6
--- /dev/null
+++ b/solutions/1868-product-of-two-run-length-encoded-arrays.js
@@ -0,0 +1,66 @@
+/**
+ * 1868. Product of Two Run-Length Encoded Arrays
+ * https://leetcode.com/problems/product-of-two-run-length-encoded-arrays/
+ * Difficulty: Medium
+ *
+ * Run-length encoding is a compression algorithm that allows for an integer array nums with
+ * many segments of consecutive repeated numbers to be represented by a (generally smaller)
+ * 2D array encoded. Each encoded[i] = [vali, freqi] describes the ith segment of repeated
+ * numbers in nums where vali is the value that is repeated freqi times.
+ * - For example, nums = [1,1,1,2,2,2,2,2] is represented by the run-length encoded array
+ * encoded = [[1,3],[2,5]]. Another way to read this is "three 1's followed by five 2's".
+ *
+ * The product of two run-length encoded arrays encoded1 and encoded2 can be calculated using
+ * the following steps:
+ * 1. Expand both encoded1 and encoded2 into the full arrays nums1 and nums2 respectively.
+ * 2. Create a new array prodNums of length nums1.length and set prodNums[i] = nums1[i] * nums2[i].
+ * 3. Compress prodNums into a run-length encoded array and return it.
+ *
+ * You are given two run-length encoded arrays encoded1 and encoded2 representing full arrays
+ * nums1 and nums2 respectively. Both nums1 and nums2 have the same length. Each
+ * encoded1[i] = [vali, freqi] describes the ith segment of nums1, and each
+ * encoded2[j] = [valj, freqj] describes the jth segment of nums2.
+ *
+ * Return the product of encoded1 and encoded2.
+ *
+ * Note: Compression should be done such that the run-length encoded array has the minimum
+ * possible length.
+ */
+
+/**
+ * @param {number[][]} encoded1
+ * @param {number[][]} encoded2
+ * @return {number[][]}
+ */
+var findRLEArray = function(encoded1, encoded2) {
+ const result = [];
+ let i = 0;
+ let j = 0;
+ let freq1 = 0;
+ let freq2 = 0;
+
+ while (i < encoded1.length && j < encoded2.length) {
+ if (freq1 === 0) {
+ freq1 = encoded1[i][1];
+ }
+ if (freq2 === 0) {
+ freq2 = encoded2[j][1];
+ }
+
+ const product = encoded1[i][0] * encoded2[j][0];
+ const minFreq = Math.min(freq1, freq2);
+ if (result.length > 0 && result[result.length - 1][0] === product) {
+ result[result.length - 1][1] += minFreq;
+ } else {
+ result.push([product, minFreq]);
+ }
+
+ freq1 -= minFreq;
+ freq2 -= minFreq;
+
+ if (freq1 === 0) i++;
+ if (freq2 === 0) j++;
+ }
+
+ return result;
+};
From dd2ade74346b15bf993603aac31978f046578ada Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 23:24:33 -0500
Subject: [PATCH 693/994] Add solution #1874
---
README.md | 1 +
...1874-minimize-product-sum-of-two-arrays.js | 25 +++++++++++++++++++
2 files changed, 26 insertions(+)
create mode 100644 solutions/1874-minimize-product-sum-of-two-arrays.js
diff --git a/README.md b/README.md
index acc67419..41c80412 100644
--- a/README.md
+++ b/README.md
@@ -1703,6 +1703,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|
+1874|[Minimize Product Sum of Two Arrays](./solutions/1874-minimize-product-sum-of-two-arrays.js)|Medium|
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|
diff --git a/solutions/1874-minimize-product-sum-of-two-arrays.js b/solutions/1874-minimize-product-sum-of-two-arrays.js
new file mode 100644
index 00000000..b02400ea
--- /dev/null
+++ b/solutions/1874-minimize-product-sum-of-two-arrays.js
@@ -0,0 +1,25 @@
+/**
+ * 1874. Minimize Product Sum of Two Arrays
+ * https://leetcode.com/problems/minimize-product-sum-of-two-arrays/
+ * Difficulty: Medium
+ *
+ * The product sum of two equal-length arrays a and b is equal to the sum of a[i] * b[i]
+ * for all 0 <= i < a.length (0-indexed).
+ * - For example, if a = [1,2,3,4] and b = [5,2,3,1], the product sum would be
+ * 1*5 + 2*2 + 3*3 + 4*1 = 22.
+ *
+ * Given two arrays nums1 and nums2 of length n, return the minimum product sum if you are
+ * allowed to rearrange the order of the elements in nums1.
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @return {number}
+ */
+var minProductSum = function(nums1, nums2) {
+ nums1.sort((a, b) => a - b);
+ nums2.sort((a, b) => b - a);
+
+ return nums1.reduce((sum, val, i) => sum + val * nums2[i], 0);
+};
From 2eb9ae2d2a95cf9e44079987db292c56f65e0910 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 23:25:26 -0500
Subject: [PATCH 694/994] Add solution #1885
---
README.md | 1 +
solutions/1885-count-pairs-in-two-arrays.js | 35 +++++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/1885-count-pairs-in-two-arrays.js
diff --git a/README.md b/README.md
index 41c80412..b08004cf 100644
--- a/README.md
+++ b/README.md
@@ -1713,6 +1713,7 @@
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|
+1885|[Count Pairs in Two Arrays](./solutions/1885-count-pairs-in-two-arrays.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|
diff --git a/solutions/1885-count-pairs-in-two-arrays.js b/solutions/1885-count-pairs-in-two-arrays.js
new file mode 100644
index 00000000..f6445029
--- /dev/null
+++ b/solutions/1885-count-pairs-in-two-arrays.js
@@ -0,0 +1,35 @@
+/**
+ * 1885. Count Pairs in Two Arrays
+ * https://leetcode.com/problems/count-pairs-in-two-arrays/
+ * Difficulty: Medium
+ *
+ * Given two integer arrays nums1 and nums2 of length n, count the pairs of indices (i, j)
+ * such that i < j and nums1[i] + nums1[j] > nums2[i] + nums2[j].
+ *
+ * Return the number of pairs satisfying the condition.
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @return {number}
+ */
+var countPairs = function(nums1, nums2) {
+ const differences = nums1.map((val, i) => val - nums2[i]);
+ differences.sort((a, b) => a - b);
+
+ let count = 0;
+ let left = 0;
+ let right = differences.length - 1;
+
+ while (left < right) {
+ if (differences[left] + differences[right] > 0) {
+ count += right - left;
+ right--;
+ } else {
+ left++;
+ }
+ }
+
+ return count;
+};
From 33e3672fdcab124d3e0fb6edb00464ad153df9ae Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 23:27:20 -0500
Subject: [PATCH 695/994] Add solution #1891
---
README.md | 1 +
solutions/1891-cutting-ribbons.js | 53 +++++++++++++++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/1891-cutting-ribbons.js
diff --git a/README.md b/README.md
index b08004cf..4ea17a4b 100644
--- a/README.md
+++ b/README.md
@@ -1718,6 +1718,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|
+1891|[Cutting Ribbons](./solutions/1891-cutting-ribbons.js)|Medium|
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|
diff --git a/solutions/1891-cutting-ribbons.js b/solutions/1891-cutting-ribbons.js
new file mode 100644
index 00000000..08abe052
--- /dev/null
+++ b/solutions/1891-cutting-ribbons.js
@@ -0,0 +1,53 @@
+/**
+ * 1891. Cutting Ribbons
+ * https://leetcode.com/problems/cutting-ribbons/
+ * Difficulty: Medium
+ *
+ * You are given an integer array ribbons, where ribbons[i] represents the length of the ith
+ * ribbon, and an integer k. You may cut any of the ribbons into any number of segments of
+ * positive integer lengths, or perform no cuts at all.
+ *
+ * - For example, if you have a ribbon of length 4, you can:
+ * - Keep the ribbon of length 4,
+ * - Cut it into one ribbon of length 3 and one ribbon of length 1,
+ * - Cut it into two ribbons of length 2,
+ * - Cut it into one ribbon of length 2 and two ribbons of length 1, or
+ * - Cut it into four ribbons of length 1.
+ *
+ * Your task is to determine the maximum length of ribbon, x, that allows you to cut at least
+ * k ribbons, each of length x. You can discard any leftover ribbon from the cuts. If it is
+ * impossible to cut k ribbons of the same length, return 0.
+ */
+
+/**
+ * @param {number[]} ribbons
+ * @param {number} k
+ * @return {number}
+ */
+var maxLength = function(ribbons, k) {
+ let left = 1;
+ let right = Math.max(...ribbons);
+ let result = 0;
+
+ while (left <= right) {
+ const mid = Math.floor((left + right) / 2);
+
+ if (helper(mid)) {
+ result = mid;
+ left = mid + 1;
+ } else {
+ right = mid - 1;
+ }
+ }
+
+ return result;
+
+ function helper(length) {
+ let count = 0;
+ for (const ribbon of ribbons) {
+ count += Math.floor(ribbon / length);
+ if (count >= k) return true;
+ }
+ return false;
+ }
+};
From e76109f0ea5cdef7eb369da3fc0a04cc25415643 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 23:54:43 -0500
Subject: [PATCH 696/994] Add solution #1902
---
README.md | 1 +
...1902-depth-of-bst-given-insertion-order.js | 63 +++++++++++++++++++
2 files changed, 64 insertions(+)
create mode 100644 solutions/1902-depth-of-bst-given-insertion-order.js
diff --git a/README.md b/README.md
index 4ea17a4b..35826cbf 100644
--- a/README.md
+++ b/README.md
@@ -1728,6 +1728,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|
+1902|[Depth of BST Given Insertion Order](./solutions/1902-depth-of-bst-given-insertion-order.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|
diff --git a/solutions/1902-depth-of-bst-given-insertion-order.js b/solutions/1902-depth-of-bst-given-insertion-order.js
new file mode 100644
index 00000000..9f568400
--- /dev/null
+++ b/solutions/1902-depth-of-bst-given-insertion-order.js
@@ -0,0 +1,63 @@
+/**
+ * 1902. Depth of BST Given Insertion Order
+ * https://leetcode.com/problems/depth-of-bst-given-insertion-order/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array order of length n, a permutation of integers
+ * from 1 to n representing the order of insertion into a binary search tree.
+ *
+ * A binary search tree is defined as follows:
+ * - The left subtree of a node contains only nodes with keys less than the node's key.
+ * - The right subtree of a node contains only nodes with keys greater than the node's key.
+ * - Both the left and right subtrees must also be binary search trees.
+ *
+ * The binary search tree is constructed as follows:
+ * - order[0] will be the root of the binary search tree.
+ * - All subsequent elements are inserted as the child of any existing node such that the
+ * binary search tree properties hold.
+ *
+ * Return the depth of the binary search tree.
+ *
+ * A binary tree's depth is the number of nodes along the longest path from the root node
+ * down to the farthest leaf node.
+ */
+
+/**
+ * @param {number[]} order
+ * @return {number}
+ */
+var maxDepthBST = function(order) {
+ const n = order.length;
+ const parents = new Array(n + 1).fill(0);
+ const insertOrders = new Array(n + 1).fill(0);
+
+ for (let i = 0; i < n; i++) {
+ insertOrders[order[i]] = i + 1;
+ }
+
+ const stack = [];
+
+ for (let node = 0; node <= n; node++) {
+ const insertOrder = insertOrders[node];
+
+ while (stack.length > 0 && insertOrders[stack[stack.length - 1]] > insertOrder) {
+ const prevNode = stack.pop();
+ if (insertOrders[parents[prevNode]] < insertOrder) {
+ parents[prevNode] = node;
+ }
+ }
+
+ if (stack.length > 0) {
+ parents[node] = stack[stack.length - 1];
+ }
+
+ stack.push(node);
+ }
+
+ const depths = new Array(n + 1).fill(0);
+ for (const num of order) {
+ depths[num] = depths[parents[num]] + 1;
+ }
+
+ return Math.max(...depths);
+};
From 93a293fb5fed7e57b55a63546618c22795406a6b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 5 Jul 2025 23:56:29 -0500
Subject: [PATCH 697/994] Add solution #1908
---
README.md | 1 +
solutions/1908-game-of-nim.js | 50 +++++++++++++++++++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/1908-game-of-nim.js
diff --git a/README.md b/README.md
index 35826cbf..e0a84286 100644
--- a/README.md
+++ b/README.md
@@ -1733,6 +1733,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|
+1908|[Game of Nim](./solutions/1908-game-of-nim.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|
diff --git a/solutions/1908-game-of-nim.js b/solutions/1908-game-of-nim.js
new file mode 100644
index 00000000..831932d9
--- /dev/null
+++ b/solutions/1908-game-of-nim.js
@@ -0,0 +1,50 @@
+/**
+ * 1908. Game of Nim
+ * https://leetcode.com/problems/game-of-nim/
+ * Difficulty: Medium
+ *
+ * Alice and Bob take turns playing a game with Alice starting first.
+ *
+ * In this game, there are n piles of stones. On each player's turn, the player should remove
+ * any positive number of stones from a non-empty pile of his or her choice. The first player
+ * who cannot make a move loses, and the other player wins.
+ *
+ * Given an integer array piles, where piles[i] is the number of stones in the ith pile, return
+ * true if Alice wins, or false if Bob wins.
+ *
+ * Both Alice and Bob play optimally.
+ */
+
+/**
+ * @param {number[]} piles
+ * @return {boolean}
+ */
+var nimGame = function(piles) {
+ const map = new Map();
+ return helper(piles);
+
+ function helper(currentPiles) {
+ const key = currentPiles.join(',');
+ if (map.has(key)) return map.get(key);
+
+ if (currentPiles.every(pile => pile === 0)) {
+ map.set(key, false);
+ return false;
+ }
+
+ for (let i = 0; i < currentPiles.length; i++) {
+ for (let take = 1; take <= currentPiles[i]; take++) {
+ const nextPiles = [...currentPiles];
+ nextPiles[i] -= take;
+
+ if (!helper(nextPiles)) {
+ map.set(key, true);
+ return true;
+ }
+ }
+ }
+
+ map.set(key, false);
+ return false;
+ }
+};
From 0691a45fb30a463728e337c0d167a6b15ec01dee Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:00:27 -0500
Subject: [PATCH 698/994] Add solution #1918
---
README.md | 1 +
solutions/1918-kth-smallest-subarray-sum.js | 51 +++++++++++++++++++++
2 files changed, 52 insertions(+)
create mode 100644 solutions/1918-kth-smallest-subarray-sum.js
diff --git a/README.md b/README.md
index e0a84286..b80f0838 100644
--- a/README.md
+++ b/README.md
@@ -1742,6 +1742,7 @@
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|
+1918|[Kth Smallest Subarray Sum](./solutions/1918-kth-smallest-subarray-sum.js)|Medium|
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|
diff --git a/solutions/1918-kth-smallest-subarray-sum.js b/solutions/1918-kth-smallest-subarray-sum.js
new file mode 100644
index 00000000..7d241827
--- /dev/null
+++ b/solutions/1918-kth-smallest-subarray-sum.js
@@ -0,0 +1,51 @@
+/**
+ * 1918. Kth Smallest Subarray Sum
+ * https://leetcode.com/problems/kth-smallest-subarray-sum/
+ * Difficulty: Medium
+ *
+ * Given an integer array nums of length n and an integer k, return the kth smallest subarray sum.
+ *
+ * A subarray is defined as a non-empty contiguous sequence of elements in an array. A subarray
+ * sum is the sum of all elements in the subarray.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var kthSmallestSubarraySum = function(nums, k) {
+ let result = Math.min(...nums);
+ let maxSum = nums.reduce((sum, num) => sum + num, 0);
+
+ while (result < maxSum) {
+ const midSum = Math.floor((result + maxSum) / 2);
+
+ if (countSubarraysWithSumLessOrEqual(midSum) < k) {
+ result = midSum + 1;
+ } else {
+ maxSum = midSum;
+ }
+ }
+
+ return result;
+
+ function countSubarraysWithSumLessOrEqual(target) {
+ let count = 0;
+ let left = 0;
+ let currentSum = 0;
+
+ for (let right = 0; right < nums.length; right++) {
+ currentSum += nums[right];
+
+ while (currentSum > target) {
+ currentSum -= nums[left];
+ left++;
+ }
+
+ count += right - left + 1;
+ }
+
+ return count;
+ }
+};
From 3cee0517e248041fa1d2e497c4944d45e5f58dd5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:01:25 -0500
Subject: [PATCH 699/994] Add solution #1924
---
README.md | 1 +
solutions/1924-erect-the-fence-ii.js | 91 ++++++++++++++++++++++++++++
2 files changed, 92 insertions(+)
create mode 100644 solutions/1924-erect-the-fence-ii.js
diff --git a/README.md b/README.md
index b80f0838..090c64de 100644
--- a/README.md
+++ b/README.md
@@ -1747,6 +1747,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|
+1924|[Erect the Fence II](./solutions/1924-erect-the-fence-ii.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|
diff --git a/solutions/1924-erect-the-fence-ii.js b/solutions/1924-erect-the-fence-ii.js
new file mode 100644
index 00000000..ba04f009
--- /dev/null
+++ b/solutions/1924-erect-the-fence-ii.js
@@ -0,0 +1,91 @@
+/**
+ * 1924. Erect the Fence II
+ * https://leetcode.com/problems/erect-the-fence-ii/
+ * Difficulty: Hard
+ *
+ * You are given a 2D integer array trees where trees[i] = [xi, yi] represents the location
+ * of the ith tree in the garden.
+ *
+ * You are asked to fence the entire garden using the minimum length of rope possible. The garden
+ * is well-fenced only if all the trees are enclosed and the rope used forms a perfect circle.
+ * A tree is considered enclosed if it is inside or on the border of the circle.
+ *
+ * More formally, you must form a circle using the rope with a center (x, y) and radius r where
+ * all trees lie inside or on the circle and r is minimum.
+ *
+ * Return the center and radius of the circle as a length 3 array [x, y, r]. Answers within 10-5
+ * of the actual answer will be accepted.
+ */
+
+/**
+ * @param {number[][]} trees
+ * @return {number[]}
+ */
+var outerTrees = function(trees) {
+ const n = trees.length;
+
+ if (n === 1) {
+ return [trees[0][0], trees[0][1], 0];
+ }
+
+ const shuffled = [...trees];
+ for (let i = shuffled.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1));
+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
+ }
+
+ return getMinimumEnclosingCircle(shuffled, []);
+
+ function distance(p1, p2) {
+ return Math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2);
+ }
+
+ function getCircleFromTwoPoints(p1, p2) {
+ const x = (p1[0] + p2[0]) / 2;
+ const y = (p1[1] + p2[1]) / 2;
+ const r = distance(p1, p2) / 2;
+ return [x, y, r];
+ }
+
+ function getCircleFromThreePoints(p1, p2, p3) {
+ const [x1, y1] = p1;
+ const [x2, y2] = p2;
+ const [x3, y3] = p3;
+
+ const d = 2 * (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2));
+
+ if (Math.abs(d) < 1e-10) {
+ return null;
+ }
+
+ const ux = ((x1 ** 2 + y1 ** 2) * (y2 - y3) + (x2 ** 2 + y2 ** 2) * (y3 - y1)
+ + (x3 ** 2 + y3 ** 2) * (y1 - y2)) / d;
+ const uy = ((x1 ** 2 + y1 ** 2) * (x3 - x2) + (x2 ** 2 + y2 ** 2) * (x1 - x3)
+ + (x3 ** 2 + y3 ** 2) * (x2 - x1)) / d;
+ const r = distance([ux, uy], p1);
+
+ return [ux, uy, r];
+ }
+
+ function isInsideCircle(point, circle) {
+ const [x, y, r] = circle;
+ return distance(point, [x, y]) <= r + 1e-7;
+ }
+
+ function getMinimumEnclosingCircle(points, boundary) {
+ if (boundary.length === 3 || points.length === 0) {
+ if (boundary.length === 0) return [0, 0, 0];
+ if (boundary.length === 1) return [boundary[0][0], boundary[0][1], 0];
+ if (boundary.length === 2) return getCircleFromTwoPoints(boundary[0], boundary[1]);
+ return getCircleFromThreePoints(boundary[0], boundary[1], boundary[2]);
+ }
+
+ const point = points[0];
+ const circle = getMinimumEnclosingCircle(points.slice(1), boundary);
+ if (isInsideCircle(point, circle)) {
+ return circle;
+ }
+
+ return getMinimumEnclosingCircle(points.slice(1), boundary.concat([point]));
+ }
+};
From fceb4e49dffc82c97a26d675b3b8b42467c2e6c8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:02:15 -0500
Subject: [PATCH 700/994] Add solution #1933
---
README.md | 1 +
...ecomposable-into-value-equal-substrings.js | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/1933-check-if-string-is-decomposable-into-value-equal-substrings.js
diff --git a/README.md b/README.md
index 090c64de..a9862f51 100644
--- a/README.md
+++ b/README.md
@@ -1756,6 +1756,7 @@
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|
+1933|[Check if String Is Decomposable Into Value-Equal Substrings](./solutions/1933-check-if-string-is-decomposable-into-value-equal-substrings.js)|Easy|
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|
diff --git a/solutions/1933-check-if-string-is-decomposable-into-value-equal-substrings.js b/solutions/1933-check-if-string-is-decomposable-into-value-equal-substrings.js
new file mode 100644
index 00000000..1267aa06
--- /dev/null
+++ b/solutions/1933-check-if-string-is-decomposable-into-value-equal-substrings.js
@@ -0,0 +1,50 @@
+/**
+ * 1933. Check if String Is Decomposable Into Value-Equal Substrings
+ * https://leetcode.com/problems/check-if-string-is-decomposable-into-value-equal-substrings/
+ * Difficulty: Easy
+ *
+ * A value-equal string is a string where all characters are the same.
+ * - For example, "1111" and "33" are value-equal strings.
+ * - In contrast, "123" is not a value-equal string.
+ *
+ * Given a digit string s, decompose the string into some number of consecutive value-equal
+ * substrings where exactly one substring has a length of 2 and the remaining substrings
+ * have a length of 3.
+ *
+ * Return true if you can decompose s according to the above rules. Otherwise, return false.
+ *
+ * A substring is a contiguous sequence of characters in a string.
+ */
+
+/**
+ * @param {string} s
+ * @return {boolean}
+ */
+var isDecomposable = function(s) {
+ const groups = [];
+ let i = 0;
+
+ while (i < s.length) {
+ let j = i;
+ while (j < s.length && s[j] === s[i]) {
+ j++;
+ }
+ groups.push(j - i);
+ i = j;
+ }
+
+ let result = false;
+
+ for (const length of groups) {
+ if (length % 3 === 1) {
+ return false;
+ } else if (length % 3 === 2) {
+ if (result) {
+ return false;
+ }
+ result = true;
+ }
+ }
+
+ return result;
+};
From 064874935c09de3072994a40bbb280b25f66321c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:05:33 -0500
Subject: [PATCH 701/994] Add solution #1940
---
README.md | 1 +
...ommon-subsequence-between-sorted-arrays.js | 35 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/1940-longest-common-subsequence-between-sorted-arrays.js
diff --git a/README.md b/README.md
index a9862f51..2c603578 100644
--- a/README.md
+++ b/README.md
@@ -1761,6 +1761,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|
+1940|[Longest Common Subsequence Between Sorted Arrays](./solutions/1940-longest-common-subsequence-between-sorted-arrays.js)|Medium|
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|
diff --git a/solutions/1940-longest-common-subsequence-between-sorted-arrays.js b/solutions/1940-longest-common-subsequence-between-sorted-arrays.js
new file mode 100644
index 00000000..a77ae4c1
--- /dev/null
+++ b/solutions/1940-longest-common-subsequence-between-sorted-arrays.js
@@ -0,0 +1,35 @@
+/**
+ * 1940. Longest Common Subsequence Between Sorted Arrays
+ * https://leetcode.com/problems/longest-common-subsequence-between-sorted-arrays/
+ * Difficulty: Medium
+ *
+ * Given an array of integer arrays arrays where each arrays[i] is sorted in strictly increasing
+ * order, return an integer array representing the longest common subsequence among all the arrays.
+ *
+ * A subsequence is a sequence that can be derived from another sequence by deleting some elements
+ * (possibly none) without changing the order of the remaining elements.
+ */
+
+/**
+ * @param {number[][]} arrays
+ * @return {number[]}
+ */
+var longestCommonSubsequence = function(arrays) {
+ const map = new Map();
+ const totalArrays = arrays.length;
+
+ for (const array of arrays) {
+ for (const num of array) {
+ map.set(num, (map.get(num) || 0) + 1);
+ }
+ }
+
+ const result = [];
+ for (const [num, count] of map) {
+ if (count === totalArrays) {
+ result.push(num);
+ }
+ }
+
+ return result.sort((a, b) => a - b);
+};
From 2835ce4a044b47bbbc718ebb2b19139e6ac00432 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:06:46 -0500
Subject: [PATCH 702/994] Add solution #1950
---
README.md | 1 +
...imum-of-minimum-values-in-all-subarrays.js | 59 +++++++++++++++++++
2 files changed, 60 insertions(+)
create mode 100644 solutions/1950-maximum-of-minimum-values-in-all-subarrays.js
diff --git a/README.md b/README.md
index 2c603578..31b3af9f 100644
--- a/README.md
+++ b/README.md
@@ -1769,6 +1769,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|
+1950|[Maximum of Minimum Values in All Subarrays](./solutions/1950-maximum-of-minimum-values-in-all-subarrays.js)|Medium|
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|
diff --git a/solutions/1950-maximum-of-minimum-values-in-all-subarrays.js b/solutions/1950-maximum-of-minimum-values-in-all-subarrays.js
new file mode 100644
index 00000000..ab95408f
--- /dev/null
+++ b/solutions/1950-maximum-of-minimum-values-in-all-subarrays.js
@@ -0,0 +1,59 @@
+/**
+ * 1950. Maximum of Minimum Values in All Subarrays
+ * https://leetcode.com/problems/maximum-of-minimum-values-in-all-subarrays/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums of size n. You are asked to solve n queries for each
+ * integer i in the range 0 <= i < n.
+ *
+ * To solve the ith query:
+ * 1. Find the minimum value in each possible subarray of size i + 1 of the array nums.
+ * 2. Find the maximum of those minimum values. This maximum is the answer to the query.
+ *
+ * Return a 0-indexed integer array ans of size n such that ans[i] is the answer to the ith query.
+ *
+ * A subarray is a contiguous sequence of elements in an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var findMaximums = function(nums) {
+ const n = nums.length;
+ const result = new Array(n);
+ const leftBound = new Array(n);
+ const rightBound = new Array(n);
+ const stack = [];
+
+ for (let i = 0; i < n; i++) {
+ while (stack.length > 0 && nums[stack[stack.length - 1]] >= nums[i]) {
+ stack.pop();
+ }
+ leftBound[i] = stack.length > 0 ? stack[stack.length - 1] : -1;
+ stack.push(i);
+ }
+
+ stack.length = 0;
+
+ for (let i = n - 1; i >= 0; i--) {
+ while (stack.length > 0 && nums[stack[stack.length - 1]] >= nums[i]) {
+ stack.pop();
+ }
+ rightBound[i] = stack.length > 0 ? stack[stack.length - 1] : n;
+ stack.push(i);
+ }
+
+ result.fill(0);
+
+ for (let i = 0; i < n; i++) {
+ const maxSubarrayLength = rightBound[i] - leftBound[i] - 1;
+ result[maxSubarrayLength - 1] = Math.max(result[maxSubarrayLength - 1], nums[i]);
+ }
+
+ for (let i = n - 2; i >= 0; i--) {
+ result[i] = Math.max(result[i], result[i + 1]);
+ }
+
+ return result;
+};
From c0531f780baa0026091a9baefa4828ff7c0aa6fa Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:10:31 -0500
Subject: [PATCH 703/994] Add solution #1956
---
README.md | 1 +
...mum-time-for-k-virus-variants-to-spread.js | 55 +++++++++++++++++++
2 files changed, 56 insertions(+)
create mode 100644 solutions/1956-minimum-time-for-k-virus-variants-to-spread.js
diff --git a/README.md b/README.md
index 31b3af9f..c8ae9e5e 100644
--- a/README.md
+++ b/README.md
@@ -1774,6 +1774,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|
+1956|[Minimum Time For K Virus Variants to Spread](./solutions/1956-minimum-time-for-k-virus-variants-to-spread.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|
diff --git a/solutions/1956-minimum-time-for-k-virus-variants-to-spread.js b/solutions/1956-minimum-time-for-k-virus-variants-to-spread.js
new file mode 100644
index 00000000..a1f469c7
--- /dev/null
+++ b/solutions/1956-minimum-time-for-k-virus-variants-to-spread.js
@@ -0,0 +1,55 @@
+/**
+ * 1956. Minimum Time For K Virus Variants to Spread
+ * https://leetcode.com/problems/minimum-time-for-k-virus-variants-to-spread/
+ * Difficulty: Hard
+ *
+ * There are n unique virus variants in an infinite 2D grid. You are given a 2D array points,
+ * where points[i] = [xi, yi] represents a virus originating at (xi, yi) on day 0. Note that
+ * it is possible for multiple virus variants to originate at the same point.
+ *
+ * Every day, each cell infected with a virus variant will spread the virus to all neighboring
+ * points in the four cardinal directions (i.e. up, down, left, and right). If a cell has multiple
+ * variants, all the variants will spread without interfering with each other.
+ *
+ * Given an integer k, return the minimum integer number of days for any point to contain at least
+ * k of the unique virus variants.
+ */
+
+/**
+ * @param {number[][]} points
+ * @param {number} k
+ * @return {number}
+ */
+var minDayskVariants = function(points, k) {
+ let left = 0;
+ let right = 200;
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+
+ if (check(mid)) {
+ right = mid;
+ } else {
+ left = mid + 1;
+ }
+ }
+
+ return left;
+
+ function check(day) {
+ for (let x = 1; x <= 100; x++) {
+ for (let y = 1; y <= 100; y++) {
+ let count = 0;
+ for (const [px, py] of points) {
+ if (Math.abs(x - px) + Math.abs(y - py) <= day) {
+ count++;
+ }
+ }
+ if (count >= k) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+};
From c6df4ef0c8ddfc1e9ecc56e0aab618066d43e327 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:12:06 -0500
Subject: [PATCH 704/994] Add solution #1966
---
README.md | 1 +
...searchable-numbers-in-an-unsorted-array.js | 60 +++++++++++++++++++
2 files changed, 61 insertions(+)
create mode 100644 solutions/1966-binary-searchable-numbers-in-an-unsorted-array.js
diff --git a/README.md b/README.md
index c8ae9e5e..d7d00e2b 100644
--- a/README.md
+++ b/README.md
@@ -1782,6 +1782,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|
+1966|[Binary Searchable Numbers in an Unsorted Array](./solutions/1966-binary-searchable-numbers-in-an-unsorted-array.js)|Medium|
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|
diff --git a/solutions/1966-binary-searchable-numbers-in-an-unsorted-array.js b/solutions/1966-binary-searchable-numbers-in-an-unsorted-array.js
new file mode 100644
index 00000000..e29fb494
--- /dev/null
+++ b/solutions/1966-binary-searchable-numbers-in-an-unsorted-array.js
@@ -0,0 +1,60 @@
+/**
+ * 1966. Binary Searchable Numbers in an Unsorted Array
+ * https://leetcode.com/problems/binary-searchable-numbers-in-an-unsorted-array/
+ * Difficulty: Medium
+ *
+ * Consider a function that implements an algorithm similar to Binary Search. The function has
+ * two input parameters: sequence is a sequence of integers, and target is an integer value.
+ * The purpose of the function is to find if the target exists in the sequence.
+ *
+ * The pseudocode of the function is as follows:
+ *
+ * func(sequence, target)
+ * while sequence is not empty
+ * randomly choose an element from sequence as the pivot
+ * if pivot = target, return true
+ * else if pivot < target, remove pivot and all elements to its left from the sequence
+ * else, remove pivot and all elements to its right from the sequence
+ * end while
+ * return false
+ *
+ * When the sequence is sorted, the function works correctly for all values. When the sequence
+ * is not sorted, the function does not work for all values, but may still work for some values.
+ *
+ * Given an integer array nums, representing the sequence, that contains unique numbers and may
+ * or may not be sorted, return the number of values that are guaranteed to be found using the
+ * function, for every possible pivot selection.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var binarySearchableNumbers = function(nums) {
+ const n = nums.length;
+ const leftMax = new Array(n);
+ const rightMin = new Array(n);
+
+ leftMax[0] = nums[0];
+ for (let i = 1; i < n; i++) {
+ leftMax[i] = Math.max(leftMax[i - 1], nums[i]);
+ }
+
+ rightMin[n - 1] = nums[n - 1];
+ for (let i = n - 2; i >= 0; i--) {
+ rightMin[i] = Math.min(rightMin[i + 1], nums[i]);
+ }
+
+ let count = 0;
+
+ for (let i = 0; i < n; i++) {
+ const leftMaxVal = i > 0 ? leftMax[i - 1] : -Infinity;
+ const rightMinVal = i < n - 1 ? rightMin[i + 1] : Infinity;
+
+ if (leftMaxVal < nums[i] && nums[i] < rightMinVal) {
+ count++;
+ }
+ }
+
+ return count;
+};
From 52aaa05aba25b0df30fc0810d615e224f23342c1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:14:00 -0500
Subject: [PATCH 705/994] Add solution #1973
---
README.md | 1 +
...count-nodes-equal-to-sum-of-descendants.js | 43 +++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/1973-count-nodes-equal-to-sum-of-descendants.js
diff --git a/README.md b/README.md
index d7d00e2b..fbbb8813 100644
--- a/README.md
+++ b/README.md
@@ -1788,6 +1788,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|
+1973|[Count Nodes Equal to Sum of Descendants](./solutions/1973-count-nodes-equal-to-sum-of-descendants.js)|Medium|
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|
diff --git a/solutions/1973-count-nodes-equal-to-sum-of-descendants.js b/solutions/1973-count-nodes-equal-to-sum-of-descendants.js
new file mode 100644
index 00000000..20203c1d
--- /dev/null
+++ b/solutions/1973-count-nodes-equal-to-sum-of-descendants.js
@@ -0,0 +1,43 @@
+/**
+ * 1973. Count Nodes Equal to Sum of Descendants
+ * https://leetcode.com/problems/count-nodes-equal-to-sum-of-descendants/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree, return the number of nodes where the value of the node is
+ * equal to the sum of the values of its descendants.
+ *
+ * A descendant of a node x is any node that is on the path from node x to some leaf node. The
+ * sum is considered to be 0 if the node has no 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 equalToDescendants = function(root) {
+ let count = 0;
+ dfs(root);
+ return count;
+
+ function dfs(node) {
+ if (!node) return 0;
+
+ const leftSum = dfs(node.left);
+ const rightSum = dfs(node.right);
+ const descendantSum = leftSum + rightSum;
+
+ if (node.val === descendantSum) {
+ count++;
+ }
+
+ return node.val + descendantSum;
+ }
+};
From 480ba6ead47a76162a11375a8ed8437cb7ec4440 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:16:02 -0500
Subject: [PATCH 706/994] Add solution #1983
---
README.md | 1 +
...st-pair-of-indices-with-equal-range-sum.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/1983-widest-pair-of-indices-with-equal-range-sum.js
diff --git a/README.md b/README.md
index fbbb8813..174112a8 100644
--- a/README.md
+++ b/README.md
@@ -1797,6 +1797,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|
+1983|[Widest Pair of Indices With Equal Range Sum](./solutions/1983-widest-pair-of-indices-with-equal-range-sum.js)|Medium|
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|
diff --git a/solutions/1983-widest-pair-of-indices-with-equal-range-sum.js b/solutions/1983-widest-pair-of-indices-with-equal-range-sum.js
new file mode 100644
index 00000000..c121129b
--- /dev/null
+++ b/solutions/1983-widest-pair-of-indices-with-equal-range-sum.js
@@ -0,0 +1,42 @@
+/**
+ * 1983. Widest Pair of Indices With Equal Range Sum
+ * https://leetcode.com/problems/widest-pair-of-indices-with-equal-range-sum/
+ * Difficulty: Medium
+ *
+ * You are given two 0-indexed binary arrays nums1 and nums2. Find the widest pair of indices (i, j)
+ * such that i <= j and nums1[i] + nums1[i+1] + ... + nums1[j] == nums2[i] + nums2[i+1] + ... +
+ * nums2[j].
+ *
+ * The widest pair of indices is the pair with the largest distance between i and j. The distance
+ * between a pair of indices is defined as j - i + 1.
+ *
+ * Return the distance of the widest pair of indices. If no pair of indices meets the conditions,
+ * return 0.
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @return {number}
+ */
+var widestPairOfIndices = function(nums1, nums2) {
+ const n = nums1.length;
+ const map = new Map();
+ map.set(0, -1);
+
+ let prefixDiff = 0;
+ let result = 0;
+
+ for (let i = 0; i < n; i++) {
+ prefixDiff += nums1[i] - nums2[i];
+
+ if (map.has(prefixDiff)) {
+ const distance = i - map.get(prefixDiff);
+ result = Math.max(result, distance);
+ } else {
+ map.set(prefixDiff, i);
+ }
+ }
+
+ return result;
+};
From c8692af1c02631c10c240cff07b2e238f4540463 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:17:55 -0500
Subject: [PATCH 707/994] Add solution #1989
---
README.md | 1 +
...ber-of-people-that-can-be-caught-in-tag.js | 49 +++++++++++++++++++
2 files changed, 50 insertions(+)
create mode 100644 solutions/1989-maximum-number-of-people-that-can-be-caught-in-tag.js
diff --git a/README.md b/README.md
index 174112a8..f3e725cb 100644
--- a/README.md
+++ b/README.md
@@ -1802,6 +1802,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|
+1989|[Maximum Number of People That Can Be Caught in Tag](./solutions/1989-maximum-number-of-people-that-can-be-caught-in-tag.js)|Medium|
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|
diff --git a/solutions/1989-maximum-number-of-people-that-can-be-caught-in-tag.js b/solutions/1989-maximum-number-of-people-that-can-be-caught-in-tag.js
new file mode 100644
index 00000000..badcb590
--- /dev/null
+++ b/solutions/1989-maximum-number-of-people-that-can-be-caught-in-tag.js
@@ -0,0 +1,49 @@
+/**
+ * 1989. Maximum Number of People That Can Be Caught in Tag
+ * https://leetcode.com/problems/maximum-number-of-people-that-can-be-caught-in-tag/
+ * Difficulty: Medium
+ *
+ * You are playing a game of tag with your friends. In tag, people are divided into two
+ * teams: people who are "it", and people who are not "it". The people who are "it" want
+ * to catch as many people as possible who are not "it".
+ *
+ * You are given a 0-indexed integer array team containing only zeros (denoting people who
+ * are not "it") and ones (denoting people who are "it"), and an integer dist. A person who
+ * is "it" at index i can catch any one person whose index is in the range [i - dist, i + dist]
+ * (inclusive) and is not "it".
+ *
+ * Return the maximum number of people that the people who are "it" can catch.
+ */
+
+/**
+ * @param {number[]} team
+ * @param {number} dist
+ * @return {number}
+ */
+var catchMaximumAmountofPeople = function(team, dist) {
+ const catchers = [];
+ const targets = [];
+
+ for (let i = 0; i < team.length; i++) {
+ if (team[i] === 1) {
+ catchers.push(i);
+ } else {
+ targets.push(i);
+ }
+ }
+
+ let result = 0;
+ let targetIndex = 0;
+ for (const catcherPos of catchers) {
+ while (targetIndex < targets.length && targets[targetIndex] < catcherPos - dist) {
+ targetIndex++;
+ }
+
+ if (targetIndex < targets.length && targets[targetIndex] <= catcherPos + dist) {
+ result++;
+ targetIndex++;
+ }
+ }
+
+ return result;
+};
From 2b2f35310a7eb0cc327a9caaeba1fa88258d4d74 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:19:59 -0500
Subject: [PATCH 708/994] Add solution #1999
---
README.md | 1 +
...est-greater-multiple-made-of-two-digits.js | 44 +++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/1999-smallest-greater-multiple-made-of-two-digits.js
diff --git a/README.md b/README.md
index f3e725cb..b02e51ae 100644
--- a/README.md
+++ b/README.md
@@ -1811,6 +1811,7 @@
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|
+1999|[Smallest Greater Multiple Made of Two Digits](./solutions/1999-smallest-greater-multiple-made-of-two-digits.js)|Medium|
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|
diff --git a/solutions/1999-smallest-greater-multiple-made-of-two-digits.js b/solutions/1999-smallest-greater-multiple-made-of-two-digits.js
new file mode 100644
index 00000000..4e4f8ce2
--- /dev/null
+++ b/solutions/1999-smallest-greater-multiple-made-of-two-digits.js
@@ -0,0 +1,44 @@
+/**
+ * 1999. Smallest Greater Multiple Made of Two Digits
+ * https://leetcode.com/problems/smallest-greater-multiple-made-of-two-digits/
+ * Difficulty: Medium
+ *
+ * Given three integers, k, digit1, and digit2, you want to find the smallest integer that is:
+ * - Larger than k,
+ * - A multiple of k, and
+ * - Comprised of only the digits digit1 and/or digit2.
+ *
+ * Return the smallest such integer. If no such integer exists or the integer exceeds the limit
+ * of a signed 32-bit integer (231 - 1), return -1.
+ */
+
+/**
+ * @param {number} k
+ * @param {number} digit1
+ * @param {number} digit2
+ * @return {number}
+ */
+var findInteger = function(k, digit1, digit2) {
+ const minDigit = Math.min(digit1, digit2);
+ const maxDigit = Math.max(digit1, digit2);
+ const queue = minDigit !== maxDigit ? [minDigit, maxDigit] : [minDigit];
+
+ while (queue.length > 0) {
+ const current = queue.shift();
+
+ if (current === 0 || current > 2147483647) {
+ continue;
+ }
+
+ if (current > k && current % k === 0) {
+ return current;
+ }
+
+ queue.push(current * 10 + minDigit);
+ if (minDigit !== maxDigit) {
+ queue.push(current * 10 + maxDigit);
+ }
+ }
+
+ return -1;
+};
From 331a13605f2dca48633451ababcdfba4761b8c51 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:21:53 -0500
Subject: [PATCH 709/994] Add solution #2005
---
README.md | 1 +
...ubtree-removal-game-with-fibonacci-tree.js | 29 +++++++++++++++++++
2 files changed, 30 insertions(+)
create mode 100644 solutions/2005-subtree-removal-game-with-fibonacci-tree.js
diff --git a/README.md b/README.md
index b02e51ae..baf25b38 100644
--- a/README.md
+++ b/README.md
@@ -1816,6 +1816,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|
+2005|[Subtree Removal Game with Fibonacci Tree](./solutions/2005-subtree-removal-game-with-fibonacci-tree.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|
diff --git a/solutions/2005-subtree-removal-game-with-fibonacci-tree.js b/solutions/2005-subtree-removal-game-with-fibonacci-tree.js
new file mode 100644
index 00000000..30e974e4
--- /dev/null
+++ b/solutions/2005-subtree-removal-game-with-fibonacci-tree.js
@@ -0,0 +1,29 @@
+/**
+ * 2005. Subtree Removal Game with Fibonacci Tree
+ * https://leetcode.com/problems/subtree-removal-game-with-fibonacci-tree/
+ * Difficulty: Hard
+ *
+ * A Fibonacci tree is a binary tree created using the order function order(n):
+ * - order(0) is the empty tree.
+ * - order(1) is a binary tree with only one node.
+ * - order(n) is a binary tree that consists of a root node with the left subtree as order(n - 2)
+ * and the right subtree as order(n - 1).
+ *
+ * Alice and Bob are playing a game with a Fibonacci tree with Alice staring first. On each turn,
+ * a player selects a node and removes that node and its subtree. The player that is forced to
+ * delete root loses.
+ *
+ * Given the integer n, return true if Alice wins the game or false if Bob wins, assuming both
+ * players play optimally.
+ *
+ * A subtree of a binary tree tree is a tree that consists of a node in tree and all of this
+ * node's descendants. The tree tree could also be considered as a subtree of itself.
+ */
+
+/**
+ * @param {number} n
+ * @return {boolean}
+ */
+var findGameWinner = function(n) {
+ return n % 6 !== 1;
+};
From e966d0aad8ca716030f78615971a577b501621d4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:23:41 -0500
Subject: [PATCH 710/994] Add solution #2015
---
README.md | 1 +
...age-height-of-buildings-in-each-segment.js | 69 +++++++++++++++++++
2 files changed, 70 insertions(+)
create mode 100644 solutions/2015-average-height-of-buildings-in-each-segment.js
diff --git a/README.md b/README.md
index baf25b38..7d94acf4 100644
--- a/README.md
+++ b/README.md
@@ -1825,6 +1825,7 @@
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|
+2015|[Average Height of Buildings in Each Segment](./solutions/2015-average-height-of-buildings-in-each-segment.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|
2018|[Check if Word Can Be Placed In Crossword](./solutions/2018-check-if-word-can-be-placed-in-crossword.js)|Medium|
diff --git a/solutions/2015-average-height-of-buildings-in-each-segment.js b/solutions/2015-average-height-of-buildings-in-each-segment.js
new file mode 100644
index 00000000..d1ec62c8
--- /dev/null
+++ b/solutions/2015-average-height-of-buildings-in-each-segment.js
@@ -0,0 +1,69 @@
+/**
+ * 2015. Average Height of Buildings in Each Segment
+ * https://leetcode.com/problems/average-height-of-buildings-in-each-segment/
+ * Difficulty: Medium
+ *
+ * A perfectly straight street is represented by a number line. The street has building(s) on
+ * it and is represented by a 2D integer array buildings, where buildings[i] = [starti, endi,
+ * heighti]. This means that there is a building with heighti in the half-closed
+ * segment [starti, endi).
+ *
+ * You want to describe the heights of the buildings on the street with the minimum number of
+ * non-overlapping segments. The street can be represented by the 2D integer array street
+ * where street[j] = [leftj, rightj, averagej] describes a half-closed segment [leftj, rightj)
+ * of the road where the average heights of the buildings in the segment is averagej.
+ *
+ * - For example, if buildings = [[1,5,2],[3,10,4]], the street could be represented by
+ * street = [[1,3,2],[3,5,3],[5,10,4]] because:
+ * - From 1 to 3, there is only the first building with an average height of 2 / 1 = 2.
+ * - From 3 to 5, both the first and the second building are there with an average height
+ * of (2+4) / 2 = 3.
+ * - From 5 to 10, there is only the second building with an average height of 4 / 1 = 4.
+ *
+ * Given buildings, return the 2D integer array street as described above (excluding any areas
+ * of the street where there are no buldings). You may return the array in any order.
+ *
+ * The average of n elements is the sum of the n elements divided (integer division) by n.
+ *
+ * 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[][]} buildings
+ * @return {number[][]}
+ */
+var averageHeightOfBuildings = function(buildings) {
+ const events = [];
+
+ for (const [start, end, height] of buildings) {
+ events.push([start, height, 1]);
+ events.push([end, -height, -1]);
+ }
+
+ events.sort((a, b) => a[0] - b[0] || a[2] - b[2]);
+
+ const result = [];
+ let currentSum = 0;
+ let currentCount = 0;
+ let prevPos = -1;
+
+ for (const [pos, height, delta] of events) {
+ if (currentCount > 0 && pos > prevPos) {
+ const avgHeight = Math.floor(currentSum / currentCount);
+
+ if (result.length > 0 && result[result.length - 1][1] === prevPos
+ && result[result.length - 1][2] === avgHeight) {
+ result[result.length - 1][1] = pos;
+ } else {
+ result.push([prevPos, pos, avgHeight]);
+ }
+ }
+
+ currentSum += height;
+ currentCount += delta;
+ prevPos = pos;
+ }
+
+ return result;
+};
From b3b86a7663f77bfec2472334d4dab0ed6a6f47f0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:25:15 -0500
Subject: [PATCH 711/994] Add solution #2021
---
README.md | 1 +
.../2021-brightest-position-on-street.js | 46 +++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/2021-brightest-position-on-street.js
diff --git a/README.md b/README.md
index 7d94acf4..bac909ab 100644
--- a/README.md
+++ b/README.md
@@ -1830,6 +1830,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|
+2021|[Brightest Position on Street](./solutions/2021-brightest-position-on-street.js)|Medium|
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|
diff --git a/solutions/2021-brightest-position-on-street.js b/solutions/2021-brightest-position-on-street.js
new file mode 100644
index 00000000..1475effb
--- /dev/null
+++ b/solutions/2021-brightest-position-on-street.js
@@ -0,0 +1,46 @@
+/**
+ * 2021. Brightest Position on Street
+ * https://leetcode.com/problems/brightest-position-on-street/
+ * Difficulty: Medium
+ *
+ * A perfectly straight street is represented by a number line. The street has street lamp(s)
+ * on it and is represented by a 2D integer array lights. Each lights[i] = [positioni, rangei]
+ * indicates that there is a street lamp at position positioni that lights up the area from
+ * [positioni - rangei, positioni + rangei] (inclusive).
+ *
+ * The brightness of a position p is defined as the number of street lamp that light up the
+ * position p.
+ *
+ * Given lights, return the brightest position on the street. If there are multiple brightest
+ * positions, return the smallest one.
+ */
+
+/**
+ * @param {number[][]} lights
+ * @return {number}
+ */
+var brightestPosition = function(lights) {
+ const events = [];
+
+ for (const [position, range] of lights) {
+ events.push([position - range, 1]);
+ events.push([position + range + 1, -1]);
+ }
+
+ events.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
+
+ let maxBrightness = 0;
+ let result = 0;
+ let currentBrightness = 0;
+
+ for (const [position, delta] of events) {
+ currentBrightness += delta;
+
+ if (currentBrightness > maxBrightness) {
+ maxBrightness = currentBrightness;
+ result = position;
+ }
+ }
+
+ return result;
+};
From 5cb69655106af8116b17e7ecf2aebf14e4b3267c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:27:04 -0500
Subject: [PATCH 712/994] Add solution #2031
---
README.md | 1 +
...unt-subarrays-with-more-ones-than-zeros.js | 48 +++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/2031-count-subarrays-with-more-ones-than-zeros.js
diff --git a/README.md b/README.md
index bac909ab..401cc7d4 100644
--- a/README.md
+++ b/README.md
@@ -1839,6 +1839,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|
+2031|[Count Subarrays With More Ones Than Zeros](./solutions/2031-count-subarrays-with-more-ones-than-zeros.js)|Medium|
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|
diff --git a/solutions/2031-count-subarrays-with-more-ones-than-zeros.js b/solutions/2031-count-subarrays-with-more-ones-than-zeros.js
new file mode 100644
index 00000000..3e6ea1ab
--- /dev/null
+++ b/solutions/2031-count-subarrays-with-more-ones-than-zeros.js
@@ -0,0 +1,48 @@
+/**
+ * 2031. Count Subarrays With More Ones Than Zeros
+ * https://leetcode.com/problems/count-subarrays-with-more-ones-than-zeros/
+ * Difficulty: Medium
+ *
+ * You are given a binary array nums containing only the integers 0 and 1. Return the number
+ * of subarrays in nums that have more 1's than 0's. Since the answer may be very large,
+ * return it modulo 109 + 7.
+ *
+ * A subarray is a contiguous sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var subarraysWithMoreZerosThanOnes = function(nums) {
+ const MOD = 1e9 + 7;
+ const dp = [0, 0];
+ const mp = new Map();
+ let sum = 0;
+ let answer = 0;
+
+ mp.set(0, 1);
+
+ for (const num of nums) {
+ const dpPrev = [...dp];
+
+ if (num === 1) {
+ sum++;
+ } else {
+ sum--;
+ }
+
+ dp[0] = mp.get(sum) || 0;
+
+ if (num === 1) {
+ dp[1] = (dpPrev[0] + dpPrev[1] + 1) % MOD;
+ } else {
+ dp[1] = (dpPrev[1] - dp[0] + MOD) % MOD;
+ }
+
+ mp.set(sum, (mp.get(sum) || 0) + 1);
+ answer = (answer + dp[1]) % MOD;
+ }
+
+ return answer;
+};
From 1399b425df6a07e1bcc198cd0953959df5a918f6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:28:52 -0500
Subject: [PATCH 713/994] Add solution #2036
---
README.md | 1 +
.../2036-maximum-alternating-subarray-sum.js | 35 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/2036-maximum-alternating-subarray-sum.js
diff --git a/README.md b/README.md
index 401cc7d4..442418bd 100644
--- a/README.md
+++ b/README.md
@@ -1843,6 +1843,7 @@
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|
+2036|[Maximum Alternating Subarray Sum](./solutions/2036-maximum-alternating-subarray-sum.js)|Medium|
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|
diff --git a/solutions/2036-maximum-alternating-subarray-sum.js b/solutions/2036-maximum-alternating-subarray-sum.js
new file mode 100644
index 00000000..9d502e5d
--- /dev/null
+++ b/solutions/2036-maximum-alternating-subarray-sum.js
@@ -0,0 +1,35 @@
+/**
+ * 2036. Maximum Alternating Subarray Sum
+ * https://leetcode.com/problems/maximum-alternating-subarray-sum/
+ * Difficulty: Medium
+ *
+ * A subarray of a 0-indexed integer array is a contiguous non-empty sequence of elements
+ * within an array.
+ *
+ * The alternating subarray sum of a subarray that ranges from index i to j (inclusive,
+ * 0 <= i <= j < nums.length) is nums[i] - nums[i+1] + nums[i+2] - ... +/- nums[j].
+ *
+ * Given a 0-indexed integer array nums, return the maximum alternating subarray sum of
+ * any subarray of nums.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maximumAlternatingSubarraySum = function(nums) {
+ let result = -Infinity;
+ let positive = -Infinity;
+ let negative = -Infinity;
+
+ for (const num of nums) {
+ const newPositive = Math.max(negative + num, num);
+ const newNegative = positive - num;
+
+ positive = newPositive;
+ negative = newNegative;
+ result = Math.max(result, positive, negative);
+ }
+
+ return result;
+};
From 67f5d56de3f1a9711e630ddf5d5eee38b76ee82f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:30:18 -0500
Subject: [PATCH 714/994] Add solution #2046
---
README.md | 1 +
...st-already-sorted-using-absolute-values.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/2046-sort-linked-list-already-sorted-using-absolute-values.js
diff --git a/README.md b/README.md
index 442418bd..9d43ab6a 100644
--- a/README.md
+++ b/README.md
@@ -1852,6 +1852,7 @@
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|
+2046|[Sort Linked List Already Sorted Using Absolute Values](./solutions/2046-sort-linked-list-already-sorted-using-absolute-values.js)|Medium|
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|
diff --git a/solutions/2046-sort-linked-list-already-sorted-using-absolute-values.js b/solutions/2046-sort-linked-list-already-sorted-using-absolute-values.js
new file mode 100644
index 00000000..a27e2779
--- /dev/null
+++ b/solutions/2046-sort-linked-list-already-sorted-using-absolute-values.js
@@ -0,0 +1,42 @@
+/**
+ * 2046. Sort Linked List Already Sorted Using Absolute Values
+ * https://leetcode.com/problems/sort-linked-list-already-sorted-using-absolute-values/
+ * Difficulty: Medium
+ *
+ * Given the head of a singly linked list that is sorted in non-decreasing order using the
+ * absolute values of its nodes, return the list sorted in non-decreasing order using the
+ * actual values of its nodes.
+ */
+
+/**
+ * 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 sortLinkedList = function(head) {
+ if (!head || !head.next) return head;
+
+ let current = head.next;
+ let prev = head;
+
+ while (current) {
+ if (current.val < 0) {
+ const next = current.next;
+ prev.next = next;
+ current.next = head;
+ head = current;
+ current = next;
+ } else {
+ prev = current;
+ current = current.next;
+ }
+ }
+
+ return head;
+};
From 603189dc02c060fd762c6afc4a6e3ffcd73055fd Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 00:33:10 -0500
Subject: [PATCH 715/994] Add solution #2052
---
README.md | 3 +-
...mum-cost-to-separate-sentence-into-rows.js | 61 +++++++++++++++++++
2 files changed, 63 insertions(+), 1 deletion(-)
create mode 100644 solutions/2052-minimum-cost-to-separate-sentence-into-rows.js
diff --git a/README.md b/README.md
index 9d43ab6a..b18f6a73 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 2,450+ LeetCode solutions in JavaScript
+# 2,500+ LeetCode solutions in JavaScript
[https://leetcodejavascript.com](https://leetcodejavascript.com)
@@ -1857,6 +1857,7 @@
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|
+2052|[Minimum Cost to Separate Sentence Into Rows](./solutions/2052-minimum-cost-to-separate-sentence-into-rows.js)|Medium|
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|
diff --git a/solutions/2052-minimum-cost-to-separate-sentence-into-rows.js b/solutions/2052-minimum-cost-to-separate-sentence-into-rows.js
new file mode 100644
index 00000000..492f72e0
--- /dev/null
+++ b/solutions/2052-minimum-cost-to-separate-sentence-into-rows.js
@@ -0,0 +1,61 @@
+/**
+ * 2052. Minimum Cost to Separate Sentence Into Rows
+ * https://leetcode.com/problems/minimum-cost-to-separate-sentence-into-rows/
+ * Difficulty: Medium
+ *
+ * You are given a string sentence containing words separated by spaces, and an integer k.
+ * Your task is to separate sentence into rows where the number of characters in each row
+ * is at most k. You may assume that sentence does not begin or end with a space, and the
+ * words in sentence are separated by a single space.
+ *
+ * You can split sentence into rows by inserting line breaks between words in sentence.
+ * A word cannot be split between two rows. Each word must be used exactly once, and the
+ * word order cannot be rearranged. Adjacent words in a row should be separated by a single
+ * space, and rows should not begin or end with spaces.
+ *
+ * The cost of a row with length n is (k - n)2, and the total cost is the sum of the costs
+ * for all rows except the last one.
+ * - For example if sentence = "i love leetcode" and k = 12:
+ * - Separating sentence into "i", "love", and "leetcode" has a cost
+ * of (12 - 1)2 + (12 - 4)2 = 185.
+ * - Separating sentence into "i love", and "leetcode" has a cost of (12 - 6)2 = 36.
+ * - Separating sentence into "i", and "love leetcode" is not possible because the
+ * length of "love leetcode" is greater than k.
+ *
+ * Return the minimum possible total cost of separating sentence into rows.
+ */
+
+/**
+ * @param {string} sentence
+ * @param {number} k
+ * @return {number}
+ */
+var minimumCost = function(sentence, k) {
+ const words = sentence.split(' ');
+ const n = words.length;
+ const map = new Map();
+
+ return dp(0);
+
+ function dp(wordIndex) {
+ if (wordIndex === n) return 0;
+ if (map.has(wordIndex)) return map.get(wordIndex);
+
+ let currentLength = 0;
+ let minCost = Infinity;
+
+ for (let i = wordIndex; i < n; i++) {
+ if (i > wordIndex) currentLength += 1;
+ currentLength += words[i].length;
+
+ if (currentLength > k) break;
+
+ const remainingCost = dp(i + 1);
+ const currentCost = i === n - 1 ? 0 : (k - currentLength) ** 2;
+ minCost = Math.min(minCost, currentCost + remainingCost);
+ }
+
+ map.set(wordIndex, minCost);
+ return minCost;
+ }
+};
From dd39e1d094863c2d3fa18c51772d22bb7da7b4af Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 20:07:03 -0500
Subject: [PATCH 716/994] Add solution #2061
---
README.md | 1 +
...number-of-spaces-cleaning-robot-cleaned.js | 52 +++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 solutions/2061-number-of-spaces-cleaning-robot-cleaned.js
diff --git a/README.md b/README.md
index b18f6a73..b32ffb08 100644
--- a/README.md
+++ b/README.md
@@ -1865,6 +1865,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|
+2061|[Number of Spaces Cleaning Robot Cleaned](./solutions/2061-number-of-spaces-cleaning-robot-cleaned.js)|Medium|
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|
diff --git a/solutions/2061-number-of-spaces-cleaning-robot-cleaned.js b/solutions/2061-number-of-spaces-cleaning-robot-cleaned.js
new file mode 100644
index 00000000..5a4871b3
--- /dev/null
+++ b/solutions/2061-number-of-spaces-cleaning-robot-cleaned.js
@@ -0,0 +1,52 @@
+/**
+ * 2061. Number of Spaces Cleaning Robot Cleaned
+ * https://leetcode.com/problems/number-of-spaces-cleaning-robot-cleaned/
+ * Difficulty: Medium
+ *
+ * A room is represented by a 0-indexed 2D binary matrix room where a 0 represents an empty
+ * space and a 1 represents a space with an object. The top left corner of the room will be
+ * empty in all test cases.
+ *
+ * A cleaning robot starts at the top left corner of the room and is facing right. The robot
+ * will continue heading straight until it reaches the edge of the room or it hits an object,
+ * after which it will turn 90 degrees clockwise and repeat this process. The starting space
+ * and all spaces that the robot visits are cleaned by it.
+ *
+ * Return the number of clean spaces in the room if the robot runs indefinitely.
+ */
+
+/**
+ * @param {number[][]} room
+ * @return {number}
+ */
+var numberOfCleanRooms = function(room) {
+ const rows = room.length;
+ const cols = room[0].length;
+ const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
+ const visited = new Set();
+ const states = new Set();
+ let row = 0;
+ let col = 0;
+ let direction = 0;
+
+ while (true) {
+ const state = `${row},${col},${direction}`;
+ if (states.has(state)) break;
+
+ states.add(state);
+ visited.add(`${row},${col}`);
+
+ const nextRow = row + directions[direction][0];
+ const nextCol = col + directions[direction][1];
+
+ if (nextRow < 0 || nextRow >= rows || nextCol < 0
+ || nextCol >= cols || room[nextRow][nextCol] === 1) {
+ direction = (direction + 1) % 4;
+ } else {
+ row = nextRow;
+ col = nextCol;
+ }
+ }
+
+ return visited.size;
+};
From e805a56763229025201745b6b8ad4e4a52059985 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 20:08:24 -0500
Subject: [PATCH 717/994] Add solution #2067
---
README.md | 1 +
.../2067-number-of-equal-count-substrings.js | 63 +++++++++++++++++++
2 files changed, 64 insertions(+)
create mode 100644 solutions/2067-number-of-equal-count-substrings.js
diff --git a/README.md b/README.md
index b32ffb08..80e050b9 100644
--- a/README.md
+++ b/README.md
@@ -1870,6 +1870,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|
+2067|[Number of Equal Count Substrings](./solutions/2067-number-of-equal-count-substrings.js)|Medium|
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|
diff --git a/solutions/2067-number-of-equal-count-substrings.js b/solutions/2067-number-of-equal-count-substrings.js
new file mode 100644
index 00000000..6a55478c
--- /dev/null
+++ b/solutions/2067-number-of-equal-count-substrings.js
@@ -0,0 +1,63 @@
+/**
+ * 2067. Number of Equal Count Substrings
+ * https://leetcode.com/problems/number-of-equal-count-substrings/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed string s consisting of only lowercase English letters, and an
+ * integer count. A substring of s is said to be an equal count substring if, for each
+ * unique letter in the substring, it appears exactly count times in the substring.
+ *
+ * Return the number of equal count substrings in s.
+ *
+ * A substring is a contiguous non-empty sequence of characters within a string.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} count
+ * @return {number}
+ */
+var equalCountSubstrings = function(s, count) {
+ const n = s.length;
+ let result = 0;
+
+ for (let uniqueChars = 1; uniqueChars <= 26; uniqueChars++) {
+ const targetLength = uniqueChars * count;
+ if (targetLength > n) break;
+
+ const charCount = new Map();
+ let validChars = 0;
+
+ for (let right = 0; right < n; right++) {
+ const rightChar = s[right];
+ charCount.set(rightChar, (charCount.get(rightChar) || 0) + 1);
+
+ if (charCount.get(rightChar) === count) {
+ validChars++;
+ } else if (charCount.get(rightChar) === count + 1) {
+ validChars--;
+ }
+
+ if (right >= targetLength) {
+ const leftChar = s[right - targetLength];
+ if (charCount.get(leftChar) === count) {
+ validChars--;
+ } else if (charCount.get(leftChar) === count + 1) {
+ validChars++;
+ }
+
+ charCount.set(leftChar, charCount.get(leftChar) - 1);
+ if (charCount.get(leftChar) === 0) {
+ charCount.delete(leftChar);
+ }
+ }
+
+ if (right >= targetLength - 1 && validChars === uniqueChars
+ && charCount.size === uniqueChars) {
+ result++;
+ }
+ }
+ }
+
+ return result;
+};
From d23895a126691f65001642abfd2feb7e6d721c0d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 20:10:12 -0500
Subject: [PATCH 718/994] Add solution #2077
---
README.md | 1 +
...77-paths-in-maze-that-lead-to-same-room.js | 53 +++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/2077-paths-in-maze-that-lead-to-same-room.js
diff --git a/README.md b/README.md
index 80e050b9..13afe7fe 100644
--- a/README.md
+++ b/README.md
@@ -1878,6 +1878,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|
+2077|[Paths in Maze That Lead to Same Room](./solutions/2077-paths-in-maze-that-lead-to-same-room.js)|Medium|
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|
diff --git a/solutions/2077-paths-in-maze-that-lead-to-same-room.js b/solutions/2077-paths-in-maze-that-lead-to-same-room.js
new file mode 100644
index 00000000..a4d069d2
--- /dev/null
+++ b/solutions/2077-paths-in-maze-that-lead-to-same-room.js
@@ -0,0 +1,53 @@
+/**
+ * 2077. Paths in Maze That Lead to Same Room
+ * https://leetcode.com/problems/paths-in-maze-that-lead-to-same-room/
+ * Difficulty: Medium
+ *
+ * A maze consists of n rooms numbered from 1 to n, and some rooms are connected by corridors.
+ * You are given a 2D integer array corridors where corridors[i] = [room1i, room2i] indicates
+ * that there is a corridor connecting room1i and room2i, allowing a person in the maze to go
+ * from room1i to room2i and vice versa.
+ *
+ * The designer of the maze wants to know how confusing the maze is. The confusion score of
+ * the maze is the number of different cycles of length 3.
+ * - For example, 1 → 2 → 3 → 1 is a cycle of length 3, but 1 → 2 → 3 → 4 and
+ * 1 → 2 → 3 → 2 → 1 are not.
+ *
+ * Two cycles are considered to be different if one or more of the rooms visited in the first
+ * cycle is not in the second cycle.
+ *
+ * Return the confusion score of the maze.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} corridors
+ * @return {number}
+ */
+var numberOfPaths = function(n, corridors) {
+ const graph = Array.from({ length: n + 1 }, () => new Set());
+
+ for (const [room1, room2] of corridors) {
+ graph[room1].add(room2);
+ graph[room2].add(room1);
+ }
+
+ let cycles = 0;
+
+ for (let i = 1; i <= n; i++) {
+ const neighbors = Array.from(graph[i]);
+
+ for (let j = 0; j < neighbors.length; j++) {
+ for (let k = j + 1; k < neighbors.length; k++) {
+ const neighbor1 = neighbors[j];
+ const neighbor2 = neighbors[k];
+
+ if (neighbor1 > i && neighbor2 > i && graph[neighbor1].has(neighbor2)) {
+ cycles++;
+ }
+ }
+ }
+ }
+
+ return cycles;
+};
From ccd18c5e156e9e1cbb590df76757c56932ecf269 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 20:11:09 -0500
Subject: [PATCH 719/994] Add solution #2083
---
README.md | 1 +
...that-begin-and-end-with-the-same-letter.js | 30 +++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 solutions/2083-substrings-that-begin-and-end-with-the-same-letter.js
diff --git a/README.md b/README.md
index 13afe7fe..82e339e9 100644
--- a/README.md
+++ b/README.md
@@ -1883,6 +1883,7 @@
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|
+2083|[Substrings That Begin and End With the Same Letter](./solutions/2083-substrings-that-begin-and-end-with-the-same-letter.js)|Medium|
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|
diff --git a/solutions/2083-substrings-that-begin-and-end-with-the-same-letter.js b/solutions/2083-substrings-that-begin-and-end-with-the-same-letter.js
new file mode 100644
index 00000000..1a80d8ba
--- /dev/null
+++ b/solutions/2083-substrings-that-begin-and-end-with-the-same-letter.js
@@ -0,0 +1,30 @@
+/**
+ * 2083. Substrings That Begin and End With the Same Letter
+ * https://leetcode.com/problems/substrings-that-begin-and-end-with-the-same-letter/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed string s consisting of only lowercase English letters.
+ * Return the number of substrings in s that begin and end with the same character.
+ *
+ * A substring is a contiguous non-empty sequence of characters within a string.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var numberOfSubstrings = function(s) {
+ const map = new Map();
+
+ for (const char of s) {
+ map.set(char, (map.get(char) || 0) + 1);
+ }
+
+ let result = 0;
+
+ for (const count of map.values()) {
+ result += (count * (count + 1)) / 2;
+ }
+
+ return result;
+};
From 739bb7a97a958d2f3115cdca1a199818c71fa7cb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 20:14:30 -0500
Subject: [PATCH 720/994] Add solution #2093
---
README.md | 1 +
...nimum-cost-to-reach-city-with-discounts.js | 59 +++++++++++++++++++
2 files changed, 60 insertions(+)
create mode 100644 solutions/2093-minimum-cost-to-reach-city-with-discounts.js
diff --git a/README.md b/README.md
index 82e339e9..15fd3079 100644
--- a/README.md
+++ b/README.md
@@ -1892,6 +1892,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|
+2093|[Minimum Cost to Reach City With Discounts](./solutions/2093-minimum-cost-to-reach-city-with-discounts.js)|Medium|
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|
diff --git a/solutions/2093-minimum-cost-to-reach-city-with-discounts.js b/solutions/2093-minimum-cost-to-reach-city-with-discounts.js
new file mode 100644
index 00000000..79047563
--- /dev/null
+++ b/solutions/2093-minimum-cost-to-reach-city-with-discounts.js
@@ -0,0 +1,59 @@
+/**
+ * 2093. Minimum Cost to Reach City With Discounts
+ * https://leetcode.com/problems/minimum-cost-to-reach-city-with-discounts/
+ * Difficulty: Medium
+ *
+ * A series of highways connect n cities numbered from 0 to n - 1. You are given a 2D
+ * integer array highways where highways[i] = [city1i, city2i, tolli] indicates that
+ * there is a highway that connects city1i and city2i, allowing a car to go from city1i
+ * to city2i and vice versa for a cost of tolli.
+ *
+ * You are also given an integer discounts which represents the number of discounts you have.
+ * You can use a discount to travel across the ith highway for a cost of tolli / 2 (integer
+ * division). Each discount may only be used once, and you can only use at most one discount
+ * per highway.
+ *
+ * Return the minimum total cost to go from city 0 to city n - 1, or -1 if it is not possible
+ * to go from city 0 to city n - 1.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} highways
+ * @param {number} discounts
+ * @return {number}
+ */
+var minimumCost = function(n, highways, discounts) {
+ const graph = Array.from({ length: n }, () => []);
+
+ for (const [a, b, c] of highways) {
+ graph[a].push([b, c]);
+ graph[b].push([a, c]);
+ }
+
+ const pq = new PriorityQueue((a, b) => a[0] - b[0]);
+ pq.enqueue([0, 0, 0]);
+ const visited = Array.from({ length: n }, () => new Array(discounts + 1).fill(Infinity));
+ visited[0][0] = 0;
+
+ while (!pq.isEmpty()) {
+ const [cost, city, discountUsed] = pq.dequeue();
+
+ if (city === n - 1) return cost;
+
+ for (const [nextCity, weight] of graph[city]) {
+ if (cost + weight < visited[nextCity][discountUsed]) {
+ pq.enqueue([cost + weight, nextCity, discountUsed]);
+ visited[nextCity][discountUsed] = cost + weight;
+ }
+
+ if (discountUsed < discounts
+ && cost + Math.floor(weight / 2) < visited[nextCity][discountUsed + 1]) {
+ pq.enqueue([cost + Math.floor(weight / 2), nextCity, discountUsed + 1]);
+ visited[nextCity][discountUsed + 1] = cost + Math.floor(weight / 2);
+ }
+ }
+ }
+
+ return -1;
+};
From 585a2985ba6b87b6baa1da733672d614f3f98a05 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 20:40:26 -0500
Subject: [PATCH 721/994] Add solution #2098
---
README.md | 1 +
...nce-of-size-k-with-the-largest-even-sum.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/2098-subsequence-of-size-k-with-the-largest-even-sum.js
diff --git a/README.md b/README.md
index 15fd3079..47118442 100644
--- a/README.md
+++ b/README.md
@@ -1897,6 +1897,7 @@
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|
+2098|[Subsequence of Size K With the Largest Even Sum](./solutions/2098-subsequence-of-size-k-with-the-largest-even-sum.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|
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|
diff --git a/solutions/2098-subsequence-of-size-k-with-the-largest-even-sum.js b/solutions/2098-subsequence-of-size-k-with-the-largest-even-sum.js
new file mode 100644
index 00000000..ce24852f
--- /dev/null
+++ b/solutions/2098-subsequence-of-size-k-with-the-largest-even-sum.js
@@ -0,0 +1,39 @@
+/**
+ * 2098. Subsequence of Size K With the Largest Even Sum
+ * https://leetcode.com/problems/subsequence-of-size-k-with-the-largest-even-sum/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums and an integer k. Find the largest even sum of any
+ * subsequence of nums that has a length of k.
+ *
+ * Return this sum, or -1 if such a sum does not exist.
+ *
+ * A subsequence is an array that can be derived from another array by deleting some or no
+ * elements without changing the order of the remaining elements.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var largestEvenSum = function(nums, k) {
+ const evenNums = nums.filter(num => num % 2 === 0).sort((a, b) => b - a);
+ const oddNums = nums.filter(num => num % 2 === 1).sort((a, b) => b - a);
+ let result = -1;
+
+ for (let evenCount = 0; evenCount <= Math.min(k, evenNums.length); evenCount++) {
+ const oddCount = k - evenCount;
+ if (oddCount > oddNums.length || oddCount % 2 === 1) continue;
+ let currentSum = 0;
+ for (let i = 0; i < evenCount; i++) {
+ currentSum += evenNums[i];
+ }
+ for (let i = 0; i < oddCount; i++) {
+ currentSum += oddNums[i];
+ }
+ result = Math.max(result, currentSum);
+ }
+
+ return result;
+};
From b982255e20684779ca5df21576a42de8f022d086 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 20:42:59 -0500
Subject: [PATCH 722/994] Add solution #2107
---
README.md | 1 +
...-unique-flavors-after-sharing-k-candies.js | 62 +++++++++++++++++++
2 files changed, 63 insertions(+)
create mode 100644 solutions/2107-number-of-unique-flavors-after-sharing-k-candies.js
diff --git a/README.md b/README.md
index 47118442..53d3b454 100644
--- a/README.md
+++ b/README.md
@@ -1905,6 +1905,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|
+2107|[Number of Unique Flavors After Sharing K Candies](./solutions/2107-number-of-unique-flavors-after-sharing-k-candies.js)|Medium|
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|
diff --git a/solutions/2107-number-of-unique-flavors-after-sharing-k-candies.js b/solutions/2107-number-of-unique-flavors-after-sharing-k-candies.js
new file mode 100644
index 00000000..d7bd172f
--- /dev/null
+++ b/solutions/2107-number-of-unique-flavors-after-sharing-k-candies.js
@@ -0,0 +1,62 @@
+/**
+ * 2107. Number of Unique Flavors After Sharing K Candies
+ * https://leetcode.com/problems/number-of-unique-flavors-after-sharing-k-candies/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array candies, where candies[i] represents the flavor
+ * of the ith candy. Your mom wants you to share these candies with your little sister by
+ * giving her k consecutive candies, but you want to keep as many flavors of candies as possible.
+ *
+ * Return the maximum number of unique flavors of candy you can keep after sharing with your sister.
+ */
+
+/**
+ * @param {number[]} candies
+ * @param {number} k
+ * @return {number}
+ */
+var shareCandies = function(candies, k) {
+ if (k === 0) return new Set(candies).size;
+ if (k === candies.length) return 0;
+
+ const totalFlavorCount = new Map();
+ for (const candy of candies) {
+ totalFlavorCount.set(candy, (totalFlavorCount.get(candy) || 0) + 1);
+ }
+
+ const windowFlavorCount = new Map();
+ let uniqueRemainingFlavors = totalFlavorCount.size;
+
+ for (let i = 0; i < k; i++) {
+ const candy = candies[i];
+ const prevWindowCount = windowFlavorCount.get(candy) || 0;
+ windowFlavorCount.set(candy, prevWindowCount + 1);
+
+ if (prevWindowCount + 1 === totalFlavorCount.get(candy)) {
+ uniqueRemainingFlavors--;
+ }
+ }
+
+ let result = uniqueRemainingFlavors;
+
+ for (let i = k; i < candies.length; i++) {
+ const addCandy = candies[i];
+ const removeCandy = candies[i - k];
+
+ const prevAddCount = windowFlavorCount.get(addCandy) || 0;
+ windowFlavorCount.set(addCandy, prevAddCount + 1);
+ if (prevAddCount + 1 === totalFlavorCount.get(addCandy)) {
+ uniqueRemainingFlavors--;
+ }
+
+ const prevRemoveCount = windowFlavorCount.get(removeCandy);
+ windowFlavorCount.set(removeCandy, prevRemoveCount - 1);
+ if (prevRemoveCount === totalFlavorCount.get(removeCandy)) {
+ uniqueRemainingFlavors++;
+ }
+
+ result = Math.max(result, uniqueRemainingFlavors);
+ }
+
+ return result;
+};
From 04fd1fed22980f0b61ffc010f549f7ba9d9f38f2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 20:44:47 -0500
Subject: [PATCH 723/994] Add solution #2113
---
README.md | 1 +
...y-after-removing-and-replacing-elements.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/2113-elements-in-array-after-removing-and-replacing-elements.js
diff --git a/README.md b/README.md
index 53d3b454..8c5537cb 100644
--- a/README.md
+++ b/README.md
@@ -1910,6 +1910,7 @@
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|
+2113|[Elements in Array After Removing and Replacing Elements](./solutions/2113-elements-in-array-after-removing-and-replacing-elements.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/2113-elements-in-array-after-removing-and-replacing-elements.js b/solutions/2113-elements-in-array-after-removing-and-replacing-elements.js
new file mode 100644
index 00000000..6994fd4a
--- /dev/null
+++ b/solutions/2113-elements-in-array-after-removing-and-replacing-elements.js
@@ -0,0 +1,41 @@
+/**
+ * 2113. Elements in Array After Removing and Replacing Elements
+ * https://leetcode.com/problems/elements-in-array-after-removing-and-replacing-elements/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums. Initially on minute 0, the array is unchanged.
+ * Every minute, the leftmost element in nums is removed until no elements remain. Then, every
+ * minute, one element is appended to the end of nums, in the order they were removed in, until
+ * the original array is restored. This process repeats indefinitely.
+ * - For example, the array [0,1,2] would change as follows: [0,1,2] → [1,2] → [2] → [] → [0] →
+ * [0,1] → [0,1,2] → [1,2] → [2] → [] → [0] → [0,1] → [0,1,2] → ...
+ *
+ * You are also given a 2D integer array queries of size n where queries[j] = [timej, indexj].
+ * The answer to the jth query is:
+ * - nums[indexj] if indexj < nums.length at minute timej
+ * - -1 if indexj >= nums.length at minute timej
+ *
+ * Return an integer array ans of size n where ans[j] is the answer to the jth query.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[][]} queries
+ * @return {number[]}
+ */
+var elementInNums = function(nums, queries) {
+ const n = nums.length;
+ const cycleLength = 2 * n;
+
+ return queries.map(([time, index]) => {
+ const position = time % cycleLength;
+
+ if (position < n) {
+ const currentLength = n - position;
+ return index < currentLength ? nums[position + index] : -1;
+ } else {
+ const currentLength = position - n;
+ return index < currentLength ? nums[index] : -1;
+ }
+ });
+};
From 2cbb0e2ecfdcb4feab0fe655a788f18d0dc3d361 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 20:47:22 -0500
Subject: [PATCH 724/994] Add solution #2123
---
README.md | 1 +
...tions-to-remove-adjacent-ones-in-matrix.js | 53 +++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/2123-minimum-operations-to-remove-adjacent-ones-in-matrix.js
diff --git a/README.md b/README.md
index 8c5537cb..26a880e5 100644
--- a/README.md
+++ b/README.md
@@ -1919,6 +1919,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|
+2123|[Minimum Operations to Remove Adjacent Ones in Matrix](./solutions/2123-minimum-operations-to-remove-adjacent-ones-in-matrix.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|
diff --git a/solutions/2123-minimum-operations-to-remove-adjacent-ones-in-matrix.js b/solutions/2123-minimum-operations-to-remove-adjacent-ones-in-matrix.js
new file mode 100644
index 00000000..2c72d6b0
--- /dev/null
+++ b/solutions/2123-minimum-operations-to-remove-adjacent-ones-in-matrix.js
@@ -0,0 +1,53 @@
+/**
+ * 2123. Minimum Operations to Remove Adjacent Ones in Matrix
+ * https://leetcode.com/problems/minimum-operations-to-remove-adjacent-ones-in-matrix/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed binary matrix grid. In one operation, you can flip any 1 in
+ * grid to be 0.
+ *
+ * A binary matrix is well-isolated if there is no 1 in the matrix that is 4-directionally
+ * connected (i.e., horizontal and vertical) to another 1.
+ *
+ * Return the minimum number of operations to make grid well-isolated.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var minimumOperations = function(grid) {
+ const m = grid.length;
+ const n = grid[0].length;
+ let count = 0;
+ const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
+ const match = Array.from({ length: m }, () => new Array(n).fill(-1));
+ const visited = Array.from({ length: m }, () => new Array(n).fill(-1));
+
+ for (let i = 0; i < m; i++) {
+ for (let j = 0; j < n; j++) {
+ if (grid[i][j] && match[i][j] === -1) {
+ visited[i][j] = i * n + j;
+ count += dfs(i, j, visited[i][j]);
+ }
+ }
+ }
+
+ return count;
+
+ function dfs(i, j, v) {
+ for (const [di, dj] of directions) {
+ const x = i + di;
+ const y = j + dj;
+ if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] && visited[x][y] !== v) {
+ visited[x][y] = v;
+ if (match[x][y] === -1 || dfs(Math.floor(match[x][y] / n), match[x][y] % n, v)) {
+ match[x][y] = i * n + j;
+ match[i][j] = x * n + y;
+ return 1;
+ }
+ }
+ }
+ return 0;
+ }
+};
From 2442843c05e0508bbe0de6edfd843e55318f3905 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 6 Jul 2025 20:48:26 -0500
Subject: [PATCH 725/994] Add solution #2128
---
README.md | 1 +
...move-all-ones-with-row-and-column-flips.js | 43 +++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/2128-remove-all-ones-with-row-and-column-flips.js
diff --git a/README.md b/README.md
index 26a880e5..d638ebff 100644
--- a/README.md
+++ b/README.md
@@ -1924,6 +1924,7 @@
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|
+2128|[Remove All Ones With Row and Column Flips](./solutions/2128-remove-all-ones-with-row-and-column-flips.js)|Medium|
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|
diff --git a/solutions/2128-remove-all-ones-with-row-and-column-flips.js b/solutions/2128-remove-all-ones-with-row-and-column-flips.js
new file mode 100644
index 00000000..198ecbd2
--- /dev/null
+++ b/solutions/2128-remove-all-ones-with-row-and-column-flips.js
@@ -0,0 +1,43 @@
+/**
+ * 2128. Remove All Ones With Row and Column Flips
+ * https://leetcode.com/problems/remove-all-ones-with-row-and-column-flips/
+ * Difficulty: Medium
+ *
+ * You are given an m x n binary matrix grid.
+ *
+ * In one operation, you can choose any row or column and flip each value in that row or
+ * column (i.e., changing all 0's to 1's, and all 1's to 0's).
+ *
+ * Return true if it is possible to remove all 1's from grid using any number of operations
+ * or false otherwise.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {boolean}
+ */
+var removeOnes = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const firstRow = grid[0];
+
+ for (let i = 1; i < rows; i++) {
+ let sameAsFirst = true;
+ let oppositeToFirst = true;
+
+ for (let j = 0; j < cols; j++) {
+ if (grid[i][j] !== firstRow[j]) {
+ sameAsFirst = false;
+ }
+ if (grid[i][j] === firstRow[j]) {
+ oppositeToFirst = false;
+ }
+ }
+
+ if (!sameAsFirst && !oppositeToFirst) {
+ return false;
+ }
+ }
+
+ return true;
+};
From a2081250a411dadbbb3b2859e006710d7f63e291 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 7 Jul 2025 00:24:51 -0500
Subject: [PATCH 726/994] Add solution #2137
---
README.md | 1 +
...ween-buckets-to-make-water-levels-equal.js | 57 +++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/2137-pour-water-between-buckets-to-make-water-levels-equal.js
diff --git a/README.md b/README.md
index d638ebff..3a30de59 100644
--- a/README.md
+++ b/README.md
@@ -1933,6 +1933,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|
+2137|[Pour Water Between Buckets to Make Water Levels Equal](./solutions/2137-pour-water-between-buckets-to-make-water-levels-equal.js)|Medium|
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|
diff --git a/solutions/2137-pour-water-between-buckets-to-make-water-levels-equal.js b/solutions/2137-pour-water-between-buckets-to-make-water-levels-equal.js
new file mode 100644
index 00000000..d75d4718
--- /dev/null
+++ b/solutions/2137-pour-water-between-buckets-to-make-water-levels-equal.js
@@ -0,0 +1,57 @@
+/**
+ * 2137. Pour Water Between Buckets to Make Water Levels Equal
+ * https://leetcode.com/problems/pour-water-between-buckets-to-make-water-levels-equal/
+ * Difficulty: Medium
+ *
+ * You have n buckets each containing some gallons of water in it, represented by a 0-indexed
+ * integer array buckets, where the ith bucket contains buckets[i] gallons of water. You are
+ * also given an integer loss.
+ *
+ * You want to make the amount of water in each bucket equal. You can pour any amount of water
+ * from one bucket to another bucket (not necessarily an integer). However, every time you
+ * pour k gallons of water, you spill loss percent of k.
+ *
+ * Return the maximum amount of water in each bucket after making the amount of water equal.
+ * Answers within 10-5 of the actual answer will be accepted.
+ */
+
+/**
+ * @param {number[]} buckets
+ * @param {number} loss
+ * @return {number}
+ */
+var equalizeWater = function(buckets, loss) {
+ const n = buckets.length;
+ const totalWater = buckets.reduce((sum, water) => sum + water, 0);
+ const retentionRate = (100 - loss) / 100;
+
+ let left = 0;
+ let right = Math.max(...buckets);
+
+ while (right - left > 1e-7) {
+ const mid = (left + right) / 2;
+
+ if (canAchieveLevel(mid)) {
+ left = mid;
+ } else {
+ right = mid;
+ }
+ }
+
+ return left;
+
+ function canAchieveLevel(targetLevel) {
+ let surplus = 0;
+ let deficit = 0;
+
+ for (const water of buckets) {
+ if (water > targetLevel) {
+ surplus += water - targetLevel;
+ } else {
+ deficit += targetLevel - water;
+ }
+ }
+
+ return surplus * retentionRate >= deficit;
+ }
+};
From 7786089732d765598be475d4d74d91b826a839f8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 7 Jul 2025 00:26:57 -0500
Subject: [PATCH 727/994] Add solution #2143
---
README.md | 1 +
...choose-numbers-from-two-arrays-in-range.js | 57 +++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/2143-choose-numbers-from-two-arrays-in-range.js
diff --git a/README.md b/README.md
index 3a30de59..6e03f717 100644
--- a/README.md
+++ b/README.md
@@ -1938,6 +1938,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|
+2143|[Choose Numbers From Two Arrays in Range](./solutions/2143-choose-numbers-from-two-arrays-in-range.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|
diff --git a/solutions/2143-choose-numbers-from-two-arrays-in-range.js b/solutions/2143-choose-numbers-from-two-arrays-in-range.js
new file mode 100644
index 00000000..a56de83e
--- /dev/null
+++ b/solutions/2143-choose-numbers-from-two-arrays-in-range.js
@@ -0,0 +1,57 @@
+/**
+ * 2143. Choose Numbers From Two Arrays in Range
+ * https://leetcode.com/problems/choose-numbers-from-two-arrays-in-range/
+ * Difficulty: Hard
+ *
+ * You are given two 0-indexed integer arrays nums1 and nums2 of length n.
+ *
+ * A range [l, r] (inclusive) where 0 <= l <= r < n is balanced if:
+ * - For every i in the range [l, r], you pick either nums1[i] or nums2[i].
+ * - The sum of the numbers you pick from nums1 equals to the sum of the numbers you pick from
+ * nums2 (the sum is considered to be 0 if you pick no numbers from an array).
+ *
+ * Two balanced ranges from [l1, r1] and [l2, r2] are considered to be different if at least
+ * one of the following is true:
+ * - l1 != l2
+ * - r1 != r2
+ * - nums1[i] is picked in the first range, and nums2[i] is picked in the second range or vice
+ * versa for at least one i.
+ *
+ * Return the number of different ranges that are balanced. Since the answer may be very large,
+ * return it modulo 109 + 7.
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @return {number}
+ */
+var countSubranges = function(nums1, nums2) {
+ const MOD = 1e9 + 7;
+ const n = nums1.length;
+ let dp = new Map();
+ let result = 0;
+
+ for (let i = 0; i < n; i++) {
+ const n1 = nums1[i];
+ const n2 = nums2[i];
+ const newDp = new Map();
+
+ newDp.set(n1, (newDp.get(n1) || 0) + 1);
+ newDp.set(-n2, (newDp.get(-n2) || 0) + 1);
+
+ for (const [key, value] of dp) {
+ newDp.set(key + n1, (newDp.get(key + n1) || 0) + value);
+ newDp.set(key - n2, (newDp.get(key - n2) || 0) + value);
+ }
+
+ for (const [key, value] of newDp) {
+ newDp.set(key, value % MOD);
+ }
+
+ result = (result + (newDp.get(0) || 0)) % MOD;
+ dp = newDp;
+ }
+
+ return result;
+};
From 7dc9a4aee6e294f77e1524ae8d13b7c6ff29dbd9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 7 Jul 2025 00:29:12 -0500
Subject: [PATCH 728/994] Add solution #2152
---
README.md | 1 +
...minimum-number-of-lines-to-cover-points.js | 77 +++++++++++++++++++
2 files changed, 78 insertions(+)
create mode 100644 solutions/2152-minimum-number-of-lines-to-cover-points.js
diff --git a/README.md b/README.md
index 6e03f717..19511909 100644
--- a/README.md
+++ b/README.md
@@ -1946,6 +1946,7 @@
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|
+2152|[Minimum Number of Lines to Cover Points](./solutions/2152-minimum-number-of-lines-to-cover-points.js)|Medium|
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|
diff --git a/solutions/2152-minimum-number-of-lines-to-cover-points.js b/solutions/2152-minimum-number-of-lines-to-cover-points.js
new file mode 100644
index 00000000..a6d56b58
--- /dev/null
+++ b/solutions/2152-minimum-number-of-lines-to-cover-points.js
@@ -0,0 +1,77 @@
+/**
+ * 2152. Minimum Number of Lines to Cover Points
+ * https://leetcode.com/problems/minimum-number-of-lines-to-cover-points/
+ * Difficulty: Medium
+ *
+ * You are given an array points where points[i] = [xi, yi] represents a point on an X-Y plane.
+ *
+ * Straight lines are going to be added to the X-Y plane, such that every point is covered by at
+ * least one line.
+ *
+ * Return the minimum number of straight lines needed to cover all the points.
+ */
+
+/**
+ * @param {number[][]} points
+ * @return {number}
+ */
+var minimumLines = function(points) {
+ const n = points.length;
+ const linePoints = new Map();
+
+ for (let i = 0; i < n; i++) {
+ const [x1, y1] = points[i];
+ for (let j = i + 1; j < n; j++) {
+ const [x2, y2] = points[j];
+ let a;
+ let b;
+
+ if (x1 === x2) {
+ a = x1;
+ b = Number.MAX_SAFE_INTEGER;
+ } else {
+ a = (y2 - y1) / (x2 - x1);
+ b = y1 - a * x1;
+ }
+
+ const key = `${a},${b}`;
+ if (!linePoints.has(key)) {
+ linePoints.set(key, new Set());
+ }
+ linePoints.get(key).add(`${x1},${y1}`);
+ linePoints.get(key).add(`${x2},${y2}`);
+ }
+ }
+
+ const lines = [];
+ for (const [line, pointSet] of linePoints) {
+ if (pointSet.size > 2) {
+ lines.push(line);
+ }
+ }
+
+ let answer = Math.ceil(n / 2);
+ const m = lines.length;
+
+ for (let mask = 1; mask < (1 << m); mask++) {
+ let j = 0;
+ const lineCount = mask.toString(2).split('1').length - 1;
+ const currentPoints = new Set();
+ let tempMask = mask;
+
+ while (tempMask > 0) {
+ if (tempMask % 2) {
+ const line = lines[m - 1 - j];
+ for (const point of linePoints.get(line)) {
+ currentPoints.add(point);
+ }
+ }
+ tempMask >>= 1;
+ j++;
+ }
+
+ answer = Math.min(answer, lineCount + Math.ceil((n - currentPoints.size) / 2));
+ }
+
+ return answer;
+};
From 8d4231bd2a5ec7b094eb3e69d2aee1f1081f9907 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 7 Jul 2025 00:31:36 -0500
Subject: [PATCH 729/994] Add solution #2158
---
README.md | 1 +
...158-amount-of-new-area-painted-each-day.js | 65 +++++++++++++++++++
2 files changed, 66 insertions(+)
create mode 100644 solutions/2158-amount-of-new-area-painted-each-day.js
diff --git a/README.md b/README.md
index 19511909..def5ae7e 100644
--- a/README.md
+++ b/README.md
@@ -1951,6 +1951,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|
+2158|[Amount of New Area Painted Each Day](./solutions/2158-amount-of-new-area-painted-each-day.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|
diff --git a/solutions/2158-amount-of-new-area-painted-each-day.js b/solutions/2158-amount-of-new-area-painted-each-day.js
new file mode 100644
index 00000000..056baa10
--- /dev/null
+++ b/solutions/2158-amount-of-new-area-painted-each-day.js
@@ -0,0 +1,65 @@
+/**
+ * 2158. Amount of New Area Painted Each Day
+ * https://leetcode.com/problems/amount-of-new-area-painted-each-day/
+ * Difficulty: Hard
+ *
+ * There is a long and thin painting that can be represented by a number line. You are given
+ * a 0-indexed 2D integer array paint of length n, where paint[i] = [starti, endi]. This means
+ * that on the ith day you need to paint the area between starti and endi.
+ *
+ * Painting the same area multiple times will create an uneven painting so you only want to
+ * paint each area of the painting at most once.
+ *
+ * Return an integer array worklog of length n, where worklog[i] is the amount of new area that
+ * you painted on the ith day.
+ */
+
+/**
+ * @param {number[][]} paint
+ * @return {number[]}
+ */
+var amountPainted = function(paint) {
+ const intervals = new Map();
+ const result = [];
+
+ for (const [start, end] of paint) {
+ let left = start;
+ let right = end;
+ let paintAmount = right - left;
+
+ const keys = Array.from(intervals.keys()).sort((a, b) => a - b);
+ const toRemove = [];
+ let merged = false;
+
+ for (const key of keys) {
+ const value = intervals.get(key);
+
+ if (key > right || value < left) continue;
+
+ if (!merged && key <= left && value >= left) {
+ left = Math.min(left, key);
+ right = Math.max(right, value);
+ paintAmount = Math.max(0, end - Math.max(start, value));
+ toRemove.push(key);
+ merged = true;
+ } else if (key >= left && key < right) {
+ paintAmount -= Math.min(right, value) - key;
+ right = Math.max(right, value);
+ toRemove.push(key);
+ } else if (value > left && value <= right) {
+ paintAmount -= value - Math.max(left, key);
+ left = Math.min(left, key);
+ toRemove.push(key);
+ }
+ }
+
+ for (const key of toRemove) {
+ intervals.delete(key);
+ }
+
+ intervals.set(left, right);
+ result.push(Math.max(0, paintAmount));
+ }
+
+ return result;
+};
From e78ae09ba6808a943cfd89855bd623f14db13bac Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 7 Jul 2025 00:32:32 -0500
Subject: [PATCH 730/994] Add solution #2168
---
README.md | 1 +
...e-substrings-with-equal-digit-frequency.js | 37 +++++++++++++++++++
2 files changed, 38 insertions(+)
create mode 100644 solutions/2168-unique-substrings-with-equal-digit-frequency.js
diff --git a/README.md b/README.md
index def5ae7e..b4891249 100644
--- a/README.md
+++ b/README.md
@@ -1959,6 +1959,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|
+2168|[Unique Substrings With Equal Digit Frequency](./solutions/2168-unique-substrings-with-equal-digit-frequency.js)|Medium|
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|
diff --git a/solutions/2168-unique-substrings-with-equal-digit-frequency.js b/solutions/2168-unique-substrings-with-equal-digit-frequency.js
new file mode 100644
index 00000000..3a9dfe8a
--- /dev/null
+++ b/solutions/2168-unique-substrings-with-equal-digit-frequency.js
@@ -0,0 +1,37 @@
+/**
+ * 2168. Unique Substrings With Equal Digit Frequency
+ * https://leetcode.com/problems/unique-substrings-with-equal-digit-frequency/
+ * Difficulty: Medium
+ *
+ * Given a digit string s, return the number of unique substrings of s where every digit appears
+ * the same number of times.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var equalDigitFrequency = function(s) {
+ const uniqueSubstrings = new Set();
+ const n = s.length;
+
+ for (let i = 0; i < n; i++) {
+ const digitCount = new Map();
+
+ for (let j = i; j < n; j++) {
+ const digit = s[j];
+ digitCount.set(digit, (digitCount.get(digit) || 0) + 1);
+
+ if (hasEqualFrequency(digitCount)) {
+ uniqueSubstrings.add(s.substring(i, j + 1));
+ }
+ }
+ }
+
+ return uniqueSubstrings.size;
+
+ function hasEqualFrequency(counts) {
+ const frequencies = Array.from(counts.values());
+ return frequencies.every(freq => freq === frequencies[0]);
+ }
+};
From db1151f1dd8075bfb9088f38265d672f9dc46e85 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 7 Jul 2025 23:15:09 -0500
Subject: [PATCH 731/994] Add solution #2174
---
README.md | 1 +
...e-all-ones-with-row-and-column-flips-ii.js | 67 +++++++++++++++++++
2 files changed, 68 insertions(+)
create mode 100644 solutions/2174-remove-all-ones-with-row-and-column-flips-ii.js
diff --git a/README.md b/README.md
index b4891249..29f0a43f 100644
--- a/README.md
+++ b/README.md
@@ -1964,6 +1964,7 @@
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|
+2174|[Remove All Ones With Row and Column Flips II](./solutions/2174-remove-all-ones-with-row-and-column-flips-ii.js)|Medium|
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|
diff --git a/solutions/2174-remove-all-ones-with-row-and-column-flips-ii.js b/solutions/2174-remove-all-ones-with-row-and-column-flips-ii.js
new file mode 100644
index 00000000..0d2bdb69
--- /dev/null
+++ b/solutions/2174-remove-all-ones-with-row-and-column-flips-ii.js
@@ -0,0 +1,67 @@
+/**
+ * 2174. Remove All Ones With Row and Column Flips II
+ * https://leetcode.com/problems/remove-all-ones-with-row-and-column-flips-ii/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed m x n binary matrix grid.
+ *
+ * In one operation, you can choose any i and j that meet the following conditions:
+ * - 0 <= i < m
+ * - 0 <= j < n
+ * - grid[i][j] == 1
+ *
+ * and change the values of all cells in row i and column j to zero.
+ *
+ * Return the minimum number of operations needed to remove all 1's from grid.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var removeOnes = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const map = new Map();
+
+ return solve(grid);
+
+ function solve(currentGrid) {
+ const key = currentGrid.map(row => row.join('')).join('|');
+ if (map.has(key)) return map.get(key);
+
+ if (hasNoOnes(currentGrid)) return 0;
+
+ let minOps = Infinity;
+
+ for (let i = 0; i < rows; i++) {
+ for (let j = 0; j < cols; j++) {
+ if (currentGrid[i][j] === 1) {
+ const newGrid = performOperation(currentGrid, i, j);
+ minOps = Math.min(minOps, 1 + solve(newGrid));
+ }
+ }
+ }
+
+ map.set(key, minOps);
+ return minOps;
+ }
+
+ function hasNoOnes(grid) {
+ return grid.every(row => row.every(cell => cell === 0));
+ }
+
+ function performOperation(grid, targetRow, targetCol) {
+ const newGrid = grid.map(row => [...row]);
+
+ for (let j = 0; j < cols; j++) {
+ newGrid[targetRow][j] = 0;
+ }
+
+ for (let i = 0; i < rows; i++) {
+ newGrid[i][targetCol] = 0;
+ }
+
+ return newGrid;
+ }
+};
From 8d3ba3b8f216c15ece1fe732b43c6d3a62c24eca Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 7 Jul 2025 23:16:36 -0500
Subject: [PATCH 732/994] Add solution #2184
---
README.md | 1 +
...mber-of-ways-to-build-sturdy-brick-wall.js | 99 +++++++++++++++++++
2 files changed, 100 insertions(+)
create mode 100644 solutions/2184-number-of-ways-to-build-sturdy-brick-wall.js
diff --git a/README.md b/README.md
index 29f0a43f..9116d949 100644
--- a/README.md
+++ b/README.md
@@ -1972,6 +1972,7 @@
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|
+2184|[Number of Ways to Build Sturdy Brick Wall](./solutions/2184-number-of-ways-to-build-sturdy-brick-wall.js)|Medium|
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|
diff --git a/solutions/2184-number-of-ways-to-build-sturdy-brick-wall.js b/solutions/2184-number-of-ways-to-build-sturdy-brick-wall.js
new file mode 100644
index 00000000..3551159b
--- /dev/null
+++ b/solutions/2184-number-of-ways-to-build-sturdy-brick-wall.js
@@ -0,0 +1,99 @@
+/**
+ * 2184. Number of Ways to Build Sturdy Brick Wall
+ * https://leetcode.com/problems/number-of-ways-to-build-sturdy-brick-wall/
+ * Difficulty: Medium
+ *
+ * You are given integers height and width which specify the dimensions of a brick wall you are
+ * building. You are also given a 0-indexed array of unique integers bricks, where the ith brick
+ * has a height of 1 and a width of bricks[i]. You have an infinite supply of each type of brick
+ * and bricks may not be rotated.
+ *
+ * Each row in the wall must be exactly width units long. For the wall to be sturdy, adjacent rows
+ * in the wall should not join bricks at the same location, except at the ends of the wall.
+ *
+ * Return the number of ways to build a sturdy wall. Since the answer may be very large, return
+ * it modulo 109 + 7.
+ */
+
+/**
+ * @param {number} height
+ * @param {number} width
+ * @param {number[]} bricks
+ * @return {number}
+ */
+var buildWall = function(height, width, bricks) {
+ const MOD = 1e9 + 7;
+ const patterns = [];
+
+ generatePatterns(0, []);
+
+ if (patterns.length === 0) return 0;
+
+ const graph = buildCompatibilityGraph();
+ let dp = new Array(patterns.length).fill(1);
+ for (let row = 1; row < height; row++) {
+ const newDp = new Array(patterns.length).fill(0);
+
+ for (let i = 0; i < patterns.length; i++) {
+ for (const j of graph[i]) {
+ newDp[i] = (newDp[i] + dp[j]) % MOD;
+ }
+ }
+
+ dp = newDp;
+ }
+
+ return dp.reduce((sum, count) => (sum + count) % MOD, 0);
+
+ function generatePatterns(currentWidth, currentPattern) {
+ if (currentWidth === width) {
+ patterns.push([...currentPattern]);
+ return;
+ }
+
+ for (const brick of bricks) {
+ if (currentWidth + brick <= width) {
+ currentPattern.push(brick);
+ generatePatterns(currentWidth + brick, currentPattern);
+ currentPattern.pop();
+ }
+ }
+ }
+
+ function buildCompatibilityGraph() {
+ const graph = Array.from({ length: patterns.length }, () => []);
+
+ for (let i = 0; i < patterns.length; i++) {
+ for (let j = 0; j < patterns.length; j++) {
+ if (areCompatible(patterns[i], patterns[j])) {
+ graph[i].push(j);
+ }
+ }
+ }
+
+ return graph;
+ }
+
+ function areCompatible(pattern1, pattern2) {
+ const cuts1 = new Set();
+ const cuts2 = new Set();
+
+ let pos = 0;
+ for (const brick of pattern1) {
+ pos += brick;
+ if (pos < width) cuts1.add(pos);
+ }
+
+ pos = 0;
+ for (const brick of pattern2) {
+ pos += brick;
+ if (pos < width) cuts2.add(pos);
+ }
+
+ for (const cut of cuts1) {
+ if (cuts2.has(cut)) return false;
+ }
+
+ return true;
+ }
+};
From e568c8f45fbde2032c1ecf72b6b562c6b3b67726 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 7 Jul 2025 23:18:42 -0500
Subject: [PATCH 733/994] Add solution #2189
---
README.md | 1 +
...-number-of-ways-to-build-house-of-cards.js | 35 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/2189-number-of-ways-to-build-house-of-cards.js
diff --git a/README.md b/README.md
index 9116d949..71fa88cd 100644
--- a/README.md
+++ b/README.md
@@ -1977,6 +1977,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|
+2189|[Number of Ways to Build House of Cards](./solutions/2189-number-of-ways-to-build-house-of-cards.js)|Medium|
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|
diff --git a/solutions/2189-number-of-ways-to-build-house-of-cards.js b/solutions/2189-number-of-ways-to-build-house-of-cards.js
new file mode 100644
index 00000000..80b2f197
--- /dev/null
+++ b/solutions/2189-number-of-ways-to-build-house-of-cards.js
@@ -0,0 +1,35 @@
+/**
+ * 2189. Number of Ways to Build House of Cards
+ * https://leetcode.com/problems/number-of-ways-to-build-house-of-cards/
+ * Difficulty: Medium
+ *
+ * You are given an integer n representing the number of playing cards you have. A house of
+ * cards meets the following conditions:
+ * - A house of cards consists of one or more rows of triangles and horizontal cards.
+ * - Triangles are created by leaning two cards against each other.
+ * - One card must be placed horizontally between all adjacent triangles in a row.
+ * - Any triangle on a row higher than the first must be placed on a horizontal card from the
+ * previous row.
+ * - Each triangle is placed in the leftmost available spot in the row.
+ *
+ * Return the number of distinct house of cards you can build using all n cards. Two houses of
+ * cards are considered distinct if there exists a row where the two houses contain a different
+ * number of cards.
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var houseOfCards = function(n) {
+ const dp = new Array(n + 1).fill(0);
+ dp[0] = 1;
+
+ for (let i = 2; i <= n; i += 3) {
+ for (let j = n; j >= i; j--) {
+ dp[j] += dp[j - i];
+ }
+ }
+
+ return dp[n];
+};
From d70bf28481fd8f08fa07f62cf9a095c8c3ba3dc5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 7 Jul 2025 23:20:29 -0500
Subject: [PATCH 734/994] Add solution #2198
---
README.md | 1 +
.../2198-number-of-single-divisor-triplets.js | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/2198-number-of-single-divisor-triplets.js
diff --git a/README.md b/README.md
index 71fa88cd..55f84833 100644
--- a/README.md
+++ b/README.md
@@ -1986,6 +1986,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|
+2198|[Number of Single Divisor Triplets](./solutions/2198-number-of-single-divisor-triplets.js)|Medium|
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|
diff --git a/solutions/2198-number-of-single-divisor-triplets.js b/solutions/2198-number-of-single-divisor-triplets.js
new file mode 100644
index 00000000..b3513233
--- /dev/null
+++ b/solutions/2198-number-of-single-divisor-triplets.js
@@ -0,0 +1,50 @@
+/**
+ * 2198. Number of Single Divisor Triplets
+ * https://leetcode.com/problems/number-of-single-divisor-triplets/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array of positive integers nums. A triplet of three distinct
+ * indices (i, j, k) is called a single divisor triplet of nums if nums[i] + nums[j] + nums[k]
+ * is divisible by exactly one of nums[i], nums[j], or nums[k].
+ *
+ * Return the number of single divisor triplets of nums.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var singleDivisorTriplet = function(nums) {
+ let result = 0;
+ const count = new Array(101).fill(0);
+
+ for (const num of nums) {
+ count[num]++;
+ }
+
+ for (let i = 1; i <= 100; i++) {
+ if (!count[i]) continue;
+ for (let j = i; j <= 100; j++) {
+ if (!count[j]) continue;
+ for (let k = j + (i === j ? 1 : 0); k <= 100; k++) {
+ if (!count[k]) continue;
+
+ const sum = i + j + k;
+ const divisors = (sum % i === 0 ? 1 : 0)
+ + (sum % j === 0 ? 1 : 0) + (sum % k === 0 ? 1 : 0);
+
+ if (divisors === 1) {
+ if (i === j) {
+ result += count[i] * (count[i] - 1) / 2 * count[k];
+ } else if (j === k) {
+ result += count[i] * count[j] * (count[j] - 1) / 2;
+ } else {
+ result += count[i] * count[j] * count[k];
+ }
+ }
+ }
+ }
+ }
+
+ return result * 6;
+};
From d137056b5633513b24b0eb02ca50efa244ec2571 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 7 Jul 2025 23:22:25 -0500
Subject: [PATCH 735/994] Add solution #2204
---
README.md | 1 +
...distance-to-a-cycle-in-undirected-graph.js | 71 +++++++++++++++++++
2 files changed, 72 insertions(+)
create mode 100644 solutions/2204-distance-to-a-cycle-in-undirected-graph.js
diff --git a/README.md b/README.md
index 55f84833..59a19d95 100644
--- a/README.md
+++ b/README.md
@@ -1991,6 +1991,7 @@
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|
+2204|[Distance to a Cycle in Undirected Graph](./solutions/2204-distance-to-a-cycle-in-undirected-graph.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|
diff --git a/solutions/2204-distance-to-a-cycle-in-undirected-graph.js b/solutions/2204-distance-to-a-cycle-in-undirected-graph.js
new file mode 100644
index 00000000..42a48b77
--- /dev/null
+++ b/solutions/2204-distance-to-a-cycle-in-undirected-graph.js
@@ -0,0 +1,71 @@
+/**
+ * 2204. Distance to a Cycle in Undirected Graph
+ * https://leetcode.com/problems/distance-to-a-cycle-in-undirected-graph/
+ * Difficulty: Hard
+ *
+ * You are given a positive integer n representing the number of nodes in a connected undirected
+ * graph containing exactly one cycle. The nodes are numbered from 0 to n - 1 (inclusive).
+ *
+ * You are also given a 2D integer array edges, where edges[i] = [node1i, node2i] denotes that
+ * there is a bidirectional edge connecting node1i and node2i in the graph.
+ *
+ * The distance between two nodes a and b is defined to be the minimum number of edges that are
+ * needed to go from a to b.
+ *
+ * Return an integer array answer of size n, where answer[i] is the minimum distance between the
+ * ith node and any node in the cycle.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @return {number[]}
+ */
+var distanceToCycle = function(n, edges) {
+ const graph = Array.from({ length: n }, () => []);
+ const result = new Array(n).fill(0);
+ const degree = new Array(n).fill(0);
+ const queue = [];
+
+ for (const [u, v] of edges) {
+ graph[u].push(v);
+ graph[v].push(u);
+ }
+
+ for (let i = 0; i < n; i++) {
+ degree[i] = graph[i].length;
+ if (degree[i] === 1) {
+ queue.push(i);
+ }
+ }
+
+ while (queue.length > 0) {
+ const node = queue.shift();
+ result[node] = Infinity;
+
+ for (const neighbor of graph[node]) {
+ if (degree[neighbor] > 1 && --degree[neighbor] === 1) {
+ queue.push(neighbor);
+ }
+ }
+ }
+
+ for (let i = 0; i < n; i++) {
+ if (degree[i] > 1) {
+ queue.push(i);
+ }
+ }
+
+ while (queue.length > 0) {
+ const node = queue.shift();
+
+ for (const neighbor of graph[node]) {
+ if (result[neighbor] > result[node] + 1) {
+ result[neighbor] = result[node] + 1;
+ queue.push(neighbor);
+ }
+ }
+ }
+
+ return result;
+};
From ff4c1cf90b043fc9c8a43381798287f41a9444db Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 8 Jul 2025 23:33:56 -0500
Subject: [PATCH 736/994] Add solution #3439
---
README.md | 1 +
...hedule-meetings-for-maximum-free-time-i.js | 53 +++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/3439-reschedule-meetings-for-maximum-free-time-i.js
diff --git a/README.md b/README.md
index 59a19d95..db28fb4a 100644
--- a/README.md
+++ b/README.md
@@ -2518,6 +2518,7 @@
3403|[Find the Lexicographically Largest String From the Box I](./solutions/3403-find-the-lexicographically-largest-string-from-the-box-i.js)|Medium|
3405|[Count the Number of Arrays with K Matching Adjacent Elements](./solutions/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.js)|Hard|
3423|[Maximum Difference Between Adjacent Elements in a Circular Array](./solutions/3423-maximum-difference-between-adjacent-elements-in-a-circular-array.js)|Easy|
+3439|[Reschedule Meetings for Maximum Free Time I](./solutions/3439-reschedule-meetings-for-maximum-free-time-i.js)|Medium|
3442|[Maximum Difference Between Even and Odd Frequency I](./solutions/3442-maximum-difference-between-even-and-odd-frequency-i.js)|Easy|
3443|[Maximum Manhattan Distance After K Changes](./solutions/3443-maximum-manhattan-distance-after-k-changes.js)|Medium|
3445|[Maximum Difference Between Even and Odd Frequency II](./solutions/3445-maximum-difference-between-even-and-odd-frequency-ii.js)|Hard|
diff --git a/solutions/3439-reschedule-meetings-for-maximum-free-time-i.js b/solutions/3439-reschedule-meetings-for-maximum-free-time-i.js
new file mode 100644
index 00000000..fb667cc4
--- /dev/null
+++ b/solutions/3439-reschedule-meetings-for-maximum-free-time-i.js
@@ -0,0 +1,53 @@
+/**
+ * 3439. Reschedule Meetings for Maximum Free Time I
+ * https://leetcode.com/problems/reschedule-meetings-for-maximum-free-time-i/
+ * Difficulty: Medium
+ *
+ * You are given an integer eventTime denoting the duration of an event, where the event occurs
+ * from time t = 0 to time t = eventTime.
+ *
+ * You are also given two integer arrays startTime and endTime, each of length n. These represent
+ * the start and end time of n non-overlapping meetings, where the ith meeting occurs during the
+ * time [startTime[i], endTime[i]].
+ *
+ * You can reschedule at most k meetings by moving their start time while maintaining the same
+ * duration, to maximize the longest continuous period of free time during the event.
+ *
+ * The relative order of all the meetings should stay the same and they should remain
+ * non-overlapping.
+ *
+ * Return the maximum amount of free time possible after rearranging the meetings.
+ *
+ * Note that the meetings can not be rescheduled to a time outside the event.
+ */
+
+/**
+ * @param {number} eventTime
+ * @param {number} k
+ * @param {number[]} startTime
+ * @param {number[]} endTime
+ * @return {number}
+ */
+var maxFreeTime = function(eventTime, k, startTime, endTime) {
+ const n = startTime.length;
+ const gaps = new Array(n + 1);
+
+ gaps[0] = startTime[0];
+ gaps[n] = eventTime - endTime[n - 1];
+ for (let i = 1; i < n; i++) {
+ gaps[i] = startTime[i] - endTime[i - 1];
+ }
+
+ let window = 0;
+ for (let i = 0; i <= k; i++) {
+ window += gaps[i];
+ }
+
+ let result = window;
+ for (let i = k + 1; i <= n; i++) {
+ window += gaps[i] - gaps[i - (k + 1)];
+ result = Math.max(result, window);
+ }
+
+ return result;
+};
From 984174b697b567b9e26dbae2e256ca9598ea8564 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 8 Jul 2025 23:35:06 -0500
Subject: [PATCH 737/994] Add solution #2214
---
README.md | 1 +
solutions/2214-minimum-health-to-beat-game.js | 30 +++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 solutions/2214-minimum-health-to-beat-game.js
diff --git a/README.md b/README.md
index db28fb4a..e60ea5f1 100644
--- a/README.md
+++ b/README.md
@@ -1999,6 +1999,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|
2213|[Longest Substring of One Repeating Character](./solutions/2213-longest-substring-of-one-repeating-character.js)|Hard|
+2214|[Minimum Health to Beat Game](./solutions/2214-minimum-health-to-beat-game.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|
diff --git a/solutions/2214-minimum-health-to-beat-game.js b/solutions/2214-minimum-health-to-beat-game.js
new file mode 100644
index 00000000..48daf2f2
--- /dev/null
+++ b/solutions/2214-minimum-health-to-beat-game.js
@@ -0,0 +1,30 @@
+/**
+ * 2214. Minimum Health to Beat Game
+ * https://leetcode.com/problems/minimum-health-to-beat-game/
+ * Difficulty: Medium
+ *
+ * You are playing a game that has n levels numbered from 0 to n - 1. You are given a 0-indexed
+ * integer array damage where damage[i] is the amount of health you will lose to complete the
+ * ith level.
+ *
+ * You are also given an integer armor. You may use your armor ability at most once during the
+ * game on any level which will protect you from at most armor damage.
+ *
+ * You must complete the levels in order and your health must be greater than 0 at all times to
+ * beat the game.
+ *
+ * Return the minimum health you need to start with to beat the game.
+ */
+
+/**
+ * @param {number[]} damage
+ * @param {number} armor
+ * @return {number}
+ */
+var minimumHealth = function(damage, armor) {
+ const totalDamage = damage.reduce((sum, dmg) => sum + dmg, 0);
+ const maxDamage = Math.max(...damage);
+ const armorReduction = Math.min(armor, maxDamage);
+
+ return totalDamage - armorReduction + 1;
+};
From 9ee8d9957fcf546f9ad9c0dac13dbd038126a1c1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 8 Jul 2025 23:36:22 -0500
Subject: [PATCH 738/994] Add solution #2219
---
README.md | 1 +
solutions/2219-maximum-sum-score-of-array.js | 33 ++++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/2219-maximum-sum-score-of-array.js
diff --git a/README.md b/README.md
index e60ea5f1..882cf17f 100644
--- a/README.md
+++ b/README.md
@@ -2004,6 +2004,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|
2218|[Maximum Value of K Coins From Piles](./solutions/2218-maximum-value-of-k-coins-from-piles.js)|Hard|
+2219|[Maximum Sum Score of Array](./solutions/2219-maximum-sum-score-of-array.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|
diff --git a/solutions/2219-maximum-sum-score-of-array.js b/solutions/2219-maximum-sum-score-of-array.js
new file mode 100644
index 00000000..4377053e
--- /dev/null
+++ b/solutions/2219-maximum-sum-score-of-array.js
@@ -0,0 +1,33 @@
+/**
+ * 2219. Maximum Sum Score of Array
+ * https://leetcode.com/problems/maximum-sum-score-of-array/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums of length n.
+ *
+ * The sum score of nums at an index i where 0 <= i < n is the maximum of:
+ * - The sum of the first i + 1 elements of nums.
+ * - The sum of the last n - i elements of nums.
+ *
+ * Return the maximum sum score of nums at any index.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maximumSumScore = function(nums) {
+ const n = nums.length;
+ const totalSum = nums.reduce((sum, num) => sum + num, 0);
+ let prefixSum = 0;
+ let maxScore = -Infinity;
+
+ for (let i = 0; i < n; i++) {
+ prefixSum += nums[i];
+ const suffixSum = totalSum - prefixSum + nums[i];
+ const score = Math.max(prefixSum, suffixSum);
+ maxScore = Math.max(maxScore, score);
+ }
+
+ return maxScore;
+};
From 2da0c5e1f167d9bc8913748004e236f75e6fb2bc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 8 Jul 2025 23:37:30 -0500
Subject: [PATCH 739/994] Add solution #2229
---
README.md | 1 +
.../2229-check-if-an-array-is-consecutive.js | 28 +++++++++++++++++++
2 files changed, 29 insertions(+)
create mode 100644 solutions/2229-check-if-an-array-is-consecutive.js
diff --git a/README.md b/README.md
index 882cf17f..39b508b6 100644
--- a/README.md
+++ b/README.md
@@ -2013,6 +2013,7 @@
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|
+2229|[Check if an Array Is Consecutive](./solutions/2229-check-if-an-array-is-consecutive.js)|Easy|
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|
diff --git a/solutions/2229-check-if-an-array-is-consecutive.js b/solutions/2229-check-if-an-array-is-consecutive.js
new file mode 100644
index 00000000..6e03f23a
--- /dev/null
+++ b/solutions/2229-check-if-an-array-is-consecutive.js
@@ -0,0 +1,28 @@
+/**
+ * 2229. Check if an Array Is Consecutive
+ * https://leetcode.com/problems/check-if-an-array-is-consecutive/
+ * Difficulty: Easy
+ *
+ * Given an integer array nums, return true if nums is consecutive, otherwise return false.
+ *
+ * An array is consecutive if it contains every number in the range [x, x + n - 1] (inclusive),
+ * where x is the minimum number in the array and n is the length of the array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {boolean}
+ */
+var isConsecutive = function(nums) {
+ const set = new Set(nums);
+ if (set.size !== nums.length) return false;
+
+ const minNum = Math.min(...nums);
+ for (let i = 0; i < nums.length; i++) {
+ if (!set.has(minNum + i)) {
+ return false;
+ }
+ }
+
+ return true;
+};
From 6b9aa9700843f388a9ec6096cdc7c130f8403b04 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 8 Jul 2025 23:38:52 -0500
Subject: [PATCH 740/994] Add solution #2237
---
README.md | 1 +
...ions-on-street-with-required-brightness.js | 48 +++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/2237-count-positions-on-street-with-required-brightness.js
diff --git a/README.md b/README.md
index 39b508b6..51cb1eca 100644
--- a/README.md
+++ b/README.md
@@ -2018,6 +2018,7 @@
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|
+2237|[Count Positions on Street With Required Brightness](./solutions/2237-count-positions-on-street-with-required-brightness.js)|Medium|
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|
diff --git a/solutions/2237-count-positions-on-street-with-required-brightness.js b/solutions/2237-count-positions-on-street-with-required-brightness.js
new file mode 100644
index 00000000..32653575
--- /dev/null
+++ b/solutions/2237-count-positions-on-street-with-required-brightness.js
@@ -0,0 +1,48 @@
+/**
+ * 2237. Count Positions on Street With Required Brightness
+ * https://leetcode.com/problems/count-positions-on-street-with-required-brightness/
+ * Difficulty: Medium
+ *
+ * You are given an integer n. A perfectly straight street is represented by a number line
+ * ranging from 0 to n - 1. You are given a 2D integer array lights representing the street
+ * lamp(s) on the street. Each lights[i] = [positioni, rangei] indicates that there is a
+ * street lamp at position positioni that lights up the area from
+ * [max(0, positioni - rangei), min(n - 1, positioni + rangei)] (inclusive).
+ *
+ * The brightness of a position p is defined as the number of street lamps that light up the
+ * position p. You are given a 0-indexed integer array requirement of size n where
+ * requirement[i] is the minimum brightness of the ith position on the street.
+ *
+ * Return the number of positions i on the street between 0 and n - 1 that have a brightness
+ * of at least requirement[i].
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} lights
+ * @param {number[]} requirement
+ * @return {number}
+ */
+var meetRequirement = function(n, lights, requirement) {
+ const brightness = new Array(n).fill(0);
+ for (const [position, range] of lights) {
+ const start = Math.max(0, position - range);
+ const end = Math.min(n - 1, position + range);
+
+ brightness[start]++;
+ if (end + 1 < n) {
+ brightness[end + 1]--;
+ }
+ }
+
+ let currentBrightness = 0;
+ let result = 0;
+ for (let i = 0; i < n; i++) {
+ currentBrightness += brightness[i];
+ if (currentBrightness >= requirement[i]) {
+ result++;
+ }
+ }
+
+ return result;
+};
From 7fdb51462ebd978a51d46a7016d58d4133906785 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 9 Jul 2025 22:37:03 -0500
Subject: [PATCH 741/994] Add solution #3440
---
README.md | 1 +
...edule-meetings-for-maximum-free-time-ii.js | 57 +++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/3440-reschedule-meetings-for-maximum-free-time-ii.js
diff --git a/README.md b/README.md
index 51cb1eca..194faef3 100644
--- a/README.md
+++ b/README.md
@@ -2523,6 +2523,7 @@
3405|[Count the Number of Arrays with K Matching Adjacent Elements](./solutions/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.js)|Hard|
3423|[Maximum Difference Between Adjacent Elements in a Circular Array](./solutions/3423-maximum-difference-between-adjacent-elements-in-a-circular-array.js)|Easy|
3439|[Reschedule Meetings for Maximum Free Time I](./solutions/3439-reschedule-meetings-for-maximum-free-time-i.js)|Medium|
+3440|[Reschedule Meetings for Maximum Free Time II](./solutions/3440-reschedule-meetings-for-maximum-free-time-ii.js)|Medium|
3442|[Maximum Difference Between Even and Odd Frequency I](./solutions/3442-maximum-difference-between-even-and-odd-frequency-i.js)|Easy|
3443|[Maximum Manhattan Distance After K Changes](./solutions/3443-maximum-manhattan-distance-after-k-changes.js)|Medium|
3445|[Maximum Difference Between Even and Odd Frequency II](./solutions/3445-maximum-difference-between-even-and-odd-frequency-ii.js)|Hard|
diff --git a/solutions/3440-reschedule-meetings-for-maximum-free-time-ii.js b/solutions/3440-reschedule-meetings-for-maximum-free-time-ii.js
new file mode 100644
index 00000000..6e7d301d
--- /dev/null
+++ b/solutions/3440-reschedule-meetings-for-maximum-free-time-ii.js
@@ -0,0 +1,57 @@
+/**
+ * 3440. Reschedule Meetings for Maximum Free Time II
+ * https://leetcode.com/problems/reschedule-meetings-for-maximum-free-time-ii/
+ * Difficulty: Medium
+ *
+ * You are given an integer eventTime denoting the duration of an event. You are also given two
+ * integer arrays startTime and endTime, each of length n.
+ *
+ * These represent the start and end times of n non-overlapping meetings that occur during the
+ * event between time t = 0 and time t = eventTime, where the ith meeting occurs during the time
+ * [startTime[i], endTime[i]].
+ *
+ * You can reschedule at most one meeting by moving its start time while maintaining the same
+ * duration, such that the meetings remain non-overlapping, to maximize the longest continuous
+ * period of free time during the event.
+ *
+ * Return the maximum amount of free time possible after rearranging the meetings.
+ *
+ * Note that the meetings can not be rescheduled to a time outside the event and they should
+ * remain non-overlapping.
+ *
+ * Note: In this version, it is valid for the relative ordering of the meetings to change after
+ * rescheduling one meeting.
+ */
+
+/**
+ * @param {number} eventTime
+ * @param {number[]} startTime
+ * @param {number[]} endTime
+ * @return {number}
+ */
+var maxFreeTime = function(eventTime, startTime, endTime) {
+ const gap = [startTime[0]];
+ for (let i = 1; i < startTime.length; i++) {
+ gap.push(startTime[i] - endTime[i - 1]);
+ }
+ gap.push(eventTime - endTime[endTime.length - 1]);
+
+ const largestRight = new Array(gap.length).fill(0);
+ for (let i = gap.length - 2; i >= 0; i--) {
+ largestRight[i] = Math.max(largestRight[i + 1], gap[i + 1]);
+ }
+
+ let result = 0;
+ let largestLeft = 0;
+
+ for (let i = 1; i < gap.length; i++) {
+ const currentGap = endTime[i - 1] - startTime[i - 1];
+ if (currentGap <= Math.max(largestLeft, largestRight[i])) {
+ result = Math.max(result, gap[i - 1] + gap[i] + currentGap);
+ }
+ result = Math.max(result, gap[i - 1] + gap[i]);
+ largestLeft = Math.max(largestLeft, gap[i - 1]);
+ }
+
+ return result;
+};
From 61347e5f7cbb8bae19771e7f8203462379607d9e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 9 Jul 2025 22:39:32 -0500
Subject: [PATCH 742/994] Add solution #2247
---
README.md | 1 +
...47-maximum-cost-of-trip-with-k-highways.js | 61 +++++++++++++++++++
2 files changed, 62 insertions(+)
create mode 100644 solutions/2247-maximum-cost-of-trip-with-k-highways.js
diff --git a/README.md b/README.md
index 194faef3..e9621ac2 100644
--- a/README.md
+++ b/README.md
@@ -2027,6 +2027,7 @@
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|
+2247|[Maximum Cost of Trip With K Highways](./solutions/2247-maximum-cost-of-trip-with-k-highways.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|
diff --git a/solutions/2247-maximum-cost-of-trip-with-k-highways.js b/solutions/2247-maximum-cost-of-trip-with-k-highways.js
new file mode 100644
index 00000000..1852369a
--- /dev/null
+++ b/solutions/2247-maximum-cost-of-trip-with-k-highways.js
@@ -0,0 +1,61 @@
+/**
+ * 2247. Maximum Cost of Trip With K Highways
+ * https://leetcode.com/problems/maximum-cost-of-trip-with-k-highways/
+ * Difficulty: Hard
+ *
+ * A series of highways connect n cities numbered from 0 to n - 1. You are given a 2D integer array
+ * highways where highways[i] = [city1i, city2i, tolli] indicates that there is a highway that
+ * connects city1i and city2i, allowing a car to go from city1i to city2i and vice versa for a cost
+ * of tolli.
+ *
+ * You are also given an integer k. You are going on a trip that crosses exactly k highways. You
+ * may start at any city, but you may only visit each city at most once during your trip.
+ *
+ * Return the maximum cost of your trip. If there is no trip that meets the requirements, return -1.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} highways
+ * @param {number} k
+ * @return {number}
+ */
+var maximumCost = function(n, highways, k) {
+ if (k + 1 > n) return -1;
+
+ const graph = Array(n).fill().map(() => []);
+ for (const [cityA, cityB, cost] of highways) {
+ graph[cityA].push([cityB, cost]);
+ graph[cityB].push([cityA, cost]);
+ }
+
+ const memo = new Map();
+ let result = -1;
+
+ for (let city = 0; city < n; city++) {
+ result = Math.max(result, dp(city, 1 << city));
+ }
+
+ return result;
+
+ function dp(city, bitmask) {
+ const citiesVisited = bitmask.toString(2).split('1').length - 1;
+ if (citiesVisited === k + 1) return 0;
+
+ const key = `${city}_${bitmask}`;
+ if (memo.has(key)) return memo.get(key);
+
+ let answer = -1;
+ for (const [neighborCity, highwayCost] of graph[city]) {
+ if (!((bitmask >> neighborCity) & 1)) {
+ const neighborAnswer = dp(neighborCity, bitmask | (1 << neighborCity));
+ if (neighborAnswer !== -1) {
+ answer = Math.max(answer, highwayCost + neighborAnswer);
+ }
+ }
+ }
+
+ memo.set(key, answer);
+ return answer;
+ }
+};
From 698da0df0b465a7e0698836d74d504fa97dd4497 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 9 Jul 2025 22:44:23 -0500
Subject: [PATCH 743/994] Add solution #2254
---
README.md | 1 +
.../2254-design-video-sharing-platform.js | 138 ++++++++++++++++++
2 files changed, 139 insertions(+)
create mode 100644 solutions/2254-design-video-sharing-platform.js
diff --git a/README.md b/README.md
index e9621ac2..10c154bd 100644
--- a/README.md
+++ b/README.md
@@ -2032,6 +2032,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|
+2254|[Design Video Sharing Platform](./solutions/2254-design-video-sharing-platform.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|
diff --git a/solutions/2254-design-video-sharing-platform.js b/solutions/2254-design-video-sharing-platform.js
new file mode 100644
index 00000000..c3e6e9fa
--- /dev/null
+++ b/solutions/2254-design-video-sharing-platform.js
@@ -0,0 +1,138 @@
+/**
+ * 2254. Design Video Sharing Platform
+ * https://leetcode.com/problems/design-video-sharing-platform/
+ * Difficulty: Hard
+ *
+ * You have a video sharing platform where users can upload and delete videos. Each video is a
+ * string of digits, where the ith digit of the string represents the content of the video at
+ * minute i. For example, the first digit represents the content at minute 0 in the video, the
+ * second digit represents the content at minute 1 in the video, and so on. Viewers of videos
+ * can also like and dislike videos. Internally, the platform keeps track of the number of views,
+ * likes, and dislikes on each video.
+ *
+ * When a video is uploaded, it is associated with the smallest available integer videoId starting
+ * from 0. Once a video is deleted, the videoId associated with that video can be reused for
+ * another video.
+ *
+ * Implement the VideoSharingPlatform class:
+ * - VideoSharingPlatform() Initializes the object.
+ * - int upload(String video) The user uploads a video. Return the videoId associated with
+ * the video.
+ * - void remove(int videoId) If there is a video associated with videoId, remove the video.
+ * - String watch(int videoId, int startMinute, int endMinute) If there is a video associated with
+ * videoId, increase the number of views on the video by 1 and return the substring of the video
+ * string starting at startMinute and ending at min(endMinute, video.length - 1) (inclusive).
+ * Otherwise, return "-1".
+ * - void like(int videoId) Increases the number of likes on the video associated with videoId by 1
+ * if there is a video associated with videoId.
+ * - void dislike(int videoId) Increases the number of dislikes on the video associated with videoId
+ * by 1 if there is a video associated with videoId.
+ * - int[] getLikesAndDislikes(int videoId) Return a 0-indexed integer array values of length 2
+ * where values[0] is the number of likes and values[1] is the number of dislikes on the video
+ * associated with videoId. If there is no video associated with videoId, return [-1].
+ * - int getViews(int videoId) Return the number of views on the video associated with videoId, if
+ * there is no video associated with videoId, return -1.
+ */
+
+var VideoSharingPlatform = function() {
+ this.videos = new Map();
+ this.availableIds = [];
+ this.nextId = 0;
+};
+
+/**
+ * @param {string} video
+ * @return {number}
+ */
+VideoSharingPlatform.prototype.upload = function(video) {
+ let videoId;
+ if (this.availableIds.length > 0) {
+ videoId = this.availableIds.shift();
+ } else {
+ videoId = this.nextId++;
+ }
+
+ this.videos.set(videoId, {
+ content: video,
+ views: 0,
+ likes: 0,
+ dislikes: 0
+ });
+
+ return videoId;
+};
+
+/**
+ * @param {number} videoId
+ * @return {void}
+ */
+VideoSharingPlatform.prototype.remove = function(videoId) {
+ if (this.videos.has(videoId)) {
+ this.videos.delete(videoId);
+ this.availableIds.push(videoId);
+ this.availableIds.sort((a, b) => a - b);
+ }
+};
+
+/**
+ * @param {number} videoId
+ * @param {number} startMinute
+ * @param {number} endMinute
+ * @return {string}
+ */
+VideoSharingPlatform.prototype.watch = function(videoId, startMinute, endMinute) {
+ if (!this.videos.has(videoId)) {
+ return '-1';
+ }
+
+ const videoData = this.videos.get(videoId);
+ videoData.views++;
+
+ const actualEndMinute = Math.min(endMinute, videoData.content.length - 1);
+ return videoData.content.substring(startMinute, actualEndMinute + 1);
+};
+
+/**
+ * @param {number} videoId
+ * @return {void}
+ */
+VideoSharingPlatform.prototype.like = function(videoId) {
+ if (this.videos.has(videoId)) {
+ this.videos.get(videoId).likes++;
+ }
+};
+
+/**
+ * @param {number} videoId
+ * @return {void}
+ */
+VideoSharingPlatform.prototype.dislike = function(videoId) {
+ if (this.videos.has(videoId)) {
+ this.videos.get(videoId).dislikes++;
+ }
+};
+
+/**
+ * @param {number} videoId
+ * @return {number[]}
+ */
+VideoSharingPlatform.prototype.getLikesAndDislikes = function(videoId) {
+ if (!this.videos.has(videoId)) {
+ return [-1];
+ }
+
+ const videoData = this.videos.get(videoId);
+ return [videoData.likes, videoData.dislikes];
+};
+
+/**
+ * @param {number} videoId
+ * @return {number}
+ */
+VideoSharingPlatform.prototype.getViews = function(videoId) {
+ if (!this.videos.has(videoId)) {
+ return -1;
+ }
+
+ return this.videos.get(videoId).views;
+};
From 8e676aed5e8eec63deae4880a6c26a3dbc462c08 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 9 Jul 2025 22:46:05 -0500
Subject: [PATCH 744/994] Add solution #2263
---
README.md | 1 +
...-array-non-decreasing-or-non-increasing.js | 45 +++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/2263-make-array-non-decreasing-or-non-increasing.js
diff --git a/README.md b/README.md
index 10c154bd..f97b5847 100644
--- a/README.md
+++ b/README.md
@@ -2041,6 +2041,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|
+2263|[Make Array Non-decreasing or Non-increasing](./solutions/2263-make-array-non-decreasing-or-non-increasing.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|
diff --git a/solutions/2263-make-array-non-decreasing-or-non-increasing.js b/solutions/2263-make-array-non-decreasing-or-non-increasing.js
new file mode 100644
index 00000000..68cf2296
--- /dev/null
+++ b/solutions/2263-make-array-non-decreasing-or-non-increasing.js
@@ -0,0 +1,45 @@
+/**
+ * 2263. Make Array Non-decreasing or Non-increasing
+ * https://leetcode.com/problems/make-array-non-decreasing-or-non-increasing/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed integer array nums. In one operation, you can:
+ * - Choose an index i in the range 0 <= i < nums.length
+ * - Set nums[i] to nums[i] + 1 or nums[i] - 1
+ *
+ * Return the minimum number of operations to make nums non-decreasing or non-increasing.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var convertArray = function(nums) {
+ const levels = [...new Set(nums)].sort((a, b) => a - b);
+ const reversedNums = [...nums].reverse();
+
+ return Math.min(helper(nums, levels), helper(reversedNums, levels));
+
+ function helper(arr, levels) {
+ const dp = new Map();
+ for (const level of levels) {
+ dp.set(level, 0);
+ }
+
+ for (const num of arr) {
+ let currentResult = Infinity;
+ const newDp = new Map();
+
+ for (const level of levels) {
+ currentResult = Math.min(currentResult, dp.get(level) + Math.abs(num - level));
+ newDp.set(level, currentResult);
+ }
+
+ for (const [level, value] of newDp) {
+ dp.set(level, value);
+ }
+ }
+
+ return dp.get(Math.max(...levels));
+ }
+};
From cdd0a66d4216b816bc290ec10c8fc5920cfc2dfa Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 9 Jul 2025 22:47:46 -0500
Subject: [PATCH 745/994] Add solution #2268
---
README.md | 1 +
.../2268-minimum-number-of-keypresses.js | 40 +++++++++++++++++++
2 files changed, 41 insertions(+)
create mode 100644 solutions/2268-minimum-number-of-keypresses.js
diff --git a/README.md b/README.md
index f97b5847..4ef7cec3 100644
--- a/README.md
+++ b/README.md
@@ -2046,6 +2046,7 @@
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|
+2268|[Minimum Number of Keypresses](./solutions/2268-minimum-number-of-keypresses.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|
2271|[Maximum White Tiles Covered by a Carpet](./solutions/2271-maximum-white-tiles-covered-by-a-carpet.js)|Medium|
diff --git a/solutions/2268-minimum-number-of-keypresses.js b/solutions/2268-minimum-number-of-keypresses.js
new file mode 100644
index 00000000..51145e7e
--- /dev/null
+++ b/solutions/2268-minimum-number-of-keypresses.js
@@ -0,0 +1,40 @@
+/**
+ * 2268. Minimum Number of Keypresses
+ * https://leetcode.com/problems/minimum-number-of-keypresses/
+ * Difficulty: Medium
+ *
+ * You have a keypad with 9 buttons, numbered from 1 to 9, each mapped to lowercase English
+ * letters. You can choose which characters each button is matched to as long as:
+ * - All 26 lowercase English letters are mapped to.
+ * - Each character is mapped to by exactly 1 button.
+ * - Each button maps to at most 3 characters.
+ *
+ * To type the first character matched to a button, you press the button once. To type the
+ * second character, you press the button twice, and so on.
+ *
+ * Given a string s, return the minimum number of keypresses needed to type s using your keypad.
+ *
+ * Note that the characters mapped to by each button, and the order they are mapped in cannot
+ * be changed.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var minimumKeypresses = function(s) {
+ const frequency = new Map();
+ for (const char of s) {
+ frequency.set(char, (frequency.get(char) || 0) + 1);
+ }
+
+ const frequencies = Array.from(frequency.values()).sort((a, b) => b - a);
+
+ let keypresses = 0;
+ for (let i = 0; i < frequencies.length; i++) {
+ const pressesPerChar = Math.floor(i / 9) + 1;
+ keypresses += frequencies[i] * pressesPerChar;
+ }
+
+ return keypresses;
+};
From 84b992a4819699636196fba8611e881c68e1bb42 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 10 Jul 2025 22:26:49 -0500
Subject: [PATCH 746/994] Add solution #2402
---
README.md | 1 +
solutions/2402-meeting-rooms-iii.js | 66 +++++++++++++++++++++++++++++
2 files changed, 67 insertions(+)
create mode 100644 solutions/2402-meeting-rooms-iii.js
diff --git a/README.md b/README.md
index 4ef7cec3..4c54a5a5 100644
--- a/README.md
+++ b/README.md
@@ -2131,6 +2131,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|
+2402|[Meeting Rooms III](./solutions/2402-meeting-rooms-iii.js)|Hard|
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|
diff --git a/solutions/2402-meeting-rooms-iii.js b/solutions/2402-meeting-rooms-iii.js
new file mode 100644
index 00000000..1be391aa
--- /dev/null
+++ b/solutions/2402-meeting-rooms-iii.js
@@ -0,0 +1,66 @@
+/**
+ * 2402. Meeting Rooms III
+ * https://leetcode.com/problems/meeting-rooms-iii/
+ * Difficulty: Hard
+ *
+ * You are given an integer n. There are n rooms numbered from 0 to n - 1.
+ *
+ * You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that
+ * a meeting will be held during the half-closed time interval [starti, endi). All the values
+ * of starti are unique.
+ *
+ * Meetings are allocated to rooms in the following manner:
+ * 1. Each meeting will take place in the unused room with the lowest number.
+ * 2. If there are no available rooms, the meeting will be delayed until a room becomes free.
+ * The delayed meeting should have the same duration as the original meeting.
+ * 3. When a room becomes unused, meetings that have an earlier original start time should be
+ * given the room.
+ *
+ * Return the number of the room that held the most meetings. If there are multiple rooms,
+ * return the room with the lowest number.
+ *
+ * A half-closed interval [a, b) is the interval between a and b including a and not including b.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} meetings
+ * @return {number}
+ */
+var mostBooked = function(n, meetings) {
+ meetings.sort((a, b) => a[0] - b[0]);
+
+ const roomCount = new Array(n).fill(0);
+ const availableRooms = [];
+ const occupiedRooms = [];
+ for (let i = 0; i < n; i++) {
+ availableRooms.push(i);
+ }
+
+ for (const [start, end] of meetings) {
+ while (occupiedRooms.length > 0 && occupiedRooms[0][0] <= start) {
+ const [endTime, roomNumber] = occupiedRooms.shift();
+ availableRooms.push(roomNumber);
+ availableRooms.sort((a, b) => a - b);
+ }
+
+ let assignedRoom;
+ let meetingEnd;
+
+ if (availableRooms.length > 0) {
+ assignedRoom = availableRooms.shift();
+ meetingEnd = end;
+ } else {
+ const [earliestEndTime, roomNumber] = occupiedRooms.shift();
+ assignedRoom = roomNumber;
+ meetingEnd = earliestEndTime + (end - start);
+ }
+
+ roomCount[assignedRoom]++;
+ occupiedRooms.push([meetingEnd, assignedRoom]);
+ occupiedRooms.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]);
+ }
+
+ const maxMeetings = Math.max(...roomCount);
+ return roomCount.indexOf(maxMeetings);
+};
From 610e8e8533ef492748c7e5948e2a34cfe5651d6c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 10 Jul 2025 23:05:46 -0500
Subject: [PATCH 747/994] Add solution #2277
---
README.md | 1 +
.../2277-closest-node-to-path-in-tree.js | 79 +++++++++++++++++++
2 files changed, 80 insertions(+)
create mode 100644 solutions/2277-closest-node-to-path-in-tree.js
diff --git a/README.md b/README.md
index 4c54a5a5..57606a12 100644
--- a/README.md
+++ b/README.md
@@ -2054,6 +2054,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|
+2277|[Closest Node to Path in Tree](./solutions/2277-closest-node-to-path-in-tree.js)|Hard|
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|
diff --git a/solutions/2277-closest-node-to-path-in-tree.js b/solutions/2277-closest-node-to-path-in-tree.js
new file mode 100644
index 00000000..642b68e6
--- /dev/null
+++ b/solutions/2277-closest-node-to-path-in-tree.js
@@ -0,0 +1,79 @@
+/**
+ * 2277. Closest Node to Path in Tree
+ * https://leetcode.com/problems/closest-node-to-path-in-tree/
+ * Difficulty: Hard
+ *
+ * You are given a positive integer n representing the number of nodes in a tree, numbered
+ * from 0 to n - 1 (inclusive). You are also given a 2D integer array edges of length n - 1,
+ * where edges[i] = [node1i, node2i] denotes that there is a bidirectional edge connecting
+ * node1i and node2i in the tree.
+ *
+ * You are given a 0-indexed integer array query of length m where query[i] = [starti, endi, nodei]
+ * means that for the ith query, you are tasked with finding the node on the path from starti to
+ * endi that is closest to nodei.
+ *
+ * Return an integer array answer of length m, where answer[i] is the answer to the ith query.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @param {number[][]} query
+ * @return {number[]}
+ */
+var closestNode = function(n, edges, query) {
+ const graph = new Array(n).fill().map(() => []);
+ for (const [a, b] of edges) {
+ graph[a].push(b);
+ graph[b].push(a);
+ }
+
+ const depths = new Array(n).fill(0);
+ const binaryParents = new Array(n).fill().map(() => new Array(16).fill(0));
+
+ dfs(0, [], 0);
+
+ return query.map(([a, b, q]) => {
+ const candidates = [lca(a, b), lca(a, q), lca(b, q)];
+ return candidates.reduce((deepest, current) =>
+ depths[current] > depths[deepest] ? current : deepest
+ );
+ });
+
+ function dfs(node, parents, depth) {
+ depths[node] = depth;
+ for (let bit = 0; bit < 16; bit++) {
+ if ((1 << bit) <= parents.length) {
+ binaryParents[node][bit] = parents[parents.length - (1 << bit)];
+ }
+ }
+ parents.push(node);
+ for (const next of graph[node]) {
+ if (parents.length >= 2 && next === parents[parents.length - 2]) {
+ continue;
+ }
+ dfs(next, parents, depth + 1);
+ }
+ parents.pop();
+ }
+
+ function getKthParent(node, k) {
+ if (!k) return node;
+ let bit = 0;
+ while ((1 << (bit + 1)) <= k) bit++;
+ return getKthParent(binaryParents[node][bit], k & (~(1 << bit)));
+ }
+
+ function lca(a, b) {
+ if (depths[a] > depths[b]) return lca(b, a);
+ b = getKthParent(b, depths[b] - depths[a]);
+ if (a === b) return a;
+ for (let i = binaryParents[a].length - 1; i >= 0; i--) {
+ if (binaryParents[a][i] !== binaryParents[b][i]) {
+ a = binaryParents[a][i];
+ b = binaryParents[b][i];
+ }
+ }
+ return binaryParents[a][0];
+ }
+};
From 11c517f1b386d7db14b94a596e111b65e54b0829 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 10 Jul 2025 23:07:32 -0500
Subject: [PATCH 748/994] Add solution #2282
---
README.md | 1 +
...er-of-people-that-can-be-seen-in-a-grid.js | 64 +++++++++++++++++++
2 files changed, 65 insertions(+)
create mode 100644 solutions/2282-number-of-people-that-can-be-seen-in-a-grid.js
diff --git a/README.md b/README.md
index 57606a12..4e7b3ed0 100644
--- a/README.md
+++ b/README.md
@@ -2058,6 +2058,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|
2280|[Minimum Lines to Represent a Line Chart](./solutions/2280-minimum-lines-to-represent-a-line-chart.js)|Medium|
+2282|[Number of People That Can Be Seen in a Grid](./solutions/2282-number-of-people-that-can-be-seen-in-a-grid.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/2282-number-of-people-that-can-be-seen-in-a-grid.js b/solutions/2282-number-of-people-that-can-be-seen-in-a-grid.js
new file mode 100644
index 00000000..561f87be
--- /dev/null
+++ b/solutions/2282-number-of-people-that-can-be-seen-in-a-grid.js
@@ -0,0 +1,64 @@
+/**
+ * 2282. Number of People That Can Be Seen in a Grid
+ * https://leetcode.com/problems/number-of-people-that-can-be-seen-in-a-grid/
+ * Difficulty: Medium
+ *
+ * You are given an m x n 0-indexed 2D array of positive integers heights where heights[i][j]
+ * is the height of the person standing at position (i, j).
+ *
+ * A person standing at position (row1, col1) can see a person standing at position (row2, col2) if:
+ * - The person at (row2, col2) is to the right or below the person at (row1, col1). More formally,
+ * this means that either row1 == row2 and col1 < col2 or row1 < row2 and col1 == col2.
+ * - Everyone in between them is shorter than both of them.
+ *
+ * Return an m x n 2D array of integers answer where answer[i][j] is the number of people that the
+ * person at position (i, j) can see.
+ */
+
+/**
+ * @param {number[][]} heights
+ * @return {number[][]}
+ */
+var seePeople = function(heights) {
+ const rows = heights.length;
+ const cols = heights[0].length;
+ const result = new Array(rows).fill().map(() => new Array(cols).fill(0));
+
+ for (let i = 0; i < rows; i++) {
+ const stack = [];
+ for (let j = cols - 1; j >= 0; j--) {
+ let equal = false;
+ while (stack.length > 0 && stack[stack.length - 1] <= heights[i][j]) {
+ if (stack[stack.length - 1] === heights[i][j]) {
+ equal = true;
+ }
+ stack.pop();
+ result[i][j]++;
+ }
+ if (stack.length > 0 && !equal) {
+ result[i][j]++;
+ }
+ stack.push(heights[i][j]);
+ }
+ }
+
+ for (let j = 0; j < cols; j++) {
+ const stack = [];
+ for (let i = rows - 1; i >= 0; i--) {
+ let equal = false;
+ while (stack.length > 0 && stack[stack.length - 1] <= heights[i][j]) {
+ if (stack[stack.length - 1] === heights[i][j]) {
+ equal = true;
+ }
+ stack.pop();
+ result[i][j]++;
+ }
+ if (stack.length > 0 && !equal) {
+ result[i][j]++;
+ }
+ stack.push(heights[i][j]);
+ }
+ }
+
+ return result;
+};
From ce0ea86983476c888cb92d572041bcfcb344dcd2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 10 Jul 2025 23:08:30 -0500
Subject: [PATCH 749/994] Add solution #2291
---
README.md | 1 +
...2291-maximum-profit-from-trading-stocks.js | 35 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/2291-maximum-profit-from-trading-stocks.js
diff --git a/README.md b/README.md
index 4e7b3ed0..27eb19cd 100644
--- a/README.md
+++ b/README.md
@@ -2063,6 +2063,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|
2288|[Apply Discount to Prices](./solutions/2288-apply-discount-to-prices.js)|Medium|
+2291|[Maximum Profit From Trading Stocks](./solutions/2291-maximum-profit-from-trading-stocks.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/2291-maximum-profit-from-trading-stocks.js b/solutions/2291-maximum-profit-from-trading-stocks.js
new file mode 100644
index 00000000..5104bb18
--- /dev/null
+++ b/solutions/2291-maximum-profit-from-trading-stocks.js
@@ -0,0 +1,35 @@
+/**
+ * 2291. Maximum Profit From Trading Stocks
+ * https://leetcode.com/problems/maximum-profit-from-trading-stocks/
+ * Difficulty: Medium
+ *
+ * You are given two 0-indexed integer arrays of the same length present and future where
+ * present[i] is the current price of the ith stock and future[i] is the price of the ith
+ * stock a year in the future. You may buy each stock at most once. You are also given an
+ * integer budget representing the amount of money you currently have.
+ *
+ * Return the maximum amount of profit you can make.
+ */
+
+/**
+ * @param {number[]} present
+ * @param {number[]} future
+ * @param {number} budget
+ * @return {number}
+ */
+var maximumProfit = function(present, future, budget) {
+ const stocks = present.map((price, i) => ({
+ cost: price,
+ profit: future[i] - price
+ })).filter(stock => stock.profit > 0)
+ .sort((a, b) => b.profit - a.profit);
+
+ const dp = new Array(budget + 1).fill(0);
+ for (const stock of stocks) {
+ for (let money = budget; money >= stock.cost; money--) {
+ dp[money] = Math.max(dp[money], dp[money - stock.cost] + stock.profit);
+ }
+ }
+
+ return dp[budget];
+};
From 38042a69b88f40ec6468ee2c0d2e25a2ba8cde1b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 10 Jul 2025 23:09:41 -0500
Subject: [PATCH 750/994] Add solution #2297
---
README.md | 1 +
solutions/2297-jump-game-viii.js | 47 ++++++++++++++++++++++++++++++++
2 files changed, 48 insertions(+)
create mode 100644 solutions/2297-jump-game-viii.js
diff --git a/README.md b/README.md
index 27eb19cd..817310de 100644
--- a/README.md
+++ b/README.md
@@ -2068,6 +2068,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|
+2297|[Jump Game VIII](./solutions/2297-jump-game-viii.js)|Medium|
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|
diff --git a/solutions/2297-jump-game-viii.js b/solutions/2297-jump-game-viii.js
new file mode 100644
index 00000000..954e9614
--- /dev/null
+++ b/solutions/2297-jump-game-viii.js
@@ -0,0 +1,47 @@
+/**
+ * 2297. Jump Game VIII
+ * https://leetcode.com/problems/jump-game-viii/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums of length n. You are initially standing at index 0.
+ * You can jump from index i to index j where i < j if:
+ * - nums[i] <= nums[j] and nums[k] < nums[i] for all indexes k in the range i < k < j, or
+ * - nums[i] > nums[j] and nums[k] >= nums[i] for all indexes k in the range i < k < j.
+ *
+ * You are also given an integer array costs of length n where costs[i] denotes the cost of jumping
+ * to index i.
+ *
+ * Return the minimum cost to jump to the index n - 1.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[]} costs
+ * @return {number}
+ */
+var minCost = function(nums, costs) {
+ const n = nums.length;
+ const dp = new Array(n).fill(Infinity);
+ dp[0] = 0;
+
+ const increasingStack = [];
+ const decreasingStack = [];
+ for (let i = 0; i < n; i++) {
+ while (increasingStack.length > 0
+ && nums[increasingStack[increasingStack.length - 1]] > nums[i]) {
+ const j = increasingStack.pop();
+ dp[i] = Math.min(dp[i], dp[j] + costs[i]);
+ }
+
+ while (decreasingStack.length > 0
+ && nums[decreasingStack[decreasingStack.length - 1]] <= nums[i]) {
+ const j = decreasingStack.pop();
+ dp[i] = Math.min(dp[i], dp[j] + costs[i]);
+ }
+
+ increasingStack.push(i);
+ decreasingStack.push(i);
+ }
+
+ return dp[n - 1];
+};
From 0c962d502e4e38a8a74825cf609320e7c7bef841 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 10 Jul 2025 23:13:19 -0500
Subject: [PATCH 751/994] Add solution #2307
---
README.md | 1 +
...7-check-for-contradictions-in-equations.js | 62 +++++++++++++++++++
2 files changed, 63 insertions(+)
create mode 100644 solutions/2307-check-for-contradictions-in-equations.js
diff --git a/README.md b/README.md
index 817310de..0a24d7c8 100644
--- a/README.md
+++ b/README.md
@@ -2077,6 +2077,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|
+2307|[Check for Contradictions in Equations](./solutions/2307-check-for-contradictions-in-equations.js)|Hard|
2309|[Greatest English Letter in Upper and Lower Case](./solutions/2309-greatest-english-letter-in-upper-and-lower-case.js)|Easy|
2311|[Longest Binary Subsequence Less Than or Equal to K](./solutions/2311-longest-binary-subsequence-less-than-or-equal-to-k.js)|Medium|
2312|[Selling Pieces of Wood](./solutions/2312-selling-pieces-of-wood.js)|Hard|
diff --git a/solutions/2307-check-for-contradictions-in-equations.js b/solutions/2307-check-for-contradictions-in-equations.js
new file mode 100644
index 00000000..56509a5c
--- /dev/null
+++ b/solutions/2307-check-for-contradictions-in-equations.js
@@ -0,0 +1,62 @@
+/**
+ * 2307. Check for Contradictions in Equations
+ * https://leetcode.com/problems/check-for-contradictions-in-equations/
+ * Difficulty: Hard
+ *
+ * You are given a 2D array of strings equations and an array of real numbers values, where
+ * equations[i] = [Ai, Bi] and values[i] means that Ai / Bi = values[i].
+ *
+ * Determine if there exists a contradiction in the equations. Return true if there is a
+ * contradiction, or false otherwise.
+ *
+ * Note:
+ * - When checking if two numbers are equal, check that their absolute difference is less than 10-5.
+ * - The testcases are generated such that there are no cases targeting precision, i.e. using double
+ * is enough to solve the problem.
+ */
+
+/**
+ * @param {string[][]} equations
+ * @param {number[]} values
+ * @return {boolean}
+ */
+var checkContradictions = function(equations, values) {
+ const graph = new Map();
+
+ for (let i = 0; i < equations.length; i++) {
+ const [a, b] = equations[i];
+ const value = values[i];
+
+ const existingValue = dfs(a, b, new Set(), 1);
+
+ if (existingValue !== null && Math.abs(existingValue - value) >= 1e-5) {
+ return true;
+ }
+
+ addEdge(a, b, value);
+ }
+
+ return false;
+
+ function addEdge(a, b, value) {
+ if (!graph.has(a)) graph.set(a, []);
+ if (!graph.has(b)) graph.set(b, []);
+ graph.get(a).push([b, value]);
+ graph.get(b).push([a, 1 / value]);
+ }
+
+ function dfs(start, target, visited, currentValue) {
+ if (start === target) return currentValue;
+ if (visited.has(start)) return null;
+
+ visited.add(start);
+
+ for (const [neighbor, value] of graph.get(start) || []) {
+ const result = dfs(neighbor, target, visited, currentValue * value);
+ if (result !== null) return result;
+ }
+
+ visited.delete(start);
+ return null;
+ }
+};
From 0131812ab0afa9c4437475b8c094e56f22821b9b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 10 Jul 2025 23:15:53 -0500
Subject: [PATCH 752/994] Add solution #2313
---
README.md | 1 +
...imum-flips-in-binary-tree-to-get-result.js | 85 +++++++++++++++++++
2 files changed, 86 insertions(+)
create mode 100644 solutions/2313-minimum-flips-in-binary-tree-to-get-result.js
diff --git a/README.md b/README.md
index 0a24d7c8..24fe9e6b 100644
--- a/README.md
+++ b/README.md
@@ -2081,6 +2081,7 @@
2309|[Greatest English Letter in Upper and Lower Case](./solutions/2309-greatest-english-letter-in-upper-and-lower-case.js)|Easy|
2311|[Longest Binary Subsequence Less Than or Equal to K](./solutions/2311-longest-binary-subsequence-less-than-or-equal-to-k.js)|Medium|
2312|[Selling Pieces of Wood](./solutions/2312-selling-pieces-of-wood.js)|Hard|
+2313|[Minimum Flips in Binary Tree to Get Result](./solutions/2313-minimum-flips-in-binary-tree-to-get-result.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|
diff --git a/solutions/2313-minimum-flips-in-binary-tree-to-get-result.js b/solutions/2313-minimum-flips-in-binary-tree-to-get-result.js
new file mode 100644
index 00000000..fc759975
--- /dev/null
+++ b/solutions/2313-minimum-flips-in-binary-tree-to-get-result.js
@@ -0,0 +1,85 @@
+/**
+ * 2313. Minimum Flips in Binary Tree to Get Result
+ * https://leetcode.com/problems/minimum-flips-in-binary-tree-to-get-result/
+ * Difficulty: Hard
+ *
+ * You are given the root of a binary tree with the following properties:
+ * - Leaf nodes have either the value 0 or 1, representing false and true respectively.
+ * - Non-leaf nodes have either the value 2, 3, 4, or 5, representing the boolean operations
+ * OR, AND, XOR, and NOT, respectively.
+ *
+ * You are also given a boolean result, which is the desired result of the evaluation of the
+ * root node.
+ *
+ * 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 children and apply the boolean operation of its value with
+ * the children's evaluations.
+ *
+ * In one operation, you can flip a leaf node, which causes a false node to become true, and
+ * a true node to become false.
+ *
+ * Return the minimum number of operations that need to be performed such that the evaluation
+ * of root yields result. It can be shown that there is always a way to achieve result.
+ *
+ * A leaf node is a node that has zero children.
+ *
+ * Note: NOT nodes have either a left child or a right child, but other non-leaf nodes have both
+ * a left child and a right child.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @param {boolean} result
+ * @return {number}
+ */
+var minimumFlips = function(root, result) {
+ const [trueFlips, falseFlips] = dfs(root);
+ return result ? trueFlips : falseFlips;
+
+ function dfs(node) {
+ if (node.val === 0) {
+ return [1, 0];
+ }
+ if (node.val === 1) {
+ return [0, 1];
+ }
+
+ if (node.val === 5) {
+ const [t, f] = dfs(node.left || node.right);
+ return [f, t];
+ }
+
+ const [leftTrue, leftFalse] = dfs(node.left);
+ const [rightTrue, rightFalse] = dfs(node.right);
+
+ if (node.val === 2) {
+ return [
+ Math.min(leftTrue + rightTrue, leftFalse + rightTrue, leftTrue + rightFalse),
+ leftFalse + rightFalse
+ ];
+ }
+
+ if (node.val === 3) {
+ return [
+ leftTrue + rightTrue,
+ Math.min(leftTrue + rightFalse, leftFalse + rightTrue, leftFalse + rightFalse)
+ ];
+ }
+
+ if (node.val === 4) {
+ return [
+ Math.min(leftFalse + rightTrue, leftTrue + rightFalse),
+ Math.min(leftTrue + rightTrue, leftFalse + rightFalse)
+ ];
+ }
+ }
+};
From 44801ab07cbed2ca9e78b5d54d376fd0db2ff184 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 10 Jul 2025 23:16:57 -0500
Subject: [PATCH 753/994] Add solution #2323
---
README.md | 1 +
...find-minimum-time-to-finish-all-jobs-ii.js | 32 +++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/2323-find-minimum-time-to-finish-all-jobs-ii.js
diff --git a/README.md b/README.md
index 24fe9e6b..18ac0dcb 100644
--- a/README.md
+++ b/README.md
@@ -2090,6 +2090,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|
+2323|[Find Minimum Time to Finish All Jobs II](./solutions/2323-find-minimum-time-to-finish-all-jobs-ii.js)|Medium|
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|
diff --git a/solutions/2323-find-minimum-time-to-finish-all-jobs-ii.js b/solutions/2323-find-minimum-time-to-finish-all-jobs-ii.js
new file mode 100644
index 00000000..b9b17bac
--- /dev/null
+++ b/solutions/2323-find-minimum-time-to-finish-all-jobs-ii.js
@@ -0,0 +1,32 @@
+/**
+ * 2323. Find Minimum Time to Finish All Jobs II
+ * https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs-ii/
+ * Difficulty: Medium
+ *
+ * You are given two 0-indexed integer arrays jobs and workers of equal length, where jobs[i]
+ * is the amount of time needed to complete the ith job, and workers[j] is the amount of time
+ * the jth worker can work each day.
+ *
+ * Each job should be assigned to exactly one worker, such that each worker completes exactly
+ * one job.
+ *
+ * Return the minimum number of days needed to complete all the jobs after assignment.
+ */
+
+/**
+ * @param {number[]} jobs
+ * @param {number[]} workers
+ * @return {number}
+ */
+var minimumTime = function(jobs, workers) {
+ jobs.sort((a, b) => b - a);
+ workers.sort((a, b) => b - a);
+
+ let result = 0;
+ for (let i = 0; i < jobs.length; i++) {
+ const daysNeeded = Math.ceil(jobs[i] / workers[i]);
+ result = Math.max(result, daysNeeded);
+ }
+
+ return result;
+};
From 54dcc0053c3425e6105fc5364293dddf72ddf0c3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 10 Jul 2025 23:17:46 -0500
Subject: [PATCH 754/994] Add solution #2330
---
README.md | 1 +
solutions/2330-valid-palindrome-iv.js | 28 +++++++++++++++++++++++++++
2 files changed, 29 insertions(+)
create mode 100644 solutions/2330-valid-palindrome-iv.js
diff --git a/README.md b/README.md
index 18ac0dcb..b40c4e28 100644
--- a/README.md
+++ b/README.md
@@ -2094,6 +2094,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|
+2330|[Valid Palindrome IV](./solutions/2330-valid-palindrome-iv.js)|Medium|
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|
diff --git a/solutions/2330-valid-palindrome-iv.js b/solutions/2330-valid-palindrome-iv.js
new file mode 100644
index 00000000..bce33766
--- /dev/null
+++ b/solutions/2330-valid-palindrome-iv.js
@@ -0,0 +1,28 @@
+/**
+ * 2330. Valid Palindrome IV
+ * https://leetcode.com/problems/valid-palindrome-iv/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed string s consisting of only lowercase English letters.
+ * In one operation, you can change any character of s to any other character.
+ *
+ * Return true if you can make s a palindrome after performing exactly one or two
+ * operations, or return false otherwise.
+ */
+
+/**
+ * @param {string} s
+ * @return {boolean}
+ */
+var makePalindrome = function(s) {
+ const n = s.length;
+ let mismatches = 0;
+
+ for (let i = 0; i < Math.floor(n / 2); i++) {
+ if (s[i] !== s[n - 1 - i]) {
+ mismatches++;
+ }
+ }
+
+ return mismatches <= 2;
+};
From 26e2cdd055ce30fd46d3b62e5d9b4a4ab284cc16 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 10 Jul 2025 23:19:33 -0500
Subject: [PATCH 755/994] Add solution #2340
---
README.md | 1 +
...um-adjacent-swaps-to-make-a-valid-array.js | 38 +++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2340-minimum-adjacent-swaps-to-make-a-valid-array.js
diff --git a/README.md b/README.md
index b40c4e28..89bf62d3 100644
--- a/README.md
+++ b/README.md
@@ -2100,6 +2100,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|
+2340|[Minimum Adjacent Swaps to Make a Valid Array](./solutions/2340-minimum-adjacent-swaps-to-make-a-valid-array.js)|Medium|
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|
diff --git a/solutions/2340-minimum-adjacent-swaps-to-make-a-valid-array.js b/solutions/2340-minimum-adjacent-swaps-to-make-a-valid-array.js
new file mode 100644
index 00000000..99f4bf4a
--- /dev/null
+++ b/solutions/2340-minimum-adjacent-swaps-to-make-a-valid-array.js
@@ -0,0 +1,38 @@
+/**
+ * 2340. Minimum Adjacent Swaps to Make a Valid Array
+ * https://leetcode.com/problems/minimum-adjacent-swaps-to-make-a-valid-array/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums.
+ *
+ * Swaps of adjacent elements are able to be performed on nums.
+ *
+ * A valid array meets the following conditions:
+ * - The largest element (any of the largest elements if there are multiple) is at the rightmost
+ * position in the array.
+ * - The smallest element (any of the smallest elements if there are multiple) is at the leftmost
+ * position in the array.
+ *
+ * Return the minimum swaps required to make nums a valid array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimumSwaps = function(nums) {
+ const n = nums.length;
+ if (n === 1) return 0;
+
+ const minValue = Math.min(...nums);
+ const maxValue = Math.max(...nums);
+ const minIndex = nums.indexOf(minValue);
+ const maxIndex = nums.lastIndexOf(maxValue);
+ let result = minIndex + (n - 1 - maxIndex);
+
+ if (minIndex > maxIndex) {
+ result -= 1;
+ }
+
+ return result;
+};
From 9ac94552b1afa8d966adf37aa6c60fac54c582ac Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 10 Jul 2025 23:56:13 -0500
Subject: [PATCH 756/994] Add solution #2345
---
README.md | 1 +
...finding-the-number-of-visible-mountains.js | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/2345-finding-the-number-of-visible-mountains.js
diff --git a/README.md b/README.md
index 89bf62d3..01d9293e 100644
--- a/README.md
+++ b/README.md
@@ -2103,6 +2103,7 @@
2340|[Minimum Adjacent Swaps to Make a Valid Array](./solutions/2340-minimum-adjacent-swaps-to-make-a-valid-array.js)|Medium|
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|
+2345|[Finding the Number of Visible Mountains](./solutions/2345-finding-the-number-of-visible-mountains.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|
diff --git a/solutions/2345-finding-the-number-of-visible-mountains.js b/solutions/2345-finding-the-number-of-visible-mountains.js
new file mode 100644
index 00000000..a382483f
--- /dev/null
+++ b/solutions/2345-finding-the-number-of-visible-mountains.js
@@ -0,0 +1,50 @@
+/**
+ * 2345. Finding the Number of Visible Mountains
+ * https://leetcode.com/problems/finding-the-number-of-visible-mountains/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed 2D integer array peaks where peaks[i] = [xi, yi] states that mountain
+ * i has a peak at coordinates (xi, yi). A mountain can be described as a right-angled isosceles
+ * triangle, with its base along the x-axis and a right angle at its peak. More formally, the
+ * gradients of ascending and descending the mountain are 1 and -1 respectively.
+ *
+ * A mountain is considered visible if its peak does not lie within another mountain (including
+ * the border of other mountains).
+ *
+ * Return the number of visible mountains.
+ */
+
+/**
+ * @param {number[][]} peaks
+ * @return {number}
+ */
+var visibleMountains = function(peaks) {
+ const n = peaks.length;
+
+ peaks.sort((a, b) => {
+ const leftA = a[0] - a[1];
+ const leftB = b[0] - b[1];
+ if (leftA === leftB) {
+ return (b[0] + b[1]) - (a[0] + a[1]);
+ }
+ return leftA - leftB;
+ });
+
+ let result = 0;
+ let maxEnd = -Infinity;
+
+ for (let i = 0; i < n; i++) {
+ const [x, y] = peaks[i];
+ const rightIntercept = x + y;
+
+ if (rightIntercept > maxEnd) {
+ maxEnd = rightIntercept;
+ if (i < n - 1 && peaks[i][0] === peaks[i + 1][0] && peaks[i][1] === peaks[i + 1][1]) {
+ continue;
+ }
+ result++;
+ }
+ }
+
+ return result;
+};
From b3a2ba874e79862aed0507027d87f0c8a4e0cf6e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 10 Jul 2025 23:57:19 -0500
Subject: [PATCH 757/994] Add solution #2355
---
README.md | 1 +
...55-maximum-number-of-books-you-can-take.js | 44 +++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/2355-maximum-number-of-books-you-can-take.js
diff --git a/README.md b/README.md
index 01d9293e..0460db13 100644
--- a/README.md
+++ b/README.md
@@ -2111,6 +2111,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|
+2355|[Maximum Number of Books You Can Take](./solutions/2355-maximum-number-of-books-you-can-take.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|
diff --git a/solutions/2355-maximum-number-of-books-you-can-take.js b/solutions/2355-maximum-number-of-books-you-can-take.js
new file mode 100644
index 00000000..f9e58b8a
--- /dev/null
+++ b/solutions/2355-maximum-number-of-books-you-can-take.js
@@ -0,0 +1,44 @@
+/**
+ * 2355. Maximum Number of Books You Can Take
+ * https://leetcode.com/problems/maximum-number-of-books-you-can-take/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed integer array books of length n where books[i] denotes the number of
+ * books on the ith shelf of a bookshelf.
+ *
+ * You are going to take books from a contiguous section of the bookshelf spanning from l to r
+ * where 0 <= l <= r < n. For each index i in the range l <= i < r, you must take strictly fewer
+ * books from shelf i than shelf i + 1.
+ *
+ * Return the maximum number of books you can take from the bookshelf.
+ */
+
+/**
+ * @param {number[]} books
+ * @return {number}
+ */
+var maximumBooks = function(books) {
+ const n = books.length;
+ const dp = new Array(n).fill(0);
+ const stack = [];
+
+ for (let i = 0; i < n; i++) {
+ while (stack.length > 0
+ && books[stack[stack.length - 1]] >= books[i] - (i - stack[stack.length - 1])) {
+ stack.pop();
+ }
+
+ if (stack.length === 0) {
+ const length = Math.min(i + 1, books[i]);
+ dp[i] = (length * (2 * books[i] - length + 1)) / 2;
+ } else {
+ const prevIndex = stack[stack.length - 1];
+ const length = i - prevIndex;
+ dp[i] = dp[prevIndex] + (length * (2 * books[i] - length + 1)) / 2;
+ }
+
+ stack.push(i);
+ }
+
+ return Math.max(...dp);
+};
From 75c48ed19498a35ee7bea9e60897a912edd1725e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 10 Jul 2025 23:59:14 -0500
Subject: [PATCH 758/994] Add solution #2361
---
README.md | 1 +
...2361-minimum-costs-using-the-train-line.js | 51 +++++++++++++++++++
2 files changed, 52 insertions(+)
create mode 100644 solutions/2361-minimum-costs-using-the-train-line.js
diff --git a/README.md b/README.md
index 0460db13..74fe398f 100644
--- a/README.md
+++ b/README.md
@@ -2115,6 +2115,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|
+2361|[Minimum Costs Using the Train Line](./solutions/2361-minimum-costs-using-the-train-line.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|
diff --git a/solutions/2361-minimum-costs-using-the-train-line.js b/solutions/2361-minimum-costs-using-the-train-line.js
new file mode 100644
index 00000000..9d4e569f
--- /dev/null
+++ b/solutions/2361-minimum-costs-using-the-train-line.js
@@ -0,0 +1,51 @@
+/**
+ * 2361. Minimum Costs Using the Train Line
+ * https://leetcode.com/problems/minimum-costs-using-the-train-line/
+ * Difficulty: Hard
+ *
+ * A train line going through a city has two routes, the regular route and the express route.
+ * Both routes go through the same n + 1 stops labeled from 0 to n. Initially, you start on
+ * the regular route at stop 0.
+ *
+ * You are given two 1-indexed integer arrays regular and express, both of length n.
+ * regular[i] describes the cost it takes to go from stop i - 1 to stop i using the regular
+ * route, and express[i] describes the cost it takes to go from stop i - 1 to stop i using
+ * the express route.
+ *
+ * You are also given an integer expressCost which represents the cost to transfer from the
+ * regular route to the express route.
+ *
+ * Note that:
+ * - There is no cost to transfer from the express route back to the regular route.
+ * - You pay expressCost every time you transfer from the regular route to the express route.
+ * - There is no extra cost to stay on the express route.
+ *
+ * Return a 1-indexed array costs of length n, where costs[i] is the minimum cost to reach
+ * stop i from stop 0.
+ *
+ * Note that a stop can be counted as reached from either route.
+ */
+
+/**
+ * @param {number[]} regular
+ * @param {number[]} express
+ * @param {number} expressCost
+ * @return {number[]}
+ */
+var minimumCosts = function(regular, express, expressCost) {
+ const n = regular.length;
+ const result = new Array(n);
+ let regularDp = 0;
+ let expressDp = expressCost;
+
+ for (let i = 1; i <= n; i++) {
+ const newRegularDp = Math.min(regularDp, expressDp) + regular[i - 1];
+ const newExpressDp = Math.min(regularDp + expressCost, expressDp) + express[i - 1];
+
+ regularDp = newRegularDp;
+ expressDp = newExpressDp;
+ result[i - 1] = Math.min(regularDp, expressDp);
+ }
+
+ return result;
+};
From 1341ee0415d726d4dadd8e3260172f94821111a9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 00:00:43 -0500
Subject: [PATCH 759/994] Add solution #2371
---
README.md | 1 +
.../2371-minimize-maximum-value-in-a-grid.js | 52 +++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 solutions/2371-minimize-maximum-value-in-a-grid.js
diff --git a/README.md b/README.md
index 74fe398f..abd1e053 100644
--- a/README.md
+++ b/README.md
@@ -2124,6 +2124,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|
+2371|[Minimize Maximum Value in a Grid](./solutions/2371-minimize-maximum-value-in-a-grid.js)|Hard|
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|
diff --git a/solutions/2371-minimize-maximum-value-in-a-grid.js b/solutions/2371-minimize-maximum-value-in-a-grid.js
new file mode 100644
index 00000000..832eafff
--- /dev/null
+++ b/solutions/2371-minimize-maximum-value-in-a-grid.js
@@ -0,0 +1,52 @@
+/**
+ * 2371. Minimize Maximum Value in a Grid
+ * https://leetcode.com/problems/minimize-maximum-value-in-a-grid/
+ * Difficulty: Hard
+ *
+ * You are given an m x n integer matrix grid containing distinct positive integers.
+ *
+ * You have to replace each integer in the matrix with a positive integer satisfying the
+ * following conditions:
+ * - The relative order of every two elements that are in the same row or column should stay
+ * the same after the replacements.
+ * - The maximum number in the matrix after the replacements should be as small as possible.
+ *
+ * The relative order stays the same if for all pairs of elements in the original matrix such
+ * that grid[r1][c1] > grid[r2][c2] where either r1 == r2 or c1 == c2, then it must be true
+ * that grid[r1][c1] > grid[r2][c2] after the replacements.
+ *
+ * For example, if grid = [[2, 4, 5], [7, 3, 9]] then a good replacement could be either
+ * grid = [[1, 2, 3], [2, 1, 4]] or grid = [[1, 2, 3], [3, 1, 4]].
+ *
+ * Return the resulting matrix. If there are multiple answers, return any of them.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number[][]}
+ */
+var minScore = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+
+ const positions = [];
+ for (let i = 0; i < rows; i++) {
+ for (let j = 0; j < cols; j++) {
+ positions.push([grid[i][j], i, j]);
+ }
+ }
+
+ positions.sort((a, b) => a[0] - b[0]);
+
+ const result = new Array(rows).fill().map(() => new Array(cols).fill(0));
+ const rowMax = new Array(rows).fill(0);
+ const colMax = new Array(cols).fill(0);
+ for (const [value, row, col] of positions) {
+ const newValue = Math.max(rowMax[row], colMax[col]) + 1;
+ result[row][col] = newValue;
+ rowMax[row] = newValue;
+ colMax[col] = newValue;
+ }
+
+ return result;
+};
From 511e44aef190c1f5a4aee1527d49a3564dbd5cf2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 00:02:58 -0500
Subject: [PATCH 760/994] Add solution #2378
---
README.md | 1 +
...hoose-edges-to-maximize-score-in-a-tree.js | 57 +++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/2378-choose-edges-to-maximize-score-in-a-tree.js
diff --git a/README.md b/README.md
index abd1e053..e5ac9cc7 100644
--- a/README.md
+++ b/README.md
@@ -2129,6 +2129,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|
2376|[Count Special Integers](./solutions/2376-count-special-integers.js)|Hard|
+2378|[Choose Edges to Maximize Score in a Tree](./solutions/2378-choose-edges-to-maximize-score-in-a-tree.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|
diff --git a/solutions/2378-choose-edges-to-maximize-score-in-a-tree.js b/solutions/2378-choose-edges-to-maximize-score-in-a-tree.js
new file mode 100644
index 00000000..a3fb4fde
--- /dev/null
+++ b/solutions/2378-choose-edges-to-maximize-score-in-a-tree.js
@@ -0,0 +1,57 @@
+/**
+ * 2378. Choose Edges to Maximize Score in a Tree
+ * https://leetcode.com/problems/choose-edges-to-maximize-score-in-a-tree/
+ * Difficulty: Medium
+ *
+ * You are given a weighted tree consisting of n nodes numbered from 0 to n - 1.
+ *
+ * The tree is rooted at node 0 and represented with a 2D array edges of size n where
+ * edges[i] = [pari, weighti] indicates that node pari is the parent of node i, and the
+ * edge between them has a weight equal to weighti. Since the root does not have a parent,
+ * you have edges[0] = [-1, -1].
+ *
+ * Choose some edges from the tree such that no two chosen edges are adjacent and the sum
+ * of the weights of the chosen edges is maximized.
+ *
+ * Return the maximum sum of the chosen edges.
+ *
+ * Note:
+ * - You are allowed to not choose any edges in the tree, the sum of weights in this case will be 0.
+ * - Two edges Edge1 and Edge2 in the tree are adjacent if they have a common node.
+ * - In other words, they are adjacent if Edge1 connects nodes a and b and Edge2 connects nodes
+ * b and c.
+ */
+
+/**
+ * @param {number[][]} edges
+ * @return {number}
+ */
+var maxScore = function(edges) {
+ const n = edges.length;
+ const children = new Array(n).fill().map(() => []);
+ let root = 0;
+
+ for (let i = 0; i < n; i++) {
+ if (edges[i][0] >= 0) {
+ children[edges[i][0]].push([i, edges[i][1]]);
+ } else {
+ root = i;
+ }
+ }
+
+ const [skipRoot, takeRoot] = dfs(root);
+ return Math.max(skipRoot, takeRoot);
+
+ function dfs(node) {
+ let skip = 0;
+ let take = 0;
+
+ for (const [child, weight] of children[node]) {
+ const [childSkip, childTake] = dfs(child);
+ skip += childTake;
+ take = Math.max(take, childSkip - childTake + weight);
+ }
+
+ return [skip, take + skip];
+ }
+};
From 03dadafc387d314b81a6a41b6ef8144c200917f1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 00:05:44 -0500
Subject: [PATCH 761/994] Add solution #2387
---
README.md | 1 +
...2387-median-of-a-row-wise-sorted-matrix.js | 52 +++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 solutions/2387-median-of-a-row-wise-sorted-matrix.js
diff --git a/README.md b/README.md
index e5ac9cc7..93e47c4a 100644
--- a/README.md
+++ b/README.md
@@ -2136,6 +2136,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|
+2387|[Median of a Row Wise Sorted Matrix](./solutions/2387-median-of-a-row-wise-sorted-matrix.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|
diff --git a/solutions/2387-median-of-a-row-wise-sorted-matrix.js b/solutions/2387-median-of-a-row-wise-sorted-matrix.js
new file mode 100644
index 00000000..485ba53b
--- /dev/null
+++ b/solutions/2387-median-of-a-row-wise-sorted-matrix.js
@@ -0,0 +1,52 @@
+/**
+ * 2387. Median of a Row Wise Sorted Matrix
+ * https://leetcode.com/problems/median-of-a-row-wise-sorted-matrix/
+ * Difficulty: Medium
+ *
+ * Given an m x n matrix grid containing an odd number of integers where each row is sorted
+ * in non-decreasing order, return the median of the matrix.
+ *
+ * You must solve the problem in less than O(m * n) time complexity.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var matrixMedian = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const totalElements = rows * cols;
+ const targetPosition = Math.floor(totalElements / 2) + 1;
+ let low = 0;
+ let high = 1000001;
+
+ while (low < high) {
+ const mid = low + Math.floor((high - low) / 2);
+ if (helper(mid)) {
+ high = mid;
+ } else {
+ low = mid + 1;
+ }
+ }
+
+ return high;
+
+ function helper(target) {
+ let count = 0;
+ for (const row of grid) {
+ let left = 0;
+ let right = cols;
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (row[mid] <= target) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+ count += left;
+ }
+ return count >= targetPosition;
+ }
+};
From 14dfeb54ec46bff730a002a35529feab0c18e1fb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 00:06:45 -0500
Subject: [PATCH 762/994] Add solution #2393
---
README.md | 1 +
...393-count-strictly-increasing-subarrays.js | 33 +++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/2393-count-strictly-increasing-subarrays.js
diff --git a/README.md b/README.md
index 93e47c4a..2b964d8e 100644
--- a/README.md
+++ b/README.md
@@ -2141,6 +2141,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|
+2393|[Count Strictly Increasing Subarrays](./solutions/2393-count-strictly-increasing-subarrays.js)|Medium|
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|
diff --git a/solutions/2393-count-strictly-increasing-subarrays.js b/solutions/2393-count-strictly-increasing-subarrays.js
new file mode 100644
index 00000000..12f7bbe3
--- /dev/null
+++ b/solutions/2393-count-strictly-increasing-subarrays.js
@@ -0,0 +1,33 @@
+/**
+ * 2393. Count Strictly Increasing Subarrays
+ * https://leetcode.com/problems/count-strictly-increasing-subarrays/
+ * Difficulty: Medium
+ *
+ * You are given an array nums consisting of positive integers.
+ *
+ * Return the number of subarrays of nums that are in strictly increasing order.
+ *
+ * A subarray is a contiguous part of an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var countSubarrays = function(nums) {
+ let result = 0;
+ let currentLength = 1;
+
+ for (let i = 1; i < nums.length; i++) {
+ if (nums[i] > nums[i - 1]) {
+ currentLength++;
+ } else {
+ result += (currentLength * (currentLength + 1)) / 2;
+ currentLength = 1;
+ }
+ }
+
+ result += (currentLength * (currentLength + 1)) / 2;
+
+ return result;
+};
From 1c9c8ab2b0e938069c7a1be21e6c7ea927880513 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 00:08:05 -0500
Subject: [PATCH 763/994] Add solution #2403
---
README.md | 1 +
.../2403-minimum-time-to-kill-all-monsters.js | 48 +++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/2403-minimum-time-to-kill-all-monsters.js
diff --git a/README.md b/README.md
index 2b964d8e..830f4b27 100644
--- a/README.md
+++ b/README.md
@@ -2148,6 +2148,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|
2402|[Meeting Rooms III](./solutions/2402-meeting-rooms-iii.js)|Hard|
+2403|[Minimum Time to Kill All Monsters](./solutions/2403-minimum-time-to-kill-all-monsters.js)|Hard|
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|
diff --git a/solutions/2403-minimum-time-to-kill-all-monsters.js b/solutions/2403-minimum-time-to-kill-all-monsters.js
new file mode 100644
index 00000000..2f4a0644
--- /dev/null
+++ b/solutions/2403-minimum-time-to-kill-all-monsters.js
@@ -0,0 +1,48 @@
+/**
+ * 2403. Minimum Time to Kill All Monsters
+ * https://leetcode.com/problems/minimum-time-to-kill-all-monsters/
+ * Difficulty: Hard
+ *
+ * You are given an integer array power where power[i] is the power of the ith monster.
+ *
+ * You start with 0 mana points, and each day you increase your mana points by gain where gain
+ * initially is equal to 1.
+ *
+ * Each day, after gaining gain mana, you can defeat a monster if your mana points are greater
+ * than or equal to the power of that monster. When you defeat a monster:
+ * - your mana points will be reset to 0, and
+ * - the value of gain increases by 1.
+ *
+ * Return the minimum number of days needed to defeat all the monsters.
+ */
+
+/**
+ * @param {number[]} power
+ * @return {number}
+ */
+var minimumTime = function(power) {
+ const n = power.length;
+ const map = new Map();
+
+ return dp(0, 1);
+
+ function dp(mask, gain) {
+ if (mask === (1 << n) - 1) return 0;
+
+ const key = `${mask}_${gain}`;
+ if (map.has(key)) return map.get(key);
+
+ let minDays = Infinity;
+
+ for (let i = 0; i < n; i++) {
+ if (!(mask & (1 << i))) {
+ const daysNeeded = Math.ceil(power[i] / gain);
+ const totalDays = daysNeeded + dp(mask | (1 << i), gain + 1);
+ minDays = Math.min(minDays, totalDays);
+ }
+ }
+
+ map.set(key, minDays);
+ return minDays;
+ }
+};
From bc444e075e684a1e2c635133e9615e8731c46751 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 00:11:37 -0500
Subject: [PATCH 764/994] Add solution #2408
---
README.md | 1 +
solutions/2408-design-sql.js | 116 +++++++++++++++++++++++++++++++++++
2 files changed, 117 insertions(+)
create mode 100644 solutions/2408-design-sql.js
diff --git a/README.md b/README.md
index 830f4b27..cfe64f9d 100644
--- a/README.md
+++ b/README.md
@@ -2151,6 +2151,7 @@
2403|[Minimum Time to Kill All Monsters](./solutions/2403-minimum-time-to-kill-all-monsters.js)|Hard|
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|
+2408|[Design SQL](./solutions/2408-design-sql.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|
diff --git a/solutions/2408-design-sql.js b/solutions/2408-design-sql.js
new file mode 100644
index 00000000..371e1b87
--- /dev/null
+++ b/solutions/2408-design-sql.js
@@ -0,0 +1,116 @@
+/**
+ * 2408. Design SQL
+ * https://leetcode.com/problems/design-sql/
+ * Difficulty: Medium
+ *
+ * You are given two string arrays, names and columns, both of size n. The ith table is represented
+ * by the name names[i] and contains columns[i] number of columns.
+ *
+ * You need to implement a class that supports the following operations:
+ * - Insert a row in a specific table with an id assigned using an auto-increment method, where the
+ * id of the first inserted row is 1, and the id of each new row inserted into the same table is
+ * one greater than the id of the last inserted row, even if the last row was removed.
+ * - Remove a row from a specific table. Removing a row does not affect the id of the next inserted
+ * row.
+ * - Select a specific cell from any table and return its value.
+ * - Export all rows from any table in csv format.
+ *
+ * Implement the SQL class:
+ * - SQL(String[] names, int[] columns)
+ * - Creates the n tables.
+ * - bool ins(String name, String[] row)
+ * - Inserts row into the table name and returns true.
+ * - If row.length does not match the expected number of columns, or name is not a valid table,
+ * returns false without any insertion.
+ * - void rmv(String name, int rowId)
+ * - Removes the row rowId from the table name.
+ * - If name is not a valid table or there is no row with id rowId, no removal is performed.
+ * - String sel(String name, int rowId, int columnId)
+ * - Returns the value of the cell at the specified rowId and columnId in the table name.
+ * - If name is not a valid table, or the cell (rowId, columnId) is invalid, returns "".
+ * - String[] exp(String name)
+ * - Returns the rows present in the table name.
+ * - If name is not a valid table, returns an empty array. Each row is represented as a string,
+ * with each cell value (including the row's id) separated by a ",".
+ */
+
+/**
+ * @param {string[]} names
+ * @param {number[]} columns
+ */
+var SQL = function(names, columns) {
+ this.tables = new Map();
+ this.nextRowIds = new Map();
+
+ for (let i = 0; i < names.length; i++) {
+ this.tables.set(names[i], {
+ columns: columns[i],
+ rows: new Map()
+ });
+ this.nextRowIds.set(names[i], 1);
+ }
+};
+
+/**
+ * @param {string} name
+ * @param {string[]} row
+ * @return {boolean}
+ */
+SQL.prototype.ins = function(name, row) {
+ if (!this.tables.has(name)) return false;
+
+ const table = this.tables.get(name);
+ if (row.length !== table.columns) return false;
+
+ const rowId = this.nextRowIds.get(name);
+ table.rows.set(rowId, row);
+ this.nextRowIds.set(name, rowId + 1);
+
+ return true;
+};
+
+/**
+ * @param {string} name
+ * @param {number} rowId
+ * @return {void}
+ */
+SQL.prototype.rmv = function(name, rowId) {
+ if (!this.tables.has(name)) return;
+
+ const table = this.tables.get(name);
+ table.rows.delete(rowId);
+};
+
+/**
+ * @param {string} name
+ * @param {number} rowId
+ * @param {number} columnId
+ * @return {string}
+ */
+SQL.prototype.sel = function(name, rowId, columnId) {
+ if (!this.tables.has(name)) return '';
+
+ const table = this.tables.get(name);
+ if (!table.rows.has(rowId) || columnId < 1 || columnId > table.columns) {
+ return '';
+ }
+
+ return table.rows.get(rowId)[columnId - 1];
+};
+
+/**
+ * @param {string} name
+ * @return {string[]}
+ */
+SQL.prototype.exp = function(name) {
+ if (!this.tables.has(name)) return [];
+
+ const table = this.tables.get(name);
+ const result = [];
+
+ for (const [rowId, row] of table.rows) {
+ result.push(`${rowId},${row.join(',')}`);
+ }
+
+ return result;
+};
From a74a50c56248ccf2cea4322facb1874922b9f525 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 00:14:15 -0500
Subject: [PATCH 765/994] Add solution #2417
---
README.md | 3 +-
solutions/2417-closest-fair-integer.js | 45 ++++++++++++++++++++++++++
2 files changed, 47 insertions(+), 1 deletion(-)
create mode 100644 solutions/2417-closest-fair-integer.js
diff --git a/README.md b/README.md
index cfe64f9d..efeb8ab2 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 2,500+ LeetCode solutions in JavaScript
+# 2,550+ LeetCode solutions in JavaScript
[https://leetcodejavascript.com](https://leetcodejavascript.com)
@@ -2160,6 +2160,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|
+2417|[Closest Fair Integer](./solutions/2417-closest-fair-integer.js)|Medium|
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|
2420|[Find All Good Indices](./solutions/2420-find-all-good-indices.js)|Medium|
diff --git a/solutions/2417-closest-fair-integer.js b/solutions/2417-closest-fair-integer.js
new file mode 100644
index 00000000..d478b184
--- /dev/null
+++ b/solutions/2417-closest-fair-integer.js
@@ -0,0 +1,45 @@
+/**
+ * 2417. Closest Fair Integer
+ * https://leetcode.com/problems/closest-fair-integer/
+ * Difficulty: Medium
+ *
+ * You are given a positive integer n.
+ *
+ * We call an integer k fair if the number of even digits in k is equal to the number of
+ * odd digits in it.
+ *
+ * Return the smallest fair integer that is greater than or equal to n.
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var closestFair = function(n) {
+ const digitCount = n.toString().length;
+ if (digitCount % 2 === 1) {
+ return smallestFairNumberWithLength(digitCount + 1);
+ }
+
+ return hasEqualEvenOddDigits(n) ? n : closestFair(n + 1);
+
+ function hasEqualEvenOddDigits(num) {
+ const counts = [0, 0];
+ while (num > 0) {
+ counts[(num % 10) % 2]++;
+ num = Math.floor(num / 10);
+ }
+ return counts[0] === counts[1];
+ }
+
+ function smallestFairNumberWithLength(length) {
+ let result = '1';
+ for (let i = 1; i <= length / 2; i++) {
+ result += '0';
+ }
+ for (let i = length / 2 + 1; i < length; i++) {
+ result += '1';
+ }
+ return parseInt(result);
+ }
+};
From f0ca2ff2266bd3a5319c4cc481a8089204a7a0c0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 22:43:38 -0500
Subject: [PATCH 766/994] Add solution #2422
---
README.md | 1 +
...rations-to-turn-array-into-a-palindrome.js | 46 +++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/2422-merge-operations-to-turn-array-into-a-palindrome.js
diff --git a/README.md b/README.md
index efeb8ab2..a551715f 100644
--- a/README.md
+++ b/README.md
@@ -2165,6 +2165,7 @@
2419|[Longest Subarray With Maximum Bitwise AND](./solutions/2419-longest-subarray-with-maximum-bitwise-and.js)|Medium|
2420|[Find All Good Indices](./solutions/2420-find-all-good-indices.js)|Medium|
2421|[Number of Good Paths](./solutions/2421-number-of-good-paths.js)|Hard|
+2422|[Merge Operations to Turn Array Into a Palindrome](./solutions/2422-merge-operations-to-turn-array-into-a-palindrome.js)|Medium|
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|
diff --git a/solutions/2422-merge-operations-to-turn-array-into-a-palindrome.js b/solutions/2422-merge-operations-to-turn-array-into-a-palindrome.js
new file mode 100644
index 00000000..ea3946c6
--- /dev/null
+++ b/solutions/2422-merge-operations-to-turn-array-into-a-palindrome.js
@@ -0,0 +1,46 @@
+/**
+ * 2422. Merge Operations to Turn Array Into a Palindrome
+ * https://leetcode.com/problems/merge-operations-to-turn-array-into-a-palindrome/
+ * Difficulty: Medium
+ *
+ * You are given an array nums consisting of positive integers.
+ *
+ * You can perform the following operation on the array any number of times:
+ * - Choose any two adjacent elements and replace them with their sum.
+ * - For example, if nums = [1,2,3,1], you can apply one operation to make it [1,5,1].
+ *
+ * Return the minimum number of operations needed to turn the array into a palindrome.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimumOperations = function(nums) {
+ let left = 0;
+ let right = nums.length - 1;
+ let leftSum = nums[left];
+ let rightSum = nums[right];
+ let result = 0;
+
+ while (left < right) {
+ if (leftSum === rightSum) {
+ left++;
+ right--;
+ if (left <= right) {
+ leftSum = nums[left];
+ rightSum = nums[right];
+ }
+ } else if (leftSum < rightSum) {
+ left++;
+ leftSum += nums[left];
+ result++;
+ } else {
+ right--;
+ rightSum += nums[right];
+ result++;
+ }
+ }
+
+ return result;
+};
From ca52c63f6718d9b694df24b2791116d827d38396 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 22:46:20 -0500
Subject: [PATCH 767/994] Add solution #2431
---
README.md | 1 +
...ize-total-tastiness-of-purchased-fruits.js | 67 +++++++++++++++++++
2 files changed, 68 insertions(+)
create mode 100644 solutions/2431-maximize-total-tastiness-of-purchased-fruits.js
diff --git a/README.md b/README.md
index a551715f..c8af3fc9 100644
--- a/README.md
+++ b/README.md
@@ -2171,6 +2171,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|
+2431|[Maximize Total Tastiness of Purchased Fruits](./solutions/2431-maximize-total-tastiness-of-purchased-fruits.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|
diff --git a/solutions/2431-maximize-total-tastiness-of-purchased-fruits.js b/solutions/2431-maximize-total-tastiness-of-purchased-fruits.js
new file mode 100644
index 00000000..5dab31aa
--- /dev/null
+++ b/solutions/2431-maximize-total-tastiness-of-purchased-fruits.js
@@ -0,0 +1,67 @@
+/**
+ * 2431. Maximize Total Tastiness of Purchased Fruits
+ * https://leetcode.com/problems/maximize-total-tastiness-of-purchased-fruits/
+ * Difficulty: Medium
+ *
+ * You are given two non-negative integer arrays price and tastiness, both arrays have the same
+ * length n. You are also given two non-negative integers maxAmount and maxCoupons.
+ *
+ * For every integer i in range [0, n - 1]:
+ * - price[i] describes the price of ith fruit.
+ * - tastiness[i] describes the tastiness of ith fruit.
+ *
+ * You want to purchase some fruits such that total tastiness is maximized and the total price
+ * does not exceed maxAmount.
+ *
+ * Additionally, you can use a coupon to purchase fruit for half of its price (rounded down to
+ * the closest integer). You can use at most maxCoupons of such coupons.
+ *
+ * Return the maximum total tastiness that can be purchased.
+ *
+ * Note that:
+ * - You can purchase each fruit at most once.
+ * - You can use coupons on some fruit at most once.
+ */
+
+/**
+ * @param {number[]} price
+ * @param {number[]} tastiness
+ * @param {number} maxAmount
+ * @param {number} maxCoupons
+ * @return {number}
+ */
+var maxTastiness = function(price, tastiness, maxAmount, maxCoupons) {
+ const n = price.length;
+ const map = new Map();
+
+ return dp(0, maxAmount, maxCoupons);
+
+ function dp(index, remainingAmount, remainingCoupons) {
+ if (index === n) return 0;
+
+ const key = `${index}_${remainingAmount}_${remainingCoupons}`;
+ if (map.has(key)) return map.get(key);
+
+ let maxValue = dp(index + 1, remainingAmount, remainingCoupons);
+
+ if (price[index] <= remainingAmount) {
+ maxValue = Math.max(
+ maxValue,
+ tastiness[index] + dp(index + 1, remainingAmount - price[index], remainingCoupons)
+ );
+ }
+
+ if (remainingCoupons > 0) {
+ const discountedPrice = Math.floor(price[index] / 2);
+ if (discountedPrice <= remainingAmount) {
+ maxValue = Math.max(
+ maxValue,
+ tastiness[index] + dp(index + 1, remainingAmount - discountedPrice, remainingCoupons - 1)
+ );
+ }
+ }
+
+ map.set(key, maxValue);
+ return maxValue;
+ }
+};
From cc9ff8660878c5ea2deef2b262fa50f3afc443c0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 22:47:58 -0500
Subject: [PATCH 768/994] Add solution #2436
---
README.md | 1 +
...nto-subarrays-with-gcd-greater-than-one.js | 49 +++++++++++++++++++
2 files changed, 50 insertions(+)
create mode 100644 solutions/2436-minimum-split-into-subarrays-with-gcd-greater-than-one.js
diff --git a/README.md b/README.md
index c8af3fc9..0bc72568 100644
--- a/README.md
+++ b/README.md
@@ -2176,6 +2176,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|
+2436|[Minimum Split Into Subarrays With GCD Greater Than One](./solutions/2436-minimum-split-into-subarrays-with-gcd-greater-than-one.js)|Medium|
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|
diff --git a/solutions/2436-minimum-split-into-subarrays-with-gcd-greater-than-one.js b/solutions/2436-minimum-split-into-subarrays-with-gcd-greater-than-one.js
new file mode 100644
index 00000000..c0410d87
--- /dev/null
+++ b/solutions/2436-minimum-split-into-subarrays-with-gcd-greater-than-one.js
@@ -0,0 +1,49 @@
+/**
+ * 2436. Minimum Split Into Subarrays With GCD Greater Than One
+ * https://leetcode.com/problems/minimum-split-into-subarrays-with-gcd-greater-than-one/
+ * Difficulty: Medium
+ *
+ * You are given an array nums consisting of positive integers.
+ *
+ * Split the array into one or more disjoint subarrays such that:
+ * - Each element of the array belongs to exactly one subarray, and
+ * - The GCD of the elements of each subarray is strictly greater than 1.
+ *
+ * Return the minimum number of subarrays that can be obtained after the split.
+ *
+ * Note that:
+ * - The GCD of a subarray is the largest positive integer that evenly divides all the elements
+ * of the subarray.
+ * - A subarray is a contiguous part of the array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimumSplits = function(nums) {
+ const n = nums.length;
+ let result = 1;
+ let currentGcd = nums[0];
+
+ for (let i = 1; i < n; i++) {
+ const newGcd = gcd(currentGcd, nums[i]);
+ if (newGcd === 1) {
+ result++;
+ currentGcd = nums[i];
+ } else {
+ currentGcd = newGcd;
+ }
+ }
+
+ return result;
+
+ function gcd(a, b) {
+ while (b !== 0) {
+ const temp = b;
+ b = a % b;
+ a = temp;
+ }
+ return a;
+ }
+};
From a7086830f08f1f9064ed8d3ceffe96572b7a2170 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 22:49:38 -0500
Subject: [PATCH 769/994] Add solution #2445
---
README.md | 1 +
.../2445-number-of-nodes-with-value-one.js | 53 +++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/2445-number-of-nodes-with-value-one.js
diff --git a/README.md b/README.md
index 0bc72568..f155f81f 100644
--- a/README.md
+++ b/README.md
@@ -2185,6 +2185,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|
+2445|[Number of Nodes With Value One](./solutions/2445-number-of-nodes-with-value-one.js)|Medium|
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|
diff --git a/solutions/2445-number-of-nodes-with-value-one.js b/solutions/2445-number-of-nodes-with-value-one.js
new file mode 100644
index 00000000..115d7dea
--- /dev/null
+++ b/solutions/2445-number-of-nodes-with-value-one.js
@@ -0,0 +1,53 @@
+/**
+ * 2445. Number of Nodes With Value One
+ * https://leetcode.com/problems/number-of-nodes-with-value-one/
+ * Difficulty: Medium
+ *
+ * There is an undirected connected tree with n nodes labeled from 1 to n and n - 1 edges.
+ * You are given the integer n. The parent node of a node with a label v is the node with
+ * the label floor (v / 2). The root of the tree is the node with the label 1.
+ *
+ * - For example, if n = 7, then the node with the label 3 has the node with the label
+ * floor(3 / 2) = 1 as its parent, and the node with the label 7 has the node with the
+ * label floor(7 / 2) = 3 as its parent.
+ *
+ * You are also given an integer array queries. Initially, every node has a value 0 on it.
+ * For each query queries[i], you should flip all values in the subtree of the node with
+ * the label queries[i].
+ *
+ * Return the total number of nodes with the value 1 after processing all the queries.
+ *
+ * Note that:
+ * - Flipping the value of a node means that the node with the value 0 becomes 1 and vice versa.
+ * - floor(x) is equivalent to rounding x down to the nearest integer.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[]} queries
+ * @return {number}
+ */
+var numberOfNodes = function(n, queries) {
+ const flipCount = new Array(n + 1).fill(0);
+
+ for (const query of queries) {
+ flipCount[query]++;
+ }
+
+ let result = 0;
+ for (let i = 1; i <= n; i++) {
+ let totalFlips = 0;
+ let current = i;
+
+ while (current >= 1) {
+ totalFlips += flipCount[current];
+ current = Math.floor(current / 2);
+ }
+
+ if (totalFlips % 2 === 1) {
+ result++;
+ }
+ }
+
+ return result;
+};
From 741b3dde15cfec50daa497ca827ded4c451c560e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 22:52:54 -0500
Subject: [PATCH 770/994] Add solution #2450
---
README.md | 1 +
...inary-strings-after-applying-operations.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/2450-number-of-distinct-binary-strings-after-applying-operations.js
diff --git a/README.md b/README.md
index f155f81f..f3070e5b 100644
--- a/README.md
+++ b/README.md
@@ -2190,6 +2190,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|
+2450|[Number of Distinct Binary Strings After Applying Operations](./solutions/2450-number-of-distinct-binary-strings-after-applying-operations.js)|Medium|
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|
diff --git a/solutions/2450-number-of-distinct-binary-strings-after-applying-operations.js b/solutions/2450-number-of-distinct-binary-strings-after-applying-operations.js
new file mode 100644
index 00000000..7db5d4be
--- /dev/null
+++ b/solutions/2450-number-of-distinct-binary-strings-after-applying-operations.js
@@ -0,0 +1,39 @@
+/**
+ * 2450. Number of Distinct Binary Strings After Applying Operations
+ * https://leetcode.com/problems/number-of-distinct-binary-strings-after-applying-operations/
+ * Difficulty: Medium
+ *
+ * You are given a binary string s and a positive integer k.
+ *
+ * You can apply the following operation on the string any number of times:
+ * - Choose any substring of size k from s and flip all its characters, that is, turn all 1's
+ * into 0's, and all 0's into 1's.
+ * - Return the number of distinct strings you can obtain. Since the answer may be too large,
+ * return it modulo 109 + 7.
+ *
+ * Note that:
+ * - A binary string is a string that consists only of the characters 0 and 1.
+ * - A substring is a contiguous part of a string.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} k
+ * @return {number}
+ */
+var countDistinctStrings = function(s, k) {
+ if (s.length <= 0) {
+ return -1;
+ }
+
+ const MOD = 1e9 + 7;
+ let n = s.length - k + 1;
+ let result = 1;
+
+ while (n > 0) {
+ result = (result << 1) % MOD;
+ n--;
+ }
+
+ return result;
+};
From 4be6f1c5f787a94413e627e23b477ec61683091e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 22:55:22 -0500
Subject: [PATCH 771/994] Add solution #2459
---
README.md | 1 +
...rt-array-by-moving-items-to-empty-space.js | 61 +++++++++++++++++++
2 files changed, 62 insertions(+)
create mode 100644 solutions/2459-sort-array-by-moving-items-to-empty-space.js
diff --git a/README.md b/README.md
index f3070e5b..602b9277 100644
--- a/README.md
+++ b/README.md
@@ -2196,6 +2196,7 @@
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|
+2459|[Sort Array by Moving Items to Empty Space](./solutions/2459-sort-array-by-moving-items-to-empty-space.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|
diff --git a/solutions/2459-sort-array-by-moving-items-to-empty-space.js b/solutions/2459-sort-array-by-moving-items-to-empty-space.js
new file mode 100644
index 00000000..ee27aa25
--- /dev/null
+++ b/solutions/2459-sort-array-by-moving-items-to-empty-space.js
@@ -0,0 +1,61 @@
+/**
+ * 2459. Sort Array by Moving Items to Empty Space
+ * https://leetcode.com/problems/sort-array-by-moving-items-to-empty-space/
+ * Difficulty: Hard
+ *
+ * You are given an integer array nums of size n containing each element from 0 to n - 1
+ * (inclusive). Each of the elements from 1 to n - 1 represents an item, and the element
+ * 0 represents an empty space.
+ *
+ * In one operation, you can move any item to the empty space. nums is considered to be sorted
+ * if the numbers of all the items are in ascending order and the empty space is either at the
+ * beginning or at the end of the array.
+ *
+ * For example, if n = 4, nums is sorted if:
+ * - nums = [0,1,2,3] or
+ * - nums = [1,2,3,0]
+ *
+ * ...and considered to be unsorted otherwise.
+ *
+ * Return the minimum number of operations needed to sort nums.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var sortArray = function(nums) {
+ const n = nums.length;
+ const positions = new Array(n);
+
+ for (let i = 0; i < n; i++) {
+ positions[nums[i]] = i;
+ }
+
+ return Math.min(
+ permute([...positions], 0),
+ permute([...positions], 1)
+ );
+
+ function permute(pos, shift) {
+ let count = 0;
+ let next = 1;
+
+ while (next < n) {
+ if (pos[0] === shift * (n - 1)) {
+ while (pos[next] === next - shift) {
+ next++;
+ if (next === n) return count;
+ }
+ var targetIndex = next;
+ } else {
+ var targetIndex = pos[0] + shift;
+ }
+
+ [pos[0], pos[targetIndex]] = [pos[targetIndex], pos[0]];
+ count++;
+ }
+
+ return count;
+ }
+};
From be8a0fe87673ff8e99860672b577c83b31e48fa6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 22:57:07 -0500
Subject: [PATCH 772/994] Add solution #2464
---
README.md | 1 +
...2464-minimum-subarrays-in-a-valid-split.js | 51 +++++++++++++++++++
2 files changed, 52 insertions(+)
create mode 100644 solutions/2464-minimum-subarrays-in-a-valid-split.js
diff --git a/README.md b/README.md
index 602b9277..f7e9f2a3 100644
--- a/README.md
+++ b/README.md
@@ -2201,6 +2201,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|
+2464|[Minimum Subarrays in a Valid Split](./solutions/2464-minimum-subarrays-in-a-valid-split.js)|Medium|
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|
diff --git a/solutions/2464-minimum-subarrays-in-a-valid-split.js b/solutions/2464-minimum-subarrays-in-a-valid-split.js
new file mode 100644
index 00000000..fa16bd70
--- /dev/null
+++ b/solutions/2464-minimum-subarrays-in-a-valid-split.js
@@ -0,0 +1,51 @@
+/**
+ * 2464. Minimum Subarrays in a Valid Split
+ * https://leetcode.com/problems/minimum-subarrays-in-a-valid-split/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums.
+ *
+ * Splitting of an integer array nums into subarrays is valid if:
+ * - the greatest common divisor of the first and last elements of each subarray is
+ * greater than 1, and
+ * - each element of nums belongs to exactly one subarray.
+ *
+ * Return the minimum number of subarrays in a valid subarray splitting of nums.
+ * If a valid subarray splitting is not possible, return -1.
+ *
+ * Note that:
+ * - The greatest common divisor of two numbers is the largest positive integer that
+ * evenly divides both numbers.
+ * - A subarray is a contiguous non-empty part of an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var validSubarraySplit = function(nums) {
+ const n = nums.length;
+ const dp = new Array(n + 1).fill(Infinity);
+ dp[0] = 0;
+
+ for (let i = 0; i < n; i++) {
+ if (dp[i] === Infinity) continue;
+
+ for (let j = i; j < n; j++) {
+ if (gcd(nums[i], nums[j]) > 1) {
+ dp[j + 1] = Math.min(dp[j + 1], dp[i] + 1);
+ }
+ }
+ }
+
+ return dp[n] === Infinity ? -1 : dp[n];
+
+ function gcd(a, b) {
+ while (b !== 0) {
+ const temp = b;
+ b = a % b;
+ a = temp;
+ }
+ return a;
+ }
+};
From facf5f775c915680c293774827b6c56220122c52 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 23:01:40 -0500
Subject: [PATCH 773/994] Add solution #2473
---
README.md | 1 +
solutions/2473-minimum-cost-to-buy-apples.js | 67 ++++++++++++++++++++
2 files changed, 68 insertions(+)
create mode 100644 solutions/2473-minimum-cost-to-buy-apples.js
diff --git a/README.md b/README.md
index f7e9f2a3..e9276aa3 100644
--- a/README.md
+++ b/README.md
@@ -2210,6 +2210,7 @@
2470|[Number of Subarrays With LCM Equal to K](./solutions/2470-number-of-subarrays-with-lcm-equal-to-k.js)|Medium|
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|
+2473|[Minimum Cost to Buy Apples](./solutions/2473-minimum-cost-to-buy-apples.js)|Medium|
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|
diff --git a/solutions/2473-minimum-cost-to-buy-apples.js b/solutions/2473-minimum-cost-to-buy-apples.js
new file mode 100644
index 00000000..ce8700b3
--- /dev/null
+++ b/solutions/2473-minimum-cost-to-buy-apples.js
@@ -0,0 +1,67 @@
+/**
+ * 2473. Minimum Cost to Buy Apples
+ * https://leetcode.com/problems/minimum-cost-to-buy-apples/
+ * 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, costi] indicates that there is a bidirectional
+ * road between cities ai and bi with a cost of traveling equal to costi.
+ *
+ * You can buy apples in any city you want, but some cities have different costs to buy apples.
+ * You are given the 1-based array appleCost where appleCost[i] is the cost of buying one apple
+ * from city i.
+ *
+ * You start at some city, traverse through various roads, and eventually buy exactly one apple
+ * from any city. After you buy that apple, you have to return back to the city you started at,
+ * but now the cost of all the roads will be multiplied by a given factor k.
+ *
+ * Given the integer k, return a 1-based array answer of size n where answer[i] is the minimum
+ * total cost to buy an apple if you start at city i.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} roads
+ * @param {number[]} appleCost
+ * @param {number} k
+ * @return {number[]}
+ */
+var minCost = function(n, roads, appleCost, k) {
+ const graph = new Array(n).fill().map(() => []);
+ for (const [cityA, cityB, cost] of roads) {
+ graph[cityA - 1].push([cityB - 1, cost]);
+ graph[cityB - 1].push([cityA - 1, cost]);
+ }
+
+ const result = new Array(n);
+ for (let startCity = 0; startCity < n; startCity++) {
+ result[startCity] = appleCost[startCity];
+ }
+
+ const heap = [];
+ for (let startCity = 0; startCity < n; startCity++) {
+ heap.push([appleCost[startCity], startCity]);
+ }
+ heap.sort((a, b) => a[0] - b[0]);
+
+ while (heap.length > 0) {
+ const [totalCost, currCity] = heap.shift();
+
+ if (result[currCity] < totalCost) continue;
+
+ for (const [neighbor, cost] of graph[currCity]) {
+ const newCost = result[currCity] + (k + 1) * cost;
+ if (result[neighbor] > newCost) {
+ result[neighbor] = newCost;
+
+ let insertIndex = 0;
+ while (insertIndex < heap.length && heap[insertIndex][0] <= newCost) {
+ insertIndex++;
+ }
+ heap.splice(insertIndex, 0, [newCost, neighbor]);
+ }
+ }
+ }
+
+ return result;
+};
From 7f96efa07c003bb6c2e62bf898a522ba3bf23dbd Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 23:12:53 -0500
Subject: [PATCH 774/994] Add solution #2479
---
README.md | 1 +
...mum-xor-of-two-non-overlapping-subtrees.js | 112 ++++++++++++++++++
2 files changed, 113 insertions(+)
create mode 100644 solutions/2479-maximum-xor-of-two-non-overlapping-subtrees.js
diff --git a/README.md b/README.md
index e9276aa3..00fa559d 100644
--- a/README.md
+++ b/README.md
@@ -2214,6 +2214,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|
+2479|[Maximum XOR of Two Non-Overlapping Subtrees](./solutions/2479-maximum-xor-of-two-non-overlapping-subtrees.js)|Hard|
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|
diff --git a/solutions/2479-maximum-xor-of-two-non-overlapping-subtrees.js b/solutions/2479-maximum-xor-of-two-non-overlapping-subtrees.js
new file mode 100644
index 00000000..0d856990
--- /dev/null
+++ b/solutions/2479-maximum-xor-of-two-non-overlapping-subtrees.js
@@ -0,0 +1,112 @@
+/**
+ * 2479. Maximum XOR of Two Non-Overlapping Subtrees
+ * https://leetcode.com/problems/maximum-xor-of-two-non-overlapping-subtrees/
+ * Difficulty: Hard
+ *
+ * There is an undirected tree with n nodes labeled from 0 to n - 1. You are given the integer
+ * n and 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. The root of the tree is the node labeled 0.
+ *
+ * Each node has an associated value. You are given an array values of length n, where values[i]
+ * is the value of the ith node.
+ *
+ * Select any two non-overlapping subtrees. Your score is the bitwise XOR of the sum of the
+ * values within those subtrees.
+ *
+ * Return the maximum possible score you can achieve. If it is impossible to find two
+ * nonoverlapping subtrees, return 0.
+ *
+ * Note that:
+ * - The subtree of a node is the tree consisting of that node and all of its descendants.
+ * - Two subtrees are non-overlapping if they do not share any common node.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @param {number[]} values
+ * @return {number}
+ */
+var maxXor = function(n, edges, values) {
+ class TrieNode {
+ constructor() {
+ this.children = [null, null];
+ }
+ }
+
+ const graph = Array(n).fill().map(() => []);
+ for (const [u, v] of edges) {
+ graph[u].push(v);
+ graph[v].push(u);
+ }
+
+ const subtreeSums = new Array(n);
+
+ calculateSubtreeSum(0, -1);
+ const root = new TrieNode();
+
+ return Number(findMaxXor(0, -1, root));
+
+ function calculateSubtreeSum(node, parent) {
+ subtreeSums[node] = BigInt(values[node]);
+ for (const child of graph[node]) {
+ if (child !== parent) {
+ subtreeSums[node] += calculateSubtreeSum(child, node);
+ }
+ }
+ return subtreeSums[node];
+ }
+
+ function insert(root, value) {
+ let current = root;
+ for (let bit = 44; bit >= 0; bit--) {
+ const bitValue = (value >> BigInt(bit)) & 1n;
+ const index = Number(bitValue);
+ if (!current.children[index]) {
+ current.children[index] = new TrieNode();
+ }
+ current = current.children[index];
+ }
+ }
+
+ function getMaxValue(root, currentValue) {
+ if (!root.children[0] && !root.children[1]) {
+ return 0n;
+ }
+
+ let result = 0n;
+ let current = root;
+
+ for (let bit = 44; bit >= 0; bit--) {
+ const currentBit = (currentValue >> BigInt(bit)) & 1n;
+ const wantedBit = 1n - currentBit;
+ const wantedIndex = Number(wantedBit);
+ const currentIndex = Number(currentBit);
+
+ if (current.children[wantedIndex]) {
+ result += 1n << BigInt(bit);
+ current = current.children[wantedIndex];
+ } else {
+ current = current.children[currentIndex];
+ }
+ }
+
+ return result;
+ }
+
+ function findMaxXor(node, parent, root) {
+ let result = getMaxValue(root, subtreeSums[node]);
+
+ for (const child of graph[node]) {
+ if (child !== parent) {
+ const childResult = findMaxXor(child, node, root);
+ if (childResult > result) {
+ result = childResult;
+ }
+ }
+ }
+
+ insert(root, subtreeSums[node]);
+ return result;
+ }
+};
From a3b9cf54d963974177cfead520a07591fe4558fd Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 23:14:35 -0500
Subject: [PATCH 775/994] Add solution #2489
---
README.md | 1 +
...9-number-of-substrings-with-fixed-ratio.js | 53 +++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/2489-number-of-substrings-with-fixed-ratio.js
diff --git a/README.md b/README.md
index 00fa559d..4f57c428 100644
--- a/README.md
+++ b/README.md
@@ -2223,6 +2223,7 @@
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|
+2489|[Number of Substrings With Fixed Ratio](./solutions/2489-number-of-substrings-with-fixed-ratio.js)|Medium|
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|
diff --git a/solutions/2489-number-of-substrings-with-fixed-ratio.js b/solutions/2489-number-of-substrings-with-fixed-ratio.js
new file mode 100644
index 00000000..4a5b9c2e
--- /dev/null
+++ b/solutions/2489-number-of-substrings-with-fixed-ratio.js
@@ -0,0 +1,53 @@
+/**
+ * 2489. Number of Substrings With Fixed Ratio
+ * https://leetcode.com/problems/number-of-substrings-with-fixed-ratio/
+ * Difficulty: Medium
+ *
+ * You are given a binary string s, and two integers num1 and num2. num1 and num2 are
+ * coprime numbers.
+ *
+ * A ratio substring is a substring of s where the ratio between the number of 0's and
+ * the number of 1's in the substring is exactly num1 : num2.
+ * - For example, if num1 = 2 and num2 = 3, then "01011" and "1110000111" are ratio substrings,
+ * while "11000" is not.
+ *
+ * Return the number of non-empty ratio substrings of s.
+ *
+ * Note that:
+ * - A substring is a contiguous sequence of characters within a string.
+ * - 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.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} num1
+ * @param {number} num2
+ * @return {number}
+ */
+var fixedRatio = function(s, num1, num2) {
+ const n = s.length;
+ const map = new Map();
+ map.set(0, 1);
+
+ let zeros = 0;
+ let ones = 0;
+ let result = 0;
+ for (let i = 0; i < n; i++) {
+ if (s[i] === '0') {
+ zeros++;
+ } else {
+ ones++;
+ }
+
+ const difference = ones * num1 - zeros * num2;
+
+ if (map.has(difference)) {
+ result += map.get(difference);
+ }
+
+ map.set(difference, (map.get(difference) || 0) + 1);
+ }
+
+ return result;
+};
From 951ca5567b46f804e022d58a5690cab0433244cb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 23:17:27 -0500
Subject: [PATCH 776/994] Add solution #2495
---
README.md | 1 +
...number-of-subarrays-having-even-product.js | 32 +++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/2495-number-of-subarrays-having-even-product.js
diff --git a/README.md b/README.md
index 4f57c428..a4ab9e47 100644
--- a/README.md
+++ b/README.md
@@ -2228,6 +2228,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|
+2495|[Number of Subarrays Having Even Product](./solutions/2495-number-of-subarrays-having-even-product.js)|Medium|
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|
diff --git a/solutions/2495-number-of-subarrays-having-even-product.js b/solutions/2495-number-of-subarrays-having-even-product.js
new file mode 100644
index 00000000..a94af32b
--- /dev/null
+++ b/solutions/2495-number-of-subarrays-having-even-product.js
@@ -0,0 +1,32 @@
+/**
+ * 2495. Number of Subarrays Having Even Product
+ * https://leetcode.com/problems/number-of-subarrays-having-even-product/
+ * Difficulty: Medium
+ *
+ * Given a 0-indexed integer array nums, return the number of subarrays of nums having an
+ * even product.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var evenProduct = function(nums) {
+ const n = nums.length;
+ const totalSubarrays = (n * (n + 1)) / 2;
+ let oddProductSubarrays = 0;
+ let currentOddLength = 0;
+
+ for (let i = 0; i < n; i++) {
+ if (nums[i] % 2 === 1) {
+ currentOddLength++;
+ } else {
+ oddProductSubarrays += (currentOddLength * (currentOddLength + 1)) / 2;
+ currentOddLength = 0;
+ }
+ }
+
+ oddProductSubarrays += (currentOddLength * (currentOddLength + 1)) / 2;
+
+ return totalSubarrays - oddProductSubarrays;
+};
From e9b74339c92a3937120dc4e41abcc439fdab83a4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 23:21:53 -0500
Subject: [PATCH 777/994] Add solution #2675
---
README.md | 1 +
solutions/2675-array-of-objects-to-matrix.js | 63 ++++++++++++++++++++
2 files changed, 64 insertions(+)
create mode 100644 solutions/2675-array-of-objects-to-matrix.js
diff --git a/README.md b/README.md
index a4ab9e47..dee317db 100644
--- a/README.md
+++ b/README.md
@@ -2338,6 +2338,7 @@
2670|[Find the Distinct Difference Array](./solutions/2670-find-the-distinct-difference-array.js)|Easy|
2672|[Number of Adjacent Elements With the Same Color](./solutions/2672-number-of-adjacent-elements-with-the-same-color.js)|Medium|
2673|[Make Costs of Paths Equal in a Binary Tree](./solutions/2673-make-costs-of-paths-equal-in-a-binary-tree.js)|Medium|
+2675|[Array of Objects to Matrix](./solutions/2675-array-of-objects-to-matrix.js)|Hard|
2676|[Throttle](./solutions/2676-throttle.js)|Medium|
2677|[Chunk Array](./solutions/2677-chunk-array.js)|Easy|
2678|[Number of Senior Citizens](./solutions/2678-number-of-senior-citizens.js)|Easy|
diff --git a/solutions/2675-array-of-objects-to-matrix.js b/solutions/2675-array-of-objects-to-matrix.js
new file mode 100644
index 00000000..c5a1c570
--- /dev/null
+++ b/solutions/2675-array-of-objects-to-matrix.js
@@ -0,0 +1,63 @@
+/**
+ * 2675. Array of Objects to Matrix
+ * https://leetcode.com/problems/array-of-objects-to-matrix/
+ * Difficulty: Hard
+ *
+ * Write a function that converts an array of objects arr into a matrix m.
+ *
+ * arr is an array of objects or arrays. Each item in the array can be deeply nested with child
+ * arrays and child objects. It can also contain numbers, strings, booleans, and null values.
+ *
+ * The first row m should be the column names. If there is no nesting, the column names are the
+ * unique keys within the objects. If there is nesting, the column names are the respective paths
+ * in the object separated by ".".
+ *
+ * Each of the remaining rows corresponds to an object in arr. Each value in the matrix corresponds
+ * to a value in an object. If a given object doesn't contain a value for a given column, the cell
+ * should contain an empty string "".
+ *
+ * The columns in the matrix should be in lexographically ascending order.
+ */
+
+/**
+ * @param {Array} arr
+ * @return {(string | number | boolean | null)[][]}
+ */
+var jsonToMatrix = function(arr) {
+ const allKeys = Array.from(
+ arr.reduce((keySet, item) => {
+ extractKeys(item).forEach(key => keySet.add(key));
+ return keySet;
+ }, new Set())
+ ).sort();
+
+ return [allKeys, ...arr.map(item => allKeys.map(key => getValue(item, key)))];
+
+ function isObject(value) {
+ return value !== null && typeof value === 'object';
+ }
+
+ function extractKeys(object) {
+ if (!isObject(object)) return [''];
+ const keys = [];
+ for (const key of Object.keys(object)) {
+ const childKeys = extractKeys(object[key]);
+ for (const childKey of childKeys) {
+ keys.push(childKey ? `${key}.${childKey}` : key);
+ }
+ }
+ return keys;
+ }
+
+ function getValue(obj, path) {
+ const segments = path.split('.');
+ let current = obj;
+ let index = 0;
+
+ while (index < segments.length && isObject(current)) {
+ current = current[segments[index++]];
+ }
+
+ return index < segments.length || isObject(current) || current === undefined ? '' : current;
+ }
+};
From 99c57cc8cdc7ed45da5887339e555062fd9e0385 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 23:22:54 -0500
Subject: [PATCH 778/994] Add solution #2690
---
README.md | 1 +
solutions/2690-infinite-method-object.js | 23 +++++++++++++++++++++++
2 files changed, 24 insertions(+)
create mode 100644 solutions/2690-infinite-method-object.js
diff --git a/README.md b/README.md
index dee317db..81a192e3 100644
--- a/README.md
+++ b/README.md
@@ -2347,6 +2347,7 @@
2683|[Neighboring Bitwise XOR](./solutions/2683-neighboring-bitwise-xor.js)|Medium|
2684|[Maximum Number of Moves in a Grid](./solutions/2684-maximum-number-of-moves-in-a-grid.js)|Medium|
2685|[Count the Number of Complete Components](./solutions/2685-count-the-number-of-complete-components.js)|Medium|
+2690|[Infinite Method Object](./solutions/2690-infinite-method-object.js)|Easy|
2693|[Call Function with Custom Context](./solutions/2693-call-function-with-custom-context.js)|Medium|
2694|[Event Emitter](./solutions/2694-event-emitter.js)|Medium|
2695|[Array Wrapper](./solutions/2695-array-wrapper.js)|Easy|
diff --git a/solutions/2690-infinite-method-object.js b/solutions/2690-infinite-method-object.js
new file mode 100644
index 00000000..9d61341a
--- /dev/null
+++ b/solutions/2690-infinite-method-object.js
@@ -0,0 +1,23 @@
+/**
+ * 2690. Infinite Method Object
+ * https://leetcode.com/problems/infinite-method-object/
+ * Difficulty: Easy
+ *
+ * Write a function that returns an infinite-method object.
+ *
+ * An infinite-method object is defined as an object that allows you to call any method and
+ * it will always return the name of the method.
+ *
+ * For example, if you execute obj.abc123(), it will return "abc123".
+ */
+
+/**
+ * @return {Object}
+ */
+var createInfiniteObject = function() {
+ return new Proxy({}, {
+ get(target, property) {
+ return () => property;
+ }
+ });
+};
From d976c9ce084d77c0d5ce689a969fa4ed965f5475 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 23:36:39 -0500
Subject: [PATCH 779/994] Add solution #2691
---
README.md | 1 +
solutions/2691-immutability-helper.js | 82 +++++++++++++++++++++++++++
2 files changed, 83 insertions(+)
create mode 100644 solutions/2691-immutability-helper.js
diff --git a/README.md b/README.md
index 81a192e3..d2bb0e6f 100644
--- a/README.md
+++ b/README.md
@@ -2348,6 +2348,7 @@
2684|[Maximum Number of Moves in a Grid](./solutions/2684-maximum-number-of-moves-in-a-grid.js)|Medium|
2685|[Count the Number of Complete Components](./solutions/2685-count-the-number-of-complete-components.js)|Medium|
2690|[Infinite Method Object](./solutions/2690-infinite-method-object.js)|Easy|
+2691|[Immutability Helper](./solutions/2691-immutability-helper.js)|Hard|
2693|[Call Function with Custom Context](./solutions/2693-call-function-with-custom-context.js)|Medium|
2694|[Event Emitter](./solutions/2694-event-emitter.js)|Medium|
2695|[Array Wrapper](./solutions/2695-array-wrapper.js)|Easy|
diff --git a/solutions/2691-immutability-helper.js b/solutions/2691-immutability-helper.js
new file mode 100644
index 00000000..ea1ffe51
--- /dev/null
+++ b/solutions/2691-immutability-helper.js
@@ -0,0 +1,82 @@
+/**
+ * 2691. Immutability Helper
+ * https://leetcode.com/problems/immutability-helper/
+ * Difficulty: Hard
+ *
+ * Creating clones of immutable objects with minor alterations can be a tedious process.
+ * Write a class ImmutableHelper that serves as a tool to help with this requirement.
+ * The constructor accepts an immutable object obj which will be a JSON object or array.
+ *
+ * The class has a single method produce which accepts a function mutator. The function
+ * returns a new object which is similar to the original except it has those mutations applied.
+ *
+ * mutator accepts a proxied version of obj. A user of this function can (appear to) mutate
+ * this object, but the original object obj should not actually be effected.
+ *
+ * For example, a user could write code like this:
+ * const originalObj = {"x": 5};
+ * const helper = new ImmutableHelper(originalObj);
+ * const newObj = helper.produce((proxy) => {
+ * proxy.x = proxy.x + 1;
+ * });
+ * console.log(originalObj); // {"x": 5}
+ * console.log(newObj); // {"x": 6}
+ *
+ * Properties of the mutator function:
+ * - It will always return undefined.
+ * - It will never access keys that don't exist.
+ * - It will never delete keys (delete obj.key)
+ * - It will never call methods on a proxied object (push, shift, etc).
+ * - It will never set keys to objects (proxy.x = {})
+ *
+ * Note on how the solution will be tested: the solution validator will only analyze differences
+ * between what was returned and the original obj. Doing a full comparison would be too
+ * computationally expensive. Also, any mutations to the original object will result in a
+ * wrong answer.
+ */
+
+var ImmutableHelper = function(obj) {
+ this.original = obj;
+};
+
+/**
+ * @param {Function} mutator
+ * @return {JSON} clone of obj
+ */
+ImmutableHelper.prototype.produce = function(mutator) {
+ const mutated = { _: this.original };
+
+ mutator(proxify(mutated, { _: this.original }, (field, value) => {
+ mutated[field] = value;
+ return mutated;
+ })._);
+
+ return mutated._;
+
+ function proxify(mutableObj, originalObj, setter) {
+ return new Proxy(mutableObj, {
+ set(_, property, value) {
+ mutableObj = setter(property, value);
+ },
+
+ get(_, property) {
+ let value = mutableObj[property];
+
+ if (!value || typeof value !== 'object') {
+ return value;
+ } else {
+ return proxify(value, originalObj[property], (field, newValue) => {
+ if (value === originalObj[property]) {
+ mutableObj = setter(
+ property,
+ value = Array.isArray(value) ? [...value] : { ...value }
+ );
+ }
+ value[field] = newValue;
+ return value;
+ });
+ }
+ }
+ });
+ }
+};
From 810c260b2a539662c7eedd47680c6055b6306827 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 23:40:12 -0500
Subject: [PATCH 780/994] Add solution #2692
---
README.md | 1 +
solutions/2692-make-object-immutable.js | 62 +++++++++++++++++++++++++
2 files changed, 63 insertions(+)
create mode 100644 solutions/2692-make-object-immutable.js
diff --git a/README.md b/README.md
index d2bb0e6f..85510180 100644
--- a/README.md
+++ b/README.md
@@ -2349,6 +2349,7 @@
2685|[Count the Number of Complete Components](./solutions/2685-count-the-number-of-complete-components.js)|Medium|
2690|[Infinite Method Object](./solutions/2690-infinite-method-object.js)|Easy|
2691|[Immutability Helper](./solutions/2691-immutability-helper.js)|Hard|
+2692|[Make Object Immutable](./solutions/2692-make-object-immutable.js)|Medium|
2693|[Call Function with Custom Context](./solutions/2693-call-function-with-custom-context.js)|Medium|
2694|[Event Emitter](./solutions/2694-event-emitter.js)|Medium|
2695|[Array Wrapper](./solutions/2695-array-wrapper.js)|Easy|
diff --git a/solutions/2692-make-object-immutable.js b/solutions/2692-make-object-immutable.js
new file mode 100644
index 00000000..00fb33e1
--- /dev/null
+++ b/solutions/2692-make-object-immutable.js
@@ -0,0 +1,62 @@
+/**
+ * 2692. Make Object Immutable
+ * https://leetcode.com/problems/make-object-immutable/
+ * Difficulty: Medium
+ *
+ * Write a function that takes an object obj and returns a new immutable version of this object.
+ *
+ * An immutable object is an object that can't be altered and will throw an error if any attempt
+ * is made to alter it.
+ *
+ * There are three types of error messages that can be produced from this new object.
+ * - Attempting to modify a key on the object will result in this error message:
+ * - `Error Modifying: ${key}`.
+ * - Attempting to modify an index on an array will result in this error message:
+ * - `Error Modifying Index: ${index}`.
+ * - Attempting to call a method that mutates an array will result in this error message:
+ * - `Error Calling Method: ${methodName}`.
+ * - You may assume the only methods that can mutate an array
+ * are ['pop', 'push', 'shift', 'unshift', 'splice', 'sort', 'reverse'].
+ *
+ * obj is a valid JSON object or array, meaning it is the output of JSON.parse().
+ *
+ * Note that a string literal should be thrown, not an Error.
+ */
+
+/**
+ * @param {Object|Array} obj
+ * @return {Object|Array} immutable obj
+ */
+var makeImmutable = function(obj) {
+ const mutatingMethods = new Set(['pop', 'push', 'shift', 'unshift', 'splice', 'sort', 'reverse']);
+
+ return new Proxy(obj, {
+ set(target, key) {
+ if (Array.isArray(target)) {
+ throw `Error Modifying Index: ${key}`;
+ }
+ throw `Error Modifying: ${key}`;
+ },
+
+ get(target, key) {
+ const value = target[key];
+
+ if (typeof value === 'object' && value !== null) {
+ return makeImmutable(value);
+ }
+
+ if (typeof value === 'function') {
+ return new Proxy(value, {
+ apply(...args) {
+ if (mutatingMethods.has(key)) {
+ throw `Error Calling Method: ${key}`;
+ }
+ return Reflect.apply(...args);
+ }
+ });
+ }
+
+ return value;
+ }
+ });
+};
From c53a3095f8f099b016938c44433e4d8a3d3a587b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 23:46:08 -0500
Subject: [PATCH 781/994] Add solution #2700
---
README.md | 1 +
.../2700-differences-between-two-objects.js | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/2700-differences-between-two-objects.js
diff --git a/README.md b/README.md
index 85510180..300361e9 100644
--- a/README.md
+++ b/README.md
@@ -2356,6 +2356,7 @@
2696|[Minimum String Length After Removing Substrings](./solutions/2696-minimum-string-length-after-removing-substrings.js)|Easy|
2697|[Lexicographically Smallest Palindrome](./solutions/2697-lexicographically-smallest-palindrome.js)|Easy|
2698|[Find the Punishment Number of an Integer](./solutions/2698-find-the-punishment-number-of-an-integer.js)|Medium|
+2700|[Differences Between Two Objects](./solutions/2700-differences-between-two-objects.js)|Medium|
2703|[Return Length of Arguments Passed](./solutions/2703-return-length-of-arguments-passed.js)|Easy|
2704|[To Be Or Not To Be](./solutions/2704-to-be-or-not-to-be.js)|Easy|
2705|[Compact Object](./solutions/2705-compact-object.js)|Medium|
diff --git a/solutions/2700-differences-between-two-objects.js b/solutions/2700-differences-between-two-objects.js
new file mode 100644
index 00000000..a62d9929
--- /dev/null
+++ b/solutions/2700-differences-between-two-objects.js
@@ -0,0 +1,50 @@
+/**
+ * 2700. Differences Between Two Objects
+ * https://leetcode.com/problems/differences-between-two-objects/
+ * Difficulty: Medium
+ *
+ * Write a function that accepts two deeply nested objects or arrays obj1 and obj2 and returns
+ * a new object representing their differences.
+ *
+ * The function should compare the properties of the two objects and identify any changes.
+ * The returned object should only contains keys where the value is different from obj1 to obj2.
+ *
+ * For each changed key, the value should be represented as an array [obj1 value, obj2 value].
+ * Keys that exist in one object but not in the other should not be included in the returned
+ * object. The end result should be a deeply nested object where each leaf value is a
+ * difference array.
+ *
+ * When comparing two arrays, the indices of the arrays are considered to be their keys.
+ *
+ * You may assume that both objects are the output of JSON.parse.
+ */
+
+/**
+ * @param {Object|Array} obj1
+ * @param {Object|Array} obj2
+ * @return {Object|Array}
+ */
+function objDiff(obj1, obj2) {
+ if (obj1 === obj2) return {};
+
+ if (obj1 === null || obj2 === null || typeof obj1 !== typeof obj2
+ || typeof obj1 !== 'object') {
+ return [obj1, obj2];
+ }
+
+ if (Array.isArray(obj1) !== Array.isArray(obj2)) {
+ return [obj1, obj2];
+ }
+
+ const result = {};
+ for (const key in obj1) {
+ if (key in obj2) {
+ const difference = objDiff(obj1[key], obj2[key]);
+ if (Object.keys(difference).length > 0 || Array.isArray(difference)) {
+ result[key] = difference;
+ }
+ }
+ }
+
+ return result;
+}
From 06fed1f1e7a91f5260277411482ac89a50259ec6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 23:47:51 -0500
Subject: [PATCH 782/994] Add solution #2754
---
README.md | 1 +
solutions/2754-bind-function-to-context.js | 38 ++++++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2754-bind-function-to-context.js
diff --git a/README.md b/README.md
index 300361e9..37904c44 100644
--- a/README.md
+++ b/README.md
@@ -2386,6 +2386,7 @@
2745|[Construct the Longest New String](./solutions/2745-construct-the-longest-new-string.js)|Medium|
2748|[Number of Beautiful Pairs](./solutions/2748-number-of-beautiful-pairs.js)|Easy|
2751|[Robot Collisions](./solutions/2751-robot-collisions.js)|Hard|
+2754|[Bind Function to Context](./solutions/2754-bind-function-to-context.js)|Medium|
2763|[Sum of Imbalance Numbers of All Subarrays](./solutions/2763-sum-of-imbalance-numbers-of-all-subarrays.js)|Hard|
2766|[Relocate Marbles](./solutions/2766-relocate-marbles.js)|Medium|
2767|[Partition String Into Minimum Beautiful Substrings](./solutions/2767-partition-string-into-minimum-beautiful-substrings.js)|Medium|
diff --git a/solutions/2754-bind-function-to-context.js b/solutions/2754-bind-function-to-context.js
new file mode 100644
index 00000000..169a61ba
--- /dev/null
+++ b/solutions/2754-bind-function-to-context.js
@@ -0,0 +1,38 @@
+/**
+ * 2754. Bind Function to Context
+ * https://leetcode.com/problems/bind-function-to-context/
+ * Difficulty: Medium
+ *
+ * Enhance all functions to have the bindPolyfill method. When bindPolyfill is called with
+ * a passed object obj, that object becomes the this context for the function.
+ *
+ * For example, if you had the code:
+ * function f() {
+ * console.log('My context is ' + this.ctx);
+ * }
+ * f();
+ *
+ * The output would be "My context is undefined". However, if you bound the function:
+ * function f() {
+ * console.log('My context is ' + this.ctx);
+ * }
+ * const boundFunc = f.boundPolyfill({ "ctx": "My Object" })
+ * boundFunc();
+ *
+ * The output should be "My context is My Object".
+ *
+ * You may assume that a single non-null object will be passed to the bindPolyfill method.
+ *
+ * Please solve it without the built-in Function.bind method.
+ */
+
+/**
+ * @param {Object} obj
+ * @return {Function}
+ */
+Function.prototype.bindPolyfill = function(obj) {
+ var fn = this;
+ return function() {
+ return fn.apply(obj, arguments);
+ };
+};
From 18da7077078b940d6bd75e2d818f9eb610afc3f9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 23:50:03 -0500
Subject: [PATCH 783/994] Add solution #2755
---
README.md | 1 +
solutions/2755-deep-merge-of-two-objects.js | 59 +++++++++++++++++++++
2 files changed, 60 insertions(+)
create mode 100644 solutions/2755-deep-merge-of-two-objects.js
diff --git a/README.md b/README.md
index 37904c44..ebaeb607 100644
--- a/README.md
+++ b/README.md
@@ -2387,6 +2387,7 @@
2748|[Number of Beautiful Pairs](./solutions/2748-number-of-beautiful-pairs.js)|Easy|
2751|[Robot Collisions](./solutions/2751-robot-collisions.js)|Hard|
2754|[Bind Function to Context](./solutions/2754-bind-function-to-context.js)|Medium|
+2755|[Deep Merge of Two Objects](./solutions/2755-deep-merge-of-two-objects.js)|Medium|
2763|[Sum of Imbalance Numbers of All Subarrays](./solutions/2763-sum-of-imbalance-numbers-of-all-subarrays.js)|Hard|
2766|[Relocate Marbles](./solutions/2766-relocate-marbles.js)|Medium|
2767|[Partition String Into Minimum Beautiful Substrings](./solutions/2767-partition-string-into-minimum-beautiful-substrings.js)|Medium|
diff --git a/solutions/2755-deep-merge-of-two-objects.js b/solutions/2755-deep-merge-of-two-objects.js
new file mode 100644
index 00000000..f9775813
--- /dev/null
+++ b/solutions/2755-deep-merge-of-two-objects.js
@@ -0,0 +1,59 @@
+/**
+ * 2755. Deep Merge of Two Objects
+ * https://leetcode.com/problems/deep-merge-of-two-objects/
+ * Difficulty: Medium
+ *
+ * Given two values obj1 and obj2, return a deepmerged value.
+ *
+ * Values should be deepmerged according to these rules:
+ * - If the two values are objects, the resulting object should have all the keys that exist
+ * on either object. If a key belongs to both objects, deepmerge the two associated values.
+ * Otherwise, add the key-value pair to the resulting object.
+ * - If the two values are arrays, the resulting array should be the same length as the longer
+ * array. Apply the same logic as you would with objects, but treat the indices as keys.
+ * - Otherwise the resulting value is obj2.
+ *
+ * You can assume obj1 and obj2 are the output of JSON.parse().
+ */
+
+/**
+ * @param {null|boolean|number|string|Array|Object} obj1
+ * @param {null|boolean|number|string|Array|Object} obj2
+ * @return {null|boolean|number|string|Array|Object}
+ */
+var deepMerge = function(obj1, obj2) {
+ if (obj2 === null || typeof obj2 !== 'object') {
+ return obj2;
+ }
+
+ if (obj1 === null || typeof obj1 !== 'object') {
+ return obj2;
+ }
+
+ if (Array.isArray(obj1) !== Array.isArray(obj2)) {
+ return obj2;
+ }
+
+ if (Array.isArray(obj1)) {
+ const maxLength = Math.max(obj1.length, obj2.length);
+ const result = [];
+
+ for (let i = 0; i < maxLength; i++) {
+ if (i < obj2.length) {
+ result[i] = deepMerge(obj1[i], obj2[i]);
+ } else {
+ result[i] = obj1[i];
+ }
+ }
+
+ return result;
+ }
+
+ const result = { ...obj1 };
+
+ Object.keys(obj2).forEach(key => {
+ result[key] = deepMerge(obj1[key], obj2[key]);
+ });
+
+ return result;
+};
From 47091715f6d7239d92c2b2800988263c27313c5b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 23:54:47 -0500
Subject: [PATCH 784/994] Add solution #2756
---
README.md | 1 +
solutions/2756-query-batching.js | 80 ++++++++++++++++++++++++++++++++
2 files changed, 81 insertions(+)
create mode 100644 solutions/2756-query-batching.js
diff --git a/README.md b/README.md
index ebaeb607..08cfd271 100644
--- a/README.md
+++ b/README.md
@@ -2388,6 +2388,7 @@
2751|[Robot Collisions](./solutions/2751-robot-collisions.js)|Hard|
2754|[Bind Function to Context](./solutions/2754-bind-function-to-context.js)|Medium|
2755|[Deep Merge of Two Objects](./solutions/2755-deep-merge-of-two-objects.js)|Medium|
+2756|[Query Batching](./solutions/2756-query-batching.js)|Hard|
2763|[Sum of Imbalance Numbers of All Subarrays](./solutions/2763-sum-of-imbalance-numbers-of-all-subarrays.js)|Hard|
2766|[Relocate Marbles](./solutions/2766-relocate-marbles.js)|Medium|
2767|[Partition String Into Minimum Beautiful Substrings](./solutions/2767-partition-string-into-minimum-beautiful-substrings.js)|Medium|
diff --git a/solutions/2756-query-batching.js b/solutions/2756-query-batching.js
new file mode 100644
index 00000000..56072f39
--- /dev/null
+++ b/solutions/2756-query-batching.js
@@ -0,0 +1,80 @@
+/**
+ * 2756. Query Batching
+ * https://leetcode.com/problems/query-batching/
+ * Difficulty: Hard
+ *
+ * Batching multiple small queries into a single large query can be a useful optimization.
+ * Write a class QueryBatcher that implements this functionality.
+ *
+ * The constructor should accept two parameters:
+ * - An asynchronous function queryMultiple which accepts an array of string keys input. It will
+ * resolve with an array of values that is the same length as the input array. Each index
+ * corresponds to the value associated with input[i]. You can assume the promise will never
+ * reject.
+ * - A throttle time in milliseconds t.
+ *
+ * The class has a single method.
+ * - async getValue(key). Accepts a single string key and resolves with a single string value.
+ * The keys passed to this function should eventually get passed to the queryMultiple function.
+ * queryMultiple should never be called consecutively within t milliseconds. The first time
+ * getValue is called, queryMultiple should immediately be called with that single key.
+ * If after t milliseconds, getValue had been called again, all the passed keys should be
+ * passed to queryMultiple and ultimately returned. You can assume every key passed to this
+ * method is unique.
+ *
+ * The following diagram illustrates how the throttling algorithm works. Each rectangle represents
+ * 100ms. The throttle time is 400ms.
+ */
+
+/**
+ * @param {Function} queryMultiple
+ * @param {number} t
+ * @return {void}
+ */
+var QueryBatcher = function(queryMultiple, t) {
+ this.queryMultiple = queryMultiple;
+ this.throttleTime = t;
+ this.pendingRequests = [];
+ this.batchTimer = null;
+ this.lastExecutionTime = 0;
+};
+
+/**
+ * @param {string} key
+ * @return {Promise}
+ */
+QueryBatcher.prototype.getValue = function(key) {
+ return new Promise((resolve) => {
+ const currentTime = Date.now();
+ const timeSinceLastExecution = currentTime - this.lastExecutionTime;
+ const remainingDelay = Math.max(0, this.throttleTime - timeSinceLastExecution);
+
+ this.lastExecutionTime = currentTime + remainingDelay;
+
+ this.pendingRequests.push({ key, resolve });
+
+ if (!this.batchTimer) {
+ clearTimeout(this.batchTimer);
+ this.batchTimer = setTimeout(() => this.executeBatch(), remainingDelay);
+ }
+ });
+};
+
+/**
+ * @return {Promise}
+ */
+QueryBatcher.prototype.executeBatch = async function() {
+ const currentBatch = this.pendingRequests.slice();
+ this.pendingRequests = [];
+ this.batchTimer = null;
+
+ const keys = currentBatch.map((request) => request.key);
+ const resolvers = currentBatch.map((request) => request.resolve);
+
+ this.lastExecutionTime = Date.now();
+ const results = await this.queryMultiple(keys);
+
+ for (let i = 0; i < keys.length; i++) {
+ resolvers[i](results[i]);
+ }
+};
From b1a107796d5980de6634af531f72a3e90a60c41d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 11 Jul 2025 23:56:05 -0500
Subject: [PATCH 785/994] Add solution #2757
---
README.md | 1 +
.../2757-generate-circular-array-values.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/2757-generate-circular-array-values.js
diff --git a/README.md b/README.md
index 08cfd271..6a0d18ba 100644
--- a/README.md
+++ b/README.md
@@ -2389,6 +2389,7 @@
2754|[Bind Function to Context](./solutions/2754-bind-function-to-context.js)|Medium|
2755|[Deep Merge of Two Objects](./solutions/2755-deep-merge-of-two-objects.js)|Medium|
2756|[Query Batching](./solutions/2756-query-batching.js)|Hard|
+2757|[Generate Circular Array Values](./solutions/2757-generate-circular-array-values.js)|Medium|
2763|[Sum of Imbalance Numbers of All Subarrays](./solutions/2763-sum-of-imbalance-numbers-of-all-subarrays.js)|Hard|
2766|[Relocate Marbles](./solutions/2766-relocate-marbles.js)|Medium|
2767|[Partition String Into Minimum Beautiful Substrings](./solutions/2767-partition-string-into-minimum-beautiful-substrings.js)|Medium|
diff --git a/solutions/2757-generate-circular-array-values.js b/solutions/2757-generate-circular-array-values.js
new file mode 100644
index 00000000..260384e6
--- /dev/null
+++ b/solutions/2757-generate-circular-array-values.js
@@ -0,0 +1,34 @@
+/**
+ * 2757. Generate Circular Array Values
+ * https://leetcode.com/problems/generate-circular-array-values/
+ * Difficulty: Medium
+ *
+ * Given a circular array arr and an integer startIndex, return a generator object gen that
+ * yields values from arr.
+ *
+ * The first time gen.next() is called on the generator, it should should yield arr[startIndex].
+ *
+ * Each subsequent time gen.next() is called, an integer jump will be passed into the function
+ * (Ex: gen.next(-3)).
+ * - If jump is positive, the index should increase by that value, however if the current index
+ * is the last index, it should instead jump to the first index.
+ * - If jump is negative, the index should decrease by the magnitude of that value, however if
+ * the current index is the first index, it should instead jump to the last index.
+ */
+
+/**
+ * @param {Array} arr
+ * @param {number} startIndex
+ * @yields {number}
+ */
+var cycleGenerator = function* (arr, startIndex) {
+ let currentIndex = startIndex;
+
+ while (true) {
+ const jump = yield arr[currentIndex];
+
+ if (jump !== undefined) {
+ currentIndex = ((currentIndex + jump) % arr.length + arr.length) % arr.length;
+ }
+ }
+};
From 43fee80e7ccfc41cfd3a83b9390b3ba74f3f9e80 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 12:44:24 -0500
Subject: [PATCH 786/994] Add solution #2758
---
README.md | 1 +
solutions/2758-next-day.js | 17 +++++++++++++++++
2 files changed, 18 insertions(+)
create mode 100644 solutions/2758-next-day.js
diff --git a/README.md b/README.md
index 6a0d18ba..7c4776ea 100644
--- a/README.md
+++ b/README.md
@@ -2390,6 +2390,7 @@
2755|[Deep Merge of Two Objects](./solutions/2755-deep-merge-of-two-objects.js)|Medium|
2756|[Query Batching](./solutions/2756-query-batching.js)|Hard|
2757|[Generate Circular Array Values](./solutions/2757-generate-circular-array-values.js)|Medium|
+2758|[Next Day](./solutions/2758-next-day.js)|Easy|
2763|[Sum of Imbalance Numbers of All Subarrays](./solutions/2763-sum-of-imbalance-numbers-of-all-subarrays.js)|Hard|
2766|[Relocate Marbles](./solutions/2766-relocate-marbles.js)|Medium|
2767|[Partition String Into Minimum Beautiful Substrings](./solutions/2767-partition-string-into-minimum-beautiful-substrings.js)|Medium|
diff --git a/solutions/2758-next-day.js b/solutions/2758-next-day.js
new file mode 100644
index 00000000..9ec99596
--- /dev/null
+++ b/solutions/2758-next-day.js
@@ -0,0 +1,17 @@
+/**
+ * 2758. Next Day
+ * https://leetcode.com/problems/next-day/
+ * Difficulty: Easy
+ *
+ * Write code that enhances all date objects such that you can call the date.nextDay() method
+ * on any date object and it will return the next day in the format YYYY-MM-DD as a string.
+ */
+
+/**
+ * @return {string}
+ */
+Date.prototype.nextDay = function() {
+ const nextDate = new Date(this);
+ nextDate.setDate(nextDate.getDate() + 1);
+ return nextDate.toISOString().split('T')[0];
+}
From 3fc9f56cddf1fe57f8b873575c53f3d17a30408d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 12:47:16 -0500
Subject: [PATCH 787/994] Add solution #2759
---
README.md | 1 +
.../2759-convert-json-string-to-object.js | 82 +++++++++++++++++++
2 files changed, 83 insertions(+)
create mode 100644 solutions/2759-convert-json-string-to-object.js
diff --git a/README.md b/README.md
index 7c4776ea..85effa49 100644
--- a/README.md
+++ b/README.md
@@ -2391,6 +2391,7 @@
2756|[Query Batching](./solutions/2756-query-batching.js)|Hard|
2757|[Generate Circular Array Values](./solutions/2757-generate-circular-array-values.js)|Medium|
2758|[Next Day](./solutions/2758-next-day.js)|Easy|
+2759|[Convert JSON String to Object](./solutions/2759-convert-json-string-to-object.js)|Hard|
2763|[Sum of Imbalance Numbers of All Subarrays](./solutions/2763-sum-of-imbalance-numbers-of-all-subarrays.js)|Hard|
2766|[Relocate Marbles](./solutions/2766-relocate-marbles.js)|Medium|
2767|[Partition String Into Minimum Beautiful Substrings](./solutions/2767-partition-string-into-minimum-beautiful-substrings.js)|Medium|
diff --git a/solutions/2759-convert-json-string-to-object.js b/solutions/2759-convert-json-string-to-object.js
new file mode 100644
index 00000000..4157918e
--- /dev/null
+++ b/solutions/2759-convert-json-string-to-object.js
@@ -0,0 +1,82 @@
+/**
+ * 2759. Convert JSON String to Object
+ * https://leetcode.com/problems/convert-json-string-to-object/
+ * Difficulty: Hard
+ *
+ * Given a string str, return parsed JSON parsedStr. You may assume the str is a valid JSON
+ * string hence it only includes strings, numbers, arrays, objects, booleans, and null. str
+ * will not include invisible characters and escape characters.
+ *
+ * Please solve it without using the built-in JSON.parse method.
+ */
+
+/**
+ * @param {string} str
+ * @return {null|boolean|number|string|Array|Object}
+ */
+var jsonParse = function(str) {
+ const length = str.length;
+ const stack = [];
+ let currentValue = null;
+ let pendingKey = null;
+
+ for (let index = 0; index < length; index++) {
+ if (str[index] === ',') continue;
+
+ if (str[index] === '[' || str[index] === '{') {
+ stack.push(currentValue);
+ let newContainer = null;
+ if (str[index] === '[') newContainer = [];
+ else newContainer = {};
+
+ if (Array.isArray(currentValue)) currentValue.push(newContainer);
+ else if (pendingKey !== null) {
+ currentValue[pendingKey] = newContainer;
+ pendingKey = null;
+ }
+ currentValue = newContainer;
+ } else if (str[index] === ']' || str[index] === '}') {
+ const previousValue = stack.pop();
+ if (index !== length - 1) currentValue = previousValue;
+ } else {
+ let parsedValue = null;
+
+ if (str[index] === '"') {
+ const startIndex = index + 1;
+ while (index + 1 < length && str[index + 1] !== '"') index++;
+ parsedValue = str.substring(startIndex, index + 1);
+ index++;
+ } else if (str[index] === '-' || ('0' <= str[index] && str[index] <= '9')) {
+ const startIndex = index;
+ while (index + 1 < length && (str[index + 1] === '-'
+ || ('0' <= str[index + 1] && str[index + 1] <= '9') || str[index + 1] === '.')) {
+ index++;
+ }
+ parsedValue = Number(str.substring(startIndex, index + 1));
+ } else {
+ if (index + 4 <= length && str.substring(index, index + 4) === 'true') {
+ parsedValue = true;
+ } else if (index + 5 <= length && str.substring(index, index + 5) === 'false') {
+ parsedValue = false;
+ } else {
+ parsedValue = null;
+ }
+ index += parsedValue || parsedValue === null ? 3 : 4;
+ }
+
+ if (str[index + 1] === ':') {
+ pendingKey = parsedValue;
+ index++;
+ } else if (Array.isArray(currentValue)) {
+ currentValue.push(parsedValue);
+ } else if (pendingKey !== null) {
+ currentValue[pendingKey] = parsedValue;
+ pendingKey = null;
+ } else {
+ currentValue = parsedValue;
+ }
+ }
+ }
+
+ return currentValue;
+};
From 62d44d08b9cb91cbd75ba99467b2da8d36446d19 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 12:48:25 -0500
Subject: [PATCH 788/994] Add solution #2774
---
README.md | 1 +
solutions/2774-array-upper-bound.js | 35 +++++++++++++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/2774-array-upper-bound.js
diff --git a/README.md b/README.md
index 85effa49..bfc6e40f 100644
--- a/README.md
+++ b/README.md
@@ -2396,6 +2396,7 @@
2766|[Relocate Marbles](./solutions/2766-relocate-marbles.js)|Medium|
2767|[Partition String Into Minimum Beautiful Substrings](./solutions/2767-partition-string-into-minimum-beautiful-substrings.js)|Medium|
2769|[Find the Maximum Achievable Number](./solutions/2769-find-the-maximum-achievable-number.js)|Easy|
+2774|[Array Upper Bound](./solutions/2774-array-upper-bound.js)|Easy|
2778|[Sum of Squares of Special Elements](./solutions/2778-sum-of-squares-of-special-elements.js)|Easy|
2779|[Maximum Beauty of an Array After Applying Operation](./solutions/2779-maximum-beauty-of-an-array-after-applying-operation.js)|Medium|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
diff --git a/solutions/2774-array-upper-bound.js b/solutions/2774-array-upper-bound.js
new file mode 100644
index 00000000..4600ca60
--- /dev/null
+++ b/solutions/2774-array-upper-bound.js
@@ -0,0 +1,35 @@
+/**
+ * 2774. Array Upper Bound
+ * https://leetcode.com/problems/array-upper-bound/
+ * Difficulty: Easy
+ *
+ * Write code that enhances all arrays such that you can call the upperBound() method on any
+ * array and it will return the last index of a given target number. nums is a sorted ascending
+ * array of numbers that may contain duplicates. If the target number is not found in the array,
+ * return -1.
+ */
+
+/**
+ * @param {number} target
+ * @return {number}
+ */
+Array.prototype.upperBound = function(target) {
+ let left = 0;
+ let right = this.length - 1;
+ let result = -1;
+
+ while (left <= right) {
+ const mid = Math.floor((left + right) / 2);
+
+ if (this[mid] === target) {
+ result = mid;
+ left = mid + 1;
+ } else if (this[mid] < target) {
+ left = mid + 1;
+ } else {
+ right = mid - 1;
+ }
+ }
+
+ return result;
+};
From 03b967d73a92f7aa8fa139b08a5d96a26c0f8507 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 12:50:28 -0500
Subject: [PATCH 789/994] Add solution #2775
---
README.md | 1 +
solutions/2775-undefined-to-null.js | 37 +++++++++++++++++++++++++++++
2 files changed, 38 insertions(+)
create mode 100644 solutions/2775-undefined-to-null.js
diff --git a/README.md b/README.md
index bfc6e40f..09de2c24 100644
--- a/README.md
+++ b/README.md
@@ -2397,6 +2397,7 @@
2767|[Partition String Into Minimum Beautiful Substrings](./solutions/2767-partition-string-into-minimum-beautiful-substrings.js)|Medium|
2769|[Find the Maximum Achievable Number](./solutions/2769-find-the-maximum-achievable-number.js)|Easy|
2774|[Array Upper Bound](./solutions/2774-array-upper-bound.js)|Easy|
+2775|[Undefined to Null](./solutions/2775-undefined-to-null.js)|Medium|
2778|[Sum of Squares of Special Elements](./solutions/2778-sum-of-squares-of-special-elements.js)|Easy|
2779|[Maximum Beauty of an Array After Applying Operation](./solutions/2779-maximum-beauty-of-an-array-after-applying-operation.js)|Medium|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
diff --git a/solutions/2775-undefined-to-null.js b/solutions/2775-undefined-to-null.js
new file mode 100644
index 00000000..c2c6ed7b
--- /dev/null
+++ b/solutions/2775-undefined-to-null.js
@@ -0,0 +1,37 @@
+/**
+ * 2775. Undefined to Null
+ * https://leetcode.com/problems/undefined-to-null/
+ * Difficulty: Medium
+ *
+ * Given a deeply nested object or array obj, return the object obj with any undefined
+ * values replaced by null.
+ *
+ * undefined values are handled differently than null values when objects are converted
+ * to a JSON string using JSON.stringify(). This function helps ensure serialized data
+ * is free of unexpected errors.
+ */
+
+/**
+ * @param {Object|Array} obj
+ * @return {Object|Array}
+ */
+var undefinedToNull = function(obj) {
+ if (obj === undefined) {
+ return null;
+ }
+
+ if (obj === null || typeof obj !== 'object') {
+ return obj;
+ }
+
+ if (Array.isArray(obj)) {
+ return obj.map(item => undefinedToNull(item));
+ }
+
+ const result = {};
+ Object.keys(obj).forEach(key => {
+ result[key] = undefinedToNull(obj[key]);
+ });
+
+ return result;
+};
From b3090072d46d4fdf9d95b5cbafc5a0a52fe7154b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 12:52:35 -0500
Subject: [PATCH 790/994] Add solution #2776
---
README.md | 1 +
...ased-function-to-promise-based-function.js | 54 +++++++++++++++++++
2 files changed, 55 insertions(+)
create mode 100644 solutions/2776-convert-callback-based-function-to-promise-based-function.js
diff --git a/README.md b/README.md
index 09de2c24..94f9c657 100644
--- a/README.md
+++ b/README.md
@@ -2398,6 +2398,7 @@
2769|[Find the Maximum Achievable Number](./solutions/2769-find-the-maximum-achievable-number.js)|Easy|
2774|[Array Upper Bound](./solutions/2774-array-upper-bound.js)|Easy|
2775|[Undefined to Null](./solutions/2775-undefined-to-null.js)|Medium|
+2776|[Convert Callback Based Function to Promise Based Function](./solutions/2776-convert-callback-based-function-to-promise-based-function.js)|Medium|
2778|[Sum of Squares of Special Elements](./solutions/2778-sum-of-squares-of-special-elements.js)|Easy|
2779|[Maximum Beauty of an Array After Applying Operation](./solutions/2779-maximum-beauty-of-an-array-after-applying-operation.js)|Medium|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
diff --git a/solutions/2776-convert-callback-based-function-to-promise-based-function.js b/solutions/2776-convert-callback-based-function-to-promise-based-function.js
new file mode 100644
index 00000000..347396ca
--- /dev/null
+++ b/solutions/2776-convert-callback-based-function-to-promise-based-function.js
@@ -0,0 +1,54 @@
+/**
+ * 2776. Convert Callback Based Function to Promise Based Function
+ * https://leetcode.com/problems/convert-callback-based-function-to-promise-based-function/
+ * Difficulty: Medium
+ *
+ * Write a function that accepts another function fn and converts the callback-based function into
+ * a promise-based function.
+ *
+ * The function fn takes a callback as its first argument, along with any additional arguments
+ * args passed as separate inputs.
+ *
+ * The promisify function returns a new function that should return a promise. The promise should
+ * resolve with the argument passed as the first parameter of the callback when the callback is
+ * invoked without error, and reject with the error when the callback is called with an error as
+ * the second argument.
+ *
+ * The following is an example of a function that could be passed into promisify.
+ * function sum(callback, a, b) {
+ * if (a < 0 || b < 0) {
+ * const err = Error('a and b must be positive');
+ * callback(undefined, err);
+ * } else {
+ * callback(a + b);
+ * }
+ * }
+ *
+ * This is the equivalent code based on promises:
+ *
+ * async function sum(a, b) {
+ * if (a < 0 || b < 0) {
+ * throw Error('a and b must be positive');
+ * } else {
+ * return a + b;
+ * }
+ * }
+ * */
+
+/**
+ * @param {Function} fn
+ * @return {Function>}
+ */
+var promisify = function(fn) {
+ return async function(...args) {
+ return new Promise((resolve, reject) => {
+ fn((result, error) => {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(result);
+ }
+ }, ...args);
+ });
+ };
+};
From 62afb31ceeb0b1a26fb82c5c6c35483e1643244a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 13:45:38 -0500
Subject: [PATCH 791/994] Add solution #2777
---
README.md | 1 +
solutions/2777-date-range-generator.js | 29 ++++++++++++++++++++++++++
2 files changed, 30 insertions(+)
create mode 100644 solutions/2777-date-range-generator.js
diff --git a/README.md b/README.md
index 94f9c657..7331f003 100644
--- a/README.md
+++ b/README.md
@@ -2399,6 +2399,7 @@
2774|[Array Upper Bound](./solutions/2774-array-upper-bound.js)|Easy|
2775|[Undefined to Null](./solutions/2775-undefined-to-null.js)|Medium|
2776|[Convert Callback Based Function to Promise Based Function](./solutions/2776-convert-callback-based-function-to-promise-based-function.js)|Medium|
+2777|[Date Range Generator](./solutions/2777-date-range-generator.js)|Medium|
2778|[Sum of Squares of Special Elements](./solutions/2778-sum-of-squares-of-special-elements.js)|Easy|
2779|[Maximum Beauty of an Array After Applying Operation](./solutions/2779-maximum-beauty-of-an-array-after-applying-operation.js)|Medium|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
diff --git a/solutions/2777-date-range-generator.js b/solutions/2777-date-range-generator.js
new file mode 100644
index 00000000..f1fb2b4b
--- /dev/null
+++ b/solutions/2777-date-range-generator.js
@@ -0,0 +1,29 @@
+/**
+ * 2777. Date Range Generator
+ * https://leetcode.com/problems/date-range-generator/
+ * Difficulty: Medium
+ *
+ * Given a start date start, an end date end, and a positive integer step, return a generator
+ * object that yields dates in the range from start to end inclusive.
+ *
+ * The value of step indicates the number of days between consecutive yielded values.
+ *
+ * All yielded dates must be in the string format YYYY-MM-DD.
+ */
+
+/**
+ * @param {string} start
+ * @param {string} end
+ * @param {number} step
+ * @yields {string}
+ */
+var dateRangeGenerator = function* (start, end, step) {
+ const startDate = new Date(start);
+ const endDate = new Date(end);
+ const currentDate = new Date(startDate);
+
+ while (currentDate <= endDate) {
+ yield currentDate.toISOString().split('T')[0];
+ currentDate.setDate(currentDate.getDate() + step);
+ }
+};
From 8ee8391755c59ca160d842d885e373ea6273cdeb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 13:46:50 -0500
Subject: [PATCH 792/994] Add solution #2794
---
README.md | 1 +
.../2794-create-object-from-two-arrays.js | 31 +++++++++++++++++++
2 files changed, 32 insertions(+)
create mode 100644 solutions/2794-create-object-from-two-arrays.js
diff --git a/README.md b/README.md
index 7331f003..9462c4a0 100644
--- a/README.md
+++ b/README.md
@@ -2408,6 +2408,7 @@
2788|[Split Strings by Separator](./solutions/2788-split-strings-by-separator.js)|Easy|
2789|[Largest Element in an Array after Merge Operations](./solutions/2789-largest-element-in-an-array-after-merge-operations.js)|Medium|
2791|[Count Paths That Can Form a Palindrome in a Tree](./solutions/2791-count-paths-that-can-form-a-palindrome-in-a-tree.js)|Hard|
+2794|[Create Object from Two Arrays](./solutions/2794-create-object-from-two-arrays.js)|Easy|
2798|[Number of Employees Who Met the Target](./solutions/2798-number-of-employees-who-met-the-target.js)|Easy|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2806|[Account Balance After Rounded Purchase](./solutions/2806-account-balance-after-rounded-purchase.js)|Easy|
diff --git a/solutions/2794-create-object-from-two-arrays.js b/solutions/2794-create-object-from-two-arrays.js
new file mode 100644
index 00000000..4fcfd1e7
--- /dev/null
+++ b/solutions/2794-create-object-from-two-arrays.js
@@ -0,0 +1,31 @@
+/**
+ * 2794. Create Object from Two Arrays
+ * https://leetcode.com/problems/create-object-from-two-arrays/
+ * Difficulty: Easy
+ *
+ * Given two arrays keysArr and valuesArr, return a new object obj. Each key-value pair in obj
+ * should come from keysArr[i] and valuesArr[i].
+ *
+ * If a duplicate key exists at a previous index, that key-value should be excluded. In other
+ * words, only the first key should be added to the object.
+ *
+ * If the key is not a string, it should be converted into a string by calling String() on it.
+ */
+
+/**
+ * @param {Array} keysArr
+ * @param {Array} valuesArr
+ * @return {Object}
+ */
+var createObject = function(keysArr, valuesArr) {
+ const result = {};
+
+ for (let i = 0; i < keysArr.length; i++) {
+ const stringKey = String(keysArr[i]);
+ if (!(stringKey in result)) {
+ result[stringKey] = valuesArr[i];
+ }
+ }
+
+ return result;
+};
From ffae9fc70882fcbb860c2f530c879b9d5b8455f3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 13:49:11 -0500
Subject: [PATCH 793/994] Add solution #2795
---
README.md | 1 +
...omises-for-individual-results-retrieval.js | 43 +++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/2795-parallel-execution-of-promises-for-individual-results-retrieval.js
diff --git a/README.md b/README.md
index 9462c4a0..65c28a3f 100644
--- a/README.md
+++ b/README.md
@@ -2409,6 +2409,7 @@
2789|[Largest Element in an Array after Merge Operations](./solutions/2789-largest-element-in-an-array-after-merge-operations.js)|Medium|
2791|[Count Paths That Can Form a Palindrome in a Tree](./solutions/2791-count-paths-that-can-form-a-palindrome-in-a-tree.js)|Hard|
2794|[Create Object from Two Arrays](./solutions/2794-create-object-from-two-arrays.js)|Easy|
+2795|[Parallel Execution of Promises for Individual Results Retrieval](./solutions/2795-parallel-execution-of-promises-for-individual-results-retrieval.js)|Medium|
2798|[Number of Employees Who Met the Target](./solutions/2798-number-of-employees-who-met-the-target.js)|Easy|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2806|[Account Balance After Rounded Purchase](./solutions/2806-account-balance-after-rounded-purchase.js)|Easy|
diff --git a/solutions/2795-parallel-execution-of-promises-for-individual-results-retrieval.js b/solutions/2795-parallel-execution-of-promises-for-individual-results-retrieval.js
new file mode 100644
index 00000000..5638a94b
--- /dev/null
+++ b/solutions/2795-parallel-execution-of-promises-for-individual-results-retrieval.js
@@ -0,0 +1,43 @@
+/**
+ * 2795. Parallel Execution of Promises for Individual Results Retrieval
+ * https://leetcode.com/problems/parallel-execution-of-promises-for-individual-results-retrieval/
+ * Difficulty: Medium
+ *
+ * Given an array functions, return a promise promise. functions is an array of functions that
+ * return promises fnPromise. Each fnPromise can be resolved or rejected.
+ *
+ * If fnPromise is resolved:
+ *
+ * obj = { status: "fulfilled", value: resolved value}
+ *
+ * If fnPromise is rejected:
+ *
+ * obj = { status: "rejected", reason: reason of rejection (catched error message)}
+ *
+ * The promise should resolve with an array of these objects obj. Each obj in the array should
+ * correspond to the promises in the original array function, maintaining the same order.
+ *
+ * Try to implement it without using the built-in method Promise.allSettled().
+ */
+
+/**
+ * @param {Array} functions
+ * @return {Promise}
+ */
+var promiseAllSettled = function(functions) {
+ return new Promise(resolve => {
+ const results = new Array(functions.length);
+ let completedCount = 0;
+
+ functions.forEach((fn, index) => {
+ fn().then(value => results[index] = { status: 'fulfilled', value })
+ .catch(reason => results[index] = { status: 'rejected', reason })
+ .finally(() => {
+ completedCount++;
+ if (completedCount === functions.length) {
+ resolve(results);
+ }
+ });
+ });
+ });
+};
From a3b9b0d4e94234a6f91826a140a5b81b84cd5ffe Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 13:50:28 -0500
Subject: [PATCH 794/994] Add solution #2796
---
README.md | 1 +
solutions/2796-repeat-string.js | 22 ++++++++++++++++++++++
2 files changed, 23 insertions(+)
create mode 100644 solutions/2796-repeat-string.js
diff --git a/README.md b/README.md
index 65c28a3f..eced8ac4 100644
--- a/README.md
+++ b/README.md
@@ -2410,6 +2410,7 @@
2791|[Count Paths That Can Form a Palindrome in a Tree](./solutions/2791-count-paths-that-can-form-a-palindrome-in-a-tree.js)|Hard|
2794|[Create Object from Two Arrays](./solutions/2794-create-object-from-two-arrays.js)|Easy|
2795|[Parallel Execution of Promises for Individual Results Retrieval](./solutions/2795-parallel-execution-of-promises-for-individual-results-retrieval.js)|Medium|
+2796|[Repeat String](./solutions/2796-repeat-string.js)|Easy|
2798|[Number of Employees Who Met the Target](./solutions/2798-number-of-employees-who-met-the-target.js)|Easy|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2806|[Account Balance After Rounded Purchase](./solutions/2806-account-balance-after-rounded-purchase.js)|Easy|
diff --git a/solutions/2796-repeat-string.js b/solutions/2796-repeat-string.js
new file mode 100644
index 00000000..d22c0cdd
--- /dev/null
+++ b/solutions/2796-repeat-string.js
@@ -0,0 +1,22 @@
+/**
+ * 2796. Repeat String
+ * https://leetcode.com/problems/repeat-string/
+ * Difficulty: Easy
+ *
+ * Write code that enhances all strings such that you can call the string.replicate(x) method
+ * on any string and it will return repeated string x times.
+ *
+ * Try to implement it without using the built-in method string.repeat.
+ */
+
+/**
+ * @param {number} times
+ * @return {string}
+ */
+String.prototype.replicate = function(times) {
+ let result = '';
+ for (let i = 0; i < times; i++) {
+ result += this;
+ }
+ return result;
+};
From 274a250d0ed282d740ae63d0e767e71f1979259f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 13:51:40 -0500
Subject: [PATCH 795/994] Add solution #2797
---
README.md | 1 +
...2797-partial-function-with-placeholders.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/2797-partial-function-with-placeholders.js
diff --git a/README.md b/README.md
index eced8ac4..34a516bd 100644
--- a/README.md
+++ b/README.md
@@ -2411,6 +2411,7 @@
2794|[Create Object from Two Arrays](./solutions/2794-create-object-from-two-arrays.js)|Easy|
2795|[Parallel Execution of Promises for Individual Results Retrieval](./solutions/2795-parallel-execution-of-promises-for-individual-results-retrieval.js)|Medium|
2796|[Repeat String](./solutions/2796-repeat-string.js)|Easy|
+2797|[Partial Function with Placeholders](./solutions/2797-partial-function-with-placeholders.js)|Easy|
2798|[Number of Employees Who Met the Target](./solutions/2798-number-of-employees-who-met-the-target.js)|Easy|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2806|[Account Balance After Rounded Purchase](./solutions/2806-account-balance-after-rounded-purchase.js)|Easy|
diff --git a/solutions/2797-partial-function-with-placeholders.js b/solutions/2797-partial-function-with-placeholders.js
new file mode 100644
index 00000000..9afa8558
--- /dev/null
+++ b/solutions/2797-partial-function-with-placeholders.js
@@ -0,0 +1,39 @@
+/**
+ * 2797. Partial Function with Placeholders
+ * https://leetcode.com/problems/partial-function-with-placeholders/
+ * Difficulty: Easy
+ *
+ * Given a function fn and an array args, return a function partialFn.
+ *
+ * Placeholders "_" in the args should be replaced with values from restArgs starting from
+ * index 0. Any remaining values in the restArgs should be added at the end of the args.
+ *
+ * partialFn should return a result of fn. fn should be called with the elements of the
+ * modified args passed as separate arguments.
+ */
+
+/**
+ * @param {Function} fn
+ * @param {Array} args
+ * @return {Function}
+ */
+var partial = function(fn, args) {
+ return function(...restArgs) {
+ const finalArgs = [...args];
+ let restIndex = 0;
+
+ for (let i = 0; i < finalArgs.length; i++) {
+ if (finalArgs[i] === '_' && restIndex < restArgs.length) {
+ finalArgs[i] = restArgs[restIndex];
+ restIndex++;
+ }
+ }
+
+ while (restIndex < restArgs.length) {
+ finalArgs.push(restArgs[restIndex]);
+ restIndex++;
+ }
+
+ return fn(...finalArgs);
+ };
+};
From 3e12f531fd881495a6da6c989a4de2938a00cda7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 14:06:37 -0500
Subject: [PATCH 796/994] Add solution #2803
---
README.md | 1 +
solutions/2803-factorial-generator.js | 29 +++++++++++++++++++++++++++
2 files changed, 30 insertions(+)
create mode 100644 solutions/2803-factorial-generator.js
diff --git a/README.md b/README.md
index 34a516bd..246e65df 100644
--- a/README.md
+++ b/README.md
@@ -2414,6 +2414,7 @@
2797|[Partial Function with Placeholders](./solutions/2797-partial-function-with-placeholders.js)|Easy|
2798|[Number of Employees Who Met the Target](./solutions/2798-number-of-employees-who-met-the-target.js)|Easy|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
+2803|[Factorial Generator](./solutions/2803-factorial-generator.js)|Easy|
2806|[Account Balance After Rounded Purchase](./solutions/2806-account-balance-after-rounded-purchase.js)|Easy|
2807|[Insert Greatest Common Divisors in Linked List](./solutions/2807-insert-greatest-common-divisors-in-linked-list.js)|Medium|
2810|[Faulty Keyboard](./solutions/2810-faulty-keyboard.js)|Easy|
diff --git a/solutions/2803-factorial-generator.js b/solutions/2803-factorial-generator.js
new file mode 100644
index 00000000..15dcfbf4
--- /dev/null
+++ b/solutions/2803-factorial-generator.js
@@ -0,0 +1,29 @@
+/**
+ * 2803. Factorial Generator
+ * https://leetcode.com/problems/factorial-generator/
+ * Difficulty: Easy
+ *
+ * Write a generator function that takes an integer n as an argument and returns a generator
+ * object which yields the factorial sequence.
+ *
+ * The factorial sequence is defined by the relation n! = n * (n-1) * (n-2) * ... * 2 * 1.
+ *
+ * The factorial of 0 is defined as 1.
+ */
+
+/**
+ * @param {number} n
+ * @yields {number}
+ */
+function* factorial(n) {
+ let currentFactorial = 1;
+
+ for (let i = 1; i <= n; i++) {
+ currentFactorial *= i;
+ yield currentFactorial;
+ }
+
+ if (n === 0) {
+ yield 1;
+ }
+}
From 904bf53a0d2003085c700f9bccd1652cc1d65816 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 14:08:44 -0500
Subject: [PATCH 797/994] Add solution #2804
---
README.md | 1 +
solutions/2804-array-prototype-foreach.js | 33 +++++++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/2804-array-prototype-foreach.js
diff --git a/README.md b/README.md
index 246e65df..da432694 100644
--- a/README.md
+++ b/README.md
@@ -2415,6 +2415,7 @@
2798|[Number of Employees Who Met the Target](./solutions/2798-number-of-employees-who-met-the-target.js)|Easy|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2803|[Factorial Generator](./solutions/2803-factorial-generator.js)|Easy|
+2804|[Array Prototype ForEach](./solutions/2804-array-prototype-foreach.js)|Easy|
2806|[Account Balance After Rounded Purchase](./solutions/2806-account-balance-after-rounded-purchase.js)|Easy|
2807|[Insert Greatest Common Divisors in Linked List](./solutions/2807-insert-greatest-common-divisors-in-linked-list.js)|Medium|
2810|[Faulty Keyboard](./solutions/2810-faulty-keyboard.js)|Easy|
diff --git a/solutions/2804-array-prototype-foreach.js b/solutions/2804-array-prototype-foreach.js
new file mode 100644
index 00000000..c694cbf7
--- /dev/null
+++ b/solutions/2804-array-prototype-foreach.js
@@ -0,0 +1,33 @@
+/**
+ * 2804. Array Prototype ForEach
+ * https://leetcode.com/problems/array-prototype-foreach/
+ * Difficulty: Easy
+ *
+ * Write your version of method forEach that enhances all arrays such that you can call the
+ * array.forEach(callback, context) method on any array and it will execute callback on each
+ * element of the array. Method forEach should not return anything.
+ *
+ * callback accepts the following arguments:
+ * - currentValue - represents the current element being processed in the array. It is the
+ * value of the element in the current iteration.
+ * - index - represents the index of the current element being processed in the array.
+ * - array - represents the array itself, allowing access to the entire array within the
+ * callback function.
+ *
+ * The context is the object that should be passed as the function context parameter to the
+ * callback function, ensuring that the this keyword within the callback function refers to
+ * this context object.
+ *
+ * Try to implement it without using the built-in array methods.
+ */
+
+/**
+ * @param {Function} callback
+ * @param {Object} context
+ * @return {void}
+ */
+Array.prototype.forEach = function(callback, context) {
+ for (let i = 0; i < this.length; i++) {
+ callback.call(context, this[i], i, this);
+ }
+};
From 898d948220871faf6b219ead2660a755f618b062 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 14:11:51 -0500
Subject: [PATCH 798/994] Add solution #2805
---
README.md | 1 +
solutions/2805-custom-interval.js | 62 +++++++++++++++++++++++++++++++
2 files changed, 63 insertions(+)
create mode 100644 solutions/2805-custom-interval.js
diff --git a/README.md b/README.md
index da432694..d3f1ff7c 100644
--- a/README.md
+++ b/README.md
@@ -2416,6 +2416,7 @@
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
2803|[Factorial Generator](./solutions/2803-factorial-generator.js)|Easy|
2804|[Array Prototype ForEach](./solutions/2804-array-prototype-foreach.js)|Easy|
+2805|[Custom Interval](./solutions/2805-custom-interval.js)|Medium|
2806|[Account Balance After Rounded Purchase](./solutions/2806-account-balance-after-rounded-purchase.js)|Easy|
2807|[Insert Greatest Common Divisors in Linked List](./solutions/2807-insert-greatest-common-divisors-in-linked-list.js)|Medium|
2810|[Faulty Keyboard](./solutions/2810-faulty-keyboard.js)|Easy|
diff --git a/solutions/2805-custom-interval.js b/solutions/2805-custom-interval.js
new file mode 100644
index 00000000..9da9d162
--- /dev/null
+++ b/solutions/2805-custom-interval.js
@@ -0,0 +1,62 @@
+/**
+ * 2805. Custom Interval
+ * https://leetcode.com/problems/custom-interval/
+ * Difficulty: Medium
+ *
+ * Function customInterval
+ *
+ * Given a function fn, a number delay and a number period, return a number id.
+ *
+ * customInterval is a function that should execute the provided function fn at intervals based
+ * on a linear pattern defined by the formula delay + period * count.
+ *
+ * The count in the formula represents the number of times the interval has been executed
+ * starting from an initial value of 0.
+ *
+ * Function customClearInterval
+ *
+ * Given the id. id is the returned value from the function customInterval.
+ *
+ * customClearInterval should stop executing provided function fn at intervals.
+ *
+ * Note: The setTimeout and setInterval functions in Node.js return an object, not a number.
+ */
+
+const intervalMap = new Map();
+let nextId = 1;
+
+/**
+ * @param {Function} fn
+ * @param {number} delay
+ * @param {number} period
+ * @return {number} id
+ */
+function customInterval(fn, delay, period) {
+ let count = 0;
+ const id = nextId++;
+
+ function scheduleNext() {
+ const nextDelay = delay + period * count;
+ const timeoutId = setTimeout(() => {
+ fn();
+ count++;
+ scheduleNext();
+ }, nextDelay);
+ intervalMap.set(id, timeoutId);
+ }
+
+ scheduleNext();
+ return id;
+}
+
+/**
+ * @param {number} id
+ * @return {void}
+ */
+function customClearInterval(id) {
+ const timeoutId = intervalMap.get(id);
+ if (timeoutId) {
+ clearTimeout(timeoutId);
+ intervalMap.delete(id);
+ }
+}
From 44c7867b3488244544f0937840821f7d38d15395 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 14:13:10 -0500
Subject: [PATCH 799/994] Add solution #2821
---
README.md | 1 +
...21-delay-the-resolution-of-each-promise.js | 36 +++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/2821-delay-the-resolution-of-each-promise.js
diff --git a/README.md b/README.md
index d3f1ff7c..a71194c5 100644
--- a/README.md
+++ b/README.md
@@ -2423,6 +2423,7 @@
2815|[Max Pair Sum in an Array](./solutions/2815-max-pair-sum-in-an-array.js)|Easy|
2816|[Double a Number Represented as a Linked List](./solutions/2816-double-a-number-represented-as-a-linked-list.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
+2821|[Delay the Resolution of Each Promise](./solutions/2821-delay-the-resolution-of-each-promise.js)|Medium|
2824|[Count Pairs Whose Sum is Less than Target](./solutions/2824-count-pairs-whose-sum-is-less-than-target.js)|Easy|
2825|[Make String a Subsequence Using Cyclic Increments](./solutions/2825-make-string-a-subsequence-using-cyclic-increments.js)|Medium|
2826|[Sorting Three Groups](./solutions/2826-sorting-three-groups.js)|Medium|
diff --git a/solutions/2821-delay-the-resolution-of-each-promise.js b/solutions/2821-delay-the-resolution-of-each-promise.js
new file mode 100644
index 00000000..ef498272
--- /dev/null
+++ b/solutions/2821-delay-the-resolution-of-each-promise.js
@@ -0,0 +1,36 @@
+/**
+ * 2821. Delay the Resolution of Each Promise
+ * https://leetcode.com/problems/delay-the-resolution-of-each-promise/
+ * Difficulty: Medium
+ *
+ * Given an array functions and a number ms, return a new array of functions.
+ * - functions is an array of functions that return promises.
+ * - ms represents the delay duration in milliseconds. It determines the amount of time to wait
+ * before resolving or rejecting each promise in the new array.
+ *
+ * Each function in the new array should return a promise that resolves or rejects after an
+ * additional delay of ms milliseconds, preserving the order of the original functions array.
+ *
+ * The delayAll function should ensure that each promise from functions is executed with a
+ * delay, forming the new array of functions returning delayed promises.
+ */
+
+/**
+ * @param {Array} functions
+ * @param {number} ms
+ * @return {Array}
+ */
+var delayAll = function(functions, ms) {
+ return functions.map(fn => {
+ return async function() {
+ try {
+ const result = await fn();
+ await new Promise(resolve => setTimeout(resolve, ms));
+ return result;
+ } catch (error) {
+ await new Promise(resolve => setTimeout(resolve, ms));
+ throw error;
+ }
+ };
+ });
+};
From 2c3745ff149cc52307393d4f78de5ded087e78fa Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 14:14:58 -0500
Subject: [PATCH 800/994] Add solution #2822
---
README.md | 1 +
solutions/2822-inversion-of-object.js | 38 +++++++++++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2822-inversion-of-object.js
diff --git a/README.md b/README.md
index a71194c5..2b203e96 100644
--- a/README.md
+++ b/README.md
@@ -2424,6 +2424,7 @@
2816|[Double a Number Represented as a Linked List](./solutions/2816-double-a-number-represented-as-a-linked-list.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
2821|[Delay the Resolution of Each Promise](./solutions/2821-delay-the-resolution-of-each-promise.js)|Medium|
+2822|[Inversion of Object](./solutions/2822-inversion-of-object.js)|Easy|
2824|[Count Pairs Whose Sum is Less than Target](./solutions/2824-count-pairs-whose-sum-is-less-than-target.js)|Easy|
2825|[Make String a Subsequence Using Cyclic Increments](./solutions/2825-make-string-a-subsequence-using-cyclic-increments.js)|Medium|
2826|[Sorting Three Groups](./solutions/2826-sorting-three-groups.js)|Medium|
diff --git a/solutions/2822-inversion-of-object.js b/solutions/2822-inversion-of-object.js
new file mode 100644
index 00000000..53bae8e5
--- /dev/null
+++ b/solutions/2822-inversion-of-object.js
@@ -0,0 +1,38 @@
+/**
+ * 2822. Inversion of Object
+ * https://leetcode.com/problems/inversion-of-object/
+ * Difficulty: Easy
+ *
+ * Given an object or an array obj, return an inverted object or array invertedObj.
+ *
+ * The invertedObj should have the keys of obj as values and the values of obj as keys.
+ * The indices of array should be treated as keys.
+ *
+ * The function should handle duplicates, meaning that if there are multiple keys in obj
+ * with the same value, the invertedObj should map the value to an array containing all
+ * corresponding keys.
+ *
+ * It is guaranteed that the values in obj are only strings.
+ */
+
+/**
+ * @param {Object|Array} obj
+ * @return {Object}
+ */
+var invertObject = function(obj) {
+ const result = {};
+
+ Object.keys(obj).forEach(key => {
+ const value = obj[key];
+
+ if (result[value] === undefined) {
+ result[value] = key;
+ } else if (Array.isArray(result[value])) {
+ result[value].push(key);
+ } else {
+ result[value] = [result[value], key];
+ }
+ });
+
+ return result;
+};
From d888a082e2afc31952cd172d01986bca7e8a5b26 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 14:20:27 -0500
Subject: [PATCH 801/994] Add solution #2823
---
README.md | 1 +
solutions/2823-deep-object-filter.js | 48 ++++++++++++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/2823-deep-object-filter.js
diff --git a/README.md b/README.md
index 2b203e96..eadd65b5 100644
--- a/README.md
+++ b/README.md
@@ -2425,6 +2425,7 @@
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
2821|[Delay the Resolution of Each Promise](./solutions/2821-delay-the-resolution-of-each-promise.js)|Medium|
2822|[Inversion of Object](./solutions/2822-inversion-of-object.js)|Easy|
+2823|[Deep Object Filter](./solutions/2823-deep-object-filter.js)|Medium|
2824|[Count Pairs Whose Sum is Less than Target](./solutions/2824-count-pairs-whose-sum-is-less-than-target.js)|Easy|
2825|[Make String a Subsequence Using Cyclic Increments](./solutions/2825-make-string-a-subsequence-using-cyclic-increments.js)|Medium|
2826|[Sorting Three Groups](./solutions/2826-sorting-three-groups.js)|Medium|
diff --git a/solutions/2823-deep-object-filter.js b/solutions/2823-deep-object-filter.js
new file mode 100644
index 00000000..99f9cd1b
--- /dev/null
+++ b/solutions/2823-deep-object-filter.js
@@ -0,0 +1,48 @@
+/**
+ * 2823. Deep Object Filter
+ * https://leetcode.com/problems/deep-object-filter/
+ * Difficulty: Medium
+ *
+ * Given an object or an array obj and a function fn, return a filtered object or array
+ * filteredObject.
+ *
+ * Function deepFilter should perform a deep filter operation on the obj. The deep filter
+ * operation should remove properties for which the output of the filter function fn is
+ * false, as well as any empty objects or arrays that remain after the keys have been removed.
+ *
+ * If the deep filter operation results in an empty object or array, with no remaining
+ * properties, deepFilter should return undefined to indicate that there is no valid data
+ * left in the filteredObject.
+ */
+
+/**
+ * @param {Object|Array} obj
+ * @param {Function} fn
+ * @return {Object|Array|undefined}
+ */
+var deepFilter = function(obj, fn) {
+ if (Array.isArray(obj)) {
+ const filteredArray = obj
+ .map(item => deepFilter(item, fn))
+ .filter(item => item !== undefined);
+
+ return filteredArray.length > 0 ? filteredArray : undefined;
+ }
+
+ if (typeof obj === 'object' && obj !== null) {
+ const filteredObject = {};
+ let hasValidProperties = false;
+
+ Object.keys(obj).forEach(key => {
+ const filteredValue = deepFilter(obj[key], fn);
+ if (filteredValue !== undefined) {
+ filteredObject[key] = filteredValue;
+ hasValidProperties = true;
+ }
+ });
+
+ return hasValidProperties ? filteredObject : undefined;
+ }
+
+ return fn(obj) ? obj : undefined;
+};
From 5f578a369763b8a03f20be5891b1b6a836d923af Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 14:23:30 -0500
Subject: [PATCH 802/994] Add solution #2505
---
README.md | 1 +
...2505-bitwise-or-of-all-subsequence-sums.js | 38 +++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2505-bitwise-or-of-all-subsequence-sums.js
diff --git a/README.md b/README.md
index eadd65b5..44de89f4 100644
--- a/README.md
+++ b/README.md
@@ -2235,6 +2235,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|
+2505|[Bitwise OR of All Subsequence Sums](./solutions/2505-bitwise-or-of-all-subsequence-sums.js)|Medium|
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|
diff --git a/solutions/2505-bitwise-or-of-all-subsequence-sums.js b/solutions/2505-bitwise-or-of-all-subsequence-sums.js
new file mode 100644
index 00000000..d7730cfc
--- /dev/null
+++ b/solutions/2505-bitwise-or-of-all-subsequence-sums.js
@@ -0,0 +1,38 @@
+/**
+ * 2505. Bitwise OR of All Subsequence Sums
+ * https://leetcode.com/problems/bitwise-or-of-all-subsequence-sums/
+ * Difficulty: Medium
+ *
+ * Given an integer array nums, return the value of the bitwise OR of the sum of all possible
+ * subsequences in the array.
+ *
+ * A subsequence is a sequence that can be derived from another sequence by removing zero or
+ * more elements without changing the order of the remaining elements.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var subsequenceSumOr = function(nums) {
+ const bitCounts = new Array(64).fill(0n);
+
+ for (const num of nums) {
+ for (let bit = 0; bit < 31; bit++) {
+ if (num & (1 << bit)) {
+ bitCounts[bit]++;
+ }
+ }
+ }
+
+ for (let bit = 0; bit < 63; bit++) {
+ bitCounts[bit + 1] += bitCounts[bit] / 2n;
+ }
+
+ let result = 0n;
+ for (let bit = 63; bit >= 0; bit--) {
+ result = (result << 1n) | (bitCounts[bit] > 0n ? 1n : 0n);
+ }
+
+ return Number(result);
+};
From c06d8da6ef4bf537e9214ef55feb28c0fd3fd667 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 14:24:42 -0500
Subject: [PATCH 803/994] Add solution #2510
---
README.md | 1 +
...s-a-path-with-equal-number-of-0s-and-1s.js | 56 +++++++++++++++++++
2 files changed, 57 insertions(+)
create mode 100644 solutions/2510-check-if-there-is-a-path-with-equal-number-of-0s-and-1s.js
diff --git a/README.md b/README.md
index 44de89f4..acb54921 100644
--- a/README.md
+++ b/README.md
@@ -2239,6 +2239,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|
+2510|[Check if There is a Path With Equal Number of 0's And 1's](./solutions/2510-check-if-there-is-a-path-with-equal-number-of-0s-and-1s.js)|Medium|
2511|[Maximum Enemy Forts That Can Be Captured](./solutions/2511-maximum-enemy-forts-that-can-be-captured.js)|Easy|
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|
diff --git a/solutions/2510-check-if-there-is-a-path-with-equal-number-of-0s-and-1s.js b/solutions/2510-check-if-there-is-a-path-with-equal-number-of-0s-and-1s.js
new file mode 100644
index 00000000..fc05209f
--- /dev/null
+++ b/solutions/2510-check-if-there-is-a-path-with-equal-number-of-0s-and-1s.js
@@ -0,0 +1,56 @@
+/**
+ * 2510. Check if There is a Path With Equal Number of 0's And 1's
+ * https://leetcode.com/problems/check-if-there-is-a-path-with-equal-number-of-0s-and-1s/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed m x n binary matrix grid. You can move from a cell (row, col) to
+ * any of the cells (row + 1, col) or (row, col + 1).
+ *
+ * Return true if there is a path from (0, 0) to (m - 1, n - 1) that visits an equal number
+ * of 0's and 1's. Otherwise return false.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {boolean}
+ */
+var isThereAPath = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const pathLength = rows + cols - 1;
+
+ if (pathLength % 2 !== 0) return false;
+
+ const visited = new Set();
+ const startBalance = grid[0][0] === 1 ? 1 : -1;
+
+ return dfs(0, 0, startBalance);
+
+ function dfs(row, col, balance) {
+ if (row === rows - 1 && col === cols - 1) {
+ return balance === 0;
+ }
+
+ const key = `${row},${col},${balance}`;
+ if (visited.has(key)) return false;
+ visited.add(key);
+
+ if (Math.abs(balance) > (rows - 1 - row) + (cols - 1 - col)) {
+ return false;
+ }
+
+ let canReach = false;
+
+ if (row + 1 < rows) {
+ const nextBalance = balance + (grid[row + 1][col] === 1 ? 1 : -1);
+ canReach = canReach || dfs(row + 1, col, nextBalance);
+ }
+
+ if (col + 1 < cols) {
+ const nextBalance = balance + (grid[row][col + 1] === 1 ? 1 : -1);
+ canReach = canReach || dfs(row, col + 1, nextBalance);
+ }
+
+ return canReach;
+ }
+};
From 650db2b16397526ea81f9602c114e1aca1c00aee Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 14:27:31 -0500
Subject: [PATCH 804/994] Add solution #2519
---
README.md | 1 +
.../2519-count-the-number-of-k-big-indices.js | 48 +++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/2519-count-the-number-of-k-big-indices.js
diff --git a/README.md b/README.md
index acb54921..48c123f8 100644
--- a/README.md
+++ b/README.md
@@ -2244,6 +2244,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|
+2519|[Count the Number of K-Big Indices](./solutions/2519-count-the-number-of-k-big-indices.js)|Hard|
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|
diff --git a/solutions/2519-count-the-number-of-k-big-indices.js b/solutions/2519-count-the-number-of-k-big-indices.js
new file mode 100644
index 00000000..b77a7cad
--- /dev/null
+++ b/solutions/2519-count-the-number-of-k-big-indices.js
@@ -0,0 +1,48 @@
+/**
+ * 2519. Count the Number of K-Big Indices
+ * https://leetcode.com/problems/count-the-number-of-k-big-indices/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed integer array nums and a positive integer k.
+ *
+ * We call an index i k-big if the following conditions are satisfied:
+ * - There exist at least k different indices idx1 such that idx1 < i and nums[idx1] < nums[i].
+ * - There exist at least k different indices idx2 such that idx2 > i and nums[idx2] < nums[i].
+ *
+ * Return the number of k-big indices.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var kBigIndices = function(nums, k) {
+ const n = nums.length;
+ const hasKSmallerLeft = new Array(n).fill(false);
+
+ const leftMaxHeap = new PriorityQueue((a, b) => b - a);
+ for (let i = 0; i < n; i++) {
+ if (leftMaxHeap.size() === k && leftMaxHeap.front() < nums[i]) {
+ hasKSmallerLeft[i] = true;
+ }
+ leftMaxHeap.enqueue(nums[i]);
+ if (leftMaxHeap.size() > k) {
+ leftMaxHeap.dequeue();
+ }
+ }
+
+ let result = 0;
+ const rightMaxHeap = new PriorityQueue((a, b) => b - a);
+ for (let i = n - 1; i >= 0; i--) {
+ if (rightMaxHeap.size() === k && rightMaxHeap.front() < nums[i] && hasKSmallerLeft[i]) {
+ result++;
+ }
+ rightMaxHeap.enqueue(nums[i]);
+ if (rightMaxHeap.size() > k) {
+ rightMaxHeap.dequeue();
+ }
+ }
+
+ return result;
+};
From 0520fc86da1f1e2d9edf4ec776ea33b8fae55a0e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 14:32:45 -0500
Subject: [PATCH 805/994] Add solution #2524
---
README.md | 1 +
...4-maximum-frequency-score-of-a-subarray.js | 56 +++++++++++++++++++
2 files changed, 57 insertions(+)
create mode 100644 solutions/2524-maximum-frequency-score-of-a-subarray.js
diff --git a/README.md b/README.md
index 48c123f8..9e039f1a 100644
--- a/README.md
+++ b/README.md
@@ -2249,6 +2249,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|
+2524|[Maximum Frequency Score of a Subarray](./solutions/2524-maximum-frequency-score-of-a-subarray.js)|Hard|
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|
diff --git a/solutions/2524-maximum-frequency-score-of-a-subarray.js b/solutions/2524-maximum-frequency-score-of-a-subarray.js
new file mode 100644
index 00000000..9bb7d33a
--- /dev/null
+++ b/solutions/2524-maximum-frequency-score-of-a-subarray.js
@@ -0,0 +1,56 @@
+/**
+ * 2524. Maximum Frequency Score of a Subarray
+ * https://leetcode.com/problems/maximum-frequency-score-of-a-subarray/
+ * Difficulty: Hard
+ *
+ * You are given an integer array nums and a positive integer k.
+ *
+ * The frequency score of an array is the sum of the distinct values in the array raised to
+ * the power of their frequencies, taking the sum modulo 109 + 7.
+ * - For example, the frequency score of the array [5,4,5,7,4,4] is (43 + 52 + 71) modulo
+ * (109 + 7) = 96.
+ *
+ * Return the maximum frequency score of a subarray of size k in nums. You should maximize
+ * the value under the modulo and not the actual value.
+ *
+ * A subarray is a contiguous part of an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var maxFrequencyScore = function(nums, k) {
+ const MOD = 1e9 + 7;
+
+ let sum = 0;
+ let result = 0;
+ const frequency = new Map();
+ for (let i = 0; i < nums.length; i++) {
+ if (!frequency.has(nums[i])) {
+ frequency.set(nums[i], []);
+ }
+ sum = adjustSum(sum, nums[i], frequency.get(nums[i]));
+
+ if (i >= k - 1) {
+ if (i >= k) {
+ sum = adjustSum(sum, nums[i - k], frequency.get(nums[i - k]), false);
+ }
+ result = Math.max(result, sum);
+ }
+ }
+
+ return result;
+
+ function adjustSum(sum, value, powers, add = true) {
+ sum = (MOD + sum - (powers.length === 0 ? 0 : powers[powers.length - 1])) % MOD;
+ if (add) {
+ const newPower = (value * (powers.length === 0 ? 1 : powers[powers.length - 1])) % MOD;
+ powers.push(newPower);
+ } else {
+ powers.pop();
+ }
+ return (sum + (powers.length === 0 ? 0 : powers[powers.length - 1])) % MOD;
+ }
+};
From 204d8413a21c0e2e7caf20671201c105607f7615 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 19:10:14 -0500
Subject: [PATCH 806/994] Add solution #2533
---
README.md | 1 +
.../2533-number-of-good-binary-strings.js | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/2533-number-of-good-binary-strings.js
diff --git a/README.md b/README.md
index 9e039f1a..0e739067 100644
--- a/README.md
+++ b/README.md
@@ -2252,6 +2252,7 @@
2524|[Maximum Frequency Score of a Subarray](./solutions/2524-maximum-frequency-score-of-a-subarray.js)|Hard|
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|
+2533|[Number of Good Binary Strings](./solutions/2533-number-of-good-binary-strings.js)|Medium|
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|
diff --git a/solutions/2533-number-of-good-binary-strings.js b/solutions/2533-number-of-good-binary-strings.js
new file mode 100644
index 00000000..5f0a03db
--- /dev/null
+++ b/solutions/2533-number-of-good-binary-strings.js
@@ -0,0 +1,50 @@
+/**
+ * 2533. Number of Good Binary Strings
+ * https://leetcode.com/problems/number-of-good-binary-strings/
+ * Difficulty: Medium
+ *
+ * You are given four integers minLength, maxLength, oneGroup and zeroGroup.
+ *
+ * A binary string is good if it satisfies the following conditions:
+ * - The length of the string is in the range [minLength, maxLength].
+ * - The size of each block of consecutive 1's is a multiple of oneGroup.
+ * - For example in a binary string 00110111100 sizes of each block of consecutive ones
+ * are [2,4].
+ * - The size of each block of consecutive 0's is a multiple of zeroGroup.
+ * - For example, in a binary string 00110111100 sizes of each block of consecutive zeros
+ * are [2,1,2].
+ *
+ * Return the number of good binary strings. Since the answer may be too large, return it
+ * modulo 109 + 7.
+ *
+ * Note that 0 is considered a multiple of all the numbers.
+ */
+
+/**
+ * @param {number} minLength
+ * @param {number} maxLength
+ * @param {number} oneGroup
+ * @param {number} zeroGroup
+ * @return {number}
+ */
+var goodBinaryStrings = function(minLength, maxLength, oneGroup, zeroGroup) {
+ const MOD = 1e9 + 7;
+ const dp = new Array(maxLength + 1).fill(0);
+ dp[0] = 1;
+
+ for (let i = 1; i <= maxLength; i++) {
+ if (oneGroup <= i) {
+ dp[i] = (dp[i] + dp[i - oneGroup]) % MOD;
+ }
+ if (zeroGroup <= i) {
+ dp[i] = (dp[i] + dp[i - zeroGroup]) % MOD;
+ }
+ }
+
+ let result = 0;
+ for (let i = minLength; i <= maxLength; i++) {
+ result = (result + dp[i]) % MOD;
+ }
+
+ return result;
+};
From 3db89e774e2dce9cc002cff9a9bc128a10d1b874 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 19:14:26 -0500
Subject: [PATCH 807/994] Add solution #2534
---
README.md | 1 +
.../2534-time-taken-to-cross-the-door.js | 79 +++++++++++++++++++
2 files changed, 80 insertions(+)
create mode 100644 solutions/2534-time-taken-to-cross-the-door.js
diff --git a/README.md b/README.md
index 0e739067..9e862425 100644
--- a/README.md
+++ b/README.md
@@ -2253,6 +2253,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|
2533|[Number of Good Binary Strings](./solutions/2533-number-of-good-binary-strings.js)|Medium|
+2534|[Time Taken to Cross the Door](./solutions/2534-time-taken-to-cross-the-door.js)|Hard|
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|
diff --git a/solutions/2534-time-taken-to-cross-the-door.js b/solutions/2534-time-taken-to-cross-the-door.js
new file mode 100644
index 00000000..07a331a2
--- /dev/null
+++ b/solutions/2534-time-taken-to-cross-the-door.js
@@ -0,0 +1,79 @@
+/**
+ * 2534. Time Taken to Cross the Door
+ * https://leetcode.com/problems/time-taken-to-cross-the-door/
+ * Difficulty: Hard
+ *
+ * There are n persons numbered from 0 to n - 1 and a door. Each person can enter or exit
+ * through the door once, taking one second.
+ *
+ * You are given a non-decreasing integer array arrival of size n, where arrival[i] is the
+ * arrival time of the ith person at the door. You are also given an array state of size n,
+ * where state[i] is 0 if person i wants to enter through the door or 1 if they want to exit
+ * through the door.
+ *
+ * If two or more persons want to use the door at the same time, they follow the following
+ * rules:
+ * - If the door was not used in the previous second, then the person who wants to exit
+ * goes first.
+ * - If the door was used in the previous second for entering, the person who wants to
+ * enter goes first.
+ * - If the door was used in the previous second for exiting, the person who wants to
+ * exit goes first.
+ * - If multiple persons want to go in the same direction, the person with the smallest
+ * index goes first.
+ *
+ * Return an array answer of size n where answer[i] is the second at which the ith person
+ * crosses the door.
+ *
+ * Note that:
+ * - Only one person can cross the door at each second.
+ * - A person may arrive at the door and wait without entering or exiting to follow the
+ * mentioned rules.
+ */
+
+/**
+ * @param {number[]} arrival
+ * @param {number[]} state
+ * @return {number[]}
+ */
+var timeTaken = function(arrival, state) {
+ const enterPool = [];
+ const exitPool = [];
+ let currentTime = 0;
+ let previousState = 1;
+ let i = 0;
+ const result = new Array(arrival.length);
+
+ while (i < arrival.length || enterPool.length > 0 || exitPool.length > 0) {
+ while (i < arrival.length && arrival[i] <= currentTime) {
+ if (state[i] === 0) {
+ enterPool.push(i);
+ } else {
+ exitPool.push(i);
+ }
+ i++;
+ }
+
+ if (previousState === 1) {
+ if (exitPool.length > 0) {
+ result[exitPool.shift()] = currentTime;
+ } else if (enterPool.length > 0) {
+ result[enterPool.shift()] = currentTime;
+ previousState = 0;
+ }
+ } else {
+ if (enterPool.length > 0) {
+ result[enterPool.shift()] = currentTime;
+ } else if (exitPool.length > 0) {
+ result[exitPool.shift()] = currentTime;
+ previousState = 1;
+ } else {
+ previousState = 1;
+ }
+ }
+
+ currentTime++;
+ }
+
+ return result;
+};
From 8daefbd5b55befc7c170d5a2c8de7f62b9eeeaf4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 19:23:37 -0500
Subject: [PATCH 808/994] Add solution #2539
---
README.md | 1 +
...9-count-the-number-of-good-subsequences.js | 80 +++++++++++++++++++
2 files changed, 81 insertions(+)
create mode 100644 solutions/2539-count-the-number-of-good-subsequences.js
diff --git a/README.md b/README.md
index 9e862425..a0833f8a 100644
--- a/README.md
+++ b/README.md
@@ -2257,6 +2257,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|
+2539|[Count the Number of Good Subsequences](./solutions/2539-count-the-number-of-good-subsequences.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|
diff --git a/solutions/2539-count-the-number-of-good-subsequences.js b/solutions/2539-count-the-number-of-good-subsequences.js
new file mode 100644
index 00000000..e6d5819e
--- /dev/null
+++ b/solutions/2539-count-the-number-of-good-subsequences.js
@@ -0,0 +1,80 @@
+/**
+ * 2539. Count the Number of Good Subsequences
+ * https://leetcode.com/problems/count-the-number-of-good-subsequences/
+ * Difficulty: Medium
+ *
+ * A subsequence of a string is good if it is not empty and the frequency of each one of its
+ * characters is the same.
+ *
+ * Given a string s, return the number of good subsequences of s. Since the answer may be too
+ * large, return it modulo 109 + 7.
+ *
+ * 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
+ * @return {number}
+ */
+var countGoodSubsequences = function(s) {
+ const MOD = 1e9 + 7;
+ const n = s.length;
+ const factorial = new Array(n + 1);
+
+ const frequency = new Array(26).fill(0);
+ let maxFrequency = 0;
+
+ for (let i = 0; i < n; i++) {
+ frequency[s.charCodeAt(i) - 97]++;
+ }
+
+ for (let i = 0; i < 26; i++) {
+ maxFrequency = Math.max(maxFrequency, frequency[i]);
+ }
+
+ let result = 0n;
+
+ for (let k = 1; k <= maxFrequency; k++) {
+ let current = 1n;
+ for (let i = 0; i < 26; i++) {
+ if (frequency[i] > 0) {
+ current = (current * (1n + combination(frequency[i], k))) % BigInt(MOD);
+ }
+ }
+ result = (result + current - 1n + BigInt(MOD)) % BigInt(MOD);
+ }
+
+ return Number(result);
+
+ function computeFactorial(num) {
+ if (factorial[num] !== undefined) return factorial[num];
+ if (num === 0) {
+ factorial[num] = 1n;
+ } else {
+ factorial[num] = (computeFactorial(num - 1) * BigInt(num)) % BigInt(MOD);
+ }
+ return factorial[num];
+ }
+
+ function modInverse(a) {
+ let result = 1n;
+ let base = a % BigInt(MOD);
+ let exp = BigInt(MOD - 2);
+ while (exp > 0n) {
+ if (exp & 1n) result = (result * base) % BigInt(MOD);
+ base = (base * base) % BigInt(MOD);
+ exp >>= 1n;
+ }
+ return result;
+ }
+
+ function combination(n, k) {
+ if (n < k) return 0n;
+ if (n === k) return 1n;
+ let result = computeFactorial(n);
+ result = (result * modInverse(computeFactorial(k))) % BigInt(MOD);
+ result = (result * modInverse(computeFactorial(n - k))) % BigInt(MOD);
+ return result;
+ }
+};
From 5300ac1400fa2bf56d3671277c511b2e004a8757 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 19:25:28 -0500
Subject: [PATCH 809/994] Add solution #2548
---
README.md | 1 +
solutions/2548-maximum-price-to-fill-a-bag.js | 38 +++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2548-maximum-price-to-fill-a-bag.js
diff --git a/README.md b/README.md
index a0833f8a..42b4650b 100644
--- a/README.md
+++ b/README.md
@@ -2265,6 +2265,7 @@
2545|[Sort the Students by Their Kth Score](./solutions/2545-sort-the-students-by-their-kth-score.js)|Medium|
2546|[Apply Bitwise Operations to Make Strings Equal](./solutions/2546-apply-bitwise-operations-to-make-strings-equal.js)|Medium|
2547|[Minimum Cost to Split an Array](./solutions/2547-minimum-cost-to-split-an-array.js)|Hard|
+2548|[Maximum Price to Fill a Bag](./solutions/2548-maximum-price-to-fill-a-bag.js)|Medium|
2549|[Count Distinct Numbers on Board](./solutions/2549-count-distinct-numbers-on-board.js)|Easy|
2551|[Put Marbles in Bags](./solutions/2551-put-marbles-in-bags.js)|Hard|
2553|[Separate the Digits in an Array](./solutions/2553-separate-the-digits-in-an-array.js)|Easy|
diff --git a/solutions/2548-maximum-price-to-fill-a-bag.js b/solutions/2548-maximum-price-to-fill-a-bag.js
new file mode 100644
index 00000000..14d9a33c
--- /dev/null
+++ b/solutions/2548-maximum-price-to-fill-a-bag.js
@@ -0,0 +1,38 @@
+/**
+ * 2548. Maximum Price to Fill a Bag
+ * https://leetcode.com/problems/maximum-price-to-fill-a-bag/
+ * Difficulty: Medium
+ *
+ * You are given a 2D integer array items where items[i] = [pricei, weighti] denotes the
+ * price and weight of the ith item, respectively.
+ *
+ * You are also given a positive integer capacity.
+ *
+ * Each item can be divided into two items with ratios part1 and part2, where part1 + part2 == 1.
+ * - The weight of the first item is weighti * part1 and the price of the first item is
+ * pricei * part1.
+ * - Similarly, the weight of the second item is weighti * part2 and the price of the second
+ * item is pricei * part2.
+ *
+ * Return the maximum total price to fill a bag of capacity capacity with given items. If it
+ * is impossible to fill a bag return -1. Answers within 10-5 of the actual answer will be
+ * considered accepted.
+ */
+
+/**
+ * @param {number[][]} items
+ * @param {number} capacity
+ * @return {number}
+ */
+var maxPrice = function(items, capacity) {
+ const sortedItems = items.sort((a, b) => (b[0] / b[1]) - (a[0] / a[1]));
+ let score = 0;
+
+ for (const [price, weight] of sortedItems) {
+ const take = Math.min(weight, capacity);
+ score += price * take / weight;
+ capacity -= take;
+ }
+
+ return capacity === 0 ? score : -1;
+};
From ecf3844e62ba4fb6f24a4ef89bfa50e168b6849a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 19:28:14 -0500
Subject: [PATCH 810/994] Add solution #2557
---
README.md | 1 +
...r-of-integers-to-choose-from-a-range-ii.js | 47 +++++++++++++++++++
2 files changed, 48 insertions(+)
create mode 100644 solutions/2557-maximum-number-of-integers-to-choose-from-a-range-ii.js
diff --git a/README.md b/README.md
index 42b4650b..f32b29dd 100644
--- a/README.md
+++ b/README.md
@@ -2270,6 +2270,7 @@
2551|[Put Marbles in Bags](./solutions/2551-put-marbles-in-bags.js)|Hard|
2553|[Separate the Digits in an Array](./solutions/2553-separate-the-digits-in-an-array.js)|Easy|
2554|[Maximum Number of Integers to Choose From a Range I](./solutions/2554-maximum-number-of-integers-to-choose-from-a-range-i.js)|Medium|
+2557|[Maximum Number of Integers to Choose From a Range II](./solutions/2557-maximum-number-of-integers-to-choose-from-a-range-ii.js)|Medium|
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|
2562|[Find the Array Concatenation Value](./solutions/2562-find-the-array-concatenation-value.js)|Easy|
diff --git a/solutions/2557-maximum-number-of-integers-to-choose-from-a-range-ii.js b/solutions/2557-maximum-number-of-integers-to-choose-from-a-range-ii.js
new file mode 100644
index 00000000..22732080
--- /dev/null
+++ b/solutions/2557-maximum-number-of-integers-to-choose-from-a-range-ii.js
@@ -0,0 +1,47 @@
+/**
+ * 2557. Maximum Number of Integers to Choose From a Range II
+ * https://leetcode.com/problems/maximum-number-of-integers-to-choose-from-a-range-ii/
+ * Difficulty: Medium
+ *
+ * You are given an integer array banned and two integers n and maxSum. You are choosing some
+ * number of integers following the below rules:
+ * - The chosen integers have to be in the range [1, n].
+ * - Each integer can be chosen at most once.
+ * - The chosen integers should not be in the array banned.
+ * - The sum of the chosen integers should not exceed maxSum.
+ *
+ * Return the maximum number of integers you can choose following the mentioned rules.
+ */
+
+/**
+ * @param {number[]} banned
+ * @param {number} n
+ * @param {number} maxSum
+ * @return {number}
+ */
+var maxCount = function(banned, n, maxSum) {
+ const initialLimit = Math.min(n, Math.floor((-1 + Math.sqrt(1 + 8 * maxSum)) / 2));
+ const bannedNumbers = new Set(banned);
+ let totalSum = Math.floor(initialLimit * (initialLimit + 1) / 2);
+ let result = initialLimit;
+
+ for (const bannedNumber of bannedNumbers) {
+ if (bannedNumber <= initialLimit) {
+ totalSum -= bannedNumber;
+ result -= 1;
+ }
+ }
+
+ for (let candidate = initialLimit + 1; candidate <= n; candidate++) {
+ if (totalSum + candidate > maxSum) {
+ return result;
+ }
+
+ if (!bannedNumbers.has(candidate)) {
+ totalSum += candidate;
+ result += 1;
+ }
+ }
+
+ return result;
+};
From 70de7ed0a045cb3f916a865fe81e0af75a31f22d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 19:31:55 -0500
Subject: [PATCH 811/994] Add solution #2590
---
README.md | 1 +
solutions/2590-design-a-todo-list.js | 99 ++++++++++++++++++++++++++++
2 files changed, 100 insertions(+)
create mode 100644 solutions/2590-design-a-todo-list.js
diff --git a/README.md b/README.md
index f32b29dd..1b289a33 100644
--- a/README.md
+++ b/README.md
@@ -2291,6 +2291,7 @@
2586|[Count the Number of Vowel Strings in Range](./solutions/2586-count-the-number-of-vowel-strings-in-range.js)|Easy|
2587|[Rearrange Array to Maximize Prefix Score](./solutions/2587-rearrange-array-to-maximize-prefix-score.js)|Medium|
2588|[Count the Number of Beautiful Subarrays](./solutions/2588-count-the-number-of-beautiful-subarrays.js)|Medium|
+2590|[Design a Todo List](./solutions/2590-design-a-todo-list.js)|Medium|
2592|[Maximize Greatness of an Array](./solutions/2592-maximize-greatness-of-an-array.js)|Medium|
2594|[Minimum Time to Repair Cars](./solutions/2594-minimum-time-to-repair-cars.js)|Medium|
2595|[Number of Even and Odd Bits](./solutions/2595-number-of-even-and-odd-bits.js)|Easy|
diff --git a/solutions/2590-design-a-todo-list.js b/solutions/2590-design-a-todo-list.js
new file mode 100644
index 00000000..b586ec45
--- /dev/null
+++ b/solutions/2590-design-a-todo-list.js
@@ -0,0 +1,99 @@
+/**
+ * 2590. Design a Todo List
+ * https://leetcode.com/problems/design-a-todo-list/
+ * Difficulty: Medium
+ *
+ * Design a Todo List Where users can add tasks, mark them as complete, or get a list of pending
+ * tasks. Users can also add tags to tasks and can filter the tasks by certain tags.
+ *
+ * Implement the TodoList class:
+ * - TodoList() Initializes the object.
+ * - int addTask(int userId, String taskDescription, int dueDate, List tags) Adds a task for
+ * the user with the ID userId with a due date equal to dueDate and a list of tags attached to the
+ * task. The return value is the ID of the task. This ID starts at 1 and is sequentially
+ * increasing. That is, the first task's id should be 1, the second task's id should be 2, and so
+ * on.
+ * - List getAllTasks(int userId) Returns a list of all the tasks not marked as complete for
+ * the user with ID userId, ordered by the due date. You should return an empty list if the user
+ * has no uncompleted tasks.
+ * - List getTasksForTag(int userId, String tag) Returns a list of all the tasks that are
+ * not marked as complete for the user with the ID userId and have tag as one of their tags,
+ * ordered by their due date. Return an empty list if no such task exists.
+ * - void completeTask(int userId, int taskId) Marks the task with the ID taskId as completed only
+ * if the task exists and the user with the ID userId has this task, and it is uncompleted.
+ */
+
+var TodoList = function() {
+ this.nextTaskId = 1;
+ this.userTasks = new Map();
+ this.allTasks = new Map();
+};
+
+/**
+ * @param {number} userId
+ * @param {string} taskDescription
+ * @param {number} dueDate
+ * @param {string[]} tags
+ * @return {number}
+ */
+TodoList.prototype.addTask = function(userId, taskDescription, dueDate, tags) {
+ const taskId = this.nextTaskId++;
+ const task = {
+ id: taskId,
+ description: taskDescription,
+ dueDate: dueDate,
+ tags: new Set(tags),
+ completed: false
+ };
+
+ if (!this.userTasks.has(userId)) {
+ this.userTasks.set(userId, []);
+ }
+ this.userTasks.get(userId).push(task);
+ this.allTasks.set(taskId, { userId, task });
+
+ return taskId;
+};
+
+/**
+ * @param {number} userId
+ * @return {string[]}
+ */
+TodoList.prototype.getAllTasks = function(userId) {
+ if (!this.userTasks.has(userId)) {
+ return [];
+ }
+
+ return this.userTasks.get(userId)
+ .filter(task => !task.completed)
+ .sort((a, b) => a.dueDate - b.dueDate)
+ .map(task => task.description);
+};
+
+/**
+ * @param {number} userId
+ * @param {string} tag
+ * @return {string[]}
+ */
+TodoList.prototype.getTasksForTag = function(userId, tag) {
+ if (!this.userTasks.has(userId)) {
+ return [];
+ }
+
+ return this.userTasks.get(userId)
+ .filter(task => !task.completed && task.tags.has(tag))
+ .sort((a, b) => a.dueDate - b.dueDate)
+ .map(task => task.description);
+};
+
+/**
+ * @param {number} userId
+ * @param {number} taskId
+ * @return {void}
+ */
+TodoList.prototype.completeTask = function(userId, taskId) {
+ const taskInfo = this.allTasks.get(taskId);
+ if (taskInfo && taskInfo.userId === userId && !taskInfo.task.completed) {
+ taskInfo.task.completed = true;
+ }
+};
From 2877ae7607d2283d53d5ecaa8981161eb199ddcc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 19:34:00 -0500
Subject: [PATCH 812/994] Add solution #2599
---
README.md | 1 +
.../2599-make-the-prefix-sum-non-negative.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/2599-make-the-prefix-sum-non-negative.js
diff --git a/README.md b/README.md
index 1b289a33..ea0e0c16 100644
--- a/README.md
+++ b/README.md
@@ -2298,6 +2298,7 @@
2596|[Check Knight Tour Configuration](./solutions/2596-check-knight-tour-configuration.js)|Medium|
2597|[The Number of Beautiful Subsets](./solutions/2597-the-number-of-beautiful-subsets.js)|Medium|
2598|[Smallest Missing Non-negative Integer After Operations](./solutions/2598-smallest-missing-non-negative-integer-after-operations.js)|Medium|
+2599|[Make the Prefix Sum Non-negative](./solutions/2599-make-the-prefix-sum-non-negative.js)|Medium|
2600|[K Items With the Maximum Sum](./solutions/2600-k-items-with-the-maximum-sum.js)|Easy|
2601|[Prime Subtraction Operation](./solutions/2601-prime-subtraction-operation.js)|Medium|
2605|[Form Smallest Number From Two Digit Arrays](./solutions/2605-form-smallest-number-from-two-digit-arrays.js)|Easy|
diff --git a/solutions/2599-make-the-prefix-sum-non-negative.js b/solutions/2599-make-the-prefix-sum-non-negative.js
new file mode 100644
index 00000000..787d7286
--- /dev/null
+++ b/solutions/2599-make-the-prefix-sum-non-negative.js
@@ -0,0 +1,42 @@
+/**
+ * 2599. Make the Prefix Sum Non-negative
+ * https://leetcode.com/problems/make-the-prefix-sum-non-negative/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums. You can apply the following operation any
+ * number of times:
+ * - Pick any element from nums and put it at the end of nums.
+ *
+ * The prefix sum array of nums is an array prefix of the same length as nums such that prefix[i]
+ * is the sum of all the integers nums[j] where j is in the inclusive range [0, i].
+ *
+ * Return the minimum number of operations such that the prefix sum array does not contain negative
+ * integers. The test cases are generated such that it is always possible to make the prefix sum
+ * array non-negative.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var makePrefSumNonNegative = function(nums) {
+ const minHeap = new PriorityQueue((a, b) => a - b);
+ let prefixSum = 0;
+ let result = 0;
+
+ for (const num of nums) {
+ prefixSum += num;
+
+ if (num < 0) {
+ minHeap.enqueue(num);
+ }
+
+ if (prefixSum < 0) {
+ const minNegative = minHeap.dequeue();
+ prefixSum -= minNegative;
+ result++;
+ }
+ }
+
+ return result;
+};
From 3ee1f9624ee409d3db757be7b6420246aaca9b83 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 19:42:07 -0500
Subject: [PATCH 813/994] Add solution #2604
---
README.md | 1 +
.../2604-minimum-time-to-eat-all-grains.js | 72 +++++++++++++++++++
2 files changed, 73 insertions(+)
create mode 100644 solutions/2604-minimum-time-to-eat-all-grains.js
diff --git a/README.md b/README.md
index ea0e0c16..d07f8469 100644
--- a/README.md
+++ b/README.md
@@ -2301,6 +2301,7 @@
2599|[Make the Prefix Sum Non-negative](./solutions/2599-make-the-prefix-sum-non-negative.js)|Medium|
2600|[K Items With the Maximum Sum](./solutions/2600-k-items-with-the-maximum-sum.js)|Easy|
2601|[Prime Subtraction Operation](./solutions/2601-prime-subtraction-operation.js)|Medium|
+2604|[Minimum Time to Eat All Grains](./solutions/2604-minimum-time-to-eat-all-grains.js)|Hard|
2605|[Form Smallest Number From Two Digit Arrays](./solutions/2605-form-smallest-number-from-two-digit-arrays.js)|Easy|
2606|[Find the Substring With Maximum Cost](./solutions/2606-find-the-substring-with-maximum-cost.js)|Medium|
2609|[Find the Longest Balanced Substring of a Binary String](./solutions/2609-find-the-longest-balanced-substring-of-a-binary-string.js)|Easy|
diff --git a/solutions/2604-minimum-time-to-eat-all-grains.js b/solutions/2604-minimum-time-to-eat-all-grains.js
new file mode 100644
index 00000000..28841317
--- /dev/null
+++ b/solutions/2604-minimum-time-to-eat-all-grains.js
@@ -0,0 +1,72 @@
+/**
+ * 2604. Minimum Time to Eat All Grains
+ * https://leetcode.com/problems/minimum-time-to-eat-all-grains/
+ * Difficulty: Hard
+ *
+ * There are n hens and m grains on a line. You are given the initial positions of the hens
+ * and the grains in two integer arrays hens and grains of size n and m respectively.
+ *
+ * Any hen can eat a grain if they are on the same position. The time taken for this is
+ * negligible. One hen can also eat multiple grains.
+ *
+ * In 1 second, a hen can move right or left by 1 unit. The hens can move simultaneously
+ * and independently of each other.
+ *
+ * Return the minimum time to eat all grains if the hens act optimally.
+ */
+
+/**
+ * @param {number[]} hens
+ * @param {number[]} grains
+ * @return {number}
+ */
+var minimumTime = function(hens, grains) {
+ hens.sort((a, b) => a - b);
+ grains.sort((a, b) => a - b);
+
+ let minTime = 0;
+ let maxTime = 2 * (Math.max(
+ grains[grains.length - 1],
+ hens[hens.length - 1]) - Math.min(grains[0], hens[0]
+ ));
+
+ while (minTime < maxTime) {
+ const midTime = Math.floor((minTime + maxTime) / 2);
+ if (isTimeReachable(midTime)) {
+ maxTime = midTime;
+ } else {
+ minTime = midTime + 1;
+ }
+ }
+
+ return minTime;
+
+ function isTimeReachable(time) {
+ let currentGrainIndex = 0;
+
+ for (const currentHenPosition of hens) {
+ let maximumRightReach = time;
+
+ if (grains[currentGrainIndex] < currentHenPosition) {
+ const costToReachLeftmost = currentHenPosition - grains[currentGrainIndex];
+ if (costToReachLeftmost > time) return false;
+
+ maximumRightReach = Math.max(
+ 0,
+ time - 2 * costToReachLeftmost, Math.floor((time - costToReachLeftmost) / 2)
+ );
+ }
+
+ if (currentHenPosition + maximumRightReach >= grains[currentGrainIndex]) {
+ const farthestReachablePosition = currentHenPosition + maximumRightReach;
+ while (currentGrainIndex < grains.length
+ && grains[currentGrainIndex] <= farthestReachablePosition) {
+ currentGrainIndex++;
+ }
+ if (currentGrainIndex === grains.length) return true;
+ }
+ }
+
+ return false;
+ }
+};
From 35846f0dd50c8136056aed57743ad6eb8d186e7c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 19:51:21 -0500
Subject: [PATCH 814/994] Add solution #2613
---
README.md | 1 +
solutions/2613-beautiful-pairs.js | 128 ++++++++++++++++++++++++++++++
2 files changed, 129 insertions(+)
create mode 100644 solutions/2613-beautiful-pairs.js
diff --git a/README.md b/README.md
index d07f8469..f62b2135 100644
--- a/README.md
+++ b/README.md
@@ -2306,6 +2306,7 @@
2606|[Find the Substring With Maximum Cost](./solutions/2606-find-the-substring-with-maximum-cost.js)|Medium|
2609|[Find the Longest Balanced Substring of a Binary String](./solutions/2609-find-the-longest-balanced-substring-of-a-binary-string.js)|Easy|
2610|[Convert an Array Into a 2D Array With Conditions](./solutions/2610-convert-an-array-into-a-2d-array-with-conditions.js)|Medium|
+2613|[Beautiful Pairs](./solutions/2613-beautiful-pairs.js)|Hard|
2615|[Sum of Distances](./solutions/2615-sum-of-distances.js)|Medium|
2616|[Minimize the Maximum Difference of Pairs](./solutions/2616-minimize-the-maximum-difference-of-pairs.js)|Medium|
2618|[Check if Object Instance of Class](./solutions/2618-check-if-object-instance-of-class.js)|Medium|
diff --git a/solutions/2613-beautiful-pairs.js b/solutions/2613-beautiful-pairs.js
new file mode 100644
index 00000000..b636fea1
--- /dev/null
+++ b/solutions/2613-beautiful-pairs.js
@@ -0,0 +1,128 @@
+/**
+ * 2613. Beautiful Pairs
+ * https://leetcode.com/problems/beautiful-pairs/
+ * Difficulty: Hard
+ *
+ * You are given two 0-indexed integer arrays nums1 and nums2 of the same length. A pair
+ * of indices (i,j) is called beautiful if|nums1[i] - nums1[j]| + |nums2[i] - nums2[j]|
+ * is the smallest amongst all possible indices pairs where i < j.
+ *
+ * Return the beautiful pair. In the case that there are multiple beautiful pairs, return
+ * the lexicographically smallest pair.
+ *
+ * Note that
+ * - |x| denotes the absolute value of x.
+ * - A pair of indices (i1, j1) is lexicographically smaller than (i2, j2) if i1 < i2
+ * or i1 == i2 and j1 < j2.
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @return {number[]}
+ */
+var beautifulPair = function(nums1, nums2) {
+ const n = nums1.length;
+ const max = Math.max(...nums1, ...nums2);
+ const size = max + 1;
+
+ const indices = Array.from({ length: n }, (_, i) => i)
+ .sort((a, b) => nums1[a] === nums1[b] ? a - b : nums1[a] - nums1[b]);
+
+ nums1.push(-100000001);
+ nums2.push(100000000);
+
+ const tree1 = new Array(2 * size).fill(-1);
+ const tree2 = new Array(2 * size).fill(-1);
+ let best = null;
+
+ update(nums2[indices[0]], indices[0], 1);
+ update(nums2[indices[0]], indices[0], -1);
+
+ for (let i = 1; i < n; i++) {
+ const index = indices[i];
+ const y = nums2[index];
+
+ const left = query(0, y, -1);
+ const right = query(y, max, 1);
+
+ best = select(index, left, right);
+
+ update(y, index, -1);
+ update(y, index, 1);
+ }
+
+ return best;
+
+ function compare(i, j, dir) {
+ if (j === -1) return i;
+ if (i === -1) return j;
+ const vi = -nums1[i] + dir * nums2[i];
+ const vj = -nums1[j] + dir * nums2[j];
+ return vi < vj || (vi === vj && i < j) ? i : j;
+ }
+
+ function update(position, index, dir) {
+ position += size;
+ const tree = dir === 1 ? tree2 : tree1;
+
+ while (position > 0) {
+ const cur = tree[position];
+ const better = compare(index, cur, dir);
+ if (better !== index) return;
+ tree[position] = better;
+ position = Math.floor(position / 2);
+ }
+ }
+
+ function query(l, r, dir) {
+ l += size;
+ r += size;
+ const tree = dir === 1 ? tree2 : tree1;
+ let result = -1;
+
+ while (l <= r) {
+ if (l & 1) {
+ result = compare(result, tree[l], dir);
+ l++;
+ }
+ if (!(r & 1)) {
+ result = compare(result, tree[r], dir);
+ r--;
+ }
+ l = Math.floor(l / 2);
+ r = Math.floor(r / 2);
+ }
+
+ return result;
+ }
+
+ function select(x, y, z) {
+ const pairs = [];
+
+ if (y !== -1) {
+ const d = nums1[x] + nums2[x] - nums1[y] - nums2[y];
+ pairs.push([d, [Math.min(x, y), Math.max(x, y)]]);
+ }
+
+ if (z !== -1) {
+ const d = nums1[x] - nums2[x] - nums1[z] + nums2[z];
+ pairs.push([d, [Math.min(x, z), Math.max(x, z)]]);
+ }
+
+ if (best !== null) {
+ const d = Math.abs(
+ nums1[best[0]] - nums1[best[1]]) + Math.abs(nums2[best[0]] - nums2[best[1]]
+ );
+ pairs.push([d, best]);
+ } else {
+ pairs.push([Infinity, [-1, -1]]);
+ }
+
+ return pairs.sort((a, b) => {
+ if (a[0] !== b[0]) return a[0] - b[0];
+ if (a[1][0] !== b[1][0]) return a[1][0] - b[1][0];
+ return a[1][1] - b[1][1];
+ })[0][1];
+ }
+};
From 2e04266b235afd5e4cda6c1c5b603f95d319aa26 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 12 Jul 2025 19:53:18 -0500
Subject: [PATCH 815/994] Add solution #2638
---
README.md | 3 +-
...2638-count-the-number-of-k-free-subsets.js | 58 +++++++++++++++++++
2 files changed, 60 insertions(+), 1 deletion(-)
create mode 100644 solutions/2638-count-the-number-of-k-free-subsets.js
diff --git a/README.md b/README.md
index f62b2135..268078f5 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 2,550+ LeetCode solutions in JavaScript
+# 2,600+ LeetCode solutions in JavaScript
[https://leetcodejavascript.com](https://leetcodejavascript.com)
@@ -2329,6 +2329,7 @@
2635|[Apply Transform Over Each Element in Array](./solutions/2635-apply-transform-over-each-element-in-array.js)|Easy|
2636|[Promise Pool](./solutions/2636-promise-pool.js)|Medium|
2637|[Promise Time Limit](./solutions/2637-promise-time-limit.js)|Medium|
+2638|[Count the Number of K-Free Subsets](./solutions/2638-count-the-number-of-k-free-subsets.js)|Medium|
2639|[Find the Width of Columns of a Grid](./solutions/2639-find-the-width-of-columns-of-a-grid.js)|Easy|
2640|[Find the Score of All Prefixes of an Array](./solutions/2640-find-the-score-of-all-prefixes-of-an-array.js)|Medium|
2641|[Cousins in Binary Tree II](./solutions/2641-cousins-in-binary-tree-ii.js)|Medium|
diff --git a/solutions/2638-count-the-number-of-k-free-subsets.js b/solutions/2638-count-the-number-of-k-free-subsets.js
new file mode 100644
index 00000000..f02dfd34
--- /dev/null
+++ b/solutions/2638-count-the-number-of-k-free-subsets.js
@@ -0,0 +1,58 @@
+/**
+ * 2638. Count the Number of K-Free Subsets
+ * https://leetcode.com/problems/count-the-number-of-k-free-subsets/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums, which contains distinct elements and an integer k.
+ *
+ * A subset is called a k-Free subset if it contains no two elements with an absolute
+ * difference equal to k. Notice that the empty set is a k-Free subset.
+ *
+ * Return the number of k-Free subsets of nums.
+ *
+ * A subset of an array is a selection of elements (possibly none) of the array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var countTheNumOfKFreeSubsets = function(nums, k) {
+ nums.sort((a, b) => a - b);
+ const visited = new Set();
+ let result = 1;
+
+ for (const num of nums) {
+ if (visited.has(num)) continue;
+
+ const chain = [];
+ let current = num;
+
+ while (nums.includes(current) && !visited.has(current)) {
+ chain.push(current);
+ visited.add(current);
+ current += k;
+ }
+
+ result *= calculateChainSubsets(chain.length);
+ }
+
+ return result;
+
+ function calculateChainSubsets(length) {
+ if (length === 0) return 1;
+ if (length === 1) return 2;
+
+ let prev2 = 1;
+ let prev1 = 2;
+
+ for (let i = 2; i <= length; i++) {
+ const current = prev1 + prev2;
+ prev2 = prev1;
+ prev1 = current;
+ }
+
+ return prev1;
+ }
+};
From 76a8bcdfef6a9ebe5bd42137c5cb037ab9e5495e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 13 Jul 2025 22:43:24 -0500
Subject: [PATCH 816/994] Add solution #2647
---
README.md | 1 +
solutions/2647-color-the-triangle-red.js | 34 ++++++++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/2647-color-the-triangle-red.js
diff --git a/README.md b/README.md
index 268078f5..442d9c8d 100644
--- a/README.md
+++ b/README.md
@@ -2337,6 +2337,7 @@
2644|[Find the Maximum Divisibility Score](./solutions/2644-find-the-maximum-divisibility-score.js)|Easy|
2645|[Minimum Additions to Make Valid String](./solutions/2645-minimum-additions-to-make-valid-string.js)|Medium|
2646|[Minimize the Total Price of the Trips](./solutions/2646-minimize-the-total-price-of-the-trips.js)|Hard|
+2647|[Color the Triangle Red](./solutions/2647-color-the-triangle-red.js)|Hard|
2648|[Generate Fibonacci Sequence](./solutions/2648-generate-fibonacci-sequence.js)|Easy|
2649|[Nested Array Generator](./solutions/2649-nested-array-generator.js)|Medium|
2650|[Design Cancellable Function](./solutions/2650-design-cancellable-function.js)|Hard|
diff --git a/solutions/2647-color-the-triangle-red.js b/solutions/2647-color-the-triangle-red.js
new file mode 100644
index 00000000..3c4ab329
--- /dev/null
+++ b/solutions/2647-color-the-triangle-red.js
@@ -0,0 +1,34 @@
+/**
+ * 2647. Color the Triangle Red
+ * https://leetcode.com/problems/color-the-triangle-red/
+ * Difficulty: Hard
+ *
+ * You are given an integer n. Consider an equilateral triangle of side length n, broken up into n2
+ * unit equilateral triangles. The triangle has n 1-indexed rows where the ith row has 2i - 1 unit
+ * equilateral triangles.
+ *
+ * The triangles in the ith row are also 1-indexed with coordinates from (i, 1) to (i, 2i - 1).
+ * The following image shows a triangle of side length 4 with the indexing of its triangle.
+ */
+
+/**
+ * @param {number} n
+ * @return {number[][]}
+ */
+var colorRed = function(n) {
+ const result = [[1, 1]];
+ const startCycle = [1, 2, 3, 1];
+ const shortCycle = [0, 1];
+
+ for (let i = n; i > 1; i--) {
+ const start = startCycle[(n - i) % 4];
+ const short = shortCycle[(n - i) % 2];
+
+ for (let j = start; j < i * 2; j += 2) {
+ result.push([i, j]);
+ if (short) break;
+ }
+ }
+
+ return result;
+};
From b6331b933c9ec8f363bd9620b06bde6b159f4fab Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 13 Jul 2025 22:45:42 -0500
Subject: [PATCH 817/994] Add solution #2655
---
README.md | 1 +
.../2655-find-maximal-uncovered-ranges.js | 68 +++++++++++++++++++
2 files changed, 69 insertions(+)
create mode 100644 solutions/2655-find-maximal-uncovered-ranges.js
diff --git a/README.md b/README.md
index 442d9c8d..70f8a385 100644
--- a/README.md
+++ b/README.md
@@ -2343,6 +2343,7 @@
2650|[Design Cancellable Function](./solutions/2650-design-cancellable-function.js)|Hard|
2651|[Calculate Delayed Arrival Time](./solutions/2651-calculate-delayed-arrival-time.js)|Easy|
2652|[Sum Multiples](./solutions/2652-sum-multiples.js)|Easy|
+2655|[Find Maximal Uncovered Ranges](./solutions/2655-find-maximal-uncovered-ranges.js)|Medium|
2656|[Maximum Sum With Exactly K Elements](./solutions/2656-maximum-sum-with-exactly-k-elements.js)|Easy|
2657|[Find the Prefix Common Array of Two Arrays](./solutions/2657-find-the-prefix-common-array-of-two-arrays.js)|Medium|
2658|[Maximum Number of Fish in a Grid](./solutions/2658-maximum-number-of-fish-in-a-grid.js)|Medium|
diff --git a/solutions/2655-find-maximal-uncovered-ranges.js b/solutions/2655-find-maximal-uncovered-ranges.js
new file mode 100644
index 00000000..56a4c8a0
--- /dev/null
+++ b/solutions/2655-find-maximal-uncovered-ranges.js
@@ -0,0 +1,68 @@
+/**
+ * 2655. Find Maximal Uncovered Ranges
+ * https://leetcode.com/problems/find-maximal-uncovered-ranges/
+ * Difficulty: Medium
+ *
+ * You are given an integer n which is the length of a 0-indexed array nums, and a 0-indexed
+ * 2D-array ranges, which is a list of sub-ranges of nums (sub-ranges may overlap).
+ *
+ * Each row ranges[i] has exactly 2 cells:
+ * - ranges[i][0], which shows the start of the ith range (inclusive)
+ * - ranges[i][1], which shows the end of the ith range (inclusive)
+ *
+ * These ranges cover some cells of nums and leave some cells uncovered. Your task is to find
+ * all of the uncovered ranges with maximal length.
+ *
+ * Return a 2D-array answer of the uncovered ranges, sorted by the starting point in ascending
+ * order.
+ *
+ * By all of the uncovered ranges with maximal length, we mean satisfying two conditions:
+ * - Each uncovered cell should belong to exactly one sub-range
+ * - There should not exist two ranges (l1, r1) and (l2, r2) such that r1 + 1 = l2
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} ranges
+ * @return {number[][]}
+ */
+var findMaximalUncoveredRanges = function(n, ranges) {
+ if (ranges.length === 0) return [[0, n - 1]];
+
+ ranges.sort((a, b) => a[0] - b[0]);
+
+ const mergedRanges = [];
+ let currentStart = ranges[0][0];
+ let currentEnd = ranges[0][1];
+ for (let i = 1; i < ranges.length; i++) {
+ const [start, end] = ranges[i];
+ if (start <= currentEnd + 1) {
+ currentEnd = Math.max(currentEnd, end);
+ } else {
+ mergedRanges.push([currentStart, currentEnd]);
+ currentStart = start;
+ currentEnd = end;
+ }
+ }
+ mergedRanges.push([currentStart, currentEnd]);
+
+ const result = [];
+
+ if (mergedRanges[0][0] > 0) {
+ result.push([0, mergedRanges[0][0] - 1]);
+ }
+
+ for (let i = 0; i < mergedRanges.length - 1; i++) {
+ const gapStart = mergedRanges[i][1] + 1;
+ const gapEnd = mergedRanges[i + 1][0] - 1;
+ if (gapStart <= gapEnd) {
+ result.push([gapStart, gapEnd]);
+ }
+ }
+
+ if (mergedRanges[mergedRanges.length - 1][1] < n - 1) {
+ result.push([mergedRanges[mergedRanges.length - 1][1] + 1, n - 1]);
+ }
+
+ return result;
+};
From 82b788b00a67b475b48cd34629e1859e6e63e83b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 13 Jul 2025 22:48:28 -0500
Subject: [PATCH 818/994] Add solution #2664
---
README.md | 1 +
solutions/2664-the-knights-tour.js | 70 ++++++++++++++++++++++++++++++
2 files changed, 71 insertions(+)
create mode 100644 solutions/2664-the-knights-tour.js
diff --git a/README.md b/README.md
index 70f8a385..76eeaaf7 100644
--- a/README.md
+++ b/README.md
@@ -2348,6 +2348,7 @@
2657|[Find the Prefix Common Array of Two Arrays](./solutions/2657-find-the-prefix-common-array-of-two-arrays.js)|Medium|
2658|[Maximum Number of Fish in a Grid](./solutions/2658-maximum-number-of-fish-in-a-grid.js)|Medium|
2661|[First Completely Painted Row or Column](./solutions/2661-first-completely-painted-row-or-column.js)|Medium|
+2664|[The Knight’s Tour](./solutions/2664-the-knights-tour.js)|Medium|
2665|[Counter II](./solutions/2665-counter-ii.js)|Easy|
2666|[Allow One Function Call](./solutions/2666-allow-one-function-call.js)|Easy|
2667|[Create Hello World Function](./solutions/2667-create-hello-world-function.js)|Easy|
diff --git a/solutions/2664-the-knights-tour.js b/solutions/2664-the-knights-tour.js
new file mode 100644
index 00000000..10147ab1
--- /dev/null
+++ b/solutions/2664-the-knights-tour.js
@@ -0,0 +1,70 @@
+/**
+ * 2664. The Knight’s Tour
+ * https://leetcode.com/problems/the-knights-tour/
+ * Difficulty: Medium
+ *
+ * Given two positive integers m and n which are the height and width of a 0-indexed 2D-array
+ * board, a pair of positive integers (r, c) which is the starting position of the knight on
+ * the board.
+ *
+ * Your task is to find an order of movements for the knight, in a manner that every cell of
+ * the board gets visited exactly once (the starting cell is considered visited and you
+ * shouldn't visit it again).
+ *
+ * Return the array board in which the cells' values show the order of visiting the cell
+ * starting from 0 (the initial place of the knight).
+ *
+ * Note that a knight can move from cell (r1, c1) to cell (r2, c2) if 0 <= r2 <= m - 1 and
+ * 0 <= c2 <= n - 1 and min(abs(r1 - r2), abs(c1 - c2)) = 1 and max(abs(r1 - r2), abs(c1 - c2)) = 2.
+ */
+
+/**
+ * @param {number} m
+ * @param {number} n
+ * @param {number} r
+ * @param {number} c
+ * @return {number[][]}
+ */
+var tourOfKnight = function(m, n, r, c) {
+ const board = new Array(m).fill().map(() => new Array(n).fill(-1));
+ const moves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]];
+
+ backtrack(r, c, 0);
+ return board;
+
+ function isValid(row, col) {
+ return row >= 0 && row < m && col >= 0 && col < n && board[row][col] === -1;
+ }
+
+ function getDegree(row, col) {
+ let count = 0;
+ for (const [dr, dc] of moves) {
+ if (isValid(row + dr, col + dc)) count++;
+ }
+ return count;
+ }
+
+ function backtrack(row, col, moveCount) {
+ board[row][col] = moveCount;
+
+ if (moveCount === m * n - 1) return true;
+
+ const nextMoves = [];
+ for (const [dr, dc] of moves) {
+ const newRow = row + dr;
+ const newCol = col + dc;
+ if (isValid(newRow, newCol)) {
+ nextMoves.push([newRow, newCol, getDegree(newRow, newCol)]);
+ }
+ }
+
+ nextMoves.sort((a, b) => a[2] - b[2]);
+
+ for (const [newRow, newCol] of nextMoves) {
+ if (backtrack(newRow, newCol, moveCount + 1)) return true;
+ }
+
+ board[row][col] = -1;
+ return false;
+ }
+};
From 5a7b19cf9dd9e82b097741c16dbd77bee8ffe44c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 13 Jul 2025 22:50:46 -0500
Subject: [PATCH 819/994] Add solution #2674
---
README.md | 1 +
.../2674-split-a-circular-linked-list.js | 57 +++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/2674-split-a-circular-linked-list.js
diff --git a/README.md b/README.md
index 76eeaaf7..07910e7f 100644
--- a/README.md
+++ b/README.md
@@ -2355,6 +2355,7 @@
2670|[Find the Distinct Difference Array](./solutions/2670-find-the-distinct-difference-array.js)|Easy|
2672|[Number of Adjacent Elements With the Same Color](./solutions/2672-number-of-adjacent-elements-with-the-same-color.js)|Medium|
2673|[Make Costs of Paths Equal in a Binary Tree](./solutions/2673-make-costs-of-paths-equal-in-a-binary-tree.js)|Medium|
+2674|[Split a Circular Linked List](./solutions/2674-split-a-circular-linked-list.js)|Medium|
2675|[Array of Objects to Matrix](./solutions/2675-array-of-objects-to-matrix.js)|Hard|
2676|[Throttle](./solutions/2676-throttle.js)|Medium|
2677|[Chunk Array](./solutions/2677-chunk-array.js)|Easy|
diff --git a/solutions/2674-split-a-circular-linked-list.js b/solutions/2674-split-a-circular-linked-list.js
new file mode 100644
index 00000000..34307396
--- /dev/null
+++ b/solutions/2674-split-a-circular-linked-list.js
@@ -0,0 +1,57 @@
+/**
+ * 2674. Split a Circular Linked List
+ * https://leetcode.com/problems/split-a-circular-linked-list/
+ * Difficulty: Medium
+ *
+ * Given a circular linked list list of positive integers, your task is to split it into 2 circular
+ * linked lists so that the first one contains the first half of the nodes in list (exactly
+ * ceil(list.length / 2) nodes) in the same order they appeared in list, and the second one contains
+ * the rest of the nodes in list in the same order they appeared in list.
+ *
+ * Return an array answer of length 2 in which the first element is a circular linked list
+ * representing the first half and the second element is a circular linked list representing the
+ * second half.
+ *
+ * A circular linked list is a normal linked list with the only difference being that the last
+ * node's next node, is the first node.
+ */
+
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val, next) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.next = (next===undefined ? null : next)
+ * }
+ */
+/**
+ * @param {ListNode} list
+ * @return {ListNode[]}
+ */
+var splitCircularLinkedList = function(list) {
+ let length = 0;
+ let current = list;
+
+ do {
+ length++;
+ current = current.next;
+ } while (current !== list);
+
+ const firstHalfLength = Math.ceil(length / 2);
+
+ let firstHalfEnd = list;
+ for (let i = 0; i < firstHalfLength - 1; i++) {
+ firstHalfEnd = firstHalfEnd.next;
+ }
+
+ const secondHalfStart = firstHalfEnd.next;
+
+ let secondHalfEnd = secondHalfStart;
+ for (let i = 0; i < length - firstHalfLength - 1; i++) {
+ secondHalfEnd = secondHalfEnd.next;
+ }
+
+ firstHalfEnd.next = list;
+ secondHalfEnd.next = secondHalfStart;
+
+ return [list, secondHalfStart];
+};
From 3f532205977cd3b08156f7007b345c77edbe90fa Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 13 Jul 2025 22:53:26 -0500
Subject: [PATCH 820/994] Add solution #2689
---
README.md | 1 +
...xtract-kth-character-from-the-rope-tree.js | 62 +++++++++++++++++++
2 files changed, 63 insertions(+)
create mode 100644 solutions/2689-extract-kth-character-from-the-rope-tree.js
diff --git a/README.md b/README.md
index 07910e7f..f9781c55 100644
--- a/README.md
+++ b/README.md
@@ -2365,6 +2365,7 @@
2683|[Neighboring Bitwise XOR](./solutions/2683-neighboring-bitwise-xor.js)|Medium|
2684|[Maximum Number of Moves in a Grid](./solutions/2684-maximum-number-of-moves-in-a-grid.js)|Medium|
2685|[Count the Number of Complete Components](./solutions/2685-count-the-number-of-complete-components.js)|Medium|
+2689|[Extract Kth Character From The Rope Tree](./solutions/2689-extract-kth-character-from-the-rope-tree.js)|Easy|
2690|[Infinite Method Object](./solutions/2690-infinite-method-object.js)|Easy|
2691|[Immutability Helper](./solutions/2691-immutability-helper.js)|Hard|
2692|[Make Object Immutable](./solutions/2692-make-object-immutable.js)|Medium|
diff --git a/solutions/2689-extract-kth-character-from-the-rope-tree.js b/solutions/2689-extract-kth-character-from-the-rope-tree.js
new file mode 100644
index 00000000..ffe7dd8e
--- /dev/null
+++ b/solutions/2689-extract-kth-character-from-the-rope-tree.js
@@ -0,0 +1,62 @@
+/**
+ * 2689. Extract Kth Character From The Rope Tree
+ * https://leetcode.com/problems/extract-kth-character-from-the-rope-tree/
+ * Difficulty: Easy
+ *
+ * You are given the root of a binary tree and an integer k. Besides the left and right children,
+ * every node of this tree has two other properties, a string node.val containing only lowercase
+ * English letters (possibly empty) and a non-negative integer node.len. There are two types of
+ * nodes in this tree:
+ * - Leaf: These nodes have no children, node.len = 0, and node.val is some non-empty string.
+ * - Internal: These nodes have at least one child (also at most two children), node.len > 0,
+ * and node.val is an empty string.
+ *
+ * The tree described above is called a Rope binary tree. Now we define S[node] recursively
+ * as follows:
+ * - If node is some leaf node, S[node] = node.val,
+ * - Otherwise if node is some internal node, S[node] = concat(S[node.left], S[node.right])
+ * and S[node].length = node.len.
+ *
+ * Return k-th character of the string S[root].
+ *
+ * Note: If s and p are two strings, concat(s, p) is a string obtained by concatenating p to s.
+ * For example, concat("ab", "zz") = "abzz".
+ */
+
+/**
+ * Definition for a rope tree node.
+ * class RopeTreeNode {
+ * constructor(len, val, left, right) {
+ * this.len = (len===undefined ? 0 : len);
+ * this.val = (val===undefined ? "" : val);
+ * this.left = (left===undefined ? null : left);
+ * this.right = (right===undefined ? null : right);
+ * }
+ * }
+ */
+/**
+ * @param {RopeTreeNode} root
+ * @param {number} k
+ * @return {character}
+ */
+var getKthCharacter = function(root, k) {
+ if (!root.left && !root.right) {
+ return root.val[k - 1];
+ }
+
+ const leftLength = getSubtreeLength(root.left);
+
+ if (k <= leftLength) {
+ return getKthCharacter(root.left, k);
+ } else {
+ return getKthCharacter(root.right, k - leftLength);
+ }
+
+ function getSubtreeLength(node) {
+ if (!node) return 0;
+ if (!node.left && !node.right) {
+ return node.val.length;
+ }
+ return node.len;
+ }
+};
From 960eb7a66a6f8c5add2b57947fa947bae2f6dc7e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 13 Jul 2025 22:59:45 -0500
Subject: [PATCH 821/994] Add solution #2702
---
README.md | 1 +
...operations-to-make-numbers-non-positive.js | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/2702-minimum-operations-to-make-numbers-non-positive.js
diff --git a/README.md b/README.md
index f9781c55..3a1af679 100644
--- a/README.md
+++ b/README.md
@@ -2376,6 +2376,7 @@
2697|[Lexicographically Smallest Palindrome](./solutions/2697-lexicographically-smallest-palindrome.js)|Easy|
2698|[Find the Punishment Number of an Integer](./solutions/2698-find-the-punishment-number-of-an-integer.js)|Medium|
2700|[Differences Between Two Objects](./solutions/2700-differences-between-two-objects.js)|Medium|
+2702|[Minimum Operations to Make Numbers Non-positive](./solutions/2702-minimum-operations-to-make-numbers-non-positive.js)|Hard|
2703|[Return Length of Arguments Passed](./solutions/2703-return-length-of-arguments-passed.js)|Easy|
2704|[To Be Or Not To Be](./solutions/2704-to-be-or-not-to-be.js)|Easy|
2705|[Compact Object](./solutions/2705-compact-object.js)|Medium|
diff --git a/solutions/2702-minimum-operations-to-make-numbers-non-positive.js b/solutions/2702-minimum-operations-to-make-numbers-non-positive.js
new file mode 100644
index 00000000..7834aac7
--- /dev/null
+++ b/solutions/2702-minimum-operations-to-make-numbers-non-positive.js
@@ -0,0 +1,50 @@
+/**
+ * 2702. Minimum Operations to Make Numbers Non-positive
+ * https://leetcode.com/problems/minimum-operations-to-make-numbers-non-positive/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed integer array nums and two integers x and y. In one operation,
+ * you must choose an index i such that 0 <= i < nums.length and perform the following:
+ * - Decrement nums[i] by x.
+ * - Decrement values by y at all indices except the ith one.
+ *
+ * Return the minimum number of operations to make all the integers in nums less than or equal
+ * to zero.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} x
+ * @param {number} y
+ * @return {number}
+ */
+var minOperations = function(nums, x, y) {
+ let left = 0;
+ let right = Math.max(...nums);
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (canMakeNonPositive(nums, x, y, mid)) {
+ right = mid;
+ } else {
+ left = mid + 1;
+ }
+ }
+
+ return left;
+
+ function canMakeNonPositive(nums, x, y, operations) {
+ const n = nums.length;
+ const remaining = nums.map(num => num - operations * y);
+
+ let totalExtraNeeded = 0;
+ for (let i = 0; i < n; i++) {
+ if (remaining[i] > 0) {
+ const extraNeeded = Math.ceil(remaining[i] / (x - y));
+ totalExtraNeeded += extraNeeded;
+ }
+ }
+
+ return totalExtraNeeded <= operations;
+ }
+};
From 2d8a76dc950bc2231a7833f1e6588df44dee37a1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 13 Jul 2025 23:01:59 -0500
Subject: [PATCH 822/994] Add solution #2714
---
README.md | 1 +
.../2714-find-shortest-path-with-k-hops.js | 62 +++++++++++++++++++
2 files changed, 63 insertions(+)
create mode 100644 solutions/2714-find-shortest-path-with-k-hops.js
diff --git a/README.md b/README.md
index 3a1af679..9fade682 100644
--- a/README.md
+++ b/README.md
@@ -2386,6 +2386,7 @@
2710|[Remove Trailing Zeros From a String](./solutions/2710-remove-trailing-zeros-from-a-string.js)|Easy|
2711|[Difference of Number of Distinct Values on Diagonals](./solutions/2711-difference-of-number-of-distinct-values-on-diagonals.js)|Medium|
2712|[Minimum Cost to Make All Characters Equal](./solutions/2712-minimum-cost-to-make-all-characters-equal.js)|Medium|
+2714|[Find Shortest Path with K Hops](./solutions/2714-find-shortest-path-with-k-hops.js)|Hard|
2715|[Timeout Cancellation](./solutions/2715-timeout-cancellation.js)|Easy|
2716|[Minimize String Length](./solutions/2716-minimize-string-length.js)|Easy|
2717|[Semi-Ordered Permutation](./solutions/2717-semi-ordered-permutation.js)|Easy|
diff --git a/solutions/2714-find-shortest-path-with-k-hops.js b/solutions/2714-find-shortest-path-with-k-hops.js
new file mode 100644
index 00000000..015a2aec
--- /dev/null
+++ b/solutions/2714-find-shortest-path-with-k-hops.js
@@ -0,0 +1,62 @@
+/**
+ * 2714. Find Shortest Path with K Hops
+ * https://leetcode.com/problems/find-shortest-path-with-k-hops/
+ * Difficulty: Hard
+ *
+ * You are given a positive integer n which is the number of nodes of a 0-indexed undirected
+ * weighted connected graph and a 0-indexed 2D array edges where edges[i] = [ui, vi, wi]
+ * indicates that there is an edge between nodes ui and vi with weight wi.
+ *
+ * You are also given two nodes s and d, and a positive integer k, your task is to find the
+ * shortest path from s to d, but you can hop over at most k edges. In other words, make the
+ * weight of at most k edges 0 and then find the shortest path from s to d.
+ *
+ * Return the length of the shortest path from s to d with the given condition.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @param {number} s
+ * @param {number} d
+ * @param {number} k
+ * @return {number}
+ */
+var shortestPathWithHops = function(n, edges, s, d, k) {
+ const graph = new Array(n).fill().map(() => []);
+
+ for (const [u, v, w] of edges) {
+ graph[u].push([v, w]);
+ graph[v].push([u, w]);
+ }
+
+ const dist = new Array(n).fill().map(() => new Array(k + 1).fill(Infinity));
+ const visited = new Array(n).fill().map(() => new Array(k + 1).fill(false));
+ const pq = new PriorityQueue((a, b) => a[0] - b[0]);
+
+ pq.enqueue([0, k, s]);
+
+ while (!pq.isEmpty()) {
+ const [currentDist, hopsLeft, node] = pq.dequeue();
+
+ if (visited[node][hopsLeft]) continue;
+ visited[node][hopsLeft] = true;
+
+ if (node === d) return currentDist;
+
+ for (const [neighbor, weight] of graph[node]) {
+ const newDist = currentDist + weight;
+ if (newDist < dist[neighbor][hopsLeft]) {
+ dist[neighbor][hopsLeft] = newDist;
+ pq.enqueue([newDist, hopsLeft, neighbor]);
+ }
+
+ if (hopsLeft > 0 && currentDist < dist[neighbor][hopsLeft - 1]) {
+ dist[neighbor][hopsLeft - 1] = currentDist;
+ pq.enqueue([currentDist, hopsLeft - 1, neighbor]);
+ }
+ }
+ }
+
+ return -1;
+};
From 401af4c5ebf032ba7a178b01252dd6cd929eec26 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 13 Jul 2025 23:13:34 -0500
Subject: [PATCH 823/994] Add solution #2728
---
README.md | 1 +
.../2728-count-houses-in-a-circular-street.js | 68 +++++++++++++++++++
2 files changed, 69 insertions(+)
create mode 100644 solutions/2728-count-houses-in-a-circular-street.js
diff --git a/README.md b/README.md
index 9fade682..a5c7b77b 100644
--- a/README.md
+++ b/README.md
@@ -2397,6 +2397,7 @@
2725|[Interval Cancellation](./solutions/2725-interval-cancellation.js)|Easy|
2726|[Calculator with Method Chaining](./solutions/2726-calculator-with-method-chaining.js)|Easy|
2727|[Is Object Empty](./solutions/2727-is-object-empty.js)|Easy|
+2728|[Count Houses in a Circular Street](./solutions/2728-count-houses-in-a-circular-street.js)|Easy|
2729|[Check if The Number is Fascinating](./solutions/2729-check-if-the-number-is-fascinating.js)|Easy|
2732|[Find a Good Subset of the Matrix](./solutions/2732-find-a-good-subset-of-the-matrix.js)|Hard|
2733|[Neither Minimum nor Maximum](./solutions/2733-neither-minimum-nor-maximum.js)|Easy|
diff --git a/solutions/2728-count-houses-in-a-circular-street.js b/solutions/2728-count-houses-in-a-circular-street.js
new file mode 100644
index 00000000..936f1699
--- /dev/null
+++ b/solutions/2728-count-houses-in-a-circular-street.js
@@ -0,0 +1,68 @@
+/**
+ * 2728. Count Houses in a Circular Street
+ * https://leetcode.com/problems/count-houses-in-a-circular-street/
+ * Difficulty: Easy
+ *
+ * You are given an object street of class Street that represents a circular street and a positive
+ * integer k which represents a maximum bound for the number of houses in that street (in other
+ * words, the number of houses is less than or equal to k). Houses' doors could be open or closed
+ * initially.
+ *
+ * Initially, you are standing in front of a door to a house on this street. Your task is to count
+ * the number of houses in the street.
+ *
+ * The class Street contains the following functions which may help you:
+ * - void openDoor(): Open the door of the house you are in front of.
+ * - void closeDoor(): Close the door of the house you are in front of.
+ * - boolean isDoorOpen(): Returns true if the door of the current house is open and false
+ * otherwise.
+ * - void moveRight(): Move to the right house.
+ * - void moveLeft(): Move to the left house.
+ *
+ * Return ans which represents the number of houses on this street.
+ */
+
+/**
+ * Definition for a street.
+ * class Street {
+ * @param {number[]} doors
+ * constructor(doors);
+ *
+ * @return {void}
+ * openDoor();
+ *
+ * @return {void}
+ * closeDoor();
+ *
+ * @return {boolean}
+ * isDoorOpen();
+ *
+ * @return {void}
+ * moveRight();
+ *
+ * @return {void}
+ * moveLeft();
+ * }
+ */
+/**
+ * @param {Street} street
+ * @param {number} k
+ * @return {number}
+ */
+var houseCount = function(street, k) {
+ for (let i = 0; i < k; i++) {
+ street.closeDoor();
+ street.moveLeft();
+ }
+
+ street.openDoor();
+ let count = 1;
+
+ street.moveLeft();
+ while (!street.isDoorOpen()) {
+ street.moveLeft();
+ count++;
+ }
+
+ return count;
+};
From 9762f6f3a7bb330d0b2ae28561ccc44c30172030 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 13 Jul 2025 23:14:40 -0500
Subject: [PATCH 824/994] Add solution #2737
---
README.md | 1 +
.../2737-find-the-closest-marked-node.js | 56 +++++++++++++++++++
2 files changed, 57 insertions(+)
create mode 100644 solutions/2737-find-the-closest-marked-node.js
diff --git a/README.md b/README.md
index a5c7b77b..d85ba68e 100644
--- a/README.md
+++ b/README.md
@@ -2401,6 +2401,7 @@
2729|[Check if The Number is Fascinating](./solutions/2729-check-if-the-number-is-fascinating.js)|Easy|
2732|[Find a Good Subset of the Matrix](./solutions/2732-find-a-good-subset-of-the-matrix.js)|Hard|
2733|[Neither Minimum nor Maximum](./solutions/2733-neither-minimum-nor-maximum.js)|Easy|
+2737|[Find the Closest Marked Node](./solutions/2737-find-the-closest-marked-node.js)|Medium|
2739|[Total Distance Traveled](./solutions/2739-total-distance-traveled.js)|Easy|
2740|[Find the Value of the Partition](./solutions/2740-find-the-value-of-the-partition.js)|Medium|
2742|[Painting the Walls](./solutions/2742-painting-the-walls.js)|Hard|
diff --git a/solutions/2737-find-the-closest-marked-node.js b/solutions/2737-find-the-closest-marked-node.js
new file mode 100644
index 00000000..dc8cba75
--- /dev/null
+++ b/solutions/2737-find-the-closest-marked-node.js
@@ -0,0 +1,56 @@
+/**
+ * 2737. Find the Closest Marked Node
+ * https://leetcode.com/problems/find-the-closest-marked-node/
+ * Difficulty: Medium
+ *
+ * You are given a positive integer n which is the number of nodes of a 0-indexed directed
+ * weighted graph and a 0-indexed 2D array edges where edges[i] = [ui, vi, wi] indicates
+ * that there is an edge from node ui to node vi with weight wi.
+ *
+ * You are also given a node s and a node array marked; your task is to find the minimum
+ * distance from s to any of the nodes in marked.
+ *
+ * Return an integer denoting the minimum distance from s to any node in marked or -1 if
+ * there are no paths from s to any of the marked nodes.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} edges
+ * @param {number} s
+ * @param {number[]} marked
+ * @return {number}
+ */
+var minimumDistance = function(n, edges, s, marked) {
+ const graph = new Array(n).fill().map(() => []);
+ const markedSet = new Set(marked);
+
+ for (const [u, v, w] of edges) {
+ graph[u].push([v, w]);
+ }
+
+ const distances = new Array(n).fill(Infinity);
+ const pq = new PriorityQueue((a, b) => a[0] - b[0]);
+ distances[s] = 0;
+ pq.enqueue([0, s]);
+
+ while (!pq.isEmpty()) {
+ const [currentDist, node] = pq.dequeue();
+
+ if (currentDist > distances[node]) continue;
+
+ if (markedSet.has(node)) {
+ return currentDist;
+ }
+
+ for (const [neighbor, weight] of graph[node]) {
+ const newDist = currentDist + weight;
+ if (newDist < distances[neighbor]) {
+ distances[neighbor] = newDist;
+ pq.enqueue([newDist, neighbor]);
+ }
+ }
+ }
+
+ return -1;
+};
From 8e3c050b776b0a1a41a0d6cffd953fdcf60732c4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 13 Jul 2025 23:16:01 -0500
Subject: [PATCH 825/994] Add solution #2743
---
README.md | 1 +
...-substrings-without-repeating-character.js | 45 +++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/2743-count-substrings-without-repeating-character.js
diff --git a/README.md b/README.md
index d85ba68e..1414d819 100644
--- a/README.md
+++ b/README.md
@@ -2405,6 +2405,7 @@
2739|[Total Distance Traveled](./solutions/2739-total-distance-traveled.js)|Easy|
2740|[Find the Value of the Partition](./solutions/2740-find-the-value-of-the-partition.js)|Medium|
2742|[Painting the Walls](./solutions/2742-painting-the-walls.js)|Hard|
+2743|[Count Substrings Without Repeating Character](./solutions/2743-count-substrings-without-repeating-character.js)|Medium|
2744|[Find Maximum Number of String Pairs](./solutions/2744-find-maximum-number-of-string-pairs.js)|Easy|
2745|[Construct the Longest New String](./solutions/2745-construct-the-longest-new-string.js)|Medium|
2748|[Number of Beautiful Pairs](./solutions/2748-number-of-beautiful-pairs.js)|Easy|
diff --git a/solutions/2743-count-substrings-without-repeating-character.js b/solutions/2743-count-substrings-without-repeating-character.js
new file mode 100644
index 00000000..37dce1d2
--- /dev/null
+++ b/solutions/2743-count-substrings-without-repeating-character.js
@@ -0,0 +1,45 @@
+/**
+ * 2743. Count Substrings Without Repeating Character
+ * https://leetcode.com/problems/count-substrings-without-repeating-character/
+ * Difficulty: Medium
+ *
+ * You are given a string s consisting only of lowercase English letters. We call a substring
+ * special if it contains no character which has occurred at least twice (in other words, it
+ * does not contain a repeating character). Your task is to count the number of special
+ * substrings. For example, in the string "pop", the substring "po" is a special substring,
+ * however, "pop" is not special (since 'p' has occurred twice).
+ *
+ * Return the number of special substrings.
+ *
+ * A substring is a contiguous sequence of characters within a string. For example, "abc" is
+ * a substring of "abcd", but "acd" is not.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var numberOfSpecialSubstrings = function(s) {
+ const n = s.length;
+ const map = new Map();
+ let result = 0;
+ let left = 0;
+
+ for (let right = 0; right < n; right++) {
+ const char = s[right];
+ map.set(char, (map.get(char) || 0) + 1);
+
+ while (map.get(char) > 1) {
+ const leftChar = s[left];
+ map.set(leftChar, map.get(leftChar) - 1);
+ if (map.get(leftChar) === 0) {
+ map.delete(leftChar);
+ }
+ left++;
+ }
+
+ result += right - left + 1;
+ }
+
+ return result;
+};
From faf6ee2f088b31992b88a5116b2541ce14a8d8c6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 13 Jul 2025 23:48:14 -0500
Subject: [PATCH 826/994] Add solution #2753
---
README.md | 1 +
...53-count-houses-in-a-circular-street-ii.js | 77 +++++++++++++++++++
2 files changed, 78 insertions(+)
create mode 100644 solutions/2753-count-houses-in-a-circular-street-ii.js
diff --git a/README.md b/README.md
index 1414d819..c49d137e 100644
--- a/README.md
+++ b/README.md
@@ -2410,6 +2410,7 @@
2745|[Construct the Longest New String](./solutions/2745-construct-the-longest-new-string.js)|Medium|
2748|[Number of Beautiful Pairs](./solutions/2748-number-of-beautiful-pairs.js)|Easy|
2751|[Robot Collisions](./solutions/2751-robot-collisions.js)|Hard|
+2753|[Count Houses in a Circular Street II](./solutions/2753-count-houses-in-a-circular-street-ii.js)|Hard|
2754|[Bind Function to Context](./solutions/2754-bind-function-to-context.js)|Medium|
2755|[Deep Merge of Two Objects](./solutions/2755-deep-merge-of-two-objects.js)|Medium|
2756|[Query Batching](./solutions/2756-query-batching.js)|Hard|
diff --git a/solutions/2753-count-houses-in-a-circular-street-ii.js b/solutions/2753-count-houses-in-a-circular-street-ii.js
new file mode 100644
index 00000000..66f385ab
--- /dev/null
+++ b/solutions/2753-count-houses-in-a-circular-street-ii.js
@@ -0,0 +1,77 @@
+/**
+ * 2753. Count Houses in a Circular Street II
+ * https://leetcode.com/problems/count-houses-in-a-circular-street-ii/
+ * Difficulty: Hard
+ *
+ * You are given an object street of class Street that represents a circular street and a positive
+ * integer k which represents a maximum bound for the number of houses in that street (in other
+ * words, the number of houses is less than or equal to k). Houses' doors could be open or closed
+ * initially (at least one is open).
+ *
+ * Initially, you are standing in front of a door to a house on this street. Your task is to count
+ * the number of houses in the street.
+ *
+ * The class Street contains the following functions which may help you:
+ * - void closeDoor(): Close the door of the house you are in front of.
+ * - boolean isDoorOpen(): Returns true if the door of the current house is open and false
+ * otherwise.
+ * - void moveRight(): Move to the right house.
+ *
+ * Note that by circular street, we mean if you number the houses from 1 to n, then the right house
+ * of housei is housei+1 for i < n, and the right house of housen is house1.
+ *
+ * Return ans which represents the number of houses on this street.
+ */
+
+/**
+ * Definition for a street.
+ * class Street {
+ * @param {number[]} doors
+ * constructor(doors);
+ *
+ * @return {void}
+ * closeDoor();
+ *
+ * @return {boolean}
+ * isDoorOpen();
+ *
+ * @return {void}
+ * moveRight();
+ * }
+ */
+/**
+ * @param {Street} street
+ * @param {number} k
+ * @return {number}
+ */
+var houseCount = function(street, k) {
+ let result = 0;
+
+ while (true) {
+ tryMoveToOpen(street, k, true);
+ const distance = tryMoveToOpen(street, k, false);
+
+ if (distance > k) {
+ return result;
+ }
+
+ result = distance;
+ street.closeDoor();
+ }
+
+ function tryMoveToOpen(street, k, considerCurrent) {
+ if (street.isDoorOpen() && considerCurrent) {
+ return 0;
+ }
+
+ let moves = 1;
+ street.moveRight();
+
+ while (!street.isDoorOpen() && moves <= k) {
+ street.moveRight();
+ moves++;
+ }
+
+ return moves;
+ }
+};
From b2ccfd9680e0625837b98f7c9bd33347c165d4e6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 13 Jul 2025 23:49:31 -0500
Subject: [PATCH 827/994] Add solution #2764
---
README.md | 1 +
...is-array-a-preorder-of-some-binary-tree.js | 64 +++++++++++++++++++
2 files changed, 65 insertions(+)
create mode 100644 solutions/2764-is-array-a-preorder-of-some-binary-tree.js
diff --git a/README.md b/README.md
index c49d137e..5cd6ed7b 100644
--- a/README.md
+++ b/README.md
@@ -2418,6 +2418,7 @@
2758|[Next Day](./solutions/2758-next-day.js)|Easy|
2759|[Convert JSON String to Object](./solutions/2759-convert-json-string-to-object.js)|Hard|
2763|[Sum of Imbalance Numbers of All Subarrays](./solutions/2763-sum-of-imbalance-numbers-of-all-subarrays.js)|Hard|
+2764|[Is Array a Preorder of Some ‌Binary Tree](./solutions/2764-is-array-a-preorder-of-some-binary-tree.js)|Medium|
2766|[Relocate Marbles](./solutions/2766-relocate-marbles.js)|Medium|
2767|[Partition String Into Minimum Beautiful Substrings](./solutions/2767-partition-string-into-minimum-beautiful-substrings.js)|Medium|
2769|[Find the Maximum Achievable Number](./solutions/2769-find-the-maximum-achievable-number.js)|Easy|
diff --git a/solutions/2764-is-array-a-preorder-of-some-binary-tree.js b/solutions/2764-is-array-a-preorder-of-some-binary-tree.js
new file mode 100644
index 00000000..908d862b
--- /dev/null
+++ b/solutions/2764-is-array-a-preorder-of-some-binary-tree.js
@@ -0,0 +1,64 @@
+/**
+ * 2764. Is Array a Preorder of Some ‌Binary Tree
+ * https://leetcode.com/problems/is-array-a-preorder-of-some-binary-tree/
+ * Difficulty: Medium
+ *
+ * Given a 0-indexed integer 2D array nodes, your task is to determine if the given array represents
+ * the preorder traversal of some binary tree.
+ *
+ * For each index i, nodes[i] = [id, parentId], where id is the id of the node at the index i and
+ * parentId is the id of its parent in the tree (if the node has no parent, then parentId == -1).
+ *
+ * Return true if the given array represents the preorder traversal of some tree, and false
+ * otherwise.
+ *
+ * Note: the preorder traversal of a tree is a recursive way to traverse a tree in which we first
+ * visit the current node, then we do the preorder traversal for the left child, and finally, we
+ * do it for the right child.
+ */
+
+/**
+ * @param {number[][]} nodes
+ * @return {boolean}
+ */
+var isPreorder = function(nodes) {
+ const children = new Map();
+ let root = null;
+
+ for (const [id, parentId] of nodes) {
+ if (parentId === -1) {
+ root = id;
+ } else {
+ if (!children.has(parentId)) {
+ children.set(parentId, []);
+ }
+ children.get(parentId).push(id);
+ }
+ }
+
+ const expectedOrder = [];
+
+ traverse(root);
+
+ for (let i = 0; i < nodes.length; i++) {
+ if (nodes[i][0] !== expectedOrder[i]) {
+ return false;
+ }
+ }
+
+ return true;
+
+ function traverse(nodeId) {
+ if (nodeId === null) return;
+
+ expectedOrder.push(nodeId);
+
+ const nodeChildren = children.get(nodeId) || [];
+ if (nodeChildren.length > 0) {
+ traverse(nodeChildren[0]);
+ }
+ if (nodeChildren.length > 1) {
+ traverse(nodeChildren[1]);
+ }
+ }
+};
From f8681cb424eb8e15a1da5de8038807a541ffb270 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 13 Jul 2025 23:51:33 -0500
Subject: [PATCH 828/994] Add solution #2773
---
README.md | 1 +
.../2773-height-of-special-binary-tree.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/2773-height-of-special-binary-tree.js
diff --git a/README.md b/README.md
index 5cd6ed7b..a3b723cd 100644
--- a/README.md
+++ b/README.md
@@ -2422,6 +2422,7 @@
2766|[Relocate Marbles](./solutions/2766-relocate-marbles.js)|Medium|
2767|[Partition String Into Minimum Beautiful Substrings](./solutions/2767-partition-string-into-minimum-beautiful-substrings.js)|Medium|
2769|[Find the Maximum Achievable Number](./solutions/2769-find-the-maximum-achievable-number.js)|Easy|
+2773|[Height of Special Binary Tree](./solutions/2773-height-of-special-binary-tree.js)|Medium|
2774|[Array Upper Bound](./solutions/2774-array-upper-bound.js)|Easy|
2775|[Undefined to Null](./solutions/2775-undefined-to-null.js)|Medium|
2776|[Convert Callback Based Function to Promise Based Function](./solutions/2776-convert-callback-based-function-to-promise-based-function.js)|Medium|
diff --git a/solutions/2773-height-of-special-binary-tree.js b/solutions/2773-height-of-special-binary-tree.js
new file mode 100644
index 00000000..0a28dcdb
--- /dev/null
+++ b/solutions/2773-height-of-special-binary-tree.js
@@ -0,0 +1,39 @@
+/**
+ * 2773. Height of Special Binary Tree
+ * https://leetcode.com/problems/height-of-special-binary-tree/
+ * Difficulty: Medium
+ *
+ * You are given a root, which is the root of a special binary tree with n nodes. The nodes of
+ * the special binary tree are numbered from 1 to n. Suppose the tree has k leaves in the
+ * following order: b1 < b2 < ... < bk.
+ *
+ * The leaves of this tree have a special property! That is, for every leaf bi, the following
+ * conditions hold:
+ * - The right child of bi is bi + 1 if i < k, and b1 otherwise.
+ * - The left child of bi is bi - 1 if i > 1, and bk otherwise.
+ *
+ * Return the height of the given tree.
+ *
+ * Note: The height of a binary tree is the length of the longest path from the root to any
+ * other 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 heightOfTree = function(root) {
+ if (!root || (root.left && root.left.right === root)) {
+ return 0;
+ }
+
+ return 1 + Math.max(heightOfTree(root.left), heightOfTree(root.right));
+};
From feaeeecff1659357ffa962dd23b822bc57c0c951 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 13 Jul 2025 23:53:39 -0500
Subject: [PATCH 829/994] Add solution #2782
---
README.md | 1 +
solutions/2782-number-of-unique-categories.js | 55 +++++++++++++++++++
2 files changed, 56 insertions(+)
create mode 100644 solutions/2782-number-of-unique-categories.js
diff --git a/README.md b/README.md
index a3b723cd..1bd2132c 100644
--- a/README.md
+++ b/README.md
@@ -2430,6 +2430,7 @@
2778|[Sum of Squares of Special Elements](./solutions/2778-sum-of-squares-of-special-elements.js)|Easy|
2779|[Maximum Beauty of an Array After Applying Operation](./solutions/2779-maximum-beauty-of-an-array-after-applying-operation.js)|Medium|
2780|[Minimum Index of a Valid Split](./solutions/2780-minimum-index-of-a-valid-split.js)|Medium|
+2782|[Number of Unique Categories](./solutions/2782-number-of-unique-categories.js)|Medium|
2784|[Check if Array is Good](./solutions/2784-check-if-array-is-good.js)|Easy|
2785|[Sort Vowels in a String](./solutions/2785-sort-vowels-in-a-string.js)|Medium|
2788|[Split Strings by Separator](./solutions/2788-split-strings-by-separator.js)|Easy|
diff --git a/solutions/2782-number-of-unique-categories.js b/solutions/2782-number-of-unique-categories.js
new file mode 100644
index 00000000..7ddebf86
--- /dev/null
+++ b/solutions/2782-number-of-unique-categories.js
@@ -0,0 +1,55 @@
+/**
+ * 2782. Number of Unique Categories
+ * https://leetcode.com/problems/number-of-unique-categories/
+ * Difficulty: Medium
+ *
+ * You are given an integer n and an object categoryHandler of class CategoryHandler.
+ *
+ * There are n elements, numbered from 0 to n - 1. Each element has a category, and your task
+ * is to find the number of unique categories.
+ *
+ * The class CategoryHandler contains the following function, which may help you:
+ * - boolean haveSameCategory(integer a, integer b): Returns true if a and b are in the same
+ * category and false otherwise. Also, if either a or b is not a valid number (i.e. it's greater
+ * than or equal to nor less than 0), it returns false.
+ *
+ * Return the number of unique categories.
+ */
+
+/**
+ * Definition for a category handler.
+ * class CategoryHandler {
+ * @param {number[]} categories
+ * constructor(categories);
+ *
+ * @param {number} a
+ * @param {number} b
+ * @return {boolean}
+ * haveSameCategory(a, b);
+ * }
+ */
+/**
+ * @param {number} n
+ * @param {CategoryHandler} categoryHandler
+ * @return {number}
+ */
+var numberOfCategories = function(n, categoryHandler) {
+ let result = 0;
+
+ for (let j = 0; j < n; j++) {
+ let isNewCategory = true;
+
+ for (let i = 0; i < j; i++) {
+ if (categoryHandler.haveSameCategory(i, j)) {
+ isNewCategory = false;
+ break;
+ }
+ }
+
+ if (isNewCategory) {
+ result++;
+ }
+ }
+
+ return result;
+};
From f0c77773659370ee5082331f636b39911c0ec35b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 13 Jul 2025 23:55:33 -0500
Subject: [PATCH 830/994] Add solution #2792
---
README.md | 1 +
.../2792-count-nodes-that-are-great-enough.js | 51 +++++++++++++++++++
2 files changed, 52 insertions(+)
create mode 100644 solutions/2792-count-nodes-that-are-great-enough.js
diff --git a/README.md b/README.md
index 1bd2132c..734373ff 100644
--- a/README.md
+++ b/README.md
@@ -2436,6 +2436,7 @@
2788|[Split Strings by Separator](./solutions/2788-split-strings-by-separator.js)|Easy|
2789|[Largest Element in an Array after Merge Operations](./solutions/2789-largest-element-in-an-array-after-merge-operations.js)|Medium|
2791|[Count Paths That Can Form a Palindrome in a Tree](./solutions/2791-count-paths-that-can-form-a-palindrome-in-a-tree.js)|Hard|
+2792|[Count Nodes That Are Great Enough](./solutions/2792-count-nodes-that-are-great-enough.js)|Hard|
2794|[Create Object from Two Arrays](./solutions/2794-create-object-from-two-arrays.js)|Easy|
2795|[Parallel Execution of Promises for Individual Results Retrieval](./solutions/2795-parallel-execution-of-promises-for-individual-results-retrieval.js)|Medium|
2796|[Repeat String](./solutions/2796-repeat-string.js)|Easy|
diff --git a/solutions/2792-count-nodes-that-are-great-enough.js b/solutions/2792-count-nodes-that-are-great-enough.js
new file mode 100644
index 00000000..4c4f4e42
--- /dev/null
+++ b/solutions/2792-count-nodes-that-are-great-enough.js
@@ -0,0 +1,51 @@
+/**
+ * 2792. Count Nodes That Are Great Enough
+ * https://leetcode.com/problems/count-nodes-that-are-great-enough/
+ * Difficulty: Hard
+ *
+ * You are given a root to a binary tree and an integer k. A node of this tree is called great
+ * enough if the followings hold:
+ * - Its subtree has at least k nodes.
+ * - Its value is greater than the value of at least k nodes in its subtree.
+ *
+ * Return the number of nodes in this tree that are great enough.
+ *
+ * The node u is in the subtree of the node v, if u == v or v is an ancestor of u.
+ */
+
+/**
+ * Definition for a binary tree node.
+ * function TreeNode(val, left, right) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ */
+/**
+ * @param {TreeNode} root
+ * @param {number} k
+ * @return {number}
+ */
+var countGreatEnoughNodes = function(root, k) {
+ let result = 0;
+
+ dfs(root);
+
+ return result;
+
+ function dfs(node) {
+ if (!node) return [];
+
+ const leftValues = dfs(node.left);
+ const rightValues = dfs(node.right);
+ const combined = [...leftValues, ...rightValues].sort((a, b) => a - b).slice(0, k);
+
+ if (combined.length >= k && combined[k - 1] < node.val) {
+ result++;
+ } else {
+ combined.push(node.val);
+ }
+
+ return combined;
+ }
+};
From 60d1ef007500325c9690fd0aab9d1eb30d7e4ee0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 14 Jul 2025 19:14:40 -0500
Subject: [PATCH 831/994] Add solution #3136
---
README.md | 1 +
solutions/3136-valid-word.js | 48 ++++++++++++++++++++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/3136-valid-word.js
diff --git a/README.md b/README.md
index 734373ff..bb1efd70 100644
--- a/README.md
+++ b/README.md
@@ -2577,6 +2577,7 @@
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|
+3136|[Valid Word](./solutions/3136-valid-word.js)|Easy|
3151|[Special Array I](./solutions/3151-special-array-i.js)|Easy|
3160|[Find the Number of Distinct Colors Among the Balls](./solutions/3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium|
3169|[Count Days Without Meetings](./solutions/3169-count-days-without-meetings.js)|Medium|
diff --git a/solutions/3136-valid-word.js b/solutions/3136-valid-word.js
new file mode 100644
index 00000000..18d98f13
--- /dev/null
+++ b/solutions/3136-valid-word.js
@@ -0,0 +1,48 @@
+/**
+ * 3136. Valid Word
+ * https://leetcode.com/problems/valid-word/
+ * Difficulty: Easy
+ *
+ * A word is considered valid if:
+ * - It contains a minimum of 3 characters.
+ * - It contains only digits (0-9), and English letters (uppercase and lowercase).
+ * - It includes at least one vowel.
+ * - It includes at least one consonant.
+ *
+ * You are given a string word.
+ *
+ * Return true if word is valid, otherwise, return false.
+ *
+ * Notes:
+ * - 'a', 'e', 'i', 'o', 'u', and their uppercases are vowels.
+ * - A consonant is an English letter that is not a vowel.
+ */
+
+/**
+ * @param {string} word
+ * @return {boolean}
+ */
+var isValid = function(word) {
+ if (word.length < 3) return false;
+
+ const vowels = new Set('aeiouAEIOU');
+ const special = new Set('@#$');
+ const digits = new Set('0123456789');
+ const wordSet = new Set(word);
+
+ if (hasIntersection(wordSet, special)) return false;
+ if (!hasIntersection(wordSet, vowels)) return false;
+
+ const result = new Set([...wordSet].filter(char => {
+ return !vowels.has(char) && !digits.has(char);
+ }));
+
+ return result.size > 0;
+
+ function hasIntersection(set1, set2) {
+ for (const item of set1) {
+ if (set2.has(item)) return true;
+ }
+ return false;
+ }
+};
From 29d422a8a440b585b3a5709f56757e2df2c2173b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 14 Jul 2025 20:00:44 -0500
Subject: [PATCH 832/994] Add solution #2802
---
README.md | 1 +
solutions/2802-find-the-k-th-lucky-number.js | 29 ++++++++++++++++++++
2 files changed, 30 insertions(+)
create mode 100644 solutions/2802-find-the-k-th-lucky-number.js
diff --git a/README.md b/README.md
index bb1efd70..68b4de03 100644
--- a/README.md
+++ b/README.md
@@ -2443,6 +2443,7 @@
2797|[Partial Function with Placeholders](./solutions/2797-partial-function-with-placeholders.js)|Easy|
2798|[Number of Employees Who Met the Target](./solutions/2798-number-of-employees-who-met-the-target.js)|Easy|
2799|[Count Complete Subarrays in an Array](./solutions/2799-count-complete-subarrays-in-an-array.js)|Medium|
+2802|[Find The K-th Lucky Number](./solutions/2802-find-the-k-th-lucky-number.js)|Medium|
2803|[Factorial Generator](./solutions/2803-factorial-generator.js)|Easy|
2804|[Array Prototype ForEach](./solutions/2804-array-prototype-foreach.js)|Easy|
2805|[Custom Interval](./solutions/2805-custom-interval.js)|Medium|
diff --git a/solutions/2802-find-the-k-th-lucky-number.js b/solutions/2802-find-the-k-th-lucky-number.js
new file mode 100644
index 00000000..00f11024
--- /dev/null
+++ b/solutions/2802-find-the-k-th-lucky-number.js
@@ -0,0 +1,29 @@
+/**
+ * 2802. Find The K-th Lucky Number
+ * https://leetcode.com/problems/find-the-k-th-lucky-number/
+ * Difficulty: Medium
+ *
+ * We know that 4 and 7 are lucky digits. Also, a number is called lucky if it contains only
+ * lucky digits.
+ *
+ * You are given an integer k, return the kth lucky number represented as a string.
+ */
+
+/**
+ * @param {number} k
+ * @return {string}
+ */
+var kthLuckyNumber = function(k) {
+ let length = 1;
+ let totalNumbers = 0;
+
+ while (totalNumbers + Math.pow(2, length) < k) {
+ totalNumbers += Math.pow(2, length);
+ length++;
+ }
+
+ const position = k - totalNumbers;
+ const binaryString = (position - 1).toString(2).padStart(length, '0');
+
+ return binaryString.replace(/0/g, '4').replace(/1/g, '7');
+};
From 1112212f4910529ec6e4d56e6fe9313c0e59bd0e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 14 Jul 2025 20:05:38 -0500
Subject: [PATCH 833/994] Add solution #2814
---
README.md | 1 +
...s-to-reach-destination-without-drowning.js | 90 +++++++++++++++++++
2 files changed, 91 insertions(+)
create mode 100644 solutions/2814-minimum-time-takes-to-reach-destination-without-drowning.js
diff --git a/README.md b/README.md
index 68b4de03..f6288ac8 100644
--- a/README.md
+++ b/README.md
@@ -2450,6 +2450,7 @@
2806|[Account Balance After Rounded Purchase](./solutions/2806-account-balance-after-rounded-purchase.js)|Easy|
2807|[Insert Greatest Common Divisors in Linked List](./solutions/2807-insert-greatest-common-divisors-in-linked-list.js)|Medium|
2810|[Faulty Keyboard](./solutions/2810-faulty-keyboard.js)|Easy|
+2814|[Minimum Time Takes to Reach Destination Without Drowning](./solutions/2814-minimum-time-takes-to-reach-destination-without-drowning.js)|Hard|
2815|[Max Pair Sum in an Array](./solutions/2815-max-pair-sum-in-an-array.js)|Easy|
2816|[Double a Number Represented as a Linked List](./solutions/2816-double-a-number-represented-as-a-linked-list.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
diff --git a/solutions/2814-minimum-time-takes-to-reach-destination-without-drowning.js b/solutions/2814-minimum-time-takes-to-reach-destination-without-drowning.js
new file mode 100644
index 00000000..c83fc741
--- /dev/null
+++ b/solutions/2814-minimum-time-takes-to-reach-destination-without-drowning.js
@@ -0,0 +1,90 @@
+/**
+ * 2814. Minimum Time Takes to Reach Destination Without Drowning
+ * https://leetcode.com/problems/minimum-time-takes-to-reach-destination-without-drowning/
+ * Difficulty: Hard
+ *
+ * You are given an n * m 0-indexed grid of string land. Right now, you are standing at the cell
+ * that contains "S", and you want to get to the cell containing "D". There are three other types
+ * of cells in this land:
+ * - ".": These cells are empty.
+ * - "X": These cells are stone.
+ * - "*": These cells are flooded.
+ *
+ * At each second, you can move to a cell that shares a side with your current cell (if it exists).
+ * Also, at each second, every empty cell that shares a side with a flooded cell becomes flooded
+ * as well.
+ *
+ * There are two problems ahead of your journey:
+ * - You can't step on stone cells.
+ * - You can't step on flooded cells since you will drown (also, you can't step on a cell that will
+ * be flooded at the same time as you step on it).
+ *
+ * Return the minimum time it takes you to reach the destination in seconds, or -1 if it is
+ * impossible.
+ *
+ * Note that the destination will never be flooded.
+ */
+
+/**
+ * @param {string[][]} land
+ * @return {number}
+ */
+var minimumSeconds = function(land) {
+ const rows = land.length;
+ const cols = land[0].length;
+ const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];
+ const floodQueue = [];
+ const startQueue = [];
+
+ for (let i = 0; i < rows; i++) {
+ for (let j = 0; j < cols; j++) {
+ if (land[i][j] === 'S') {
+ startQueue.push([i, j]);
+ } else if (land[i][j] === '*') {
+ floodQueue.push([i, j]);
+ }
+ }
+ }
+
+ let time = 0;
+
+ while (startQueue.length > 0) {
+ time++;
+
+ const floodSize = floodQueue.length;
+ for (let f = 0; f < floodSize; f++) {
+ const [i, j] = floodQueue.shift();
+ for (const [dx, dy] of directions) {
+ const x = i + dx;
+ const y = j + dy;
+ if (isValidPosition(x, y) && land[x][y] === '.') {
+ land[x][y] = '*';
+ floodQueue.push([x, y]);
+ }
+ }
+ }
+
+ const startSize = startQueue.length;
+ for (let s = 0; s < startSize; s++) {
+ const [i, j] = startQueue.shift();
+ for (const [dx, dy] of directions) {
+ const x = i + dx;
+ const y = j + dy;
+ if (isValidPosition(x, y)) {
+ if (land[x][y] === 'D') {
+ return time;
+ } else if (land[x][y] === '.') {
+ land[x][y] = 'S';
+ startQueue.push([x, y]);
+ }
+ }
+ }
+ }
+ }
+
+ return -1;
+
+ function isValidPosition(x, y) {
+ return x >= 0 && x < rows && y >= 0 && y < cols;
+ }
+};
From 1111d6d123e12554e60e0e1add87b94e7f4af3fa Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 14 Jul 2025 20:07:56 -0500
Subject: [PATCH 834/994] Add solution #2819
---
README.md | 1 +
...m-relative-loss-after-buying-chocolates.js | 77 +++++++++++++++++++
2 files changed, 78 insertions(+)
create mode 100644 solutions/2819-minimum-relative-loss-after-buying-chocolates.js
diff --git a/README.md b/README.md
index f6288ac8..f56fe1e6 100644
--- a/README.md
+++ b/README.md
@@ -2454,6 +2454,7 @@
2815|[Max Pair Sum in an Array](./solutions/2815-max-pair-sum-in-an-array.js)|Easy|
2816|[Double a Number Represented as a Linked List](./solutions/2816-double-a-number-represented-as-a-linked-list.js)|Medium|
2818|[Apply Operations to Maximize Score](./solutions/2818-apply-operations-to-maximize-score.js)|Hard|
+2819|[Minimum Relative Loss After Buying Chocolates](./solutions/2819-minimum-relative-loss-after-buying-chocolates.js)|Hard|
2821|[Delay the Resolution of Each Promise](./solutions/2821-delay-the-resolution-of-each-promise.js)|Medium|
2822|[Inversion of Object](./solutions/2822-inversion-of-object.js)|Easy|
2823|[Deep Object Filter](./solutions/2823-deep-object-filter.js)|Medium|
diff --git a/solutions/2819-minimum-relative-loss-after-buying-chocolates.js b/solutions/2819-minimum-relative-loss-after-buying-chocolates.js
new file mode 100644
index 00000000..7e32fb22
--- /dev/null
+++ b/solutions/2819-minimum-relative-loss-after-buying-chocolates.js
@@ -0,0 +1,77 @@
+/**
+ * 2819. Minimum Relative Loss After Buying Chocolates
+ * https://leetcode.com/problems/minimum-relative-loss-after-buying-chocolates/
+ * Difficulty: Hard
+ *
+ * You are given an integer array prices, which shows the chocolate prices and a 2D integer
+ * array queries, where queries[i] = [ki, mi].
+ *
+ * Alice and Bob went to buy some chocolates, and Alice suggested a way to pay for them, and
+ * Bob agreed.
+ *
+ * The terms for each query are as follows:
+ * - If the price of a chocolate is less than or equal to ki, Bob pays for it.
+ * - Otherwise, Bob pays ki of it, and Alice pays the rest.
+ *
+ * Bob wants to select exactly mi chocolates such that his relative loss is minimized, more
+ * formally, if, in total, Alice has paid ai and Bob has paid bi, Bob wants to minimize bi - ai.
+ *
+ * Return an integer array ans where ans[i] is Bob's minimum relative loss possible for queries[i].
+ */
+
+/**
+ * @param {number[]} prices
+ * @param {number[][]} queries
+ * @return {number[]}
+ */
+var minimumRelativeLosses = function(prices, queries) {
+ prices.sort((a, b) => a - b);
+ const n = prices.length;
+ const result = [];
+
+ const prefixSum = [0];
+ for (let i = 0; i < n; i++) {
+ prefixSum[i + 1] = prefixSum[i] + prices[i];
+ }
+
+ for (const [k, m] of queries) {
+ const split = Math.min(bisectLeft(prices, k), m);
+ const cut = bisectLeftWithKey(split, 2 * k, x => prices[x] + prices[n - m + x]);
+ const relativeLoss = (m - cut) * 2 * k + prefixSum[n - m + cut] + prefixSum[cut] - prefixSum[n];
+ result.push(relativeLoss);
+ }
+
+ return result;
+
+ function bisectLeft(arr, target) {
+ let left = 0;
+ let right = arr.length;
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (arr[mid] < target) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+
+ return left;
+ }
+
+ function bisectLeftWithKey(length, target, keyFunc) {
+ let left = 0;
+ let right = length;
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (keyFunc(mid) < target) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+
+ return left;
+ }
+};
From 0e46c55aef1dde956ace3d525128bd12ef4ae713 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 14 Jul 2025 20:09:07 -0500
Subject: [PATCH 835/994] Add solution #2832
---
README.md | 1 +
...ange-that-each-element-is-maximum-in-it.js | 51 +++++++++++++++++++
2 files changed, 52 insertions(+)
create mode 100644 solutions/2832-maximal-range-that-each-element-is-maximum-in-it.js
diff --git a/README.md b/README.md
index f56fe1e6..882aa425 100644
--- a/README.md
+++ b/README.md
@@ -2463,6 +2463,7 @@
2826|[Sorting Three Groups](./solutions/2826-sorting-three-groups.js)|Medium|
2828|[Check if a String Is an Acronym of Words](./solutions/2828-check-if-a-string-is-an-acronym-of-words.js)|Easy|
2829|[Determine the Minimum Sum of a k-avoiding Array](./solutions/2829-determine-the-minimum-sum-of-a-k-avoiding-array.js)|Medium|
+2832|[Maximal Range That Each Element Is Maximum in It](./solutions/2832-maximal-range-that-each-element-is-maximum-in-it.js)|Medium|
2833|[Furthest Point From Origin](./solutions/2833-furthest-point-from-origin.js)|Easy|
2839|[Check if Strings Can be Made Equal With Operations I](./solutions/2839-check-if-strings-can-be-made-equal-with-operations-i.js)|Easy|
2840|[Check if Strings Can be Made Equal With Operations II](./solutions/2840-check-if-strings-can-be-made-equal-with-operations-ii.js)|Medium|
diff --git a/solutions/2832-maximal-range-that-each-element-is-maximum-in-it.js b/solutions/2832-maximal-range-that-each-element-is-maximum-in-it.js
new file mode 100644
index 00000000..b554dd4a
--- /dev/null
+++ b/solutions/2832-maximal-range-that-each-element-is-maximum-in-it.js
@@ -0,0 +1,51 @@
+/**
+ * 2832. Maximal Range That Each Element Is Maximum in It
+ * https://leetcode.com/problems/maximal-range-that-each-element-is-maximum-in-it/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array nums of distinct integers.
+ *
+ * Let us define a 0-indexed array ans of the same length as nums in the following way:
+ * - ans[i] is the maximum length of a subarray nums[l..r], such that the maximum element
+ * in that subarray is equal to nums[i].
+ *
+ * Return the array ans.
+ *
+ * Note that a subarray is a contiguous part of the array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var maximumLengthOfRanges = function(nums) {
+ const n = nums.length;
+ const leftBounds = new Array(n);
+ const rightBounds = new Array(n);
+ const stack = [];
+
+ for (let i = 0; i < n; i++) {
+ while (stack.length > 0 && nums[stack[stack.length - 1]] < nums[i]) {
+ stack.pop();
+ }
+ leftBounds[i] = stack.length > 0 ? stack[stack.length - 1] + 1 : 0;
+ stack.push(i);
+ }
+
+ stack.length = 0;
+
+ for (let i = n - 1; i >= 0; i--) {
+ while (stack.length > 0 && nums[stack[stack.length - 1]] < nums[i]) {
+ stack.pop();
+ }
+ rightBounds[i] = stack.length > 0 ? stack[stack.length - 1] - 1 : n - 1;
+ stack.push(i);
+ }
+
+ const result = new Array(n);
+ for (let i = 0; i < n; i++) {
+ result[i] = rightBounds[i] - leftBounds[i] + 1;
+ }
+
+ return result;
+};
From d8f82f1a82021c8a2e419625fc30daa0cfd49af6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 14 Jul 2025 23:53:13 -0500
Subject: [PATCH 836/994] Add solution #2838
---
README.md | 1 +
.../2838-maximum-coins-heroes-can-collect.js | 64 +++++++++++++++++++
2 files changed, 65 insertions(+)
create mode 100644 solutions/2838-maximum-coins-heroes-can-collect.js
diff --git a/README.md b/README.md
index 882aa425..d00ac97d 100644
--- a/README.md
+++ b/README.md
@@ -2465,6 +2465,7 @@
2829|[Determine the Minimum Sum of a k-avoiding Array](./solutions/2829-determine-the-minimum-sum-of-a-k-avoiding-array.js)|Medium|
2832|[Maximal Range That Each Element Is Maximum in It](./solutions/2832-maximal-range-that-each-element-is-maximum-in-it.js)|Medium|
2833|[Furthest Point From Origin](./solutions/2833-furthest-point-from-origin.js)|Easy|
+2838|[Maximum Coins Heroes Can Collect](./solutions/2838-maximum-coins-heroes-can-collect.js)|Medium|
2839|[Check if Strings Can be Made Equal With Operations I](./solutions/2839-check-if-strings-can-be-made-equal-with-operations-i.js)|Easy|
2840|[Check if Strings Can be Made Equal With Operations II](./solutions/2840-check-if-strings-can-be-made-equal-with-operations-ii.js)|Medium|
2841|[Maximum Sum of Almost Unique Subarray](./solutions/2841-maximum-sum-of-almost-unique-subarray.js)|Medium|
diff --git a/solutions/2838-maximum-coins-heroes-can-collect.js b/solutions/2838-maximum-coins-heroes-can-collect.js
new file mode 100644
index 00000000..c32274a3
--- /dev/null
+++ b/solutions/2838-maximum-coins-heroes-can-collect.js
@@ -0,0 +1,64 @@
+/**
+ * 2838. Maximum Coins Heroes Can Collect
+ * https://leetcode.com/problems/maximum-coins-heroes-can-collect/
+ * Difficulty: Medium
+ *
+ * There is a battle and n heroes are trying to defeat m monsters. You are given two 1-indexed
+ * arrays of positive integers heroes and monsters of length n and m, respectively. heroes[i]
+ * is the power of ith hero, and monsters[i] is the power of ith monster.
+ *
+ * The ith hero can defeat the jth monster if monsters[j] <= heroes[i].
+ *
+ * You are also given a 1-indexed array coins of length m consisting of positive integers.
+ * coins[i] is the number of coins that each hero earns after defeating the ith monster.
+ *
+ * Return an array ans of length n where ans[i] is the maximum number of coins that the ith
+ * hero can collect from this battle.
+ *
+ * Notes
+ * - The health of a hero doesn't get reduced after defeating a monster.
+ * - Multiple heroes can defeat a monster, but each monster can be defeated by a given hero
+ * only once.
+ */
+
+/**
+ * @param {number[]} heroes
+ * @param {number[]} monsters
+ * @param {number[]} coins
+ * @return {number[]}
+ */
+var maximumCoins = function(heroes, monsters, coins) {
+ const monsterCoinPairs = monsters.map((monster, i) => [monster, coins[i]]);
+ monsterCoinPairs.sort((a, b) => a[0] - b[0]);
+ const sortedMonsters = monsterCoinPairs.map(pair => pair[0]);
+ const sortedCoins = monsterCoinPairs.map(pair => pair[1]);
+
+ const prefixSum = [0];
+ for (let i = 0; i < sortedCoins.length; i++) {
+ prefixSum[i + 1] = prefixSum[i] + sortedCoins[i];
+ }
+
+ const result = [];
+ for (const heroPower of heroes) {
+ const defeatedCount = bisectRight(sortedMonsters, heroPower);
+ result.push(prefixSum[defeatedCount]);
+ }
+
+ return result;
+
+ function bisectRight(arr, target) {
+ let left = 0;
+ let right = arr.length;
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (arr[mid] <= target) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+
+ return left;
+ }
+};
From 78c7ece7d8ebc4eb8cc45a260d71a04ebb9e2151 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 14 Jul 2025 23:57:03 -0500
Subject: [PATCH 837/994] Add solution #2847
---
README.md | 1 +
...mallest-number-with-given-digit-product.js | 30 +++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 solutions/2847-smallest-number-with-given-digit-product.js
diff --git a/README.md b/README.md
index d00ac97d..4c69949a 100644
--- a/README.md
+++ b/README.md
@@ -2472,6 +2472,7 @@
2843|[Count Symmetric Integers](./solutions/2843-count-symmetric-integers.js)|Easy|
2845|[Count of Interesting Subarrays](./solutions/2845-count-of-interesting-subarrays.js)|Medium|
2846|[Minimum Edge Weight Equilibrium Queries in a Tree](./solutions/2846-minimum-edge-weight-equilibrium-queries-in-a-tree.js)|Hard|
+2847|[Smallest Number With Given Digit Product](./solutions/2847-smallest-number-with-given-digit-product.js)|Medium|
2848|[Points That Intersect With Cars](./solutions/2848-points-that-intersect-with-cars.js)|Easy|
2850|[Minimum Moves to Spread Stones Over Grid](./solutions/2850-minimum-moves-to-spread-stones-over-grid.js)|Medium|
2855|[Minimum Right Shifts to Sort the Array](./solutions/2855-minimum-right-shifts-to-sort-the-array.js)|Easy|
diff --git a/solutions/2847-smallest-number-with-given-digit-product.js b/solutions/2847-smallest-number-with-given-digit-product.js
new file mode 100644
index 00000000..f1eeec41
--- /dev/null
+++ b/solutions/2847-smallest-number-with-given-digit-product.js
@@ -0,0 +1,30 @@
+/**
+ * 2847. Smallest Number With Given Digit Product
+ * https://leetcode.com/problems/smallest-number-with-given-digit-product/
+ * Difficulty: Medium
+ *
+ * Given a positive integer n, return a string representing the smallest positive integer
+ * such that the product of its digits is equal to n, or "-1" if no such number exists.
+ */
+
+/**
+ * @param {number} n
+ * @return {string}
+ */
+var smallestNumber = function(n) {
+ if (n < 10) return n.toString();
+
+ const digits = [];
+ let remaining = BigInt(n);
+ for (let digit = 9; digit > 1 && remaining > 1n; digit--) {
+ const bigDigit = BigInt(digit);
+ while (remaining % bigDigit === 0n) {
+ digits.push(digit);
+ remaining /= bigDigit;
+ }
+ }
+
+ if (remaining !== 1n) return '-1';
+
+ return digits.reverse().join('');
+};
From e07ba5a739b2835074c798355ecf71cad17cdb1d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 14 Jul 2025 23:59:27 -0500
Subject: [PATCH 838/994] Add solution #2852
---
README.md | 1 +
.../2852-sum-of-remoteness-of-all-cells.js | 66 +++++++++++++++++++
2 files changed, 67 insertions(+)
create mode 100644 solutions/2852-sum-of-remoteness-of-all-cells.js
diff --git a/README.md b/README.md
index 4c69949a..6c3ba1e2 100644
--- a/README.md
+++ b/README.md
@@ -2475,6 +2475,7 @@
2847|[Smallest Number With Given Digit Product](./solutions/2847-smallest-number-with-given-digit-product.js)|Medium|
2848|[Points That Intersect With Cars](./solutions/2848-points-that-intersect-with-cars.js)|Easy|
2850|[Minimum Moves to Spread Stones Over Grid](./solutions/2850-minimum-moves-to-spread-stones-over-grid.js)|Medium|
+2852|[Sum of Remoteness of All Cells](./solutions/2852-sum-of-remoteness-of-all-cells.js)|Medium|
2855|[Minimum Right Shifts to Sort the Array](./solutions/2855-minimum-right-shifts-to-sort-the-array.js)|Easy|
2858|[Minimum Edge Reversals So Every Node Is Reachable](./solutions/2858-minimum-edge-reversals-so-every-node-is-reachable.js)|Hard|
2859|[Sum of Values at Indices With K Set Bits](./solutions/2859-sum-of-values-at-indices-with-k-set-bits.js)|Easy|
diff --git a/solutions/2852-sum-of-remoteness-of-all-cells.js b/solutions/2852-sum-of-remoteness-of-all-cells.js
new file mode 100644
index 00000000..94af23c5
--- /dev/null
+++ b/solutions/2852-sum-of-remoteness-of-all-cells.js
@@ -0,0 +1,66 @@
+/**
+ * 2852. Sum of Remoteness of All Cells
+ * https://leetcode.com/problems/sum-of-remoteness-of-all-cells/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed matrix grid of order n * n. Each cell in this matrix has a
+ * value grid[i][j], which is either a positive integer or -1 representing a blocked cell.
+ *
+ * You can move from a non-blocked cell to any non-blocked cell that shares an edge.
+ *
+ * For any cell (i, j), we represent its remoteness as R[i][j] which is defined as the following:
+ * - If the cell (i, j) is a non-blocked cell, R[i][j] is the sum of the values grid[x][y] such
+ * that there is no path from the non-blocked cell (x, y) to the cell (i, j).
+ * - For blocked cells, R[i][j] == 0.
+ *
+ * Return the sum of R[i][j] over all cells.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var sumRemoteness = function(grid) {
+ const n = grid.length;
+ const m = grid[0].length;
+ const directions = [[-1, 0], [0, 1], [1, 0], [0, -1]];
+
+ let totalSum = 0;
+ for (let i = 0; i < n; i++) {
+ for (let j = 0; j < m; j++) {
+ totalSum += Math.max(grid[i][j], 0);
+ }
+ }
+
+ let result = 0;
+ for (let i = 0; i < n; i++) {
+ for (let j = 0; j < m; j++) {
+ if (grid[i][j] > 0) {
+ const [componentSum, componentCount] = dfs(i, j, grid);
+ result += (totalSum - componentSum) * componentCount;
+ }
+ }
+ }
+
+ return result;
+
+ function dfs(x, y, grid) {
+ if (x < 0 || x >= n || y < 0 || y >= m || grid[x][y] < 0) {
+ return [0, 0];
+ }
+
+ const cellValue = grid[x][y];
+ grid[x][y] = -1;
+
+ let componentSum = cellValue;
+ let componentCount = 1;
+
+ for (const [dx, dy] of directions) {
+ const [sum, count] = dfs(x + dx, y + dy, grid);
+ componentSum += sum;
+ componentCount += count;
+ }
+
+ return [componentSum, componentCount];
+ }
+};
From 2744e632031c1a6ae16ce136ce6638244d7db8a6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 15 Jul 2025 00:01:49 -0500
Subject: [PATCH 839/994] Add solution #2863
---
README.md | 1 +
...mum-length-of-semi-decreasing-subarrays.js | 46 +++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/2863-maximum-length-of-semi-decreasing-subarrays.js
diff --git a/README.md b/README.md
index 6c3ba1e2..8d6c391c 100644
--- a/README.md
+++ b/README.md
@@ -2481,6 +2481,7 @@
2859|[Sum of Values at Indices With K Set Bits](./solutions/2859-sum-of-values-at-indices-with-k-set-bits.js)|Easy|
2860|[Happy Students](./solutions/2860-happy-students.js)|Medium|
2862|[Maximum Element-Sum of a Complete Subset of Indices](./solutions/2862-maximum-element-sum-of-a-complete-subset-of-indices.js)|Hard|
+2863|[Maximum Length of Semi-Decreasing Subarrays](./solutions/2863-maximum-length-of-semi-decreasing-subarrays.js)|Medium|
2864|[Maximum Odd Binary Number](./solutions/2864-maximum-odd-binary-number.js)|Easy|
2865|[Beautiful Towers I](./solutions/2865-beautiful-towers-i.js)|Medium|
2869|[Minimum Operations to Collect Elements](./solutions/2869-minimum-operations-to-collect-elements.js)|Easy|
diff --git a/solutions/2863-maximum-length-of-semi-decreasing-subarrays.js b/solutions/2863-maximum-length-of-semi-decreasing-subarrays.js
new file mode 100644
index 00000000..d6b19fc6
--- /dev/null
+++ b/solutions/2863-maximum-length-of-semi-decreasing-subarrays.js
@@ -0,0 +1,46 @@
+/**
+ * 2863. Maximum Length of Semi-Decreasing Subarrays
+ * https://leetcode.com/problems/maximum-length-of-semi-decreasing-subarrays/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums.
+ *
+ * Return the length of the longest semi-decreasing subarray of nums, and 0 if there are no
+ * such subarrays.
+ * - A subarray is a contiguous non-empty sequence of elements within an array.
+ * - A non-empty array is semi-decreasing if its first element is strictly greater than its
+ * last element.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maxSubarrayLength = function(nums) {
+ const n = nums.length;
+ const stack = [];
+
+ for (let i = n - 1; i >= 0; i--) {
+ if (stack.length === 0 || nums[i] < nums[stack[stack.length - 1]]) {
+ stack.push(i);
+ }
+ }
+
+ let result = 0;
+ let maxSeen = -Infinity;
+ for (let i = 0; i < n && stack.length > 0; i++) {
+ while (stack.length > 0 && stack[stack.length - 1] <= i) {
+ stack.pop();
+ }
+
+ if (nums[i] > maxSeen) {
+ maxSeen = nums[i];
+ while (stack.length > 0 && nums[stack[stack.length - 1]] < maxSeen) {
+ result = Math.max(result, stack[stack.length - 1] - i + 1);
+ stack.pop();
+ }
+ }
+ }
+
+ return result;
+};
From f0dcc1d1cf1c3e28b7b17a27ae088711c88a195d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 15 Jul 2025 00:04:30 -0500
Subject: [PATCH 840/994] Add solution #2868
---
README.md | 1 +
solutions/2868-the-wording-game.js | 77 ++++++++++++++++++++++++++++++
2 files changed, 78 insertions(+)
create mode 100644 solutions/2868-the-wording-game.js
diff --git a/README.md b/README.md
index 8d6c391c..eaa24385 100644
--- a/README.md
+++ b/README.md
@@ -2484,6 +2484,7 @@
2863|[Maximum Length of Semi-Decreasing Subarrays](./solutions/2863-maximum-length-of-semi-decreasing-subarrays.js)|Medium|
2864|[Maximum Odd Binary Number](./solutions/2864-maximum-odd-binary-number.js)|Easy|
2865|[Beautiful Towers I](./solutions/2865-beautiful-towers-i.js)|Medium|
+2868|[The Wording Game](./solutions/2868-the-wording-game.js)|Hard|
2869|[Minimum Operations to Collect Elements](./solutions/2869-minimum-operations-to-collect-elements.js)|Easy|
2870|[Minimum Number of Operations to Make Array Empty](./solutions/2870-minimum-number-of-operations-to-make-array-empty.js)|Medium|
2871|[Split Array Into Maximum Number of Subarrays](./solutions/2871-split-array-into-maximum-number-of-subarrays.js)|Medium|
diff --git a/solutions/2868-the-wording-game.js b/solutions/2868-the-wording-game.js
new file mode 100644
index 00000000..56e33a12
--- /dev/null
+++ b/solutions/2868-the-wording-game.js
@@ -0,0 +1,77 @@
+/**
+ * 2868. The Wording Game
+ * https://leetcode.com/problems/the-wording-game/
+ * Difficulty: Hard
+ *
+ * Alice and Bob each have a lexicographically sorted array of strings named a and b respectively.
+ *
+ * They are playing a wording game with the following rules:
+ * - On each turn, the current player should play a word from their list such that the new word is
+ * closely greater than the last played word; then it's the other player's turn.
+ * - If a player can't play a word on their turn, they lose.
+ *
+ * Alice starts the game by playing her lexicographically smallest word.
+ *
+ * Given a and b, return true if Alice can win knowing that both players play their best, and
+ * false otherwise.
+ *
+ * A word w is closely greater than a word z if the following conditions are met:
+ * - w is lexicographically greater than z.
+ * - If w1 is the first letter of w and z1 is the first letter of z, w1 should either be equal
+ * to z1 or be the letter after z1 in the alphabet.
+ * - For example, the word "care" is closely greater than "book" and "car", but is not closely
+ * greater than "ant" or "cook".
+ *
+ * A string s is lexicographically greater than a string t if in the first position where s and
+ * t differ, string s has a letter that appears later in the alphabet than the corresponding
+ * letter in t. If the first min(s.length, t.length) characters do not differ, then the longer
+ * string is the lexicographically greater one.
+ */
+
+/**
+ * @param {string[]} a
+ * @param {string[]} b
+ * @return {boolean}
+ */
+var canAliceWin = function(a, b) {
+ const dictionaries = [{}, {}];
+
+ [a, b].forEach((words, playerIndex) => {
+ for (let i = words.length - 1; i >= 0; i--) {
+ const firstChar = words[i][0];
+ if (!(firstChar in dictionaries[playerIndex])) {
+ dictionaries[playerIndex][firstChar] = words[i];
+ }
+ }
+ });
+
+ const memo = new Map();
+
+ return !canCurrentPlayerWin(a[0], 1);
+
+ function canCurrentPlayerWin(previousWord, playerIndex) {
+ const key = `${previousWord},${playerIndex}`;
+ if (memo.has(key)) return memo.get(key);
+
+ const initialChar = previousWord[0];
+ const nextChar = String.fromCharCode(initialChar.charCodeAt(0) + 1);
+
+ if (initialChar in dictionaries[playerIndex]
+ && dictionaries[playerIndex][initialChar] > previousWord) {
+ if (!canCurrentPlayerWin(dictionaries[playerIndex][initialChar], playerIndex ^ 1)) {
+ memo.set(key, true);
+ return true;
+ }
+ }
+
+ if (nextChar in dictionaries[playerIndex]) {
+ if (!canCurrentPlayerWin(dictionaries[playerIndex][nextChar], playerIndex ^ 1)) {
+ memo.set(key, true);
+ return true;
+ }
+ }
+
+ memo.set(key, false);
+ return false;
+ }
+};
From dfe51ac748a8fd5c77e6c8c0874badf1cf4ca9ff Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 15 Jul 2025 00:11:09 -0500
Subject: [PATCH 841/994] Add solution #2892
---
README.md | 1 +
...fter-replacing-pairs-with-their-product.js | 52 +++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 solutions/2892-minimizing-array-after-replacing-pairs-with-their-product.js
diff --git a/README.md b/README.md
index eaa24385..5e623572 100644
--- a/README.md
+++ b/README.md
@@ -2491,6 +2491,7 @@
2872|[Maximum Number of K-Divisible Components](./solutions/2872-maximum-number-of-k-divisible-components.js)|Hard|
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|
+2892|[Minimizing Array After Replacing Pairs With Their Product](./solutions/2892-minimizing-array-after-replacing-pairs-with-their-product.js)|Medium|
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
2895|[Minimum Processing Time](./solutions/2895-minimum-processing-time.js)|Medium|
2897|[Apply Operations on Array to Maximize Sum of Squares](./solutions/2897-apply-operations-on-array-to-maximize-sum-of-squares.js)|Hard|
diff --git a/solutions/2892-minimizing-array-after-replacing-pairs-with-their-product.js b/solutions/2892-minimizing-array-after-replacing-pairs-with-their-product.js
new file mode 100644
index 00000000..ce0b9856
--- /dev/null
+++ b/solutions/2892-minimizing-array-after-replacing-pairs-with-their-product.js
@@ -0,0 +1,52 @@
+/**
+ * 2892. Minimizing Array After Replacing Pairs With Their Product
+ * https://leetcode.com/problems/minimizing-array-after-replacing-pairs-with-their-product/
+ * Difficulty: Medium
+ *
+ * Given an integer array nums and an integer k, you can perform the following operation on the
+ * array any number of times:
+ * - Select two adjacent elements of the array like x and y, such that x * y <= k, and replace
+ * both of them with a single element with value x * y (e.g. in one operation the array
+ * [1, 2, 2, 3] with k = 5 can become [1, 4, 3] or [2, 2, 3], but can't become [1, 2, 6]).
+ *
+ * Return the minimum possible length of nums after any number of operations.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var minArrayLength = function(nums, k) {
+ if (nums.some(num => num === 0)) {
+ return 1;
+ }
+
+ const segments = [];
+ let currentProduct = 1;
+ let currentLength = 0;
+
+ for (const num of nums) {
+ if (num > k) {
+ if (currentLength > 0) {
+ segments.push(currentLength);
+ currentProduct = 1;
+ currentLength = 0;
+ }
+ segments.push(1);
+ } else if (currentProduct * num <= k) {
+ currentProduct *= num;
+ currentLength++;
+ } else {
+ segments.push(currentLength);
+ currentProduct = num;
+ currentLength = 1;
+ }
+ }
+
+ if (currentLength > 0) {
+ segments.push(currentLength);
+ }
+
+ return segments.length;
+};
From 1ebab6a4c8d373c3835e4c3ee0ee530a65d91927 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 15 Jul 2025 00:13:07 -0500
Subject: [PATCH 842/994] Add solution #2898
---
README.md | 1 +
solutions/2898-maximum-linear-stock-score.js | 38 ++++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2898-maximum-linear-stock-score.js
diff --git a/README.md b/README.md
index 5e623572..af9d01f9 100644
--- a/README.md
+++ b/README.md
@@ -2495,6 +2495,7 @@
2894|[Divisible and Non-divisible Sums Difference](./solutions/2894-divisible-and-non-divisible-sums-difference.js)|Easy|
2895|[Minimum Processing Time](./solutions/2895-minimum-processing-time.js)|Medium|
2897|[Apply Operations on Array to Maximize Sum of Squares](./solutions/2897-apply-operations-on-array-to-maximize-sum-of-squares.js)|Hard|
+2898|[Maximum Linear Stock Score](./solutions/2898-maximum-linear-stock-score.js)|Medium|
2899|[Last Visited Integers](./solutions/2899-last-visited-integers.js)|Easy|
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|
diff --git a/solutions/2898-maximum-linear-stock-score.js b/solutions/2898-maximum-linear-stock-score.js
new file mode 100644
index 00000000..72c44a7d
--- /dev/null
+++ b/solutions/2898-maximum-linear-stock-score.js
@@ -0,0 +1,38 @@
+/**
+ * 2898. Maximum Linear Stock Score
+ * https://leetcode.com/problems/maximum-linear-stock-score/
+ * Difficulty: Medium
+ *
+ * Given a 1-indexed integer array prices, where prices[i] is the price of a particular stock
+ * on the ith day, your task is to select some of the elements of prices such that your
+ * selection is linear.
+ *
+ * A selection indexes, where indexes is a 1-indexed integer array of length k which is a
+ * subsequence of the array [1, 2, ..., n], is linear if:
+ * - For every 1 < j <= k,
+ * prices[indexes[j]] - prices[indexes[j - 1]] == indexes[j] - indexes[j - 1].
+ *
+ * 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.
+ *
+ * The score of a selection indexes, is equal to the sum of the following array:
+ * [prices[indexes[1]], prices[indexes[2]], ..., prices[indexes[k]].
+ *
+ * Return the maximum score that a linear selection can have.
+ */
+
+/**
+ * @param {number[]} prices
+ * @return {number}
+ */
+var maxScore = function(prices) {
+ const values = prices.map((price, index) => price - index);
+ const map = new Map();
+
+ for (let i = 0; i < prices.length; i++) {
+ const value = values[i];
+ map.set(value, (map.get(value) || 0) + prices[i]);
+ }
+
+ return Math.max(...map.values());
+};
From 4f348be213422a1c6cb15cd2eefc262dcf60302a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 15 Jul 2025 00:14:17 -0500
Subject: [PATCH 843/994] Add solution #2907
---
README.md | 1 +
...table-triplets-with-increasing-prices-i.js | 55 +++++++++++++++++++
2 files changed, 56 insertions(+)
create mode 100644 solutions/2907-maximum-profitable-triplets-with-increasing-prices-i.js
diff --git a/README.md b/README.md
index af9d01f9..640ee747 100644
--- a/README.md
+++ b/README.md
@@ -2501,6 +2501,7 @@
2901|[Longest Unequal Adjacent Groups Subsequence II](./solutions/2901-longest-unequal-adjacent-groups-subsequence-ii.js)|Medium|
2903|[Find Indices With Index and Value Difference I](./solutions/2903-find-indices-with-index-and-value-difference-i.js)|Easy|
2904|[Shortest and Lexicographically Smallest Beautiful String](./solutions/2904-shortest-and-lexicographically-smallest-beautiful-string.js)|Medium|
+2907|[Maximum Profitable Triplets With Increasing Prices I](./solutions/2907-maximum-profitable-triplets-with-increasing-prices-i.js)|Medium|
2908|[Minimum Sum of Mountain Triplets I](./solutions/2908-minimum-sum-of-mountain-triplets-i.js)|Easy|
2909|[Minimum Sum of Mountain Triplets II](./solutions/2909-minimum-sum-of-mountain-triplets-ii.js)|Medium|
2913|[Subarrays Distinct Element Sum of Squares I](./solutions/2913-subarrays-distinct-element-sum-of-squares-i.js)|Easy|
diff --git a/solutions/2907-maximum-profitable-triplets-with-increasing-prices-i.js b/solutions/2907-maximum-profitable-triplets-with-increasing-prices-i.js
new file mode 100644
index 00000000..387785c4
--- /dev/null
+++ b/solutions/2907-maximum-profitable-triplets-with-increasing-prices-i.js
@@ -0,0 +1,55 @@
+/**
+ * 2907. Maximum Profitable Triplets With Increasing Prices I
+ * https://leetcode.com/problems/maximum-profitable-triplets-with-increasing-prices-i/
+ * Difficulty: Medium
+ *
+ * Given the 0-indexed arrays prices and profits of length n. There are n items in an store
+ * where the ith item has a price of prices[i] and a profit of profits[i].
+ *
+ * We have to pick three items with the following condition:
+ * - prices[i] < prices[j] < prices[k] where i < j < k.
+ *
+ * If we pick items with indices i, j and k satisfying the above condition, the profit
+ * would be profits[i] + profits[j] + profits[k].
+ *
+ * Return the maximum profit we can get, and -1 if it's not possible to pick three items
+ * with the given condition.
+ */
+
+/**
+ * @param {number[]} prices
+ * @param {number[]} profits
+ * @return {number}
+ */
+var maxProfit = function(prices, profits) {
+ const n = prices.length;
+ let result = -1;
+
+ for (let j = 1; j < n - 1; j++) {
+ let maxLeftProfit = 0;
+ let maxRightProfit = 0;
+ let hasLeft = false;
+ let hasRight = false;
+
+ for (let i = 0; i < j; i++) {
+ if (prices[i] < prices[j]) {
+ maxLeftProfit = Math.max(maxLeftProfit, profits[i]);
+ hasLeft = true;
+ }
+ }
+
+ for (let k = j + 1; k < n; k++) {
+ if (prices[j] < prices[k]) {
+ maxRightProfit = Math.max(maxRightProfit, profits[k]);
+ hasRight = true;
+ }
+ }
+
+ if (hasLeft && hasRight) {
+ const tripletProfit = maxLeftProfit + profits[j] + maxRightProfit;
+ result = Math.max(result, tripletProfit);
+ }
+ }
+
+ return result;
+};
From ff5b427debaf0bfcd67af7f6778da27e9f67c718 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 15 Jul 2025 00:17:02 -0500
Subject: [PATCH 844/994] Add solution #2912
---
README.md | 1 +
...f-ways-to-reach-destination-in-the-grid.js | 56 +++++++++++++++++++
2 files changed, 57 insertions(+)
create mode 100644 solutions/2912-number-of-ways-to-reach-destination-in-the-grid.js
diff --git a/README.md b/README.md
index 640ee747..00010394 100644
--- a/README.md
+++ b/README.md
@@ -2504,6 +2504,7 @@
2907|[Maximum Profitable Triplets With Increasing Prices I](./solutions/2907-maximum-profitable-triplets-with-increasing-prices-i.js)|Medium|
2908|[Minimum Sum of Mountain Triplets I](./solutions/2908-minimum-sum-of-mountain-triplets-i.js)|Easy|
2909|[Minimum Sum of Mountain Triplets II](./solutions/2909-minimum-sum-of-mountain-triplets-ii.js)|Medium|
+2912|[Number of Ways to Reach Destination in the Grid](./solutions/2912-number-of-ways-to-reach-destination-in-the-grid.js)|Hard|
2913|[Subarrays Distinct Element Sum of Squares I](./solutions/2913-subarrays-distinct-element-sum-of-squares-i.js)|Easy|
2914|[Minimum Number of Changes to Make Binary String Beautiful](./solutions/2914-minimum-number-of-changes-to-make-binary-string-beautiful.js)|Medium|
2917|[Find the K-or of an Array](./solutions/2917-find-the-k-or-of-an-array.js)|Easy|
diff --git a/solutions/2912-number-of-ways-to-reach-destination-in-the-grid.js b/solutions/2912-number-of-ways-to-reach-destination-in-the-grid.js
new file mode 100644
index 00000000..030dea47
--- /dev/null
+++ b/solutions/2912-number-of-ways-to-reach-destination-in-the-grid.js
@@ -0,0 +1,56 @@
+/**
+ * 2912. Number of Ways to Reach Destination in the Grid
+ * https://leetcode.com/problems/number-of-ways-to-reach-destination-in-the-grid/
+ * Difficulty: Hard
+ *
+ * You are given two integers n and m which represent the size of a 1-indexed grid. You are
+ * also given an integer k, a 1-indexed integer array source and a 1-indexed integer array
+ * dest, where source and dest are in the form [x, y] representing a cell on the given grid.
+ *
+ * You can move through the grid in the following way:
+ * - You can go from cell [x1, y1] to cell [x2, y2] if either x1 == x2 or y1 == y2.
+ * - Note that you can't move to the cell you are already in e.g. x1 == x2 and y1 == y2.
+ *
+ * Return the number of ways you can reach dest from source by moving through the grid exactly
+ * k times.
+ *
+ * Since the answer may be very large, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} m
+ * @param {number} k
+ * @param {number[]} source
+ * @param {number[]} dest
+ * @return {number}
+ */
+var numberOfWays = function(n, m, k, source, dest) {
+ const MOD = 1e9 + 7;
+ const dp = new Array(k + 1).fill().map(() => new Array(4).fill(0));
+
+ if (source[0] === dest[0] && source[1] === dest[1]) {
+ dp[0][0] = 1;
+ } else if (source[0] === dest[0]) {
+ dp[0][1] = 1;
+ } else if (source[1] === dest[1]) {
+ dp[0][2] = 1;
+ } else {
+ dp[0][3] = 1;
+ }
+
+ for (let i = 1; i <= k; i++) {
+ dp[i][0] = (dp[i - 1][1] + dp[i - 1][2]) % MOD;
+ dp[i][1] = (BigInt(dp[i - 1][0]) * BigInt(m - 1) + BigInt(dp[i - 1][1])
+ * BigInt(m - 2) + BigInt(dp[i - 1][3])) % BigInt(MOD);
+ dp[i][2] = (BigInt(dp[i - 1][0]) * BigInt(n - 1) + BigInt(dp[i - 1][2])
+ * BigInt(n - 2) + BigInt(dp[i - 1][3])) % BigInt(MOD);
+ dp[i][3] = (BigInt(dp[i - 1][1]) * BigInt(n - 1) + BigInt(dp[i - 1][2])
+ * BigInt(m - 1) + BigInt(dp[i - 1][3]) * BigInt(m + n - 4)) % BigInt(MOD);
+ dp[i][1] = Number(dp[i][1]);
+ dp[i][2] = Number(dp[i][2]);
+ dp[i][3] = Number(dp[i][3]);
+ }
+
+ return dp[k][0];
+};
From f05ce31a8f63dba6c5684f5e8e86e9e13375eebb Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 15 Jul 2025 00:19:37 -0500
Subject: [PATCH 845/994] Add solution #2921
---
README.md | 1 +
...able-triplets-with-increasing-prices-ii.js | 63 +++++++++++++++++++
2 files changed, 64 insertions(+)
create mode 100644 solutions/2921-maximum-profitable-triplets-with-increasing-prices-ii.js
diff --git a/README.md b/README.md
index 00010394..55e417b9 100644
--- a/README.md
+++ b/README.md
@@ -2509,6 +2509,7 @@
2914|[Minimum Number of Changes to Make Binary String Beautiful](./solutions/2914-minimum-number-of-changes-to-make-binary-string-beautiful.js)|Medium|
2917|[Find the K-or of an Array](./solutions/2917-find-the-k-or-of-an-array.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|
+2921|[Maximum Profitable Triplets With Increasing Prices II](./solutions/2921-maximum-profitable-triplets-with-increasing-prices-ii.js)|Hard|
2923|[Find Champion I](./solutions/2923-find-champion-i.js)|Easy|
2924|[Find Champion II](./solutions/2924-find-champion-ii.js)|Medium|
2925|[Maximum Score After Applying Operations on a Tree](./solutions/2925-maximum-score-after-applying-operations-on-a-tree.js)|Medium|
diff --git a/solutions/2921-maximum-profitable-triplets-with-increasing-prices-ii.js b/solutions/2921-maximum-profitable-triplets-with-increasing-prices-ii.js
new file mode 100644
index 00000000..061d9b36
--- /dev/null
+++ b/solutions/2921-maximum-profitable-triplets-with-increasing-prices-ii.js
@@ -0,0 +1,63 @@
+/**
+ * 2921. Maximum Profitable Triplets With Increasing Prices II
+ * https://leetcode.com/problems/maximum-profitable-triplets-with-increasing-prices-ii/
+ * Difficulty: Hard
+ *
+ * Given the 0-indexed arrays prices and profits of length n. There are n items in an store
+ * where the ith item has a price of prices[i] and a profit of profits[i].
+ *
+ * We have to pick three items with the following condition:
+ * - prices[i] < prices[j] < prices[k] where i < j < k.
+ *
+ * If we pick items with indices i, j and k satisfying the above condition, the profit would
+ * be profits[i] + profits[j] + profits[k].
+ *
+ * Return the maximum profit we can get, and -1 if it's not possible to pick three items with
+ * the given condition.
+ */
+
+/**
+ * @param {number[]} prices
+ * @param {number[]} profits
+ * @return {number}
+ */
+var maxProfit = function(prices, profits) {
+ const bit1 = new Array(5001).fill(0);
+ const bit2 = new Array(5001).fill(0);
+ let result = -1;
+
+ for (let i = 0; i < prices.length; i++) {
+ const price = prices[i];
+ const profit = profits[i];
+ const maxLeft = query(bit1, price - 1);
+ const maxPair = query(bit2, price - 1);
+
+ if (maxPair > 0) {
+ result = Math.max(result, maxPair + profit);
+ }
+
+ update(bit1, price, profit);
+
+ if (maxLeft > 0) {
+ update(bit2, price, profit + maxLeft);
+ }
+ }
+
+ return result;
+
+ function query(bit, price) {
+ let maxValue = 0;
+ while (price > 0) {
+ maxValue = Math.max(maxValue, bit[price]);
+ price &= price - 1;
+ }
+ return maxValue;
+ }
+
+ function update(bit, price, value) {
+ while (price < 5001) {
+ bit[price] = Math.max(bit[price], value);
+ price += price & (-price);
+ }
+ }
+};
From d9e6a0486d789d1ba3d2d59de902a2b1750eb3ee Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 15 Jul 2025 22:54:15 -0500
Subject: [PATCH 846/994] Add solution #3201
---
README.md | 1 +
...e-maximum-length-of-valid-subsequence-i.js | 36 +++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/3201-find-the-maximum-length-of-valid-subsequence-i.js
diff --git a/README.md b/README.md
index 55e417b9..2fd5138d 100644
--- a/README.md
+++ b/README.md
@@ -2599,6 +2599,7 @@
3174|[Clear Digits](./solutions/3174-clear-digits.js)|Easy|
3178|[Find the Child Who Has the Ball After K Seconds](./solutions/3178-find-the-child-who-has-the-ball-after-k-seconds.js)|Easy|
3191|[Minimum Operations to Make Binary Array Elements Equal to One I](./solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js)|Medium|
+3201|[Find the Maximum Length of Valid Subsequence I](./solutions/3201-find-the-maximum-length-of-valid-subsequence-i.js)|Medium|
3208|[Alternating Groups II](./solutions/3208-alternating-groups-ii.js)|Medium|
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|
diff --git a/solutions/3201-find-the-maximum-length-of-valid-subsequence-i.js b/solutions/3201-find-the-maximum-length-of-valid-subsequence-i.js
new file mode 100644
index 00000000..da026ba9
--- /dev/null
+++ b/solutions/3201-find-the-maximum-length-of-valid-subsequence-i.js
@@ -0,0 +1,36 @@
+/**
+ * 3201. Find the Maximum Length of Valid Subsequence I
+ * https://leetcode.com/problems/find-the-maximum-length-of-valid-subsequence-i/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums.
+ *
+ * A subsequence sub of nums with length x is called valid if it satisfies:
+ * - (sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2.
+ *
+ * Return the length of the longest valid subsequence of nums.
+ *
+ * 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 maximumLength = function(nums) {
+ const evenCount = nums.filter(num => num % 2 === 0).length;
+ const oddCount = nums.length - evenCount;
+
+ let alternatingCount = 0;
+ let lastParity = -1;
+ for (const num of nums) {
+ const currentParity = num % 2;
+ if (lastParity === -1 || currentParity !== lastParity) {
+ alternatingCount++;
+ lastParity = currentParity;
+ }
+ }
+
+ return Math.max(evenCount, oddCount, alternatingCount);
+};
From c35684d1009f7751c9208a50fdac3ffa8a64678f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 15 Jul 2025 22:57:47 -0500
Subject: [PATCH 847/994] Add solution #2927
---
README.md | 1 +
...7-distribute-candies-among-children-iii.js | 28 +++++++++++++++++++
2 files changed, 29 insertions(+)
create mode 100644 solutions/2927-distribute-candies-among-children-iii.js
diff --git a/README.md b/README.md
index 2fd5138d..c34979e2 100644
--- a/README.md
+++ b/README.md
@@ -2513,6 +2513,7 @@
2923|[Find Champion I](./solutions/2923-find-champion-i.js)|Easy|
2924|[Find Champion II](./solutions/2924-find-champion-ii.js)|Medium|
2925|[Maximum Score After Applying Operations on a Tree](./solutions/2925-maximum-score-after-applying-operations-on-a-tree.js)|Medium|
+2927|[Distribute Candies Among Children III](./solutions/2927-distribute-candies-among-children-iii.js)|Hard|
2928|[Distribute Candies Among Children I](./solutions/2928-distribute-candies-among-children-i.js)|Easy|
2929|[Distribute Candies Among Children II](./solutions/2929-distribute-candies-among-children-ii.js)|Medium|
2932|[Maximum Strong Pair XOR I](./solutions/2932-maximum-strong-pair-xor-i.js)|Easy|
diff --git a/solutions/2927-distribute-candies-among-children-iii.js b/solutions/2927-distribute-candies-among-children-iii.js
new file mode 100644
index 00000000..984791b0
--- /dev/null
+++ b/solutions/2927-distribute-candies-among-children-iii.js
@@ -0,0 +1,28 @@
+/**
+ * 2927. Distribute Candies Among Children III
+ * https://leetcode.com/problems/distribute-candies-among-children-iii/
+ * Difficulty: Hard
+ *
+ * You are given two positive integers n and limit.
+ *
+ * Return the total number of ways to distribute n candies among 3 children such that no child
+ * gets more than limit candies.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} limit
+ * @return {number}
+ */
+var distributeCandies = function(n, limit) {
+ if (n > 3 * limit) return 0;
+
+ const overLimit = limit + 1;
+ return countWays(n) - 3 * countWays(n - overLimit)
+ + 3 * countWays(n - 2 * overLimit) - countWays(n - 3 * overLimit);
+
+ function countWays(candies) {
+ if (candies < 0) return 0;
+ return Math.floor((candies + 2) * (candies + 1) / 2);
+ }
+};
From cc8dd4f715bcd717709bea59aee5d9b8e14c857d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 15 Jul 2025 22:59:03 -0500
Subject: [PATCH 848/994] Add solution #2936
---
README.md | 1 +
.../2936-number-of-equal-numbers-blocks.js | 75 +++++++++++++++++++
2 files changed, 76 insertions(+)
create mode 100644 solutions/2936-number-of-equal-numbers-blocks.js
diff --git a/README.md b/README.md
index c34979e2..98defb3c 100644
--- a/README.md
+++ b/README.md
@@ -2519,6 +2519,7 @@
2932|[Maximum Strong Pair XOR I](./solutions/2932-maximum-strong-pair-xor-i.js)|Easy|
2933|[High-Access Employees](./solutions/2933-high-access-employees.js)|Medium|
2934|[Minimum Operations to Maximize Last Elements in Arrays](./solutions/2934-minimum-operations-to-maximize-last-elements-in-arrays.js)|Medium|
+2936|[Number of Equal Numbers Blocks](./solutions/2936-number-of-equal-numbers-blocks.js)|Medium|
2937|[Make Three Strings Equal](./solutions/2937-make-three-strings-equal.js)|Easy|
2938|[Separate Black and White Balls](./solutions/2938-separate-black-and-white-balls.js)|Medium|
2942|[Find Words Containing Character](./solutions/2942-find-words-containing-character.js)|Easy|
diff --git a/solutions/2936-number-of-equal-numbers-blocks.js b/solutions/2936-number-of-equal-numbers-blocks.js
new file mode 100644
index 00000000..c35e60e1
--- /dev/null
+++ b/solutions/2936-number-of-equal-numbers-blocks.js
@@ -0,0 +1,75 @@
+/**
+ * 2936. Number of Equal Numbers Blocks
+ * https://leetcode.com/problems/number-of-equal-numbers-blocks/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array of integers, nums. The following property holds for nums:
+ * - All occurrences of a value are adjacent. In other words, if there are two indices i < j
+ * such that nums[i] == nums[j], then for every index k that i < k < j, nums[k] == nums[i].
+ *
+ * Since nums is a very large array, you are given an instance of the class BigArray which has
+ * the following functions:
+ * - int at(long long index): Returns the value of nums[i].
+ * - void size(): Returns nums.length.
+ *
+ * Let's partition the array into maximal blocks such that each block contains equal values.
+ * Return the number of these blocks.
+ *
+ * Note that if you want to test your solution using a custom test, behavior for tests with
+ * nums.length > 10 is undefined.
+ */
+
+/**
+ * Definition for BigArray.
+ * class BigArray {
+ * @param {number[]} elements
+ * constructor(elements);
+ *
+ * @param {number} index
+ * @return {number}
+ * at(index);
+ *
+ * @return {number}
+ * size();
+ * }
+ */
+/**
+ * @param {BigArray} nums
+ * @return {number}
+ */
+var countBlocks = function(nums) {
+ const n = nums.size();
+ if (n === 0) return 0;
+
+ let blocks = 1;
+ let currentIndex = 0;
+
+ while (currentIndex < n - 1) {
+ const nextBlockStart = findNextBlockStart(nums, currentIndex, n);
+ if (nextBlockStart < n) {
+ blocks++;
+ currentIndex = nextBlockStart;
+ } else {
+ break;
+ }
+ }
+
+ return blocks;
+
+ function findNextBlockStart(nums, startIndex, n) {
+ const currentValue = nums.at(startIndex);
+ let left = startIndex + 1;
+ let right = n;
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (nums.at(mid) === currentValue) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+
+ return left;
+ }
+};
From 857eb14ff8e6350db7c95eed05d7fa719dced038 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 15 Jul 2025 23:01:34 -0500
Subject: [PATCH 849/994] Add solution #2941
---
README.md | 1 +
.../2941-maximum-gcd-sum-of-a-subarray.js | 57 +++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/2941-maximum-gcd-sum-of-a-subarray.js
diff --git a/README.md b/README.md
index 98defb3c..d77ef0f1 100644
--- a/README.md
+++ b/README.md
@@ -2522,6 +2522,7 @@
2936|[Number of Equal Numbers Blocks](./solutions/2936-number-of-equal-numbers-blocks.js)|Medium|
2937|[Make Three Strings Equal](./solutions/2937-make-three-strings-equal.js)|Easy|
2938|[Separate Black and White Balls](./solutions/2938-separate-black-and-white-balls.js)|Medium|
+2941|[Maximum GCD-Sum of a Subarray](./solutions/2941-maximum-gcd-sum-of-a-subarray.js)|Hard|
2942|[Find Words Containing Character](./solutions/2942-find-words-containing-character.js)|Easy|
2946|[Matrix Similarity After Cyclic Shifts](./solutions/2946-matrix-similarity-after-cyclic-shifts.js)|Easy|
2947|[Count Beautiful Substrings I](./solutions/2947-count-beautiful-substrings-i.js)|Medium|
diff --git a/solutions/2941-maximum-gcd-sum-of-a-subarray.js b/solutions/2941-maximum-gcd-sum-of-a-subarray.js
new file mode 100644
index 00000000..abfacd26
--- /dev/null
+++ b/solutions/2941-maximum-gcd-sum-of-a-subarray.js
@@ -0,0 +1,57 @@
+/**
+ * 2941. Maximum GCD-Sum of a Subarray
+ * https://leetcode.com/problems/maximum-gcd-sum-of-a-subarray/
+ * Difficulty: Hard
+ *
+ * You are given an array of integers nums and an integer k.
+ *
+ * The gcd-sum of an array a is calculated as follows:
+ * - Let s be the sum of all the elements of a.
+ * - Let g be the greatest common divisor of all the elements of a.
+ * - The gcd-sum of a is equal to s * g.
+ *
+ * Return the maximum gcd-sum of a subarray of nums with at least k elements.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var maxGcdSum = function(nums, k) {
+ const prefixSum = [0];
+ let gcdPairs = [];
+ let result = 0;
+
+ for (let i = 0; i < nums.length; i++) {
+ prefixSum.push(prefixSum[prefixSum.length - 1] + nums[i]);
+
+ const newGcdPairs = [];
+ const candidates = [...gcdPairs, [i, nums[i]]];
+ for (const [startIndex, currentGcd] of candidates) {
+ const newGcd = gcd(currentGcd, nums[i]);
+ if (newGcdPairs.length === 0 || newGcdPairs[newGcdPairs.length - 1][1] !== newGcd) {
+ newGcdPairs.push([startIndex, newGcd]);
+ }
+ }
+
+ gcdPairs = newGcdPairs;
+
+ for (const [startIndex, gcdValue] of gcdPairs) {
+ if (i - startIndex + 1 < k) break;
+ const subarraySum = prefixSum[prefixSum.length - 1] - prefixSum[startIndex];
+ result = Math.max(result, subarraySum * gcdValue);
+ }
+ }
+
+ return result;
+
+ function gcd(a, b) {
+ while (b !== 0) {
+ const temp = b;
+ b = a % b;
+ a = temp;
+ }
+ return a;
+ }
+};
From 7b25632809e0d8a0dcceca61dd1c2707b0e468b4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 15 Jul 2025 23:03:17 -0500
Subject: [PATCH 850/994] Add solution #2950
---
README.md | 1 +
.../2950-number-of-divisible-substrings.js | 36 +++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/2950-number-of-divisible-substrings.js
diff --git a/README.md b/README.md
index d77ef0f1..521ee446 100644
--- a/README.md
+++ b/README.md
@@ -2527,6 +2527,7 @@
2946|[Matrix Similarity After Cyclic Shifts](./solutions/2946-matrix-similarity-after-cyclic-shifts.js)|Easy|
2947|[Count Beautiful Substrings I](./solutions/2947-count-beautiful-substrings-i.js)|Medium|
2948|[Make Lexicographically Smallest Array by Swapping Elements](./solutions/2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium|
+2950|[Number of Divisible Substrings](./solutions/2950-number-of-divisible-substrings.js)|Medium|
2951|[Find the Peaks](./solutions/2951-find-the-peaks.js)|Easy|
2952|[Minimum Number of Coins to be Added](./solutions/2952-minimum-number-of-coins-to-be-added.js)|Medium|
2956|[Find Common Elements Between Two Arrays](./solutions/2956-find-common-elements-between-two-arrays.js)|Easy|
diff --git a/solutions/2950-number-of-divisible-substrings.js b/solutions/2950-number-of-divisible-substrings.js
new file mode 100644
index 00000000..62734820
--- /dev/null
+++ b/solutions/2950-number-of-divisible-substrings.js
@@ -0,0 +1,36 @@
+/**
+ * 2950. Number of Divisible Substrings
+ * https://leetcode.com/problems/number-of-divisible-substrings/
+ * Difficulty: Medium
+ *
+ * Each character of the English alphabet has been mapped to a digit as shown below.
+ *
+ * A string is divisible if the sum of the mapped values of its characters is divisible
+ * by its length.
+ *
+ * Given a string s, return the number of divisible substrings of s.
+ *
+ * A substring is a contiguous non-empty sequence of characters within a string.
+ */
+
+/**
+ * @param {string} word
+ * @return {number}
+ */
+var countDivisibleSubstrings = function(word) {
+ let result = 0;
+
+ for (let i = 1; i < 10; i++) {
+ const prefixCount = new Map([[0, 1]]);
+ let prefixSum = 0;
+
+ for (const char of word) {
+ const charValue = 9 - Math.floor((122 - char.charCodeAt(0)) / 3);
+ prefixSum += charValue - i;
+ result += prefixCount.get(prefixSum) || 0;
+ prefixCount.set(prefixSum, (prefixCount.get(prefixSum) || 0) + 1);
+ }
+ }
+
+ return result;
+};
From 12fc8cf990c11c90c0e8fbc0f00d6b50a27801ff Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 21:18:10 -0500
Subject: [PATCH 851/994] Add solution #3202
---
README.md | 1 +
...-maximum-length-of-valid-subsequence-ii.js | 35 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/3202-find-the-maximum-length-of-valid-subsequence-ii.js
diff --git a/README.md b/README.md
index 521ee446..7f5bfcb0 100644
--- a/README.md
+++ b/README.md
@@ -2604,6 +2604,7 @@
3178|[Find the Child Who Has the Ball After K Seconds](./solutions/3178-find-the-child-who-has-the-ball-after-k-seconds.js)|Easy|
3191|[Minimum Operations to Make Binary Array Elements Equal to One I](./solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js)|Medium|
3201|[Find the Maximum Length of Valid Subsequence I](./solutions/3201-find-the-maximum-length-of-valid-subsequence-i.js)|Medium|
+3202|[Find the Maximum Length of Valid Subsequence II](./solutions/3202-find-the-maximum-length-of-valid-subsequence-ii.js)|Medium|
3208|[Alternating Groups II](./solutions/3208-alternating-groups-ii.js)|Medium|
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|
diff --git a/solutions/3202-find-the-maximum-length-of-valid-subsequence-ii.js b/solutions/3202-find-the-maximum-length-of-valid-subsequence-ii.js
new file mode 100644
index 00000000..e295b891
--- /dev/null
+++ b/solutions/3202-find-the-maximum-length-of-valid-subsequence-ii.js
@@ -0,0 +1,35 @@
+/**
+ * 3202. Find the Maximum Length of Valid Subsequence II
+ * https://leetcode.com/problems/find-the-maximum-length-of-valid-subsequence-ii/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums and a positive integer k.
+ *
+ * A subsequence sub of nums with length x is called valid if it satisfies:
+ * - (sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.
+ *
+ * Return the length of the longest valid subsequence of nums.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var maximumLength = function(nums, k) {
+ let result = 0;
+
+ for (let target = 0; target < k; target++) {
+ const dp = new Array(k).fill(0);
+
+ for (const num of nums) {
+ const mod = num % k;
+ const prev = (target - mod + k) % k;
+ dp[mod] = Math.max(dp[mod], dp[prev] + 1);
+ }
+
+ result = Math.max(result, Math.max(...dp));
+ }
+
+ return result;
+};
From 6c368e8f92e9fb67c4c8f2e9b1b0aea6605dd79b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 21:23:20 -0500
Subject: [PATCH 852/994] Add solution #2955
---
README.md | 1 +
.../2955-number-of-same-end-substrings.js | 49 +++++++++++++++++++
2 files changed, 50 insertions(+)
create mode 100644 solutions/2955-number-of-same-end-substrings.js
diff --git a/README.md b/README.md
index 7f5bfcb0..9f424853 100644
--- a/README.md
+++ b/README.md
@@ -2530,6 +2530,7 @@
2950|[Number of Divisible Substrings](./solutions/2950-number-of-divisible-substrings.js)|Medium|
2951|[Find the Peaks](./solutions/2951-find-the-peaks.js)|Easy|
2952|[Minimum Number of Coins to be Added](./solutions/2952-minimum-number-of-coins-to-be-added.js)|Medium|
+2955|[Number of Same-End Substrings](./solutions/2955-number-of-same-end-substrings.js)|Medium|
2956|[Find Common Elements Between Two Arrays](./solutions/2956-find-common-elements-between-two-arrays.js)|Easy|
2957|[Remove Adjacent Almost-Equal Characters](./solutions/2957-remove-adjacent-almost-equal-characters.js)|Medium|
2958|[Length of Longest Subarray With at Most K Frequency](./solutions/2958-length-of-longest-subarray-with-at-most-k-frequency.js)|Medium|
diff --git a/solutions/2955-number-of-same-end-substrings.js b/solutions/2955-number-of-same-end-substrings.js
new file mode 100644
index 00000000..c61040ef
--- /dev/null
+++ b/solutions/2955-number-of-same-end-substrings.js
@@ -0,0 +1,49 @@
+/**
+ * 2955. Number of Same-End Substrings
+ * https://leetcode.com/problems/number-of-same-end-substrings/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed string s, and a 2D array of integers queries, where
+ * queries[i] = [li, ri] indicates a substring of s starting from the index li and
+ * ending at the index ri (both inclusive), i.e. s[li..ri].
+ *
+ * Return an array ans where ans[i] is the number of same-end substrings of queries[i].
+ *
+ * A 0-indexed string t of length n is called same-end if it has the same character at
+ * both of its ends, i.e., t[0] == t[n - 1].
+ *
+ * A substring is a contiguous non-empty sequence of characters within a string.
+ */
+
+/**
+ * @param {string} s
+ * @param {number[][]} queries
+ * @return {number[]}
+ */
+var sameEndSubstringCount = function(s, queries) {
+ const n = s.length;
+ const prefixCounts = new Array(26).fill().map(() => new Array(n + 1).fill(0));
+
+ for (let i = 0; i < n; i++) {
+ const charIndex = s.charCodeAt(i) - 97;
+ for (let j = 0; j < 26; j++) {
+ prefixCounts[j][i + 1] = prefixCounts[j][i];
+ }
+ prefixCounts[charIndex][i + 1]++;
+ }
+
+ const result = [];
+
+ for (const [left, right] of queries) {
+ let count = 0;
+
+ for (let charIndex = 0; charIndex < 26; charIndex++) {
+ const charCount = prefixCounts[charIndex][right + 1] - prefixCounts[charIndex][left];
+ count += Math.floor(charCount * (charCount + 1) / 2);
+ }
+
+ result.push(count);
+ }
+
+ return result;
+};
From 5b0db995abb6a29a7128cb951994144b5f7e5253 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 21:25:42 -0500
Subject: [PATCH 853/994] Add solution #2964
---
README.md | 1 +
.../2964-number-of-divisible-triplet-sums.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/2964-number-of-divisible-triplet-sums.js
diff --git a/README.md b/README.md
index 9f424853..b3504ff9 100644
--- a/README.md
+++ b/README.md
@@ -2538,6 +2538,7 @@
2961|[Double Modular Exponentiation](./solutions/2961-double-modular-exponentiation.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|
2963|[Count the Number of Good Partitions](./solutions/2963-count-the-number-of-good-partitions.js)|Hard|
+2964|[Number of Divisible Triplet Sums](./solutions/2964-number-of-divisible-triplet-sums.js)|Medium|
2965|[Find Missing and Repeated Values](./solutions/2965-find-missing-and-repeated-values.js)|Easy|
2966|[Divide Array Into Arrays With Max Difference](./solutions/2966-divide-array-into-arrays-with-max-difference.js)|Medium|
2970|[Count the Number of Incremovable Subarrays I](./solutions/2970-count-the-number-of-incremovable-subarrays-i.js)|Easy|
diff --git a/solutions/2964-number-of-divisible-triplet-sums.js b/solutions/2964-number-of-divisible-triplet-sums.js
new file mode 100644
index 00000000..bc5a141c
--- /dev/null
+++ b/solutions/2964-number-of-divisible-triplet-sums.js
@@ -0,0 +1,42 @@
+/**
+ * 2964. Number of Divisible Triplet Sums
+ * https://leetcode.com/problems/number-of-divisible-triplet-sums/
+ * Difficulty: Medium
+ *
+ * Given a 0-indexed integer array nums and an integer d, return the number of triplets
+ * (i, j, k) such that i < j < k and (nums[i] + nums[j] + nums[k]) % d == 0.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} d
+ * @return {number}
+ */
+var divisibleTripletCount = function(nums, d) {
+ const n = nums.length;
+ const pairSums = new Map();
+
+ for (let i = 0; i < n - 1; i++) {
+ for (let j = i + 1; j < n; j++) {
+ const sumMod = (nums[i] + nums[j]) % d;
+ if (!pairSums.has(sumMod)) {
+ pairSums.set(sumMod, []);
+ }
+ pairSums.get(sumMod).push([i, j]);
+ }
+ }
+
+ let result = 0;
+ for (let k = 0; k < n; k++) {
+ const targetKey = (d - nums[k] % d) % d;
+ if (pairSums.has(targetKey)) {
+ for (const [i, j] of pairSums.get(targetKey)) {
+ if (j < k) {
+ result++;
+ }
+ }
+ }
+ }
+
+ return result;
+};
From e1a0774536eb335b819ed0508c947746fffa4434 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 21:27:50 -0500
Subject: [PATCH 854/994] Add solution #2969
---
README.md | 1 +
...9-minimum-number-of-coins-for-fruits-ii.js | 46 +++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/2969-minimum-number-of-coins-for-fruits-ii.js
diff --git a/README.md b/README.md
index b3504ff9..d2f7992d 100644
--- a/README.md
+++ b/README.md
@@ -2541,6 +2541,7 @@
2964|[Number of Divisible Triplet Sums](./solutions/2964-number-of-divisible-triplet-sums.js)|Medium|
2965|[Find Missing and Repeated Values](./solutions/2965-find-missing-and-repeated-values.js)|Easy|
2966|[Divide Array Into Arrays With Max Difference](./solutions/2966-divide-array-into-arrays-with-max-difference.js)|Medium|
+2969|[Minimum Number of Coins for Fruits II](./solutions/2969-minimum-number-of-coins-for-fruits-ii.js)|Hard|
2970|[Count the Number of Incremovable Subarrays I](./solutions/2970-count-the-number-of-incremovable-subarrays-i.js)|Easy|
2971|[Find Polygon With the Largest Perimeter](./solutions/2971-find-polygon-with-the-largest-perimeter.js)|Medium|
2976|[Minimum Cost to Convert String I](./solutions/2976-minimum-cost-to-convert-string-i.js)|Medium|
diff --git a/solutions/2969-minimum-number-of-coins-for-fruits-ii.js b/solutions/2969-minimum-number-of-coins-for-fruits-ii.js
new file mode 100644
index 00000000..ee4d6479
--- /dev/null
+++ b/solutions/2969-minimum-number-of-coins-for-fruits-ii.js
@@ -0,0 +1,46 @@
+/**
+ * 2969. Minimum Number of Coins for Fruits II
+ * https://leetcode.com/problems/minimum-number-of-coins-for-fruits-ii/
+ * Difficulty: Hard
+ *
+ * You are at a fruit market with different types of exotic fruits on display.
+ *
+ * You are given a 1-indexed array prices, where prices[i] denotes the number of coins
+ * needed to purchase the ith fruit.
+ *
+ * The fruit market has the following offer:
+ * - If you purchase the ith fruit at prices[i] coins, you can get the next i fruits for free.
+ *
+ * Note that even if you can take fruit j for free, you can still purchase it for prices[j]
+ * coins to receive a new offer.
+ *
+ * Return the minimum number of coins needed to acquire all the fruits.
+ */
+
+/**
+ * @param {number[]} prices
+ * @return {number}
+ */
+var minimumCoins = function(prices) {
+ const n = prices.length;
+ const dp = new Array(n);
+ const deque = [];
+
+ dp[0] = prices[0];
+ deque.push(0);
+
+ for (let i = 1; i < n; i++) {
+ dp[i] = dp[deque[0]] + prices[i];
+
+ while (deque.length > 0 && deque[0] + deque[0] + 1 < i) {
+ deque.shift();
+ }
+ while (deque.length > 0 && dp[deque[deque.length - 1]] >= dp[i]) {
+ deque.pop();
+ }
+
+ deque.push(i);
+ }
+
+ return dp[deque[0]];
+};
From a8c597147e7b88fbf1e2db69efa088a41b891030 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 21:28:54 -0500
Subject: [PATCH 855/994] Add solution #2979
---
README.md | 1 +
...t-expensive-item-that-can-not-be-bought.js | 24 +++++++++++++++++++
2 files changed, 25 insertions(+)
create mode 100644 solutions/2979-most-expensive-item-that-can-not-be-bought.js
diff --git a/README.md b/README.md
index d2f7992d..d3e274d8 100644
--- a/README.md
+++ b/README.md
@@ -2545,6 +2545,7 @@
2970|[Count the Number of Incremovable Subarrays I](./solutions/2970-count-the-number-of-incremovable-subarrays-i.js)|Easy|
2971|[Find Polygon With the Largest Perimeter](./solutions/2971-find-polygon-with-the-largest-perimeter.js)|Medium|
2976|[Minimum Cost to Convert String I](./solutions/2976-minimum-cost-to-convert-string-i.js)|Medium|
+2979|[Most Expensive Item That Can Not Be Bought](./solutions/2979-most-expensive-item-that-can-not-be-bought.js)|Medium|
2980|[Check if Bitwise OR Has Trailing Zeros](./solutions/2980-check-if-bitwise-or-has-trailing-zeros.js)|Easy|
2981|[Find Longest Special Substring That Occurs Thrice I](./solutions/2981-find-longest-special-substring-that-occurs-thrice-i.js)|Medium|
2997|[Minimum Number of Operations to Make Array XOR Equal to K](./solutions/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k.js)|Medium|
diff --git a/solutions/2979-most-expensive-item-that-can-not-be-bought.js b/solutions/2979-most-expensive-item-that-can-not-be-bought.js
new file mode 100644
index 00000000..b4fe3671
--- /dev/null
+++ b/solutions/2979-most-expensive-item-that-can-not-be-bought.js
@@ -0,0 +1,24 @@
+/**
+ * 2979. Most Expensive Item That Can Not Be Bought
+ * https://leetcode.com/problems/most-expensive-item-that-can-not-be-bought/
+ * Difficulty: Medium
+ *
+ * You are given two distinct prime numbers primeOne and primeTwo.
+ *
+ * Alice and Bob are visiting a market. The market has an infinite number of items, for any
+ * positive integer x there exists an item whose price is x. Alice wants to buy some items
+ * from the market to gift to Bob. She has an infinite number of coins in the denomination
+ * primeOne and primeTwo. She wants to know the most expensive item she can not buy to gift
+ * to Bob.
+ *
+ * Return the price of the most expensive item which Alice can not gift to Bob.
+ */
+
+/**
+ * @param {number} primeOne
+ * @param {number} primeTwo
+ * @return {number}
+ */
+var mostExpensiveItem = function(primeOne, primeTwo) {
+ return primeOne * primeTwo - primeOne - primeTwo;
+};
From a68f5b7ce297b532ecf5e0194d7ea9de8e4728da Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 21:31:38 -0500
Subject: [PATCH 856/994] Add solution #2992
---
README.md | 1 +
...2-number-of-self-divisible-permutations.js | 59 +++++++++++++++++++
2 files changed, 60 insertions(+)
create mode 100644 solutions/2992-number-of-self-divisible-permutations.js
diff --git a/README.md b/README.md
index d3e274d8..4c9c8676 100644
--- a/README.md
+++ b/README.md
@@ -2548,6 +2548,7 @@
2979|[Most Expensive Item That Can Not Be Bought](./solutions/2979-most-expensive-item-that-can-not-be-bought.js)|Medium|
2980|[Check if Bitwise OR Has Trailing Zeros](./solutions/2980-check-if-bitwise-or-has-trailing-zeros.js)|Easy|
2981|[Find Longest Special Substring That Occurs Thrice I](./solutions/2981-find-longest-special-substring-that-occurs-thrice-i.js)|Medium|
+2992|[Number of Self-Divisible Permutations](./solutions/2992-number-of-self-divisible-permutations.js)|Medium|
2997|[Minimum Number of Operations to Make Array XOR Equal to K](./solutions/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k.js)|Medium|
2998|[Minimum Number of Operations to Make X and Y Equal](./solutions/2998-minimum-number-of-operations-to-make-x-and-y-equal.js)|Medium|
2999|[Count the Number of Powerful Integers](./solutions/2999-count-the-number-of-powerful-integers.js)|Hard|
diff --git a/solutions/2992-number-of-self-divisible-permutations.js b/solutions/2992-number-of-self-divisible-permutations.js
new file mode 100644
index 00000000..a66cd661
--- /dev/null
+++ b/solutions/2992-number-of-self-divisible-permutations.js
@@ -0,0 +1,59 @@
+/**
+ * 2992. Number of Self-Divisible Permutations
+ * https://leetcode.com/problems/number-of-self-divisible-permutations/
+ * Difficulty: Medium
+ *
+ * Given an integer n, return the number of permutations of the 1-indexed array
+ * nums = [1, 2, ..., n], such that it's self-divisible.
+ *
+ * A 1-indexed array a of length n is self-divisible if for every 1 <= i <= n, gcd(a[i], i) == 1.
+ *
+ * A permutation of an array is a rearrangement of the elements of that array, for example here
+ * are all of the permutations of the array [1, 2, 3]:
+ * - [1, 2, 3]
+ * - [1, 3, 2]
+ * - [2, 1, 3]
+ * - [2, 3, 1]
+ * - [3, 1, 2]
+ * - [3, 2, 1]
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var selfDivisiblePermutationCount = function(n) {
+ const graph = new Array(n + 1).fill().map(() => []);
+
+ for (let position = 1; position <= n; position++) {
+ for (let value = 1; value <= n; value++) {
+ if (gcd(value, position) === 1) {
+ graph[position].push(value);
+ }
+ }
+ }
+
+ return countPermutations(1, 0);
+
+ function countPermutations(position, usedMask) {
+ if (position > n) return 1;
+
+ let count = 0;
+ for (const value of graph[position]) {
+ if ((usedMask & (1 << value)) === 0) {
+ count += countPermutations(position + 1, usedMask | (1 << value));
+ }
+ }
+
+ return count;
+ }
+
+ function gcd(a, b) {
+ while (b !== 0) {
+ const temp = b;
+ b = a % b;
+ a = temp;
+ }
+ return a;
+ }
+};
From a1f833a827747593b96b20ecd9abd7c494dd35b5 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 21:33:05 -0500
Subject: [PATCH 857/994] Add solution #3004
---
README.md | 1 +
.../3004-maximum-subtree-of-the-same-color.js | 61 +++++++++++++++++++
2 files changed, 62 insertions(+)
create mode 100644 solutions/3004-maximum-subtree-of-the-same-color.js
diff --git a/README.md b/README.md
index 4c9c8676..1e70a079 100644
--- a/README.md
+++ b/README.md
@@ -2553,6 +2553,7 @@
2998|[Minimum Number of Operations to Make X and Y Equal](./solutions/2998-minimum-number-of-operations-to-make-x-and-y-equal.js)|Medium|
2999|[Count the Number of Powerful Integers](./solutions/2999-count-the-number-of-powerful-integers.js)|Hard|
3002|[Maximum Size of a Set After Removals](./solutions/3002-maximum-size-of-a-set-after-removals.js)|Medium|
+3004|[Maximum Subtree of the Same Color](./solutions/3004-maximum-subtree-of-the-same-color.js)|Medium|
3005|[Count Elements With Maximum Frequency](./solutions/3005-count-elements-with-maximum-frequency.js)|Easy|
3010|[Divide an Array Into Subarrays With Minimum Cost I](./solutions/3010-divide-an-array-into-subarrays-with-minimum-cost-i.js)|Easy|
3011|[Find if Array Can Be Sorted](./solutions/3011-find-if-array-can-be-sorted.js)|Medium|
diff --git a/solutions/3004-maximum-subtree-of-the-same-color.js b/solutions/3004-maximum-subtree-of-the-same-color.js
new file mode 100644
index 00000000..2078b9d2
--- /dev/null
+++ b/solutions/3004-maximum-subtree-of-the-same-color.js
@@ -0,0 +1,61 @@
+/**
+ * 3004. Maximum Subtree of the Same Color
+ * https://leetcode.com/problems/maximum-subtree-of-the-same-color/
+ * Difficulty: Medium
+ *
+ * You are given a 2D integer array edges representing a tree with n nodes, numbered from
+ * 0 to n - 1, rooted at node 0, where edges[i] = [ui, vi] means there is an edge between
+ * the nodes vi and ui.
+ *
+ * You are also given a 0-indexed integer array colors of size n, where colors[i] is the
+ * color assigned to node i.
+ *
+ * We want to find a node v such that every node in the subtree of v has the same color.
+ *
+ * Return the size of such subtree with the maximum number of nodes possible.
+ */
+
+/**
+ * @param {number[][]} edges
+ * @param {number[]} colors
+ * @return {number}
+ */
+var maximumSubtreeSize = function(edges, colors) {
+ const n = colors.length;
+ const graph = new Array(n).fill().map(() => []);
+
+ for (const [u, v] of edges) {
+ graph[u].push(v);
+ graph[v].push(u);
+ }
+
+ let result = 1;
+
+ dfs(0, -1);
+
+ return result;
+
+ function dfs(node, parent) {
+ let subtreeSize = 1;
+ let isValidSubtree = true;
+
+ for (const child of graph[node]) {
+ if (child !== parent) {
+ const childSize = dfs(child, node);
+
+ if (colors[child] === colors[node] && childSize > 0) {
+ subtreeSize += childSize;
+ } else {
+ isValidSubtree = false;
+ }
+ }
+ }
+
+ if (isValidSubtree) {
+ result = Math.max(result, subtreeSize);
+ return subtreeSize;
+ }
+
+ return 0;
+ }
+};
From f1f8fe0001a23ec8e121b8598e92ccb836787d85 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 21:35:51 -0500
Subject: [PATCH 858/994] Add solution #3009
---
README.md | 1 +
...um-number-of-intersections-on-the-chart.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/3009-maximum-number-of-intersections-on-the-chart.js
diff --git a/README.md b/README.md
index 1e70a079..c3956d7f 100644
--- a/README.md
+++ b/README.md
@@ -2555,6 +2555,7 @@
3002|[Maximum Size of a Set After Removals](./solutions/3002-maximum-size-of-a-set-after-removals.js)|Medium|
3004|[Maximum Subtree of the Same Color](./solutions/3004-maximum-subtree-of-the-same-color.js)|Medium|
3005|[Count Elements With Maximum Frequency](./solutions/3005-count-elements-with-maximum-frequency.js)|Easy|
+3009|[Maximum Number of Intersections on the Chart](./solutions/3009-maximum-number-of-intersections-on-the-chart.js)|Hard|
3010|[Divide an Array Into Subarrays With Minimum Cost I](./solutions/3010-divide-an-array-into-subarrays-with-minimum-cost-i.js)|Easy|
3011|[Find if Array Can Be Sorted](./solutions/3011-find-if-array-can-be-sorted.js)|Medium|
3014|[Minimum Number of Pushes to Type Word I](./solutions/3014-minimum-number-of-pushes-to-type-word-i.js)|Easy|
diff --git a/solutions/3009-maximum-number-of-intersections-on-the-chart.js b/solutions/3009-maximum-number-of-intersections-on-the-chart.js
new file mode 100644
index 00000000..5c0f0852
--- /dev/null
+++ b/solutions/3009-maximum-number-of-intersections-on-the-chart.js
@@ -0,0 +1,42 @@
+/**
+ * 3009. Maximum Number of Intersections on the Chart
+ * https://leetcode.com/problems/maximum-number-of-intersections-on-the-chart/
+ * Difficulty: Hard
+ *
+ * There is a line chart consisting of n points connected by line segments. You are given a
+ * 1-indexed integer array y. The kth point has coordinates (k, y[k]). There are no horizontal
+ * lines; that is, no two consecutive points have the same y-coordinate.
+ *
+ * We can draw an infinitely long horizontal line. Return the maximum number of points of
+ * intersection of the line with the chart.
+ */
+
+/**
+ * @param {number[]} y
+ * @return {number}
+ */
+var maxIntersectionCount = function(y) {
+ const n = y.length;
+ const coordinateEvents = new Map();
+
+ for (let segmentIndex = 1; segmentIndex < n; segmentIndex++) {
+ const segmentStart = 2 * y[segmentIndex - 1];
+ const segmentEnd = 2 * y[segmentIndex]
+ + (segmentIndex === n - 1 ? 0 : y[segmentIndex] > y[segmentIndex - 1] ? -1 : 1);
+ const intervalStart = Math.min(segmentStart, segmentEnd);
+ const intervalEnd = Math.max(segmentStart, segmentEnd);
+
+ coordinateEvents.set(intervalStart, (coordinateEvents.get(intervalStart) || 0) + 1);
+ coordinateEvents.set(intervalEnd + 1, (coordinateEvents.get(intervalEnd + 1) || 0) - 1);
+ }
+
+ const sortedEvents = [...coordinateEvents.entries()].sort((a, b) => a[0] - b[0]);
+ let activeSegments = 0;
+ let result = 0;
+ for (const [coordinate, segmentChange] of sortedEvents) {
+ activeSegments += segmentChange;
+ result = Math.max(result, activeSegments);
+ }
+
+ return result;
+};
From cd644122d3690dbbf812babb0b0a45077dbee25d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 21:39:16 -0500
Subject: [PATCH 859/994] Add solution #3018
---
README.md | 1 +
...removal-queries-that-can-be-processed-i.js | 70 +++++++++++++++++++
2 files changed, 71 insertions(+)
create mode 100644 solutions/3018-maximum-number-of-removal-queries-that-can-be-processed-i.js
diff --git a/README.md b/README.md
index c3956d7f..3e3ada96 100644
--- a/README.md
+++ b/README.md
@@ -2561,6 +2561,7 @@
3014|[Minimum Number of Pushes to Type Word I](./solutions/3014-minimum-number-of-pushes-to-type-word-i.js)|Easy|
3015|[Count the Number of Houses at a Certain Distance I](./solutions/3015-count-the-number-of-houses-at-a-certain-distance-i.js)|Medium|
3016|[Minimum Number of Pushes to Type Word II](./solutions/3016-minimum-number-of-pushes-to-type-word-ii.js)|Medium|
+3018|[Maximum Number of Removal Queries That Can Be Processed I](./solutions/3018-maximum-number-of-removal-queries-that-can-be-processed-i.js)|Hard|
3019|[Number of Changing Keys](./solutions/3019-number-of-changing-keys.js)|Easy|
3021|[Alice and Bob Playing Flower Game](./solutions/3021-alice-and-bob-playing-flower-game.js)|Medium|
3024|[Type of Triangle](./solutions/3024-type-of-triangle.js)|Easy|
diff --git a/solutions/3018-maximum-number-of-removal-queries-that-can-be-processed-i.js b/solutions/3018-maximum-number-of-removal-queries-that-can-be-processed-i.js
new file mode 100644
index 00000000..f8386a90
--- /dev/null
+++ b/solutions/3018-maximum-number-of-removal-queries-that-can-be-processed-i.js
@@ -0,0 +1,70 @@
+/**
+ * 3018. Maximum Number of Removal Queries That Can Be Processed I
+ * https://leetcode.com/problems/maximum-number-of-removal-queries-that-can-be-processed-i/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed array nums and a 0-indexed array queries.
+ *
+ * You can do the following operation at the beginning at most once:
+ * - Replace nums with a subsequence of nums.
+ *
+ * We start processing queries in the given order; for each query, we do the following:
+ * - If the first and the last element of nums is less than queries[i], the processing of
+ * queries ends.
+ * - Otherwise, we choose either the first or the last element of nums if it is greater
+ * than or equal to queries[i], and we remove the chosen element from nums.
+ *
+ * Return the maximum number of queries that can be processed by doing the operation optimally.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[]} queries
+ * @return {number}
+ */
+var maximumProcessableQueries = function(nums, queries) {
+ const queryCount = queries.length;
+ const arrayLength = nums.length;
+ const dp = new Array(arrayLength + 1).fill().map(() => new Array(arrayLength + 1).fill(0));
+
+ nums.push(-1);
+ let result = 0;
+
+ for (let segmentLength = arrayLength - 1; segmentLength >= 0; segmentLength--) {
+ for (let leftIndex = 0; leftIndex < arrayLength; leftIndex++) {
+ const rightIndex = leftIndex + segmentLength;
+
+ if (rightIndex < arrayLength) {
+ dp[leftIndex][rightIndex] = Math.max(
+ dp[leftIndex - 1] ? dp[leftIndex - 1][rightIndex] : 0,
+ dp[leftIndex][rightIndex + 1] || 0
+ );
+
+ const prevLeftQueries = dp[leftIndex - 1] ? dp[leftIndex - 1][rightIndex] : 0;
+ const prevRightQueries = dp[leftIndex][rightIndex + 1] || 0;
+ if (prevLeftQueries < queryCount && nums[leftIndex - 1] >= queries[prevLeftQueries]) {
+ dp[leftIndex][rightIndex] = Math.max(dp[leftIndex][rightIndex], prevLeftQueries + 1);
+ }
+
+ if (prevRightQueries < queryCount && nums[rightIndex + 1] >= queries[prevRightQueries]) {
+ dp[leftIndex][rightIndex] = Math.max(dp[leftIndex][rightIndex], prevRightQueries + 1);
+ }
+
+ if (dp[leftIndex][rightIndex] === queryCount) {
+ return queryCount;
+ }
+ } else {
+ break;
+ }
+ }
+ }
+
+ for (let singleIndex = 0; singleIndex < arrayLength; singleIndex++) {
+ const currentQueries = dp[singleIndex][singleIndex];
+ const canProcessCurrent = currentQueries < queryCount
+ && nums[singleIndex] >= queries[currentQueries] ? 1 : 0;
+ result = Math.max(result, currentQueries + canProcessCurrent);
+ }
+
+ return result;
+};
From 8e31ffb430e77637f524616cf3c40168b6426bb2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 21:40:29 -0500
Subject: [PATCH 860/994] Add solution #3023
---
README.md | 1 +
.../3023-find-pattern-in-infinite-stream-i.js | 59 +++++++++++++++++++
2 files changed, 60 insertions(+)
create mode 100644 solutions/3023-find-pattern-in-infinite-stream-i.js
diff --git a/README.md b/README.md
index 3e3ada96..6a92477e 100644
--- a/README.md
+++ b/README.md
@@ -2564,6 +2564,7 @@
3018|[Maximum Number of Removal Queries That Can Be Processed I](./solutions/3018-maximum-number-of-removal-queries-that-can-be-processed-i.js)|Hard|
3019|[Number of Changing Keys](./solutions/3019-number-of-changing-keys.js)|Easy|
3021|[Alice and Bob Playing Flower Game](./solutions/3021-alice-and-bob-playing-flower-game.js)|Medium|
+3023|[Find Pattern in Infinite Stream I](./solutions/3023-find-pattern-in-infinite-stream-i.js)|Medium|
3024|[Type of Triangle](./solutions/3024-type-of-triangle.js)|Easy|
3025|[Find the Number of Ways to Place People I](./solutions/3025-find-the-number-of-ways-to-place-people-i.js)|Medium|
3027|[Find the Number of Ways to Place People II](./solutions/3027-find-the-number-of-ways-to-place-people-ii.js)|Hard|
diff --git a/solutions/3023-find-pattern-in-infinite-stream-i.js b/solutions/3023-find-pattern-in-infinite-stream-i.js
new file mode 100644
index 00000000..7634ac80
--- /dev/null
+++ b/solutions/3023-find-pattern-in-infinite-stream-i.js
@@ -0,0 +1,59 @@
+/**
+ * 3023. Find Pattern in Infinite Stream I
+ * https://leetcode.com/problems/find-pattern-in-infinite-stream-i/
+ * Difficulty: Medium
+ *
+ * You are given a binary array pattern and an object stream of class InfiniteStream
+ * representing a 0-indexed infinite stream of bits.
+ *
+ * The class InfiniteStream contains the following function:
+ * - int next(): Reads a single bit (which is either 0 or 1) from the stream and returns it.
+ *
+ * Return the first starting index where the pattern matches the bits read from the stream.
+ * For example, if the pattern is [1, 0], the first match is the highlighted part in the
+ * stream [0, 1, 0, 1, ...].
+ */
+
+/**
+ * Definition for an infinite stream.
+ * class InfiniteStream {
+ * @param {number[]} bits
+ * constructor(bits);
+ *
+ * @return {number}
+ * next();
+ * }
+ */
+/**
+ * @param {InfiniteStream} stream
+ * @param {number[]} pattern
+ * @return {number}
+ */
+var findPattern = function(stream, pattern) {
+ const patternLength = pattern.length;
+ const buffer = [];
+ let currentIndex = 0;
+
+ while (buffer.length < patternLength) {
+ buffer.push(stream.next());
+ }
+
+ while (true) {
+ if (isPatternMatch(buffer, pattern)) {
+ return currentIndex;
+ }
+
+ buffer.shift();
+ buffer.push(stream.next());
+ currentIndex++;
+ }
+
+ function isPatternMatch(buffer, pattern) {
+ for (let i = 0; i < pattern.length; i++) {
+ if (buffer[i] !== pattern[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+};
From ed3e6f8f3676351497f8bca06b11617cfc04b8a6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 22:38:18 -0500
Subject: [PATCH 861/994] Add solution #373
---
.../0373-find-k-pairs-with-smallest-sums.js | 26 ++++++++++++-------
1 file changed, 16 insertions(+), 10 deletions(-)
diff --git a/solutions/0373-find-k-pairs-with-smallest-sums.js b/solutions/0373-find-k-pairs-with-smallest-sums.js
index 59ab2d80..bc0ca7d5 100644
--- a/solutions/0373-find-k-pairs-with-smallest-sums.js
+++ b/solutions/0373-find-k-pairs-with-smallest-sums.js
@@ -18,20 +18,26 @@
* @return {number[][]}
*/
var kSmallestPairs = function(nums1, nums2, k) {
- const heap = new MinPriorityQueue({ compare: (a, b) => a[0] - b[0] });
+ const minHeap = new PriorityQueue((a, b) => a[0] - b[0]);
const result = [];
+ const visited = new Set();
- for (let i = 0; i < nums1.length; i++) {
- heap.enqueue([nums1[i] + nums2[0], 0]);
- }
+ minHeap.enqueue([nums1[0] + nums2[0], 0, 0]);
+ visited.add('0,0');
+
+ for (let count = 0; count < k && !minHeap.isEmpty(); count++) {
+ const [currentSum, index1, index2] = minHeap.dequeue();
+ result.push([nums1[index1], nums2[index2]]);
+
+ if (index1 + 1 < nums1.length && !visited.has(`${index1 + 1},${index2}`)) {
+ minHeap.enqueue([nums1[index1 + 1] + nums2[index2], index1 + 1, index2]);
+ visited.add(`${index1 + 1},${index2}`);
+ }
- while (k > 0 && !heap.isEmpty()) {
- const [n, index] = heap.dequeue();
- result.push([n - nums2[index], nums2[index]]);
- if (index + 1 < nums2.length) {
- heap.enqueue([n - nums2[index] + nums2[index + 1], index + 1]);
+ if (index2 + 1 < nums2.length && !visited.has(`${index1},${index2 + 1}`)) {
+ minHeap.enqueue([nums1[index1] + nums2[index2 + 1], index1, index2 + 1]);
+ visited.add(`${index1},${index2 + 1}`);
}
- k--;
}
return result;
From 2e32f489b481fec1a69c75f104a83cd86889cfdd Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 22:52:36 -0500
Subject: [PATCH 862/994] Add solution #3032
---
README.md | 1 +
...032-count-numbers-with-unique-digits-ii.js | 40 +++++++++++++++++++
2 files changed, 41 insertions(+)
create mode 100644 solutions/3032-count-numbers-with-unique-digits-ii.js
diff --git a/README.md b/README.md
index 6a92477e..3961aff2 100644
--- a/README.md
+++ b/README.md
@@ -2571,6 +2571,7 @@
3028|[Ant on the Boundary](./solutions/3028-ant-on-the-boundary.js)|Easy|
3029|[Minimum Time to Revert Word to Initial State I](./solutions/3029-minimum-time-to-revert-word-to-initial-state-i.js)|Medium|
3030|[Find the Grid of Region Average](./solutions/3030-find-the-grid-of-region-average.js)|Medium|
+3032|[Count Numbers With Unique Digits II](./solutions/3032-count-numbers-with-unique-digits-ii.js)|Easy|
3033|[Modify the Matrix](./solutions/3033-modify-the-matrix.js)|Easy|
3034|[Number of Subarrays That Match a Pattern I](./solutions/3034-number-of-subarrays-that-match-a-pattern-i.js)|Medium|
3035|[Maximum Palindromes After Operations](./solutions/3035-maximum-palindromes-after-operations.js)|Medium|
diff --git a/solutions/3032-count-numbers-with-unique-digits-ii.js b/solutions/3032-count-numbers-with-unique-digits-ii.js
new file mode 100644
index 00000000..b332bfaf
--- /dev/null
+++ b/solutions/3032-count-numbers-with-unique-digits-ii.js
@@ -0,0 +1,40 @@
+/**
+ * 3032. Count Numbers With Unique Digits II
+ * https://leetcode.com/problems/count-numbers-with-unique-digits-ii/
+ * Difficulty: Easy
+ *
+ * Given two positive integers a and b, return the count of numbers having unique digits
+ * in the range [a, b] (inclusive).
+ */
+
+/**
+ * @param {number} a
+ * @param {number} b
+ * @return {number}
+ */
+var numberCount = function(a, b) {
+ let result = 0;
+
+ for (let number = a; number <= b; number++) {
+ if (hasUniqueDigits(number)) {
+ result++;
+ }
+ }
+
+ return result;
+
+ function hasUniqueDigits(number) {
+ const set = new Set();
+
+ while (number > 0) {
+ const digit = number % 10;
+ if (set.has(digit)) {
+ return false;
+ }
+ set.add(digit);
+ number = Math.floor(number / 10);
+ }
+
+ return true;
+ }
+};
From 896787d1471c81c8db5c1d9b15834fa49366da48 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 22:53:54 -0500
Subject: [PATCH 863/994] Add solution #3037
---
README.md | 1 +
...3037-find-pattern-in-infinite-stream-ii.js | 74 +++++++++++++++++++
2 files changed, 75 insertions(+)
create mode 100644 solutions/3037-find-pattern-in-infinite-stream-ii.js
diff --git a/README.md b/README.md
index 3961aff2..ee324d06 100644
--- a/README.md
+++ b/README.md
@@ -2575,6 +2575,7 @@
3033|[Modify the Matrix](./solutions/3033-modify-the-matrix.js)|Easy|
3034|[Number of Subarrays That Match a Pattern I](./solutions/3034-number-of-subarrays-that-match-a-pattern-i.js)|Medium|
3035|[Maximum Palindromes After Operations](./solutions/3035-maximum-palindromes-after-operations.js)|Medium|
+3037|[Find Pattern in Infinite Stream II](./solutions/3037-find-pattern-in-infinite-stream-ii.js)|Hard|
3038|[Maximum Number of Operations With the Same Score I](./solutions/3038-maximum-number-of-operations-with-the-same-score-i.js)|Easy|
3039|[Apply Operations to Make String Empty](./solutions/3039-apply-operations-to-make-string-empty.js)|Medium|
3042|[Count Prefix and Suffix Pairs I](./solutions/3042-count-prefix-and-suffix-pairs-i.js)|Easy|
diff --git a/solutions/3037-find-pattern-in-infinite-stream-ii.js b/solutions/3037-find-pattern-in-infinite-stream-ii.js
new file mode 100644
index 00000000..f1c22607
--- /dev/null
+++ b/solutions/3037-find-pattern-in-infinite-stream-ii.js
@@ -0,0 +1,74 @@
+/**
+ * 3037. Find Pattern in Infinite Stream II
+ * https://leetcode.com/problems/find-pattern-in-infinite-stream-ii/
+ * Difficulty: Hard
+ *
+ * You are given a binary array pattern and an object stream of class InfiniteStream
+ * representing a 0-indexed infinite stream of bits.
+ *
+ * The class InfiniteStream contains the following function:
+ * - int next(): Reads a single bit (which is either 0 or 1) from the stream and returns it.
+ *
+ * Return the first starting index where the pattern matches the bits read from the stream.
+ * For example, if the pattern is [1, 0], the first match is the highlighted part in the
+ * stream [0, 1, 0, 1, ...].
+ */
+
+/**
+ * Definition for an infinite stream.
+ * class InfiniteStream {
+ * @param {number[]} bits
+ * constructor(bits);
+ *
+ * @return {number}
+ * next();
+ * }
+ */
+/**
+ * @param {InfiniteStream} stream
+ * @param {number[]} pattern
+ * @return {number}
+ */
+var findPattern = function(stream, pattern) {
+ const patternLength = pattern.length;
+ const failureFunction = buildFailureFunction(pattern);
+ let streamIndex = 0;
+ let patternIndex = 0;
+
+ while (true) {
+ const streamBit = stream.next();
+
+ while (patternIndex > 0 && pattern[patternIndex] !== streamBit) {
+ patternIndex = failureFunction[patternIndex - 1];
+ }
+
+ if (pattern[patternIndex] === streamBit) {
+ patternIndex++;
+ }
+
+ if (patternIndex === patternLength) {
+ return streamIndex - patternLength + 1;
+ }
+
+ streamIndex++;
+ }
+
+ function buildFailureFunction(pattern) {
+ const failure = new Array(pattern.length).fill(0);
+ let prefixLength = 0;
+
+ for (let suffixEnd = 1; suffixEnd < pattern.length; suffixEnd++) {
+ while (prefixLength > 0 && pattern[prefixLength] !== pattern[suffixEnd]) {
+ prefixLength = failure[prefixLength - 1];
+ }
+
+ if (pattern[prefixLength] === pattern[suffixEnd]) {
+ prefixLength++;
+ }
+
+ failure[suffixEnd] = prefixLength;
+ }
+
+ return failure;
+ }
+};
From 7e48c59c2f4af52d22c309573e2a7bfe2b346291 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 22:55:12 -0500
Subject: [PATCH 864/994] Add solution #3062
---
README.md | 1 +
.../3062-winner-of-the-linked-list-game.js | 57 +++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/3062-winner-of-the-linked-list-game.js
diff --git a/README.md b/README.md
index ee324d06..52741798 100644
--- a/README.md
+++ b/README.md
@@ -2583,6 +2583,7 @@
3044|[Most Frequent Prime](./solutions/3044-most-frequent-prime.js)|Medium|
3046|[Split the Array](./solutions/3046-split-the-array.js)|Easy|
3047|[Find the Largest Area of Square Inside Two Rectangles](./solutions/3047-find-the-largest-area-of-square-inside-two-rectangles.js)|Medium|
+3062|[Winner of the Linked List Game](./solutions/3062-winner-of-the-linked-list-game.js)|Easy|
3065|[Minimum Operations to Exceed Threshold Value I](./solutions/3065-minimum-operations-to-exceed-threshold-value-i.js)|Easy|
3066|[Minimum Operations to Exceed Threshold Value II](./solutions/3066-minimum-operations-to-exceed-threshold-value-ii.js)|Medium|
3067|[Count Pairs of Connectable Servers in a Weighted Tree Network](./solutions/3067-count-pairs-of-connectable-servers-in-a-weighted-tree-network.js)|Medium|
diff --git a/solutions/3062-winner-of-the-linked-list-game.js b/solutions/3062-winner-of-the-linked-list-game.js
new file mode 100644
index 00000000..1576fcfe
--- /dev/null
+++ b/solutions/3062-winner-of-the-linked-list-game.js
@@ -0,0 +1,57 @@
+/**
+ * 3062. Winner of the Linked List Game
+ * https://leetcode.com/problems/winner-of-the-linked-list-game/
+ * Difficulty: Easy
+ *
+ * You are given the head of a linked list of even length containing integers.
+ *
+ * Each odd-indexed node contains an odd integer and each even-indexed node contains an
+ * even integer.
+ *
+ * We call each even-indexed node and its next node a pair, e.g., the nodes with indices
+ * 0 and 1 are a pair, the nodes with indices 2 and 3 are a pair, and so on.
+ *
+ * For every pair, we compare the values of the nodes in the pair:
+ * - If the odd-indexed node is higher, the "Odd" team gets a point.
+ * - If the even-indexed node is higher, the "Even" team gets a point.
+ *
+ * Return the name of the team with the higher points, if the points are equal, return "Tie".
+ */
+
+/**
+ * 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 {string}
+ */
+var gameResult = function(head) {
+ let evenScore = 0;
+ let oddScore = 0;
+ let currentNode = head;
+
+ while (currentNode && currentNode.next) {
+ const evenValue = currentNode.val;
+ const oddValue = currentNode.next.val;
+
+ if (evenValue > oddValue) {
+ evenScore++;
+ } else if (oddValue > evenValue) {
+ oddScore++;
+ }
+
+ currentNode = currentNode.next.next;
+ }
+
+ if (evenScore > oddScore) {
+ return 'Even';
+ } else if (oddScore > evenScore) {
+ return 'Odd';
+ } else {
+ return 'Tie';
+ }
+};
From 1a9ca9bf3a3af9df9905febc43c172a3f8d4f596 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 22:56:26 -0500
Subject: [PATCH 865/994] Add solution #3063
---
README.md | 1 +
solutions/3063-linked-list-frequency.js | 44 +++++++++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/3063-linked-list-frequency.js
diff --git a/README.md b/README.md
index 52741798..03585bae 100644
--- a/README.md
+++ b/README.md
@@ -2584,6 +2584,7 @@
3046|[Split the Array](./solutions/3046-split-the-array.js)|Easy|
3047|[Find the Largest Area of Square Inside Two Rectangles](./solutions/3047-find-the-largest-area-of-square-inside-two-rectangles.js)|Medium|
3062|[Winner of the Linked List Game](./solutions/3062-winner-of-the-linked-list-game.js)|Easy|
+3063|[Linked List Frequency](./solutions/3063-linked-list-frequency.js)|Easy|
3065|[Minimum Operations to Exceed Threshold Value I](./solutions/3065-minimum-operations-to-exceed-threshold-value-i.js)|Easy|
3066|[Minimum Operations to Exceed Threshold Value II](./solutions/3066-minimum-operations-to-exceed-threshold-value-ii.js)|Medium|
3067|[Count Pairs of Connectable Servers in a Weighted Tree Network](./solutions/3067-count-pairs-of-connectable-servers-in-a-weighted-tree-network.js)|Medium|
diff --git a/solutions/3063-linked-list-frequency.js b/solutions/3063-linked-list-frequency.js
new file mode 100644
index 00000000..6b6cf078
--- /dev/null
+++ b/solutions/3063-linked-list-frequency.js
@@ -0,0 +1,44 @@
+/**
+ * 3063. Linked List Frequency
+ * https://leetcode.com/problems/linked-list-frequency/
+ * Difficulty: Easy
+ *
+ * Given the head of a linked list containing k distinct elements, return the head to a linked
+ * list of length k containing the frequency of each distinct element in the given linked list
+ * in any order.
+ */
+
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val, next) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.next = (next===undefined ? null : next)
+ * }
+ */
+/**
+ * @param {ListNode} head
+ * @return {ListNode}
+ */
+var frequenciesOfElements = function(head) {
+ const map = new Map();
+ let currentNode = head;
+
+ while (currentNode) {
+ map.set(currentNode.val, (map.get(currentNode.val) || 0) + 1);
+ currentNode = currentNode.next;
+ }
+
+ const frequencies = Array.from(map.values());
+
+ if (frequencies.length === 0) return null;
+
+ const resultHead = new ListNode(frequencies[0]);
+ let resultCurrent = resultHead;
+
+ for (let i = 1; i < frequencies.length; i++) {
+ resultCurrent.next = new ListNode(frequencies[i]);
+ resultCurrent = resultCurrent.next;
+ }
+
+ return resultHead;
+};
From ab7dc1ddc8bf7bf9f9e5f18618c3be7a8f58e5e7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 22:57:57 -0500
Subject: [PATCH 866/994] Add solution #3064
---
README.md | 3 +-
...ss-the-number-using-bitwise-questions-i.js | 36 +++++++++++++++++++
2 files changed, 38 insertions(+), 1 deletion(-)
create mode 100644 solutions/3064-guess-the-number-using-bitwise-questions-i.js
diff --git a/README.md b/README.md
index 03585bae..04c3ad6c 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 2,600+ LeetCode solutions in JavaScript
+# 2,650+ LeetCode solutions in JavaScript
[https://leetcodejavascript.com](https://leetcodejavascript.com)
@@ -2585,6 +2585,7 @@
3047|[Find the Largest Area of Square Inside Two Rectangles](./solutions/3047-find-the-largest-area-of-square-inside-two-rectangles.js)|Medium|
3062|[Winner of the Linked List Game](./solutions/3062-winner-of-the-linked-list-game.js)|Easy|
3063|[Linked List Frequency](./solutions/3063-linked-list-frequency.js)|Easy|
+3064|[Guess the Number Using Bitwise Questions I](./solutions/3064-guess-the-number-using-bitwise-questions-i.js)|Medium|
3065|[Minimum Operations to Exceed Threshold Value I](./solutions/3065-minimum-operations-to-exceed-threshold-value-i.js)|Easy|
3066|[Minimum Operations to Exceed Threshold Value II](./solutions/3066-minimum-operations-to-exceed-threshold-value-ii.js)|Medium|
3067|[Count Pairs of Connectable Servers in a Weighted Tree Network](./solutions/3067-count-pairs-of-connectable-servers-in-a-weighted-tree-network.js)|Medium|
diff --git a/solutions/3064-guess-the-number-using-bitwise-questions-i.js b/solutions/3064-guess-the-number-using-bitwise-questions-i.js
new file mode 100644
index 00000000..95aa9b8a
--- /dev/null
+++ b/solutions/3064-guess-the-number-using-bitwise-questions-i.js
@@ -0,0 +1,36 @@
+/**
+ * 3064. Guess the Number Using Bitwise Questions I
+ * https://leetcode.com/problems/guess-the-number-using-bitwise-questions-i/
+ * Difficulty: Medium
+ *
+ * There is a number n that you have to find.
+ *
+ * There is also a pre-defined API int commonSetBits(int num), which returns the number of bits
+ * where both n and num are 1 in that position of their binary representation. In other words,
+ * it returns the number of set bits in n & num, where & is the bitwise AND operator.
+ *
+ * Return the number n.
+ */
+
+/**
+ * Definition of commonSetBits API.
+ * @param {number} num
+ * @return {integer}
+ * var commonSetBits = function(num) {}
+ */
+
+/**
+ * @return {number}
+ */
+var findNumber = function() {
+ let result = 0;
+
+ for (let bitPosition = 0; bitPosition < 30; bitPosition++) {
+ const powerOfTwo = 1 << bitPosition;
+ if (commonSetBits(powerOfTwo) === 1) {
+ result |= powerOfTwo;
+ }
+ }
+
+ return result;
+};
From f8f04eb7a63683148515bfb6f59b15f3dd47516f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 23:22:46 -0500
Subject: [PATCH 867/994] Add solution #3073
---
README.md | 1 +
.../3073-maximum-increasing-triplet-value.js | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/3073-maximum-increasing-triplet-value.js
diff --git a/README.md b/README.md
index 04c3ad6c..06990cd8 100644
--- a/README.md
+++ b/README.md
@@ -2593,6 +2593,7 @@
3069|[Distribute Elements Into Two Arrays I](./solutions/3069-distribute-elements-into-two-arrays-i.js)|Easy|
3070|[Count Submatrices with Top-Left Element and Sum Less Than k](./solutions/3070-count-submatrices-with-top-left-element-and-sum-less-than-k.js)|Medium|
3071|[Minimum Operations to Write the Letter Y on a Grid](./solutions/3071-minimum-operations-to-write-the-letter-y-on-a-grid.js)|Medium|
+3073|[Maximum Increasing Triplet Value](./solutions/3073-maximum-increasing-triplet-value.js)|Medium|
3074|[Apple Redistribution into Boxes](./solutions/3074-apple-redistribution-into-boxes.js)|Easy|
3075|[Maximize Happiness of Selected Children](./solutions/3075-maximize-happiness-of-selected-children.js)|Medium|
3076|[Shortest Uncommon Substring in an Array](./solutions/3076-shortest-uncommon-substring-in-an-array.js)|Medium|
diff --git a/solutions/3073-maximum-increasing-triplet-value.js b/solutions/3073-maximum-increasing-triplet-value.js
new file mode 100644
index 00000000..856c217c
--- /dev/null
+++ b/solutions/3073-maximum-increasing-triplet-value.js
@@ -0,0 +1,50 @@
+/**
+ * 3073. Maximum Increasing Triplet Value
+ * https://leetcode.com/problems/maximum-increasing-triplet-value/
+ * Difficulty: Medium
+ *
+ * Given an array nums, return the maximum value of a triplet (i, j, k) such that i < j < k
+ * and nums[i] < nums[j] < nums[k].
+ *
+ * The value of a triplet (i, j, k) is nums[i] - nums[j] + nums[k].
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maximumTripletValue = function(nums) {
+ const n = nums.length;
+ const maxRight = new Array(n).fill(-1);
+ let currentMax = 0;
+ let result = 0;
+
+ for (let i = n - 1; i >= 0; i--) {
+ if (nums[i] >= currentMax) {
+ currentMax = nums[i];
+ } else {
+ maxRight[i] = currentMax;
+ }
+ }
+
+ const sortedIndices = Array.from({ length: n }, (_, i) => i)
+ .sort((a, b) => nums[a] - nums[b] || b - a);
+
+ const stack = [];
+
+ for (const currentIndex of sortedIndices) {
+ while (stack.length > 0 && stack[stack.length - 1] > currentIndex) {
+ stack.pop();
+ }
+
+ if (stack.length > 0 && maxRight[currentIndex] >= 0) {
+ const leftIndex = stack[stack.length - 1];
+ const tripletValue = nums[leftIndex] - nums[currentIndex] + maxRight[currentIndex];
+ result = Math.max(result, tripletValue);
+ }
+
+ stack.push(currentIndex);
+ }
+
+ return result;
+};
From 90fca49eb3a2bc45b363e7bd64fc34324c3f1d15 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 23:24:28 -0500
Subject: [PATCH 868/994] Add solution #3078
---
README.md | 1 +
...atch-alphanumerical-pattern-in-matrix-i.js | 86 +++++++++++++++++++
2 files changed, 87 insertions(+)
create mode 100644 solutions/3078-match-alphanumerical-pattern-in-matrix-i.js
diff --git a/README.md b/README.md
index 06990cd8..e5ac4d61 100644
--- a/README.md
+++ b/README.md
@@ -2597,6 +2597,7 @@
3074|[Apple Redistribution into Boxes](./solutions/3074-apple-redistribution-into-boxes.js)|Easy|
3075|[Maximize Happiness of Selected Children](./solutions/3075-maximize-happiness-of-selected-children.js)|Medium|
3076|[Shortest Uncommon Substring in an Array](./solutions/3076-shortest-uncommon-substring-in-an-array.js)|Medium|
+3078|[Match Alphanumerical Pattern in Matrix I](./solutions/3078-match-alphanumerical-pattern-in-matrix-i.js)|Medium|
3079|[Find the Sum of Encrypted Integers](./solutions/3079-find-the-sum-of-encrypted-integers.js)|Easy|
3083|[Existence of a Substring in a String and Its Reverse](./solutions/3083-existence-of-a-substring-in-a-string-and-its-reverse.js)|Easy|
3084|[Count Substrings Starting and Ending with Given Character](./solutions/3084-count-substrings-starting-and-ending-with-given-character.js)|Medium|
diff --git a/solutions/3078-match-alphanumerical-pattern-in-matrix-i.js b/solutions/3078-match-alphanumerical-pattern-in-matrix-i.js
new file mode 100644
index 00000000..cc5fe605
--- /dev/null
+++ b/solutions/3078-match-alphanumerical-pattern-in-matrix-i.js
@@ -0,0 +1,86 @@
+/**
+ * 3078. Match Alphanumerical Pattern in Matrix I
+ * https://leetcode.com/problems/match-alphanumerical-pattern-in-matrix-i/
+ * Difficulty: Medium
+ *
+ * You are given a 2D integer matrix board and a 2D character matrix pattern.
+ * Where 0 <= board[r][c] <= 9 and each element of pattern is either a digit or a
+ * lowercase English letter.
+ *
+ * Your task is to find a submatrix of board that matches pattern.
+ *
+ * An integer matrix part matches pattern if we can replace cells containing letters in
+ * pattern with some digits (each distinct letter with a unique digit) in such a way that
+ * the resulting matrix becomes identical to the integer matrix part. In other words,
+ * - The matrices have identical dimensions.
+ * - If pattern[r][c] is a digit, then part[r][c] must be the same digit.
+ * - If pattern[r][c] is a letter x:
+ * - For every pattern[i][j] == x, part[i][j] must be the same as part[r][c].
+ * - For every pattern[i][j] != x, part[i][j] must be different than part[r][c].
+ *
+ * Return an array of length 2 containing the row number and column number of the upper-left
+ * corner of a submatrix of board which matches pattern. If there is more than one such submatrix,
+ * return the coordinates of the submatrix with the lowest row index, and in case there is still
+ * a tie, return the coordinates of the submatrix with the lowest column index. If there are no
+ * suitable answers, return [-1, -1].
+ */
+
+/**
+ * @param {number[][]} board
+ * @param {string[]} pattern
+ * @return {number[]}
+ */
+var findPattern = function(board, pattern) {
+ const boardRows = board.length;
+ const boardCols = board[0].length;
+ const patternRows = pattern.length;
+ const patternCols = pattern[0].length;
+
+ for (let startRow = 0; startRow <= boardRows - patternRows; startRow++) {
+ for (let startCol = 0; startCol <= boardCols - patternCols; startCol++) {
+ if (isPatternMatch(board, pattern, startRow, startCol)) {
+ return [startRow, startCol];
+ }
+ }
+ }
+
+ return [-1, -1];
+
+ function isPatternMatch(board, pattern, startRow, startCol) {
+ const letterToDigit = new Map();
+ const digitToLetter = new Map();
+ const usedDigits = new Set();
+
+ for (let patternRow = 0; patternRow < pattern.length; patternRow++) {
+ for (let patternCol = 0; patternCol < pattern[0].length; patternCol++) {
+ const patternChar = pattern[patternRow][patternCol];
+ const boardDigit = board[startRow + patternRow][startCol + patternCol];
+
+ if (isDigit(patternChar)) {
+ if (parseInt(patternChar) !== boardDigit) {
+ return false;
+ }
+ } else {
+ if (letterToDigit.has(patternChar)) {
+ if (letterToDigit.get(patternChar) !== boardDigit) {
+ return false;
+ }
+ } else {
+ if (usedDigits.has(boardDigit) || digitToLetter.has(boardDigit)) {
+ return false;
+ }
+ letterToDigit.set(patternChar, boardDigit);
+ digitToLetter.set(boardDigit, patternChar);
+ usedDigits.add(boardDigit);
+ }
+ }
+ }
+ }
+
+ return true;
+ }
+
+ function isDigit(char) {
+ return char >= '0' && char <= '9';
+ }
+};
From 4e82829a8badef5d4fa1be18e837984569bcb5cd Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 23:26:33 -0500
Subject: [PATCH 869/994] Add solution #3088
---
README.md | 1 +
solutions/3088-make-string-anti-palindrome.js | 41 +++++++++++++++++++
2 files changed, 42 insertions(+)
create mode 100644 solutions/3088-make-string-anti-palindrome.js
diff --git a/README.md b/README.md
index e5ac4d61..0cc667ec 100644
--- a/README.md
+++ b/README.md
@@ -2602,6 +2602,7 @@
3083|[Existence of a Substring in a String and Its Reverse](./solutions/3083-existence-of-a-substring-in-a-string-and-its-reverse.js)|Easy|
3084|[Count Substrings Starting and Ending with Given Character](./solutions/3084-count-substrings-starting-and-ending-with-given-character.js)|Medium|
3085|[Minimum Deletions to Make String K-Special](./solutions/3085-minimum-deletions-to-make-string-k-special.js)|Medium|
+3088|[Make String Anti-palindrome](./solutions/3088-make-string-anti-palindrome.js)|Hard|
3090|[Maximum Length Substring With Two Occurrences](./solutions/3090-maximum-length-substring-with-two-occurrences.js)|Easy|
3091|[Apply Operations to Make Sum of Array Greater Than or Equal to k](./solutions/3091-apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k.js)|Medium|
3095|[Shortest Subarray With OR at Least K I](./solutions/3095-shortest-subarray-with-or-at-least-k-i.js)|Easy|
diff --git a/solutions/3088-make-string-anti-palindrome.js b/solutions/3088-make-string-anti-palindrome.js
new file mode 100644
index 00000000..087bd89f
--- /dev/null
+++ b/solutions/3088-make-string-anti-palindrome.js
@@ -0,0 +1,41 @@
+/**
+ * 3088. Make String Anti-palindrome
+ * https://leetcode.com/problems/make-string-anti-palindrome/
+ * Difficulty: Hard
+ *
+ * We call a string s of even length n an anti-palindrome if for each index
+ * 0 <= i < n, s[i] != s[n - i - 1].
+ *
+ * Given a string s, your task is to make s an anti-palindrome by doing any number of
+ * operations (including zero).
+ *
+ * In one operation, you can select two characters from s and swap them.
+ *
+ * Return the resulting string. If multiple strings meet the conditions, return the
+ * lexicographically smallest one. If it can't be made into an anti-palindrome, return "-1".
+ */
+
+/**
+ * @param {string} s
+ * @return {string}
+ */
+var makeAntiPalindrome = function(s) {
+ const n = s.length;
+ const result = Array.from(s).sort();
+ let leftIndex = Math.floor((n + 1) / 2);
+ let rightIndex = Math.floor((n + 1) / 2);
+
+ while (rightIndex < n && result[rightIndex] === result[leftIndex]) {
+ rightIndex++;
+ }
+ while (result[leftIndex] === result[n - leftIndex - 1]) {
+ if (rightIndex === n) {
+ return '-1';
+ }
+ [result[leftIndex], result[rightIndex]] = [result[rightIndex], result[leftIndex]];
+ leftIndex++;
+ rightIndex++;
+ }
+
+ return result.join('');
+};
From d15d5550d889e6d6a2a14b8ca954e75f7c06f893 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 23:28:28 -0500
Subject: [PATCH 870/994] Add solution #3094
---
README.md | 1 +
...s-the-number-using-bitwise-questions-ii.js | 43 +++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/3094-guess-the-number-using-bitwise-questions-ii.js
diff --git a/README.md b/README.md
index 0cc667ec..ef7b0262 100644
--- a/README.md
+++ b/README.md
@@ -2605,6 +2605,7 @@
3088|[Make String Anti-palindrome](./solutions/3088-make-string-anti-palindrome.js)|Hard|
3090|[Maximum Length Substring With Two Occurrences](./solutions/3090-maximum-length-substring-with-two-occurrences.js)|Easy|
3091|[Apply Operations to Make Sum of Array Greater Than or Equal to k](./solutions/3091-apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k.js)|Medium|
+3094|[Guess the Number Using Bitwise Questions II](./solutions/3094-guess-the-number-using-bitwise-questions-ii.js)|Medium|
3095|[Shortest Subarray With OR at Least K I](./solutions/3095-shortest-subarray-with-or-at-least-k-i.js)|Easy|
3097|[Shortest Subarray With OR at Least K II](./solutions/3097-shortest-subarray-with-or-at-least-k-ii.js)|Medium|
3099|[Harshad Number](./solutions/3099-harshad-number.js)|Easy|
diff --git a/solutions/3094-guess-the-number-using-bitwise-questions-ii.js b/solutions/3094-guess-the-number-using-bitwise-questions-ii.js
new file mode 100644
index 00000000..e05bc390
--- /dev/null
+++ b/solutions/3094-guess-the-number-using-bitwise-questions-ii.js
@@ -0,0 +1,43 @@
+/**
+ * 3094. Guess the Number Using Bitwise Questions II
+ * https://leetcode.com/problems/guess-the-number-using-bitwise-questions-ii/
+ * Difficulty: Medium
+ *
+ * There is a number n between 0 and 230 - 1 (both inclusive) that you have to find.
+ *
+ * There is a pre-defined API int commonBits(int num) that helps you with your mission.
+ * But here is the challenge, every time you call this function, n changes in some way.
+ * But keep in mind, that you have to find the initial value of n.
+ *
+ * commonBits(int num) acts as follows:
+ * - Calculate count which is the number of bits where both n and num have the same value
+ * in that position of their binary representation.
+ * - n = n XOR num
+ * - Return count.
+ *
+ * Return the number n.
+ *
+ * Note: In this world, all numbers are between 0 and 230 - 1 (both inclusive), thus for counting
+ * common bits, we see only the first 30 bits of those numbers.
+ */
+
+/**
+ * Definition of commonBits API.
+ * @param {number} num
+ * @return {integer}
+ * var commonBits = function(num) {}
+ */
+/**
+ * @return {number}
+ */
+var findNumber = function() {
+ let result = 0;
+
+ for (let bitMask = 1; bitMask < 1073741824; bitMask <<= 1) {
+ if (commonBits(bitMask) > commonBits(bitMask)) {
+ result |= bitMask;
+ }
+ }
+
+ return result;
+};
From e336217f81a858ce859ab6b8609d19ae5a02e7fe Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 23:30:55 -0500
Subject: [PATCH 871/994] Add solution #3104
---
README.md | 1 +
...4-find-longest-self-contained-substring.js | 56 +++++++++++++++++++
2 files changed, 57 insertions(+)
create mode 100644 solutions/3104-find-longest-self-contained-substring.js
diff --git a/README.md b/README.md
index ef7b0262..62f40917 100644
--- a/README.md
+++ b/README.md
@@ -2610,6 +2610,7 @@
3097|[Shortest Subarray With OR at Least K II](./solutions/3097-shortest-subarray-with-or-at-least-k-ii.js)|Medium|
3099|[Harshad Number](./solutions/3099-harshad-number.js)|Easy|
3100|[Water Bottles II](./solutions/3100-water-bottles-ii.js)|Medium|
+3104|[Find Longest Self-Contained Substring](./solutions/3104-find-longest-self-contained-substring.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/3104-find-longest-self-contained-substring.js b/solutions/3104-find-longest-self-contained-substring.js
new file mode 100644
index 00000000..78dee0dd
--- /dev/null
+++ b/solutions/3104-find-longest-self-contained-substring.js
@@ -0,0 +1,56 @@
+/**
+ * 3104. Find Longest Self-Contained Substring
+ * https://leetcode.com/problems/find-longest-self-contained-substring/
+ * Difficulty: Hard
+ *
+ * Given a string s, your task is to find the length of the longest self-contained substring
+ * of s.
+ *
+ * A substring t of a string s is called self-contained if t != s and for every character in
+ * t, it doesn't exist in the rest of s.
+ *
+ * Return the length of the longest self-contained substring of s if it exists, otherwise,
+ * return -1.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var maxSubstringLength = function(s) {
+ const firstOccurrences = new Map();
+ const lastOccurrences = new Map();
+
+ for (let i = 0; i < s.length; i++) {
+ const char = s[i];
+ if (!firstOccurrences.has(char)) {
+ firstOccurrences.set(char, i);
+ lastOccurrences.set(char, i);
+ } else {
+ lastOccurrences.set(char, i);
+ }
+ }
+
+ let result = -1;
+
+ for (const [startChar, startIndex] of firstOccurrences) {
+ const currentStart = startIndex;
+ let currentEnd = lastOccurrences.get(startChar);
+
+ for (let j = currentStart; j < s.length; j++) {
+ const currentChar = s[j];
+
+ if (firstOccurrences.get(currentChar) < currentStart) {
+ break;
+ }
+
+ currentEnd = Math.max(currentEnd, lastOccurrences.get(currentChar));
+
+ if (currentEnd === j && currentEnd - currentStart + 1 !== s.length) {
+ result = Math.max(result, currentEnd - currentStart + 1);
+ }
+ }
+ }
+
+ return result;
+};
From 466a5cef6a6942abfd0f6f131539e29346a6a1a7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 23:34:40 -0500
Subject: [PATCH 872/994] Add solution #3109
---
README.md | 1 +
.../3109-find-the-index-of-permutation.js | 61 +++++++++++++++++++
2 files changed, 62 insertions(+)
create mode 100644 solutions/3109-find-the-index-of-permutation.js
diff --git a/README.md b/README.md
index 62f40917..db5f44fb 100644
--- a/README.md
+++ b/README.md
@@ -2613,6 +2613,7 @@
3104|[Find Longest Self-Contained Substring](./solutions/3104-find-longest-self-contained-substring.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|
+3109|[Find the Index of Permutation](./solutions/3109-find-the-index-of-permutation.js)|Medium|
3110|[Score of a String](./solutions/3110-score-of-a-string.js)|Easy|
3136|[Valid Word](./solutions/3136-valid-word.js)|Easy|
3151|[Special Array I](./solutions/3151-special-array-i.js)|Easy|
diff --git a/solutions/3109-find-the-index-of-permutation.js b/solutions/3109-find-the-index-of-permutation.js
new file mode 100644
index 00000000..2304b57e
--- /dev/null
+++ b/solutions/3109-find-the-index-of-permutation.js
@@ -0,0 +1,61 @@
+/**
+ * 3109. Find the Index of Permutation
+ * https://leetcode.com/problems/find-the-index-of-permutation/
+ * Difficulty: Medium
+ *
+ * Given an array perm of length n which is a permutation of [1, 2, ..., n], return the index
+ * of perm in the lexicographically sorted array of all of the permutations of [1, 2, ..., n].
+ *
+ * Since the answer may be very large, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {number[]} perm
+ * @return {number}
+ */
+var getPermutationIndex = function(perm) {
+ const smallerToRight = perm.map(() => 0);
+
+ mergeSort(0, perm.length - 1);
+
+ const MOD = 10 ** 9 + 7;
+ const factorials = computeFactorials(perm.length);
+
+ return perm.reduce((total, _, i) => {
+ return (total + smallerToRight[i] * factorials[perm.length - 1 - i]) % MOD;
+ }, 0);
+
+ function mergeSort(left, right) {
+ if (left >= right) return [left];
+
+ const mid = (left + right) >> 1;
+ const leftIndices = mergeSort(left, mid);
+ const rightIndices = mergeSort(mid + 1, right);
+ const merged = [];
+ let [leftPointer, rightPointer] = [0, 0];
+
+ while (leftPointer < leftIndices.length || rightPointer < rightIndices.length) {
+ if (rightPointer === rightIndices.length
+ || (leftPointer < leftIndices.length
+ && perm[leftIndices[leftPointer]] < perm[rightIndices[rightPointer]])) {
+ smallerToRight[leftIndices[leftPointer]] += rightPointer;
+ merged.push(leftIndices[leftPointer++]);
+ } else {
+ merged.push(rightIndices[rightPointer++]);
+ }
+ }
+
+ return merged;
+ }
+
+ function computeFactorials(n) {
+ const MOD = 10n ** 9n + 7n;
+ const factorials = [1n, 1n];
+
+ for (let i = 2n; i <= BigInt(n); i++) {
+ factorials.push(i * factorials[factorials.length - 1] % MOD);
+ }
+
+ return factorials.map(val => parseInt(val));
+ }
+};
From 2362e9f6a84b762c29162a2aac400603697777b1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 23:35:52 -0500
Subject: [PATCH 873/994] Add solution #3119
---
README.md | 1 +
...um-number-of-potholes-that-can-be-fixed.js | 57 +++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/3119-maximum-number-of-potholes-that-can-be-fixed.js
diff --git a/README.md b/README.md
index db5f44fb..56b34b81 100644
--- a/README.md
+++ b/README.md
@@ -2615,6 +2615,7 @@
3108|[Minimum Cost Walk in Weighted Graph](./solutions/3108-minimum-cost-walk-in-weighted-graph.js)|Hard|
3109|[Find the Index of Permutation](./solutions/3109-find-the-index-of-permutation.js)|Medium|
3110|[Score of a String](./solutions/3110-score-of-a-string.js)|Easy|
+3119|[Maximum Number of Potholes That Can Be Fixed](./solutions/3119-maximum-number-of-potholes-that-can-be-fixed.js)|Medium|
3136|[Valid Word](./solutions/3136-valid-word.js)|Easy|
3151|[Special Array I](./solutions/3151-special-array-i.js)|Easy|
3160|[Find the Number of Distinct Colors Among the Balls](./solutions/3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium|
diff --git a/solutions/3119-maximum-number-of-potholes-that-can-be-fixed.js b/solutions/3119-maximum-number-of-potholes-that-can-be-fixed.js
new file mode 100644
index 00000000..f5d16513
--- /dev/null
+++ b/solutions/3119-maximum-number-of-potholes-that-can-be-fixed.js
@@ -0,0 +1,57 @@
+/**
+ * 3119. Maximum Number of Potholes That Can Be Fixed
+ * https://leetcode.com/problems/maximum-number-of-potholes-that-can-be-fixed/
+ * Difficulty: Medium
+ *
+ * You are given a string road, consisting only of characters "x" and ".", where each "x" denotes
+ * a pothole and each "." denotes a smooth road, and an integer budget.
+ *
+ * In one repair operation, you can repair n consecutive potholes for a price of n + 1.
+ *
+ * Return the maximum number of potholes that can be fixed such that the sum of the prices of all
+ * of the fixes doesn't go over the given budget.
+ */
+
+/**
+ * @param {string} road
+ * @param {number} budget
+ * @return {number}
+ */
+var maxPotholes = function(road, budget) {
+ const potholeSections = [];
+ let currentLength = 0;
+
+ for (const char of road) {
+ if (char === 'x') {
+ currentLength++;
+ } else {
+ if (currentLength > 0) {
+ potholeSections.push(currentLength);
+ currentLength = 0;
+ }
+ }
+ }
+
+ if (currentLength > 0) {
+ potholeSections.push(currentLength);
+ }
+
+ potholeSections.sort((a, b) => (a + 1) / a - (b + 1) / b);
+
+ let result = 0;
+ let remainingBudget = budget;
+ for (const sectionLength of potholeSections) {
+ const costToFixAll = sectionLength + 1;
+
+ if (costToFixAll <= remainingBudget) {
+ result += sectionLength;
+ remainingBudget -= costToFixAll;
+ } else {
+ const maxFixable = Math.max(0, remainingBudget - 1);
+ result += Math.min(maxFixable, sectionLength);
+ break;
+ }
+ }
+
+ return result;
+};
From 37a404097d76d8695e691904ca490e5104883f02 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 23:38:08 -0500
Subject: [PATCH 874/994] Add solution #3125
---
README.md | 1 +
...r-that-makes-result-of-bitwise-and-zero.js | 22 +++++++++++++++++++
2 files changed, 23 insertions(+)
create mode 100644 solutions/3125-maximum-number-that-makes-result-of-bitwise-and-zero.js
diff --git a/README.md b/README.md
index 56b34b81..1fe62449 100644
--- a/README.md
+++ b/README.md
@@ -2616,6 +2616,7 @@
3109|[Find the Index of Permutation](./solutions/3109-find-the-index-of-permutation.js)|Medium|
3110|[Score of a String](./solutions/3110-score-of-a-string.js)|Easy|
3119|[Maximum Number of Potholes That Can Be Fixed](./solutions/3119-maximum-number-of-potholes-that-can-be-fixed.js)|Medium|
+3125|[Maximum Number That Makes Result of Bitwise AND Zero](./solutions/3125-maximum-number-that-makes-result-of-bitwise-and-zero.js)|Medium|
3136|[Valid Word](./solutions/3136-valid-word.js)|Easy|
3151|[Special Array I](./solutions/3151-special-array-i.js)|Easy|
3160|[Find the Number of Distinct Colors Among the Balls](./solutions/3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium|
diff --git a/solutions/3125-maximum-number-that-makes-result-of-bitwise-and-zero.js b/solutions/3125-maximum-number-that-makes-result-of-bitwise-and-zero.js
new file mode 100644
index 00000000..73305584
--- /dev/null
+++ b/solutions/3125-maximum-number-that-makes-result-of-bitwise-and-zero.js
@@ -0,0 +1,22 @@
+/**
+ * 3125. Maximum Number That Makes Result of Bitwise AND Zero
+ * https://leetcode.com/problems/maximum-number-that-makes-result-of-bitwise-and-zero/
+ * Difficulty: Medium
+ *
+ * Given an integer n, return the maximum integer x such that x <= n, and the bitwise AND of
+ * all the numbers in the range [x, n] is 0.
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var maxNumber = function(n) {
+ let bit = 1;
+
+ while (bit <= n) {
+ bit *= 2;
+ }
+
+ return bit / 2 - 1;
+};
From d60318e9608a55b1cda8548b12b88d717772bfe7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 23:39:45 -0500
Subject: [PATCH 875/994] Add solution #3135
---
README.md | 1 +
...y-adding-or-removing-characters-at-ends.js | 40 +++++++++++++++++++
2 files changed, 41 insertions(+)
create mode 100644 solutions/3135-equalize-strings-by-adding-or-removing-characters-at-ends.js
diff --git a/README.md b/README.md
index 1fe62449..c0d69dfd 100644
--- a/README.md
+++ b/README.md
@@ -2617,6 +2617,7 @@
3110|[Score of a String](./solutions/3110-score-of-a-string.js)|Easy|
3119|[Maximum Number of Potholes That Can Be Fixed](./solutions/3119-maximum-number-of-potholes-that-can-be-fixed.js)|Medium|
3125|[Maximum Number That Makes Result of Bitwise AND Zero](./solutions/3125-maximum-number-that-makes-result-of-bitwise-and-zero.js)|Medium|
+3135|[Equalize Strings by Adding or Removing Characters at Ends](./solutions/3135-equalize-strings-by-adding-or-removing-characters-at-ends.js)|Medium|
3136|[Valid Word](./solutions/3136-valid-word.js)|Easy|
3151|[Special Array I](./solutions/3151-special-array-i.js)|Easy|
3160|[Find the Number of Distinct Colors Among the Balls](./solutions/3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium|
diff --git a/solutions/3135-equalize-strings-by-adding-or-removing-characters-at-ends.js b/solutions/3135-equalize-strings-by-adding-or-removing-characters-at-ends.js
new file mode 100644
index 00000000..afed0bca
--- /dev/null
+++ b/solutions/3135-equalize-strings-by-adding-or-removing-characters-at-ends.js
@@ -0,0 +1,40 @@
+/**
+ * 3135. Equalize Strings by Adding or Removing Characters at Ends
+ * https://leetcode.com/problems/equalize-strings-by-adding-or-removing-characters-at-ends/
+ * Difficulty: Medium
+ *
+ * Given two strings initial and target, your task is to modify initial by performing a series
+ * of operations to make it equal to target.
+ *
+ * In one operation, you can add or remove one character only at the beginning or the end of
+ * the string initial.
+ *
+ * Return the minimum number of operations required to transform initial into target.
+ */
+
+/**
+ * @param {string} initial
+ * @param {string} target
+ * @return {number}
+ */
+var minOperations = function(initial, target) {
+ const initialLength = initial.length;
+ const targetLength = target.length;
+ let previousRow = new Array(targetLength).fill(0);
+ let maxCommonSubsequence = 0;
+
+ for (let i = 0; i < initialLength; i++) {
+ const currentRow = new Array(targetLength).fill(0);
+
+ for (let j = 0; j < targetLength; j++) {
+ if (initial[i] === target[j]) {
+ currentRow[j] = 1 + (j - 1 >= 0 ? previousRow[j - 1] : 0);
+ maxCommonSubsequence = Math.max(maxCommonSubsequence, currentRow[j]);
+ }
+ }
+
+ previousRow = currentRow;
+ }
+
+ return initialLength + targetLength - 2 * maxCommonSubsequence;
+};
From 057f7c47f318508bc8149357f66814891e7ee360 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 16 Jul 2025 23:41:42 -0500
Subject: [PATCH 876/994] Add solution #3141
---
README.md | 1 +
solutions/3141-maximum-hamming-distances.js | 36 +++++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/3141-maximum-hamming-distances.js
diff --git a/README.md b/README.md
index c0d69dfd..5c2ddbe3 100644
--- a/README.md
+++ b/README.md
@@ -2619,6 +2619,7 @@
3125|[Maximum Number That Makes Result of Bitwise AND Zero](./solutions/3125-maximum-number-that-makes-result-of-bitwise-and-zero.js)|Medium|
3135|[Equalize Strings by Adding or Removing Characters at Ends](./solutions/3135-equalize-strings-by-adding-or-removing-characters-at-ends.js)|Medium|
3136|[Valid Word](./solutions/3136-valid-word.js)|Easy|
+3141|[Maximum Hamming Distances](./solutions/3141-maximum-hamming-distances.js)|Hard|
3151|[Special Array I](./solutions/3151-special-array-i.js)|Easy|
3160|[Find the Number of Distinct Colors Among the Balls](./solutions/3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium|
3169|[Count Days Without Meetings](./solutions/3169-count-days-without-meetings.js)|Medium|
diff --git a/solutions/3141-maximum-hamming-distances.js b/solutions/3141-maximum-hamming-distances.js
new file mode 100644
index 00000000..f8cb1d0e
--- /dev/null
+++ b/solutions/3141-maximum-hamming-distances.js
@@ -0,0 +1,36 @@
+/**
+ * 3141. Maximum Hamming Distances
+ * https://leetcode.com/problems/maximum-hamming-distances/
+ * Difficulty: Hard
+ *
+ * Given an array nums and an integer m, with each element nums[i] satisfying 0 <= nums[i] < 2m,
+ * return an array answer. The answer array should be of the same length as nums, where each
+ * element answer[i] represents the maximum Hamming distance between nums[i] and any other element
+ * nums[j] in the array.
+ *
+ * The Hamming distance between two binary integers is defined as the number of positions at which
+ * the corresponding bits differ (add leading zeroes if needed).
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} m
+ * @return {number[]}
+ */
+var maxHammingDistances = function(nums, m) {
+ const totalSize = 1 << m;
+ const maxDistances = new Array(totalSize).fill(-Infinity);
+
+ for (const num of nums) {
+ maxDistances[num] = 0;
+ }
+ for (let bitPosition = 0; bitPosition < m; bitPosition++) {
+ const previousDistances = [...maxDistances];
+ for (let number = 0; number < totalSize; number++) {
+ const flippedNumber = number ^ (1 << bitPosition);
+ maxDistances[number] = Math.max(maxDistances[number], previousDistances[flippedNumber] + 1);
+ }
+ }
+
+ return nums.map(num => maxDistances[num]);
+};
From f9a077d3e738f4e85e036e155bd3160d1a3d3a48 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 17 Jul 2025 22:55:39 -0500
Subject: [PATCH 877/994] Add solution #2163
---
README.md | 1 +
...rence-in-sums-after-removal-of-elements.js | 70 +++++++++++++++++++
2 files changed, 71 insertions(+)
create mode 100644 solutions/2163-minimum-difference-in-sums-after-removal-of-elements.js
diff --git a/README.md b/README.md
index 5c2ddbe3..9366183d 100644
--- a/README.md
+++ b/README.md
@@ -1955,6 +1955,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|
+2163|[Minimum Difference in Sums After Removal of Elements](./solutions/2163-minimum-difference-in-sums-after-removal-of-elements.js)|Hard|
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|
diff --git a/solutions/2163-minimum-difference-in-sums-after-removal-of-elements.js b/solutions/2163-minimum-difference-in-sums-after-removal-of-elements.js
new file mode 100644
index 00000000..82544302
--- /dev/null
+++ b/solutions/2163-minimum-difference-in-sums-after-removal-of-elements.js
@@ -0,0 +1,70 @@
+/**
+ * 2163. Minimum Difference in Sums After Removal of Elements
+ * https://leetcode.com/problems/minimum-difference-in-sums-after-removal-of-elements/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed integer array nums consisting of 3 * n elements.
+ *
+ * You are allowed to remove any subsequence of elements of size exactly n from nums.
+ * The remaining 2 * n elements will be divided into two equal parts:
+ * - The first n elements belonging to the first part and their sum is sumfirst.
+ * - The next n elements belonging to the second part and their sum is sumsecond.
+ *
+ * The difference in sums of the two parts is denoted as sumfirst - sumsecond.
+ * - For example, if sumfirst = 3 and sumsecond = 2, their difference is 1.
+ * - Similarly, if sumfirst = 2 and sumsecond = 3, their difference is -1.
+ *
+ * Return the minimum difference possible between the sums of the two parts after the removal
+ * of n elements.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimumDifference = function(nums) {
+ const n = nums.length / 3;
+ const minFirstPart = new Array(nums.length).fill(0);
+ const maxSecondPart = new Array(nums.length).fill(0);
+ const maxHeap = new PriorityQueue((a, b) => b - a);
+ const minHeap = new PriorityQueue((a, b) => a - b);
+
+ let currentSum = 0;
+ for (let i = 0; i < n; i++) {
+ maxHeap.enqueue(nums[i]);
+ currentSum += nums[i];
+ }
+ minFirstPart[n - 1] = currentSum;
+
+ for (let i = n; i < 2 * n; i++) {
+ maxHeap.enqueue(nums[i]);
+ currentSum += nums[i];
+ const removed = maxHeap.dequeue();
+ currentSum -= removed;
+ minFirstPart[i] = currentSum;
+ }
+
+ currentSum = 0;
+ minHeap.clear();
+ for (let i = 2 * n; i < 3 * n; i++) {
+ minHeap.enqueue(nums[i]);
+ currentSum += nums[i];
+ }
+ maxSecondPart[2 * n] = currentSum;
+
+ for (let i = 2 * n - 1; i >= n; i--) {
+ minHeap.enqueue(nums[i]);
+ currentSum += nums[i];
+ const removed = minHeap.dequeue();
+ currentSum -= removed;
+ maxSecondPart[i] = currentSum;
+ }
+
+ let result = Infinity;
+ for (let i = n - 1; i < 2 * n; i++) {
+ const difference = minFirstPart[i] - maxSecondPart[i + 1];
+ result = Math.min(result, difference);
+ }
+
+ return result;
+};
From 992a120a0e5aaf956853780ac561f50479b42519 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 17 Jul 2025 23:31:58 -0500
Subject: [PATCH 878/994] Add solution #3155
---
README.md | 1 +
...55-maximum-number-of-upgradable-servers.js | 43 +++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/3155-maximum-number-of-upgradable-servers.js
diff --git a/README.md b/README.md
index 9366183d..f957e171 100644
--- a/README.md
+++ b/README.md
@@ -2622,6 +2622,7 @@
3136|[Valid Word](./solutions/3136-valid-word.js)|Easy|
3141|[Maximum Hamming Distances](./solutions/3141-maximum-hamming-distances.js)|Hard|
3151|[Special Array I](./solutions/3151-special-array-i.js)|Easy|
+3155|[Maximum Number of Upgradable Servers](./solutions/3155-maximum-number-of-upgradable-servers.js)|Medium|
3160|[Find the Number of Distinct Colors Among the Balls](./solutions/3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium|
3169|[Count Days Without Meetings](./solutions/3169-count-days-without-meetings.js)|Medium|
3170|[Lexicographically Minimum String After Removing Stars](./solutions/3170-lexicographically-minimum-string-after-removing-stars.js)|Medium|
diff --git a/solutions/3155-maximum-number-of-upgradable-servers.js b/solutions/3155-maximum-number-of-upgradable-servers.js
new file mode 100644
index 00000000..f0bf5045
--- /dev/null
+++ b/solutions/3155-maximum-number-of-upgradable-servers.js
@@ -0,0 +1,43 @@
+/**
+ * 3155. Maximum Number of Upgradable Servers
+ * https://leetcode.com/problems/maximum-number-of-upgradable-servers/
+ * Difficulty: Medium
+ *
+ * You have n data centers and need to upgrade their servers.
+ *
+ * You are given four arrays count, upgrade, sell, and money of length n, which show:
+ * - The number of servers
+ * - The cost of upgrading a single server
+ * - The money you get by selling a server
+ * - The money you initially have
+ * - for each data center respectively.
+ *
+ * Return an array answer, where for each data center, the corresponding element in answer
+ * represents the maximum number of servers that can be upgraded.
+ *
+ * Note that the money from one data center cannot be used for another data center.
+ */
+
+/**
+ * @param {number[]} count
+ * @param {number[]} upgrade
+ * @param {number[]} sell
+ * @param {number[]} money
+ * @return {number[]}
+ */
+var maxUpgrades = function(count, upgrade, sell, money) {
+ const n = count.length;
+ const result = [...count];
+
+ for (let i = 0; i < n; i++) {
+ const totalUpgradeCost = count[i] * upgrade[i] - money[i];
+
+ if (totalUpgradeCost > 0) {
+ const netGainPerSale = sell[i] + upgrade[i];
+ const serversToSell = Math.ceil(totalUpgradeCost / netGainPerSale);
+ result[i] -= serversToSell;
+ }
+ }
+
+ return result;
+};
From a6b6c9c3ca0fe00b7ecc1a32e069dad33cd90e54 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 17 Jul 2025 23:33:05 -0500
Subject: [PATCH 879/994] Add solution #3157
---
README.md | 1 +
...find-the-level-of-tree-with-minimum-sum.js | 55 +++++++++++++++++++
2 files changed, 56 insertions(+)
create mode 100644 solutions/3157-find-the-level-of-tree-with-minimum-sum.js
diff --git a/README.md b/README.md
index f957e171..fef50ca6 100644
--- a/README.md
+++ b/README.md
@@ -2623,6 +2623,7 @@
3141|[Maximum Hamming Distances](./solutions/3141-maximum-hamming-distances.js)|Hard|
3151|[Special Array I](./solutions/3151-special-array-i.js)|Easy|
3155|[Maximum Number of Upgradable Servers](./solutions/3155-maximum-number-of-upgradable-servers.js)|Medium|
+3157|[Find the Level of Tree with Minimum Sum](./solutions/3157-find-the-level-of-tree-with-minimum-sum.js)|Medium|
3160|[Find the Number of Distinct Colors Among the Balls](./solutions/3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium|
3169|[Count Days Without Meetings](./solutions/3169-count-days-without-meetings.js)|Medium|
3170|[Lexicographically Minimum String After Removing Stars](./solutions/3170-lexicographically-minimum-string-after-removing-stars.js)|Medium|
diff --git a/solutions/3157-find-the-level-of-tree-with-minimum-sum.js b/solutions/3157-find-the-level-of-tree-with-minimum-sum.js
new file mode 100644
index 00000000..97beb4c7
--- /dev/null
+++ b/solutions/3157-find-the-level-of-tree-with-minimum-sum.js
@@ -0,0 +1,55 @@
+/**
+ * 3157. Find the Level of Tree with Minimum Sum
+ * https://leetcode.com/problems/find-the-level-of-tree-with-minimum-sum/
+ * Difficulty: Medium
+ *
+ * Given the root of a binary tree root where each node has a value, return the level of the
+ * tree that has the minimum sum of values among all the levels (in case of a tie, return the
+ * lowest level).
+ *
+ * Note that the root of the tree is at level 1 and the level of any other node is its distance
+ * from the root + 1.
+ */
+
+/**
+ * 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 minimumLevel = function(root) {
+ if (!root) return 1;
+
+ const queue = [root];
+ let currentLevel = 1;
+ let minSum = Infinity;
+ let result = 1;
+
+ while (queue.length > 0) {
+ const levelSize = queue.length;
+ let levelSum = 0;
+
+ for (let i = 0; i < levelSize; i++) {
+ const node = queue.shift();
+ levelSum += node.val;
+
+ if (node.left) queue.push(node.left);
+ if (node.right) queue.push(node.right);
+ }
+
+ if (levelSum < minSum) {
+ minSum = levelSum;
+ result = currentLevel;
+ }
+
+ currentLevel++;
+ }
+
+ return result;
+};
From 59e000395a79c9a156186fe818bafd1e55d6bb36 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 17 Jul 2025 23:34:25 -0500
Subject: [PATCH 880/994] Add solution #3167
---
README.md | 1 +
.../3167-better-compression-of-string.js | 45 +++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/3167-better-compression-of-string.js
diff --git a/README.md b/README.md
index fef50ca6..33acfb40 100644
--- a/README.md
+++ b/README.md
@@ -2625,6 +2625,7 @@
3155|[Maximum Number of Upgradable Servers](./solutions/3155-maximum-number-of-upgradable-servers.js)|Medium|
3157|[Find the Level of Tree with Minimum Sum](./solutions/3157-find-the-level-of-tree-with-minimum-sum.js)|Medium|
3160|[Find the Number of Distinct Colors Among the Balls](./solutions/3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium|
+3167|[Better Compression of String](./solutions/3167-better-compression-of-string.js)|Medium|
3169|[Count Days Without Meetings](./solutions/3169-count-days-without-meetings.js)|Medium|
3170|[Lexicographically Minimum String After Removing Stars](./solutions/3170-lexicographically-minimum-string-after-removing-stars.js)|Medium|
3174|[Clear Digits](./solutions/3174-clear-digits.js)|Easy|
diff --git a/solutions/3167-better-compression-of-string.js b/solutions/3167-better-compression-of-string.js
new file mode 100644
index 00000000..82761258
--- /dev/null
+++ b/solutions/3167-better-compression-of-string.js
@@ -0,0 +1,45 @@
+/**
+ * 3167. Better Compression of String
+ * https://leetcode.com/problems/better-compression-of-string/
+ * Difficulty: Medium
+ *
+ * You are given a string compressed representing a compressed version of a string. The format
+ * is a character followed by its frequency. For example, "a3b1a1c2" is a compressed version
+ * of the string "aaabacc".
+ *
+ * We seek a better compression with the following conditions:
+ * 1. Each character should appear only once in the compressed version.
+ * 2. The characters should be in alphabetical order.
+ *
+ * Return the better compression of compressed.
+ *
+ * Note: In the better version of compression, the order of letters may change, which is acceptable.
+ */
+
+/**
+ * @param {string} compressed
+ * @return {string}
+ */
+var betterCompression = function(compressed) {
+ const map = new Map();
+ let i = 0;
+
+ while (i < compressed.length) {
+ const char = compressed[i];
+ i++;
+
+ let frequency = '';
+ while (i < compressed.length && !isNaN(compressed[i])) {
+ frequency += compressed[i];
+ i++;
+ }
+
+ const count = parseInt(frequency);
+ map.set(char, (map.get(char) || 0) + count);
+ }
+
+ const sortedChars = [...map.keys()].sort();
+ const result = sortedChars.map(char => char + map.get(char)).join('');
+
+ return result;
+};
From 4899f5a6a00ba5ccafed8e5aae6d7ff848734714 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 17 Jul 2025 23:35:28 -0500
Subject: [PATCH 881/994] Add solution #3173
---
README.md | 1 +
.../3173-bitwise-or-of-adjacent-elements.js | 22 +++++++++++++++++++
2 files changed, 23 insertions(+)
create mode 100644 solutions/3173-bitwise-or-of-adjacent-elements.js
diff --git a/README.md b/README.md
index 33acfb40..c23ada31 100644
--- a/README.md
+++ b/README.md
@@ -2628,6 +2628,7 @@
3167|[Better Compression of String](./solutions/3167-better-compression-of-string.js)|Medium|
3169|[Count Days Without Meetings](./solutions/3169-count-days-without-meetings.js)|Medium|
3170|[Lexicographically Minimum String After Removing Stars](./solutions/3170-lexicographically-minimum-string-after-removing-stars.js)|Medium|
+3173|[Bitwise OR of Adjacent Elements](./solutions/3173-bitwise-or-of-adjacent-elements.js)|Easy|
3174|[Clear Digits](./solutions/3174-clear-digits.js)|Easy|
3178|[Find the Child Who Has the Ball After K Seconds](./solutions/3178-find-the-child-who-has-the-ball-after-k-seconds.js)|Easy|
3191|[Minimum Operations to Make Binary Array Elements Equal to One I](./solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js)|Medium|
diff --git a/solutions/3173-bitwise-or-of-adjacent-elements.js b/solutions/3173-bitwise-or-of-adjacent-elements.js
new file mode 100644
index 00000000..78f53116
--- /dev/null
+++ b/solutions/3173-bitwise-or-of-adjacent-elements.js
@@ -0,0 +1,22 @@
+/**
+ * 3173. Bitwise OR of Adjacent Elements
+ * https://leetcode.com/problems/bitwise-or-of-adjacent-elements/
+ * Difficulty: Easy
+ *
+ * Given an array nums of length n, return an array answer of length n - 1 such that
+ * answer[i] = nums[i] | nums[i + 1] where | is the bitwise OR operation.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var orArray = function(nums) {
+ const result = [];
+
+ for (let i = 0; i < nums.length - 1; i++) {
+ result.push(nums[i] | nums[i + 1]);
+ }
+
+ return result;
+};
From 368f0a4c58a6a973522c03e9742bfbbead0177b3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 17 Jul 2025 23:37:58 -0500
Subject: [PATCH 882/994] Add solution #3183
---
README.md | 1 +
...3183-the-number-of-ways-to-make-the-sum.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/3183-the-number-of-ways-to-make-the-sum.js
diff --git a/README.md b/README.md
index c23ada31..08b57dff 100644
--- a/README.md
+++ b/README.md
@@ -2631,6 +2631,7 @@
3173|[Bitwise OR of Adjacent Elements](./solutions/3173-bitwise-or-of-adjacent-elements.js)|Easy|
3174|[Clear Digits](./solutions/3174-clear-digits.js)|Easy|
3178|[Find the Child Who Has the Ball After K Seconds](./solutions/3178-find-the-child-who-has-the-ball-after-k-seconds.js)|Easy|
+3183|[The Number of Ways to Make the Sum](./solutions/3183-the-number-of-ways-to-make-the-sum.js)|Medium|
3191|[Minimum Operations to Make Binary Array Elements Equal to One I](./solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js)|Medium|
3201|[Find the Maximum Length of Valid Subsequence I](./solutions/3201-find-the-maximum-length-of-valid-subsequence-i.js)|Medium|
3202|[Find the Maximum Length of Valid Subsequence II](./solutions/3202-find-the-maximum-length-of-valid-subsequence-ii.js)|Medium|
diff --git a/solutions/3183-the-number-of-ways-to-make-the-sum.js b/solutions/3183-the-number-of-ways-to-make-the-sum.js
new file mode 100644
index 00000000..0be1707c
--- /dev/null
+++ b/solutions/3183-the-number-of-ways-to-make-the-sum.js
@@ -0,0 +1,39 @@
+/**
+ * 3183. The Number of Ways to Make the Sum
+ * https://leetcode.com/problems/the-number-of-ways-to-make-the-sum/
+ * Difficulty: Medium
+ *
+ * You have an infinite number of coins with values 1, 2, and 6, and only 2 coins with value 4.
+ *
+ * Given an integer n, return the number of ways to make the sum of n with the coins you have.
+ *
+ * Since the answer may be very large, return it modulo 109 + 7.
+ *
+ * Note that the order of the coins doesn't matter and [2, 2, 3] is the same as [2, 3, 2].
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var numberOfWays = function(n) {
+ const MOD = 1e9 + 7;
+ const dp = new Array(n + 1).fill(0);
+ dp[0] = 1;
+
+ for (const coin of [1, 2, 6]) {
+ for (let amount = coin; amount <= n; amount++) {
+ dp[amount] = (dp[amount] + dp[amount - coin]) % MOD;
+ }
+ }
+
+ let result = dp[n];
+ if (n >= 4) {
+ result = (result + dp[n - 4]) % MOD;
+ }
+ if (n >= 8) {
+ result = (result + dp[n - 8]) % MOD;
+ }
+
+ return result;
+};
From a50a1e1910f3576b0f5e8d1d4e921f050bb8e636 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 17 Jul 2025 23:40:27 -0500
Subject: [PATCH 883/994] Add solution #3189
---
README.md | 1 +
...9-minimum-moves-to-get-a-peaceful-board.js | 31 +++++++++++++++++++
2 files changed, 32 insertions(+)
create mode 100644 solutions/3189-minimum-moves-to-get-a-peaceful-board.js
diff --git a/README.md b/README.md
index 08b57dff..cdb5bf11 100644
--- a/README.md
+++ b/README.md
@@ -2632,6 +2632,7 @@
3174|[Clear Digits](./solutions/3174-clear-digits.js)|Easy|
3178|[Find the Child Who Has the Ball After K Seconds](./solutions/3178-find-the-child-who-has-the-ball-after-k-seconds.js)|Easy|
3183|[The Number of Ways to Make the Sum](./solutions/3183-the-number-of-ways-to-make-the-sum.js)|Medium|
+3189|[Minimum Moves to Get a Peaceful Board](./solutions/3189-minimum-moves-to-get-a-peaceful-board.js)|Medium|
3191|[Minimum Operations to Make Binary Array Elements Equal to One I](./solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js)|Medium|
3201|[Find the Maximum Length of Valid Subsequence I](./solutions/3201-find-the-maximum-length-of-valid-subsequence-i.js)|Medium|
3202|[Find the Maximum Length of Valid Subsequence II](./solutions/3202-find-the-maximum-length-of-valid-subsequence-ii.js)|Medium|
diff --git a/solutions/3189-minimum-moves-to-get-a-peaceful-board.js b/solutions/3189-minimum-moves-to-get-a-peaceful-board.js
new file mode 100644
index 00000000..0d0e05be
--- /dev/null
+++ b/solutions/3189-minimum-moves-to-get-a-peaceful-board.js
@@ -0,0 +1,31 @@
+/**
+ * 3189. Minimum Moves to Get a Peaceful Board
+ * https://leetcode.com/problems/minimum-moves-to-get-a-peaceful-board/
+ * Difficulty: Medium
+ *
+ * Given a 2D array rooks of length n, where rooks[i] = [xi, yi] indicates the position of a
+ * rook on an n x n chess board. Your task is to move the rooks 1 cell at a time vertically
+ * or horizontally (to an adjacent cell) such that the board becomes peaceful.
+ *
+ * A board is peaceful if there is exactly one rook in each row and each column.
+ *
+ * Return the minimum number of moves required to get a peaceful board.
+ *
+ * Note that at no point can there be two rooks in the same cell.
+ */
+
+/**
+ * @param {number[][]} rooks
+ * @return {number}
+ */
+var minMoves = function(rooks) {
+ const rows = rooks.map(rook => rook[0]).sort((a, b) => a - b);
+ const cols = rooks.map(rook => rook[1]).sort((a, b) => a - b);
+
+ let result = 0;
+ for (let i = 0; i < rooks.length; i++) {
+ result += Math.abs(rows[i] - i) + Math.abs(cols[i] - i);
+ }
+
+ return result;
+};
From b6667c5bf7b35565cef47660c08813cd7f78e5fc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 17 Jul 2025 23:42:06 -0500
Subject: [PATCH 884/994] Add solution #3199
---
README.md | 1 +
...count-triplets-with-even-xor-set-bits-i.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/3199-count-triplets-with-even-xor-set-bits-i.js
diff --git a/README.md b/README.md
index cdb5bf11..0c793755 100644
--- a/README.md
+++ b/README.md
@@ -2634,6 +2634,7 @@
3183|[The Number of Ways to Make the Sum](./solutions/3183-the-number-of-ways-to-make-the-sum.js)|Medium|
3189|[Minimum Moves to Get a Peaceful Board](./solutions/3189-minimum-moves-to-get-a-peaceful-board.js)|Medium|
3191|[Minimum Operations to Make Binary Array Elements Equal to One I](./solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js)|Medium|
+3199|[Count Triplets with Even XOR Set Bits I](./solutions/3199-count-triplets-with-even-xor-set-bits-i.js)|Easy|
3201|[Find the Maximum Length of Valid Subsequence I](./solutions/3201-find-the-maximum-length-of-valid-subsequence-i.js)|Medium|
3202|[Find the Maximum Length of Valid Subsequence II](./solutions/3202-find-the-maximum-length-of-valid-subsequence-ii.js)|Medium|
3208|[Alternating Groups II](./solutions/3208-alternating-groups-ii.js)|Medium|
diff --git a/solutions/3199-count-triplets-with-even-xor-set-bits-i.js b/solutions/3199-count-triplets-with-even-xor-set-bits-i.js
new file mode 100644
index 00000000..8c9838f6
--- /dev/null
+++ b/solutions/3199-count-triplets-with-even-xor-set-bits-i.js
@@ -0,0 +1,42 @@
+/**
+ * 3199. Count Triplets with Even XOR Set Bits I
+ * https://leetcode.com/problems/count-triplets-with-even-xor-set-bits-i/
+ * Difficulty: Easy
+ *
+ * Given three integer arrays a, b, and c, return the number of triplets (a[i], b[j], c[k]),
+ * such that the bitwise XOR of the elements of each triplet has an even number of set bits.
+ */
+
+/**
+ * @param {number[]} a
+ * @param {number[]} b
+ * @param {number[]} c
+ * @return {number}
+ */
+var tripletCount = function(a, b, c) {
+ let result = 0;
+
+ for (const numA of a) {
+ for (const numB of b) {
+ for (const numC of c) {
+ const xorResult = numA ^ numB ^ numC;
+ if (hasEvenSetBits(xorResult)) {
+ result++;
+ }
+ }
+ }
+ }
+
+ return result;
+
+ function hasEvenSetBits(num) {
+ let setBitsCount = 0;
+
+ while (num > 0) {
+ setBitsCount += num & 1;
+ num >>= 1;
+ }
+
+ return setBitsCount % 2 === 0;
+ }
+};
From 48bcbb084222813fce5991edc2c23c6f7a56f2b3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 17 Jul 2025 23:43:08 -0500
Subject: [PATCH 885/994] Add solution #3205
---
README.md | 1 +
.../3205-maximum-array-hopping-score-i.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/3205-maximum-array-hopping-score-i.js
diff --git a/README.md b/README.md
index 0c793755..2361716f 100644
--- a/README.md
+++ b/README.md
@@ -2637,6 +2637,7 @@
3199|[Count Triplets with Even XOR Set Bits I](./solutions/3199-count-triplets-with-even-xor-set-bits-i.js)|Easy|
3201|[Find the Maximum Length of Valid Subsequence I](./solutions/3201-find-the-maximum-length-of-valid-subsequence-i.js)|Medium|
3202|[Find the Maximum Length of Valid Subsequence II](./solutions/3202-find-the-maximum-length-of-valid-subsequence-ii.js)|Medium|
+3205|[Maximum Array Hopping Score I](./solutions/3205-maximum-array-hopping-score-i.js)|Medium|
3208|[Alternating Groups II](./solutions/3208-alternating-groups-ii.js)|Medium|
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|
diff --git a/solutions/3205-maximum-array-hopping-score-i.js b/solutions/3205-maximum-array-hopping-score-i.js
new file mode 100644
index 00000000..7b4faa30
--- /dev/null
+++ b/solutions/3205-maximum-array-hopping-score-i.js
@@ -0,0 +1,34 @@
+/**
+ * 3205. Maximum Array Hopping Score I
+ * https://leetcode.com/problems/maximum-array-hopping-score-i/
+ * Difficulty: Medium
+ *
+ * Given an array nums, you have to get the maximum score starting from index 0 and
+ * hopping until you reach the last element of the array.
+ *
+ * In each hop, you can jump from index i to an index j > i, and you get a score of
+ * (j - i) * nums[j].
+ *
+ * Return the maximum score you can get.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maxScore = function(nums) {
+ const n = nums.length;
+ const dp = new Array(n).fill(-Infinity);
+ dp[0] = 0;
+
+ for (let i = 0; i < n; i++) {
+ if (dp[i] === -Infinity) continue;
+
+ for (let j = i + 1; j < n; j++) {
+ const jumpScore = (j - i) * nums[j];
+ dp[j] = Math.max(dp[j], dp[i] + jumpScore);
+ }
+ }
+
+ return dp[n - 1];
+};
From 791bd43679734ada4f24a81a2d39181a7a7b0baa Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 17 Jul 2025 23:45:11 -0500
Subject: [PATCH 886/994] Add solution #3215
---
README.md | 1 +
...ount-triplets-with-even-xor-set-bits-ii.js | 47 +++++++++++++++++++
2 files changed, 48 insertions(+)
create mode 100644 solutions/3215-count-triplets-with-even-xor-set-bits-ii.js
diff --git a/README.md b/README.md
index 2361716f..a074eb7f 100644
--- a/README.md
+++ b/README.md
@@ -2639,6 +2639,7 @@
3202|[Find the Maximum Length of Valid Subsequence II](./solutions/3202-find-the-maximum-length-of-valid-subsequence-ii.js)|Medium|
3205|[Maximum Array Hopping Score I](./solutions/3205-maximum-array-hopping-score-i.js)|Medium|
3208|[Alternating Groups II](./solutions/3208-alternating-groups-ii.js)|Medium|
+3215|[Count Triplets with Even XOR Set Bits II](./solutions/3215-count-triplets-with-even-xor-set-bits-ii.js)|Medium|
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|
3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
diff --git a/solutions/3215-count-triplets-with-even-xor-set-bits-ii.js b/solutions/3215-count-triplets-with-even-xor-set-bits-ii.js
new file mode 100644
index 00000000..cf408718
--- /dev/null
+++ b/solutions/3215-count-triplets-with-even-xor-set-bits-ii.js
@@ -0,0 +1,47 @@
+/**
+ * 3215. Count Triplets with Even XOR Set Bits II
+ * https://leetcode.com/problems/count-triplets-with-even-xor-set-bits-ii/
+ * Difficulty: Medium
+ *
+ * Given three integer arrays a, b, and c, return the number of triplets (a[i], b[j], c[k]),
+ * such that the bitwise XOR between the elements of each triplet has an even number of set bits.
+ */
+
+/**
+ * @param {number[]} a
+ * @param {number[]} b
+ * @param {number[]} c
+ * @return {number}
+ */
+var tripletCount = function(a, b, c) {
+ const countA = [0, 0];
+ const countB = [0, 0];
+ const countC = [0, 0];
+
+ for (const num of a) {
+ countA[countSetBits(num) % 2]++;
+ }
+ for (const num of b) {
+ countB[countSetBits(num) % 2]++;
+ }
+ for (const num of c) {
+ countC[countSetBits(num) % 2]++;
+ }
+
+ let result = 0;
+ result += countA[0] * countB[0] * countC[0];
+ result += countA[1] * countB[1] * countC[0];
+ result += countA[1] * countB[0] * countC[1];
+ result += countA[0] * countB[1] * countC[1];
+
+ return result;
+
+ function countSetBits(num) {
+ let count = 0;
+ while (num > 0) {
+ count += num & 1;
+ num >>= 1;
+ }
+ return count;
+ }
+};
From a701a931d9fce47e3fcceab55c5a3e6a95c4e8e6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 17 Jul 2025 23:47:37 -0500
Subject: [PATCH 887/994] Add solution #3221
---
README.md | 1 +
.../3221-maximum-array-hopping-score-ii.js | 29 +++++++++++++++++++
2 files changed, 30 insertions(+)
create mode 100644 solutions/3221-maximum-array-hopping-score-ii.js
diff --git a/README.md b/README.md
index a074eb7f..3c5fb649 100644
--- a/README.md
+++ b/README.md
@@ -2640,6 +2640,7 @@
3205|[Maximum Array Hopping Score I](./solutions/3205-maximum-array-hopping-score-i.js)|Medium|
3208|[Alternating Groups II](./solutions/3208-alternating-groups-ii.js)|Medium|
3215|[Count Triplets with Even XOR Set Bits II](./solutions/3215-count-triplets-with-even-xor-set-bits-ii.js)|Medium|
+3221|[Maximum Array Hopping Score II](./solutions/3221-maximum-array-hopping-score-ii.js)|Medium|
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|
3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
diff --git a/solutions/3221-maximum-array-hopping-score-ii.js b/solutions/3221-maximum-array-hopping-score-ii.js
new file mode 100644
index 00000000..5abe3e4a
--- /dev/null
+++ b/solutions/3221-maximum-array-hopping-score-ii.js
@@ -0,0 +1,29 @@
+/**
+ * 3221. Maximum Array Hopping Score II
+ * https://leetcode.com/problems/maximum-array-hopping-score-ii/
+ * Difficulty: Medium
+ *
+ * Given an array nums, you have to get the maximum score starting from index 0 and
+ * hopping until you reach the last element of the array.
+ *
+ * In each hop, you can jump from index i to an index j > i, and you get a score of
+ * (j - i) * nums[j].
+ *
+ * Return the maximum score you can get.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maxScore = function(nums) {
+ let result = 0;
+ let max = 0;
+
+ for (let i = nums.length - 1; i >= 1; i--) {
+ max = Math.max(max, nums[i]);
+ result += max;
+ }
+
+ return result;
+};
From 42c9a41931ef78ddeaf07c8da08184f65b810b96 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 17 Jul 2025 23:49:21 -0500
Subject: [PATCH 888/994] Add solution #3231
---
README.md | 1 +
...of-increasing-subsequence-to-be-removed.js | 48 +++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/3231-minimum-number-of-increasing-subsequence-to-be-removed.js
diff --git a/README.md b/README.md
index 3c5fb649..4434ada4 100644
--- a/README.md
+++ b/README.md
@@ -2642,6 +2642,7 @@
3215|[Count Triplets with Even XOR Set Bits II](./solutions/3215-count-triplets-with-even-xor-set-bits-ii.js)|Medium|
3221|[Maximum Array Hopping Score II](./solutions/3221-maximum-array-hopping-score-ii.js)|Medium|
3223|[Minimum Length of String After Operations](./solutions/3223-minimum-length-of-string-after-operations.js)|Medium|
+3231|[Minimum Number of Increasing Subsequence to Be Removed](./solutions/3231-minimum-number-of-increasing-subsequence-to-be-removed.js)|Hard|
3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard|
3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
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|
diff --git a/solutions/3231-minimum-number-of-increasing-subsequence-to-be-removed.js b/solutions/3231-minimum-number-of-increasing-subsequence-to-be-removed.js
new file mode 100644
index 00000000..8d4897ea
--- /dev/null
+++ b/solutions/3231-minimum-number-of-increasing-subsequence-to-be-removed.js
@@ -0,0 +1,48 @@
+/**
+ * 3231. Minimum Number of Increasing Subsequence to Be Removed
+ * https://leetcode.com/problems/minimum-number-of-increasing-subsequence-to-be-removed/
+ * Difficulty: Hard
+ *
+ * Given an array of integers nums, you are allowed to perform the following operation any
+ * number of times:
+ * - Remove a strictly increasing subsequence from the array.
+ *
+ * Your task is to find the minimum number of operations required to make the array empty.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minOperations = function(nums) {
+ const dp = [nums[nums.length - 1]];
+
+ for (let i = nums.length - 2; i >= 0; i--) {
+ const currentNum = nums[i];
+
+ if (currentNum >= dp[dp.length - 1]) {
+ dp.push(currentNum);
+ } else {
+ const insertionIndex = binarySearchRight(dp, currentNum);
+ dp[insertionIndex] = currentNum;
+ }
+ }
+
+ return dp.length;
+
+ function binarySearchRight(arr, target) {
+ let left = 0;
+ let right = arr.length;
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (arr[mid] <= target) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+
+ return left;
+ }
+};
From a46b6bc353669df850aafff17ceda600d86f819a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 17 Jul 2025 23:51:02 -0500
Subject: [PATCH 889/994] Add solution #3237
---
README.md | 1 +
solutions/3237-alt-and-tab-simulation.js | 43 ++++++++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/3237-alt-and-tab-simulation.js
diff --git a/README.md b/README.md
index 4434ada4..a950f50f 100644
--- a/README.md
+++ b/README.md
@@ -2643,6 +2643,7 @@
3221|[Maximum Array Hopping Score II](./solutions/3221-maximum-array-hopping-score-ii.js)|Medium|
3223|[Minimum Length of String After Operations](./solutions/3223-minimum-length-of-string-after-operations.js)|Medium|
3231|[Minimum Number of Increasing Subsequence to Be Removed](./solutions/3231-minimum-number-of-increasing-subsequence-to-be-removed.js)|Hard|
+3237|[Alt and Tab Simulation](./solutions/3237-alt-and-tab-simulation.js)|Medium|
3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard|
3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
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|
diff --git a/solutions/3237-alt-and-tab-simulation.js b/solutions/3237-alt-and-tab-simulation.js
new file mode 100644
index 00000000..005f9b54
--- /dev/null
+++ b/solutions/3237-alt-and-tab-simulation.js
@@ -0,0 +1,43 @@
+/**
+ * 3237. Alt and Tab Simulation
+ * https://leetcode.com/problems/alt-and-tab-simulation/
+ * Difficulty: Medium
+ *
+ * There are n windows open numbered from 1 to n, we want to simulate using alt + tab to
+ * navigate between the windows.
+ *
+ * You are given an array windows which contains the initial order of the windows (the
+ * first element is at the top and the last one is at the bottom).
+ *
+ * You are also given an array queries where for each query, the window queries[i] is
+ * brought to the top.
+ *
+ * Return the final state of the array windows.
+ */
+
+/**
+ * @param {number[]} windows
+ * @param {number[]} queries
+ * @return {number[]}
+ */
+var simulationResult = function(windows, queries) {
+ const result = [];
+ const set = new Set();
+
+ for (let i = queries.length - 1; i >= 0; i--) {
+ const window = queries[i];
+
+ if (!set.has(window)) {
+ result.push(window);
+ set.add(window);
+ }
+ }
+
+ for (const window of windows) {
+ if (!set.has(window)) {
+ result.push(window);
+ }
+ }
+
+ return result;
+};
From 2ec9e1c062c68a106eb2650c97712193a6919bfc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 17 Jul 2025 23:52:07 -0500
Subject: [PATCH 890/994] Add solution #3247
---
README.md | 1 +
...247-number-of-subsequences-with-odd-sum.js | 33 +++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/3247-number-of-subsequences-with-odd-sum.js
diff --git a/README.md b/README.md
index a950f50f..eb3d79b4 100644
--- a/README.md
+++ b/README.md
@@ -2644,6 +2644,7 @@
3223|[Minimum Length of String After Operations](./solutions/3223-minimum-length-of-string-after-operations.js)|Medium|
3231|[Minimum Number of Increasing Subsequence to Be Removed](./solutions/3231-minimum-number-of-increasing-subsequence-to-be-removed.js)|Hard|
3237|[Alt and Tab Simulation](./solutions/3237-alt-and-tab-simulation.js)|Medium|
+3247|[Number of Subsequences with Odd Sum](./solutions/3247-number-of-subsequences-with-odd-sum.js)|Medium|
3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard|
3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
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|
diff --git a/solutions/3247-number-of-subsequences-with-odd-sum.js b/solutions/3247-number-of-subsequences-with-odd-sum.js
new file mode 100644
index 00000000..3e40ac6e
--- /dev/null
+++ b/solutions/3247-number-of-subsequences-with-odd-sum.js
@@ -0,0 +1,33 @@
+/**
+ * 3247. Number of Subsequences with Odd Sum
+ * https://leetcode.com/problems/number-of-subsequences-with-odd-sum/
+ * Difficulty: Medium
+ *
+ * Given an array nums, return the number of subsequences with an odd sum of elements.
+ *
+ * Since the answer may be very large, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var subsequenceCount = function(nums) {
+ const MOD = 1e9 + 7;
+ let oddCount = 0;
+ let evenCount = 1;
+
+ for (const num of nums) {
+ if (num % 2 === 1) {
+ const newOddCount = (oddCount + evenCount) % MOD;
+ const newEvenCount = (evenCount + oddCount) % MOD;
+ oddCount = newOddCount;
+ evenCount = newEvenCount;
+ } else {
+ oddCount = (oddCount * 2) % MOD;
+ evenCount = (evenCount * 2) % MOD;
+ }
+ }
+
+ return oddCount;
+};
From 373a58933dbda6f27970d1954d91fe07ba2d1f18 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 17 Jul 2025 23:55:05 -0500
Subject: [PATCH 891/994] Add solution #3253
---
README.md | 1 +
...construct-string-with-minimum-cost-easy.js | 44 +++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/3253-construct-string-with-minimum-cost-easy.js
diff --git a/README.md b/README.md
index eb3d79b4..20d7df59 100644
--- a/README.md
+++ b/README.md
@@ -2645,6 +2645,7 @@
3231|[Minimum Number of Increasing Subsequence to Be Removed](./solutions/3231-minimum-number-of-increasing-subsequence-to-be-removed.js)|Hard|
3237|[Alt and Tab Simulation](./solutions/3237-alt-and-tab-simulation.js)|Medium|
3247|[Number of Subsequences with Odd Sum](./solutions/3247-number-of-subsequences-with-odd-sum.js)|Medium|
+3253|[Construct String with Minimum Cost (Easy)](./solutions/3253-construct-string-with-minimum-cost-easy.js)|Medium|
3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard|
3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
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|
diff --git a/solutions/3253-construct-string-with-minimum-cost-easy.js b/solutions/3253-construct-string-with-minimum-cost-easy.js
new file mode 100644
index 00000000..3475d89e
--- /dev/null
+++ b/solutions/3253-construct-string-with-minimum-cost-easy.js
@@ -0,0 +1,44 @@
+/**
+ * 3253. Construct String with Minimum Cost (Easy)
+ * https://leetcode.com/problems/construct-string-with-minimum-cost-easy/
+ * Difficulty: Medium
+ *
+ * You are given a string target, an array of strings words, and an integer array costs,
+ * both arrays of the same length.
+ *
+ * Imagine an empty string s.
+ *
+ * You can perform the following operation any number of times (including zero):
+ * - Choose an index i in the range [0, words.length - 1].
+ * - Append words[i] to s.
+ * - The cost of operation is costs[i].
+ *
+ * Return the minimum cost to make s equal to target. If it's not possible, return -1.
+ */
+
+/**
+ * @param {string} target
+ * @param {string[]} words
+ * @param {number[]} costs
+ * @return {number}
+ */
+var minimumCost = function(target, words, costs) {
+ const n = target.length;
+ const dp = new Array(n + 1).fill(Infinity);
+ dp[0] = 0;
+
+ for (let i = 0; i < n; i++) {
+ if (dp[i] === Infinity) continue;
+
+ for (let j = 0; j < words.length; j++) {
+ const word = words[j];
+ const cost = costs[j];
+
+ if (i + word.length <= n && target.substring(i, i + word.length) === word) {
+ dp[i + word.length] = Math.min(dp[i + word.length], dp[i] + cost);
+ }
+ }
+ }
+
+ return dp[n] === Infinity ? -1 : dp[n];
+};
From cd64f786bd5d2163cf263cd498edaa8349a95dba Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 18 Jul 2025 23:29:59 -0500
Subject: [PATCH 892/994] Add solution #3263
---
README.md | 1 +
...3-convert-doubly-linked-list-to-array-i.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/3263-convert-doubly-linked-list-to-array-i.js
diff --git a/README.md b/README.md
index 20d7df59..b3a08e74 100644
--- a/README.md
+++ b/README.md
@@ -2646,6 +2646,7 @@
3237|[Alt and Tab Simulation](./solutions/3237-alt-and-tab-simulation.js)|Medium|
3247|[Number of Subsequences with Odd Sum](./solutions/3247-number-of-subsequences-with-odd-sum.js)|Medium|
3253|[Construct String with Minimum Cost (Easy)](./solutions/3253-construct-string-with-minimum-cost-easy.js)|Medium|
+3263|[Convert Doubly Linked List to Array I](./solutions/3263-convert-doubly-linked-list-to-array-i.js)|Easy|
3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard|
3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
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|
diff --git a/solutions/3263-convert-doubly-linked-list-to-array-i.js b/solutions/3263-convert-doubly-linked-list-to-array-i.js
new file mode 100644
index 00000000..63969081
--- /dev/null
+++ b/solutions/3263-convert-doubly-linked-list-to-array-i.js
@@ -0,0 +1,34 @@
+/**
+ * 3263. Convert Doubly Linked List to Array I
+ * https://leetcode.com/problems/convert-doubly-linked-list-to-array-i/
+ * Difficulty: Easy
+ *
+ * You are given the head of a doubly linked list, which contains nodes that have a next
+ * pointer and a previous pointer.
+ *
+ * Return an integer array which contains the elements of the linked list in order.
+ */
+
+/**
+ * // Definition for a _Node.
+ * function _Node(val,prev,next) {
+ * this.val = val;
+ * this.prev = prev;
+ * this.next = next;
+ * };
+ */
+/**
+ * @param {_Node} head
+ * @return {number[]}
+ */
+var toArray = function(head) {
+ const result = [];
+ let currentNode = head;
+
+ while (currentNode) {
+ result.push(currentNode.val);
+ currentNode = currentNode.next;
+ }
+
+ return result;
+};
From 3d1cfd5cc0ac0d7878dda12378344e44658190ae Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 18 Jul 2025 23:31:35 -0500
Subject: [PATCH 893/994] Add solution #3269
---
README.md | 1 +
...3269-constructing-two-increasing-arrays.js | 48 +++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/3269-constructing-two-increasing-arrays.js
diff --git a/README.md b/README.md
index b3a08e74..219ea491 100644
--- a/README.md
+++ b/README.md
@@ -2647,6 +2647,7 @@
3247|[Number of Subsequences with Odd Sum](./solutions/3247-number-of-subsequences-with-odd-sum.js)|Medium|
3253|[Construct String with Minimum Cost (Easy)](./solutions/3253-construct-string-with-minimum-cost-easy.js)|Medium|
3263|[Convert Doubly Linked List to Array I](./solutions/3263-convert-doubly-linked-list-to-array-i.js)|Easy|
+3269|[Constructing Two Increasing Arrays](./solutions/3269-constructing-two-increasing-arrays.js)|Hard|
3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard|
3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
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|
diff --git a/solutions/3269-constructing-two-increasing-arrays.js b/solutions/3269-constructing-two-increasing-arrays.js
new file mode 100644
index 00000000..d8db2331
--- /dev/null
+++ b/solutions/3269-constructing-two-increasing-arrays.js
@@ -0,0 +1,48 @@
+/**
+ * 3269. Constructing Two Increasing Arrays
+ * https://leetcode.com/problems/constructing-two-increasing-arrays/
+ * Difficulty: Hard
+ *
+ * Given 2 integer arrays nums1 and nums2 consisting only of 0 and 1, your task is to calculate
+ * the minimum possible largest number in arrays nums1 and nums2, after doing the following.
+ *
+ * Replace every 0 with an even positive integer and every 1 with an odd positive integer.
+ * After replacement, both arrays should be increasing and each integer should be used at most once.
+ *
+ * Return the minimum possible largest number after applying the changes.
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @return {number}
+ */
+var minLargest = function(nums1, nums2) {
+ const n1 = nums1.length;
+ const n2 = nums2.length;
+ const dp = new Array(n1 + 1).fill().map(() => new Array(n2 + 1).fill(-Infinity));
+
+ dp[0][0] = 0;
+
+ for (let i = 0; i < n1; i++) {
+ dp[i + 1][0] = getNextValue(dp[i][0], nums1[i]);
+ }
+ for (let j = 0; j < n2; j++) {
+ dp[0][j + 1] = getNextValue(dp[0][j], nums2[j]);
+ }
+ for (let i = 0; i < n1; i++) {
+ for (let j = 0; j < n2; j++) {
+ dp[i + 1][j + 1] = Math.min(
+ getNextValue(dp[i][j + 1], nums1[i]),
+ getNextValue(dp[i + 1][j], nums2[j])
+ );
+ }
+ }
+
+ return dp[n1][n2];
+
+ function getNextValue(currentValue, targetParity) {
+ const nextValue = currentValue + 1;
+ return nextValue % 2 === targetParity % 2 ? nextValue : nextValue + 1;
+ }
+};
From 399a17d9b7e9c29bfed37b2879e0ec557826f957 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 18 Jul 2025 23:35:12 -0500
Subject: [PATCH 894/994] Add solution #3279
---
README.md | 1 +
...-maximum-total-area-occupied-by-pistons.js | 65 +++++++++++++++++++
2 files changed, 66 insertions(+)
create mode 100644 solutions/3279-maximum-total-area-occupied-by-pistons.js
diff --git a/README.md b/README.md
index 219ea491..da938caf 100644
--- a/README.md
+++ b/README.md
@@ -2649,6 +2649,7 @@
3263|[Convert Doubly Linked List to Array I](./solutions/3263-convert-doubly-linked-list-to-array-i.js)|Easy|
3269|[Constructing Two Increasing Arrays](./solutions/3269-constructing-two-increasing-arrays.js)|Hard|
3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard|
+3279|[Maximum Total Area Occupied by Pistons](./solutions/3279-maximum-total-area-occupied-by-pistons.js)|Hard|
3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
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|
3307|[Find the K-th Character in String Game II](./solutions/3307-find-the-k-th-character-in-string-game-ii.js)|Hard|
diff --git a/solutions/3279-maximum-total-area-occupied-by-pistons.js b/solutions/3279-maximum-total-area-occupied-by-pistons.js
new file mode 100644
index 00000000..9c4801f5
--- /dev/null
+++ b/solutions/3279-maximum-total-area-occupied-by-pistons.js
@@ -0,0 +1,65 @@
+/**
+ * 3279. Maximum Total Area Occupied by Pistons
+ * https://leetcode.com/problems/maximum-total-area-occupied-by-pistons/
+ * Difficulty: Hard
+ *
+ * There are several pistons in an old car engine, and we want to calculate the maximum
+ * possible area under the pistons.
+ *
+ * You are given:
+ * - An integer height, representing the maximum height a piston can reach.
+ * - An integer array positions, where positions[i] is the current position of piston i,
+ * which is equal to the current area under it.
+ * - A string directions, where directions[i] is the current moving direction of piston
+ * i, 'U' for up, and 'D' for down.
+ *
+ * Each second:
+ * - Every piston moves in its current direction 1 unit. e.g., if the direction is up,
+ * positions[i] is incremented by 1.
+ * - If a piston has reached one of the ends, i.e., positions[i] == 0 or
+ * positions[i] == height, its direction will change.
+ *
+ * Return the maximum possible area under all the pistons.
+ */
+
+/**
+ * @param {number} height
+ * @param {number[]} positions
+ * @param {string} directions
+ * @return {number}
+ */
+var maxArea = function(height, positions, directions) {
+ const n = directions.length;
+ let upCount = directions.split('').filter(dir => dir === 'U').length;
+ let result = positions.reduce((sum, pos) => sum + pos, 0);
+ let currentArea = result;
+ const vertices = new Map();
+ vertices.set(0, 0);
+
+ for (let i = 0; i < n; i++) {
+ const direction = directions[i];
+ const position = positions[i];
+
+ if (direction === 'U') {
+ vertices.set(height - position, (vertices.get(height - position) || 0) - 1);
+ vertices.set(2 * height - position, (vertices.get(2 * height - position) || 0) + 1);
+ } else {
+ vertices.set(height + position, (vertices.get(height + position) || 0) - 1);
+ vertices.set(position, (vertices.get(position) || 0) + 1);
+ }
+ }
+
+ const sortedTimes = Array.from(vertices.keys()).sort((a, b) => a - b);
+ for (let i = 0; i < sortedTimes.length - 1; i++) {
+ const leftTime = sortedTimes[i];
+ const rightTime = sortedTimes[i + 1];
+
+ currentArea += (rightTime - leftTime) * (2 * upCount - n);
+ if (currentArea > result) {
+ result = currentArea;
+ }
+ upCount += vertices.get(rightTime) || 0;
+ }
+
+ return result;
+};
From 2f4aee315444e08edfb6f444a5f6b4d412807aab Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 18 Jul 2025 23:37:48 -0500
Subject: [PATCH 895/994] Add solution #3284
---
README.md | 1 +
.../3284-sum-of-consecutive-subarrays.js | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/3284-sum-of-consecutive-subarrays.js
diff --git a/README.md b/README.md
index da938caf..375e0ab9 100644
--- a/README.md
+++ b/README.md
@@ -2650,6 +2650,7 @@
3269|[Constructing Two Increasing Arrays](./solutions/3269-constructing-two-increasing-arrays.js)|Hard|
3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard|
3279|[Maximum Total Area Occupied by Pistons](./solutions/3279-maximum-total-area-occupied-by-pistons.js)|Hard|
+3284|[Sum of Consecutive Subarrays](./solutions/3284-sum-of-consecutive-subarrays.js)|Medium|
3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
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|
3307|[Find the K-th Character in String Game II](./solutions/3307-find-the-k-th-character-in-string-game-ii.js)|Hard|
diff --git a/solutions/3284-sum-of-consecutive-subarrays.js b/solutions/3284-sum-of-consecutive-subarrays.js
new file mode 100644
index 00000000..58d7fe8b
--- /dev/null
+++ b/solutions/3284-sum-of-consecutive-subarrays.js
@@ -0,0 +1,50 @@
+/**
+ * 3284. Sum of Consecutive Subarrays
+ * https://leetcode.com/problems/sum-of-consecutive-subarrays/
+ * Difficulty: Medium
+ *
+ * We call an array arr of length n consecutive if one of the following holds:
+ * - arr[i] - arr[i - 1] == 1 for all 1 <= i < n.
+ * - arr[i] - arr[i - 1] == -1 for all 1 <= i < n.
+ *
+ * The value of an array is the sum of its elements.
+ *
+ * For example, [3, 4, 5] is a consecutive array of value 12 and [9, 8] is another of
+ * value 17. While [3, 4, 3] and [8, 6] are not consecutive.
+ *
+ * Given an array of integers nums, return the sum of the values of all consecutive subarrays.
+ *
+ * Since the answer may be very large, return it modulo 109 + 7.
+ *
+ * Note that an array of length 1 is also considered consecutive.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var getSum = function(nums) {
+ const MOD = 1e9 + 7;
+ let result = nums[0];
+ let currentContribution = nums[0];
+ let leftBoundary = 0;
+ let previousDifference = 0;
+
+ for (let rightIndex = 1; rightIndex < nums.length; rightIndex++) {
+ const currentDifference = nums[rightIndex] - nums[rightIndex - 1];
+ if (Math.abs(currentDifference) !== 1) {
+ previousDifference = 0;
+ leftBoundary = rightIndex;
+ currentContribution = 0;
+ } else if (previousDifference !== currentDifference) {
+ currentContribution = nums[rightIndex - 1];
+ leftBoundary = rightIndex - 1;
+ previousDifference = currentDifference;
+ }
+
+ currentContribution += nums[rightIndex] * (rightIndex - leftBoundary + 1);
+ result = (result + currentContribution) % MOD;
+ }
+
+ return result;
+};
From 56afaf8c98b4a91948b8a9000e12d4e8310d59de Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 18 Jul 2025 23:39:00 -0500
Subject: [PATCH 896/994] Add solution #3294
---
README.md | 1 +
...-convert-doubly-linked-list-to-array-ii.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/3294-convert-doubly-linked-list-to-array-ii.js
diff --git a/README.md b/README.md
index 375e0ab9..f8d18887 100644
--- a/README.md
+++ b/README.md
@@ -2651,6 +2651,7 @@
3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard|
3279|[Maximum Total Area Occupied by Pistons](./solutions/3279-maximum-total-area-occupied-by-pistons.js)|Hard|
3284|[Sum of Consecutive Subarrays](./solutions/3284-sum-of-consecutive-subarrays.js)|Medium|
+3294|[Convert Doubly Linked List to Array II](./solutions/3294-convert-doubly-linked-list-to-array-ii.js)|Medium|
3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
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|
3307|[Find the K-th Character in String Game II](./solutions/3307-find-the-k-th-character-in-string-game-ii.js)|Hard|
diff --git a/solutions/3294-convert-doubly-linked-list-to-array-ii.js b/solutions/3294-convert-doubly-linked-list-to-array-ii.js
new file mode 100644
index 00000000..42fb0c28
--- /dev/null
+++ b/solutions/3294-convert-doubly-linked-list-to-array-ii.js
@@ -0,0 +1,39 @@
+/**
+ * 3294. Convert Doubly Linked List to Array II
+ * https://leetcode.com/problems/convert-doubly-linked-list-to-array-ii/
+ * Difficulty: Medium
+ *
+ * You are given an arbitrary node from a doubly linked list, which contains nodes that
+ * have a next pointer and a previous pointer.
+ *
+ * Return an integer array which contains the elements of the linked list in order.
+ */
+
+/**
+ * // Definition for a _Node.
+ * function _Node(val,prev,next) {
+ * this.val = val;
+ * this.prev = prev;
+ * this.next = next;
+ * };
+ */
+/**
+ * @param {_Node} node
+ * @return {number[]}
+ */
+var toArray = function(node) {
+ const result = [];
+ let headNode = node;
+
+ while (headNode.prev) {
+ headNode = headNode.prev;
+ }
+
+ let currentNode = headNode;
+ while (currentNode) {
+ result.push(currentNode.val);
+ currentNode = currentNode.next;
+ }
+
+ return result;
+};
From 8270bda9781313ec68f848e96270863cd3fa97d1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 18 Jul 2025 23:41:40 -0500
Subject: [PATCH 897/994] Add solution #3299
---
README.md | 1 +
.../3299-sum-of-consecutive-subsequences.js | 48 +++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/3299-sum-of-consecutive-subsequences.js
diff --git a/README.md b/README.md
index f8d18887..583e5e6a 100644
--- a/README.md
+++ b/README.md
@@ -2652,6 +2652,7 @@
3279|[Maximum Total Area Occupied by Pistons](./solutions/3279-maximum-total-area-occupied-by-pistons.js)|Hard|
3284|[Sum of Consecutive Subarrays](./solutions/3284-sum-of-consecutive-subarrays.js)|Medium|
3294|[Convert Doubly Linked List to Array II](./solutions/3294-convert-doubly-linked-list-to-array-ii.js)|Medium|
+3299|[Sum of Consecutive Subsequences](./solutions/3299-sum-of-consecutive-subsequences.js)|Hard|
3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
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|
3307|[Find the K-th Character in String Game II](./solutions/3307-find-the-k-th-character-in-string-game-ii.js)|Hard|
diff --git a/solutions/3299-sum-of-consecutive-subsequences.js b/solutions/3299-sum-of-consecutive-subsequences.js
new file mode 100644
index 00000000..84340f66
--- /dev/null
+++ b/solutions/3299-sum-of-consecutive-subsequences.js
@@ -0,0 +1,48 @@
+/**
+ * 3299. Sum of Consecutive Subsequences
+ * https://leetcode.com/problems/sum-of-consecutive-subsequences/
+ * Difficulty: Hard
+ *
+ * We call an array arr of length n consecutive if one of the following holds:
+ * - arr[i] - arr[i - 1] == 1 for all 1 <= i < n.
+ * - arr[i] - arr[i - 1] == -1 for all 1 <= i < n.
+ *
+ * The value of an array is the sum of its elements.
+ *
+ * For example, [3, 4, 5] is a consecutive array of value 12 and [9, 8] is another of
+ * value 17. While [3, 4, 3] and [8, 6] are not consecutive.
+ *
+ * Given an array of integers nums, return the sum of the values of all consecutive
+ * non-empty subsequences.
+ *
+ * Since the answer may be very large, return it modulo 109 + 7.
+ *
+ * Note that an array of length 1 is also considered consecutive.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var getSum = function(nums) {
+ const MOD = 1e9 + 7;
+ const singleElementSum = nums.reduce((sum, num) => (sum + num) % MOD, 0);
+
+ return (getSubSum(nums, 1) + getSubSum(nums, -1) + singleElementSum) % MOD;
+
+ function getSubSum(nums, direction) {
+ const count = new Array(100002).fill(0);
+ const sum = new Array(100002).fill(0);
+ let result = 0;
+
+ for (const num of nums) {
+ const prev = num - direction;
+ const sumAtNum = (sum[prev] + num * (count[prev] + 1)) % MOD;
+ result = (result + sumAtNum - num + MOD) % MOD;
+ sum[num] = (sum[num] + sumAtNum) % MOD;
+ count[num] = (count[num] + count[prev] + 1) % MOD;
+ }
+
+ return result;
+ }
+};
From 3b76e9e4627593d7284c8976c5c79c987b6177dd Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 18 Jul 2025 23:48:06 -0500
Subject: [PATCH 898/994] Add solution #3313
---
README.md | 1 +
...3313-find-the-last-marked-nodes-in-tree.js | 89 +++++++++++++++++++
2 files changed, 90 insertions(+)
create mode 100644 solutions/3313-find-the-last-marked-nodes-in-tree.js
diff --git a/README.md b/README.md
index 583e5e6a..7859341b 100644
--- a/README.md
+++ b/README.md
@@ -2656,6 +2656,7 @@
3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
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|
3307|[Find the K-th Character in String Game II](./solutions/3307-find-the-k-th-character-in-string-game-ii.js)|Hard|
+3313|[Find the Last Marked Nodes in Tree](./solutions/3313-find-the-last-marked-nodes-in-tree.js)|Hard|
3330|[Find the Original Typed String I](./solutions/3330-find-the-original-typed-string-i.js)|Easy|
3333|[Find the Original Typed String II](./solutions/3333-find-the-original-typed-string-ii.js)|Hard|
3335|[Total Characters in String After Transformations I](./solutions/3335-total-characters-in-string-after-transformations-i.js)|Medium|
diff --git a/solutions/3313-find-the-last-marked-nodes-in-tree.js b/solutions/3313-find-the-last-marked-nodes-in-tree.js
new file mode 100644
index 00000000..e72ce1f6
--- /dev/null
+++ b/solutions/3313-find-the-last-marked-nodes-in-tree.js
@@ -0,0 +1,89 @@
+/**
+ * 3313. Find the Last Marked Nodes in Tree
+ * https://leetcode.com/problems/find-the-last-marked-nodes-in-tree/
+ * Difficulty: Hard
+ *
+ * There exists an undirected tree with n nodes numbered 0 to n - 1. You are given a 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.
+ *
+ * Initially, all nodes are unmarked. After every second, you mark all unmarked nodes which
+ * have at least one marked node adjacent to them.
+ *
+ * Return an array nodes where nodes[i] is the last node to get marked in the tree, if you
+ * mark node i at time t = 0. If nodes[i] has multiple answers for any node i, you can
+ * choose any one answer.
+ */
+
+/**
+ * @param {number[][]} edges
+ * @return {number[]}
+ */
+var lastMarkedNodes = function(edges) {
+ const n = edges.length + 1;
+ const tree = new Array(n).fill().map(() => []);
+
+ for (const [u, v] of edges) {
+ tree[u].push(v);
+ tree[v].push(u);
+ }
+
+ const diameterEndpointA = findFarthestNode(0);
+ const diameterEndpointB = findFarthestNode(diameterEndpointA);
+ const distancesFromA = getDistances(diameterEndpointA);
+ const distancesFromB = getDistances(diameterEndpointB);
+ const result = [];
+
+ for (let i = 0; i < n; i++) {
+ result.push(distancesFromA[i] > distancesFromB[i] ? diameterEndpointA : diameterEndpointB);
+ }
+
+ return result;
+
+ function findFarthestNode(startNode) {
+ const visited = new Array(n).fill(false);
+ visited[startNode] = true;
+ const stack = [[startNode, 0]];
+ let maxSteps = 0;
+ let farthestNode = startNode;
+
+ while (stack.length > 0) {
+ const [node, steps] = stack.pop();
+
+ if (steps > maxSteps) {
+ farthestNode = node;
+ maxSteps = steps;
+ }
+
+ for (const neighbor of tree[node]) {
+ if (!visited[neighbor]) {
+ visited[neighbor] = true;
+ stack.push([neighbor, steps + 1]);
+ }
+ }
+ }
+
+ return farthestNode;
+ }
+
+ function getDistances(startNode) {
+ const visited = new Array(n).fill(false);
+ visited[startNode] = true;
+ const stack = [[startNode, 0]];
+ const distances = new Array(n);
+
+ while (stack.length > 0) {
+ const [node, steps] = stack.pop();
+ distances[node] = steps;
+
+ for (const neighbor of tree[node]) {
+ if (!visited[neighbor]) {
+ visited[neighbor] = true;
+ stack.push([neighbor, steps + 1]);
+ }
+ }
+ }
+
+ return distances;
+ }
+};
From 49644f38c80583e32b68c90f760eadaf8312bd8f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 18 Jul 2025 23:50:25 -0500
Subject: [PATCH 899/994] Add solution #3323
---
README.md | 1 +
...-connected-groups-by-inserting-interval.js | 71 +++++++++++++++++++
2 files changed, 72 insertions(+)
create mode 100644 solutions/3323-minimize-connected-groups-by-inserting-interval.js
diff --git a/README.md b/README.md
index 7859341b..5e6015ff 100644
--- a/README.md
+++ b/README.md
@@ -2657,6 +2657,7 @@
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|
3307|[Find the K-th Character in String Game II](./solutions/3307-find-the-k-th-character-in-string-game-ii.js)|Hard|
3313|[Find the Last Marked Nodes in Tree](./solutions/3313-find-the-last-marked-nodes-in-tree.js)|Hard|
+3323|[Minimize Connected Groups by Inserting Interval](./solutions/3323-minimize-connected-groups-by-inserting-interval.js)|Medium|
3330|[Find the Original Typed String I](./solutions/3330-find-the-original-typed-string-i.js)|Easy|
3333|[Find the Original Typed String II](./solutions/3333-find-the-original-typed-string-ii.js)|Hard|
3335|[Total Characters in String After Transformations I](./solutions/3335-total-characters-in-string-after-transformations-i.js)|Medium|
diff --git a/solutions/3323-minimize-connected-groups-by-inserting-interval.js b/solutions/3323-minimize-connected-groups-by-inserting-interval.js
new file mode 100644
index 00000000..739e066b
--- /dev/null
+++ b/solutions/3323-minimize-connected-groups-by-inserting-interval.js
@@ -0,0 +1,71 @@
+/**
+ * 3323. Minimize Connected Groups by Inserting Interval
+ * https://leetcode.com/problems/minimize-connected-groups-by-inserting-interval/
+ * Difficulty: Medium
+ *
+ * You are given a 2D array intervals, where intervals[i] = [starti, endi] represents the
+ * start and the end of interval i. You are also given an integer k.
+ *
+ * You must add exactly one new interval [startnew, endnew] to the array such that:
+ * - The length of the new interval, endnew - startnew, is at most k.
+ * - After adding, the number of connected groups in intervals is minimized.
+ *
+ * A connected group of intervals is a maximal collection of intervals that, when considered
+ * together, cover a continuous range from the smallest point to the largest point with no gaps
+ * between them. Here are some examples:
+ * - A group of intervals [[1, 2], [2, 5], [3, 3]] is connected because together they cover the
+ * range from 1 to 5 without any gaps.
+ * - However, a group of intervals [[1, 2], [3, 4]] is not connected because the segment (2, 3)
+ * is not covered.
+ *
+ * Return the minimum number of connected groups after adding exactly one new interval to the array.
+ */
+
+/**
+ * @param {number[][]} intervals
+ * @param {number} k
+ * @return {number}
+ */
+var minConnectedGroups = function(intervals, k) {
+ intervals.sort((a, b) => a[0] - b[0]);
+
+ const groupStarts = [intervals[0][0]];
+ const groupEnds = [intervals[0][1]];
+
+ for (let i = 1; i < intervals.length; i++) {
+ const [start, end] = intervals[i];
+
+ if (start > groupEnds[groupEnds.length - 1]) {
+ groupStarts.push(start);
+ groupEnds.push(end);
+ } else if (start <= groupEnds[groupEnds.length - 1] && groupEnds[groupEnds.length - 1] < end) {
+ groupEnds[groupEnds.length - 1] = end;
+ }
+ }
+
+ let maxGroupsToMerge = 0;
+ for (let i = 0; i < groupEnds.length; i++) {
+ const searchTarget = groupEnds[i] + k + 1;
+ const rightmostIndex = binarySearchLeft(groupStarts, searchTarget) - 1;
+ const groupsCanReach = rightmostIndex - i;
+ maxGroupsToMerge = Math.max(maxGroupsToMerge, groupsCanReach);
+ }
+
+ return groupStarts.length - maxGroupsToMerge;
+
+ function binarySearchLeft(arr, target) {
+ let left = 0;
+ let right = arr.length;
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (arr[mid] < target) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+
+ return left;
+ }
+};
From 896cd7e849a6c5ea08138c1703295e9cd4f56c77 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 18 Jul 2025 23:52:26 -0500
Subject: [PATCH 900/994] Add solution #3329
---
README.md | 1 +
...bstrings-with-k-frequency-characters-ii.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/3329-count-substrings-with-k-frequency-characters-ii.js
diff --git a/README.md b/README.md
index 5e6015ff..27a997dd 100644
--- a/README.md
+++ b/README.md
@@ -2658,6 +2658,7 @@
3307|[Find the K-th Character in String Game II](./solutions/3307-find-the-k-th-character-in-string-game-ii.js)|Hard|
3313|[Find the Last Marked Nodes in Tree](./solutions/3313-find-the-last-marked-nodes-in-tree.js)|Hard|
3323|[Minimize Connected Groups by Inserting Interval](./solutions/3323-minimize-connected-groups-by-inserting-interval.js)|Medium|
+3329|[Count Substrings With K-Frequency Characters II](./solutions/3329-count-substrings-with-k-frequency-characters-ii.js)|Hard|
3330|[Find the Original Typed String I](./solutions/3330-find-the-original-typed-string-i.js)|Easy|
3333|[Find the Original Typed String II](./solutions/3333-find-the-original-typed-string-ii.js)|Hard|
3335|[Total Characters in String After Transformations I](./solutions/3335-total-characters-in-string-after-transformations-i.js)|Medium|
diff --git a/solutions/3329-count-substrings-with-k-frequency-characters-ii.js b/solutions/3329-count-substrings-with-k-frequency-characters-ii.js
new file mode 100644
index 00000000..e6fb73df
--- /dev/null
+++ b/solutions/3329-count-substrings-with-k-frequency-characters-ii.js
@@ -0,0 +1,34 @@
+/**
+ * 3329. Count Substrings With K-Frequency Characters II
+ * https://leetcode.com/problems/count-substrings-with-k-frequency-characters-ii/
+ * Difficulty: Hard
+ *
+ * Given a string s and an integer k, return the total number of substrings of s where at
+ * least one character appears at least k times.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} k
+ * @return {number}
+ */
+var numberOfSubstrings = function(s, k) {
+ const n = s.length;
+ const map = new Array(26).fill(0);
+ let result = 0;
+ let leftPointer = 0;
+
+ for (let rightPointer = 0; rightPointer < n; rightPointer++) {
+ const rightCharIndex = s.charCodeAt(rightPointer) - 97;
+ map[rightCharIndex]++;
+
+ while (map[rightCharIndex] >= k) {
+ result += n - rightPointer;
+ const leftCharIndex = s.charCodeAt(leftPointer) - 97;
+ map[leftCharIndex]--;
+ leftPointer++;
+ }
+ }
+
+ return result;
+};
From 9de1f43769ebb87e9baae55225f3b8342d058b7d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 18 Jul 2025 23:54:49 -0500
Subject: [PATCH 901/994] Add solution #3339
---
README.md | 1 +
.../3339-find-the-number-of-k-even-arrays.js | 46 +++++++++++++++++++
2 files changed, 47 insertions(+)
create mode 100644 solutions/3339-find-the-number-of-k-even-arrays.js
diff --git a/README.md b/README.md
index 27a997dd..95d4fbcd 100644
--- a/README.md
+++ b/README.md
@@ -2663,6 +2663,7 @@
3333|[Find the Original Typed String II](./solutions/3333-find-the-original-typed-string-ii.js)|Hard|
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|
+3339|[Find the Number of K-Even Arrays](./solutions/3339-find-the-number-of-k-even-arrays.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/3339-find-the-number-of-k-even-arrays.js b/solutions/3339-find-the-number-of-k-even-arrays.js
new file mode 100644
index 00000000..3b499ff4
--- /dev/null
+++ b/solutions/3339-find-the-number-of-k-even-arrays.js
@@ -0,0 +1,46 @@
+/**
+ * 3339. Find the Number of K-Even Arrays
+ * https://leetcode.com/problems/find-the-number-of-k-even-arrays/
+ * Difficulty: Medium
+ *
+ * You are given three integers n, m, and k.
+ *
+ * An array arr is called k-even if there are exactly k indices such that, for each
+ * of these indices i (0 <= i < n - 1):
+ * - (arr[i] * arr[i + 1]) - arr[i] - arr[i + 1] is even.
+ *
+ * Return the number of possible k-even arrays of size n where all elements are in the range [1, m].
+ *
+ * Since the answer may be very large, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} m
+ * @param {number} k
+ * @return {number}
+ */
+var countOfArrays = function(n, m, k) {
+ const MOD = 1e9 + 7;
+ const oddCount = Math.floor((m + 1) / 2);
+ const evenCount = Math.floor(m / 2);
+ const dpOdd = new Array(k + 1).fill(0);
+ const dpEven = new Array(k + 1).fill(0);
+
+ dpOdd[0] = oddCount;
+ dpEven[0] = evenCount;
+
+ for (let position = 1; position < n; position++) {
+ for (let evenPairs = k; evenPairs >= 0; evenPairs--) {
+ const tempOdd = dpOdd[evenPairs];
+ dpOdd[evenPairs] = ((dpEven[evenPairs] + dpOdd[evenPairs]) * oddCount) % MOD;
+ if (evenPairs > 0) {
+ dpEven[evenPairs] = ((dpEven[evenPairs - 1] + tempOdd) * evenCount) % MOD;
+ } else {
+ dpEven[evenPairs] = (tempOdd * evenCount) % MOD;
+ }
+ }
+ }
+
+ return (dpOdd[k] + dpEven[k]) % MOD;
+};
From 527ddc26e3053c35e8a2461653377fe74eadd2d1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 19 Jul 2025 23:57:51 -0500
Subject: [PATCH 902/994] Add solution #3344
---
README.md | 1 +
solutions/3344-maximum-sized-array.js | 55 +++++++++++++++++++++++++++
2 files changed, 56 insertions(+)
create mode 100644 solutions/3344-maximum-sized-array.js
diff --git a/README.md b/README.md
index 95d4fbcd..b42f7f00 100644
--- a/README.md
+++ b/README.md
@@ -2667,6 +2667,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|
+3344|[Maximum Sized Array](./solutions/3344-maximum-sized-array.js)|Medium|
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|
diff --git a/solutions/3344-maximum-sized-array.js b/solutions/3344-maximum-sized-array.js
new file mode 100644
index 00000000..76a47f3f
--- /dev/null
+++ b/solutions/3344-maximum-sized-array.js
@@ -0,0 +1,55 @@
+/**
+ * 3344. Maximum Sized Array
+ * https://leetcode.com/problems/maximum-sized-array/
+ * Difficulty: Medium
+ *
+ * Given a positive integer s, let A be a 3D array of dimensions n × n × n, where each
+ * element A[i][j][k] is defined as:
+ * - A[i][j][k] = i * (j OR k), where 0 <= i, j, k < n.
+ *
+ * Return the maximum possible value of n such that the sum of all elements in array A
+ * does not exceed s.
+ */
+
+/**
+ * @param {number} s
+ * @return {number}
+ */
+var maxSizedArray = function(s) {
+ let left = Math.floor(Math.pow(4 * s, 0.2) / 2);
+ let right = Math.floor(Math.sqrt(2 * Math.sqrt(s))) + 2;
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+
+ if (calculateArraySum(mid) > s) {
+ right = mid;
+ } else {
+ left = mid + 1;
+ }
+ }
+
+ return left - 1;
+
+ function getBitOnesCount(n, bitPosition) {
+ const blockSize = 1 << bitPosition;
+ const cycleSize = 1 << (bitPosition + 1);
+ const fullCycles = Math.floor(n / cycleSize);
+ const remainder = n % cycleSize;
+
+ return fullCycles * blockSize + (remainder > blockSize ? remainder - blockSize : 0);
+ }
+
+ function calculateArraySum(n) {
+ let totalSum = 0;
+
+ for (let bitPos = 0; (1 << bitPos) < n; bitPos++) {
+ const onesCount = getBitOnesCount(n, bitPos);
+ const zerosCount = n - onesCount;
+
+ totalSum += (n * n - zerosCount * zerosCount) * (1 << bitPos);
+ }
+
+ return totalSum * (n - 1) * n / 2;
+ }
+};
From 06c09069083d492e66515977f9b31254d686a032 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 20 Jul 2025 23:36:25 -0500
Subject: [PATCH 903/994] Add solution #3353
---
README.md | 1 +
solutions/3353-minimum-total-operations.js | 32 ++++++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/3353-minimum-total-operations.js
diff --git a/README.md b/README.md
index b42f7f00..41361d1e 100644
--- a/README.md
+++ b/README.md
@@ -2668,6 +2668,7 @@
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|
3344|[Maximum Sized Array](./solutions/3344-maximum-sized-array.js)|Medium|
+3353|[Minimum Total Operations](./solutions/3353-minimum-total-operations.js)|Easy|
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|
diff --git a/solutions/3353-minimum-total-operations.js b/solutions/3353-minimum-total-operations.js
new file mode 100644
index 00000000..dcda0262
--- /dev/null
+++ b/solutions/3353-minimum-total-operations.js
@@ -0,0 +1,32 @@
+/**
+ * 3353. Minimum Total Operations
+ * https://leetcode.com/problems/minimum-total-operations/
+ * Difficulty: Easy
+ *
+ * Given an array of integers nums, you can perform any number of operations on this array.
+ *
+ * In each operation, you can:
+ * - Choose a prefix of the array.
+ * - Choose an integer k (which can be negative) and add k to each element in the chosen prefix.
+ *
+ * A prefix of an array is a subarray that starts from the beginning of the array and extends to
+ * any point within it.
+ *
+ * Return the minimum number of operations required to make all elements in arr equal.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minOperations = function(nums) {
+ let result = 0;
+
+ for (let i = 1; i < nums.length; i++) {
+ if (nums[i] !== nums[i - 1]) {
+ result++;
+ }
+ }
+
+ return result;
+};
From d2ae3bcd05be65a0ca7f572fcab324507dc32ed8 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 20 Jul 2025 23:39:41 -0500
Subject: [PATCH 904/994] Add solution #3359
---
README.md | 1 +
...matrices-with-maximum-element-at-most-k.js | 60 +++++++++++++++++++
2 files changed, 61 insertions(+)
create mode 100644 solutions/3359-find-sorted-submatrices-with-maximum-element-at-most-k.js
diff --git a/README.md b/README.md
index 41361d1e..b954317f 100644
--- a/README.md
+++ b/README.md
@@ -2671,6 +2671,7 @@
3353|[Minimum Total Operations](./solutions/3353-minimum-total-operations.js)|Easy|
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|
+3359|[Find Sorted Submatrices With Maximum Element at Most K](./solutions/3359-find-sorted-submatrices-with-maximum-element-at-most-k.js)|Hard|
3362|[Zero Array Transformation III](./solutions/3362-zero-array-transformation-iii.js)|Medium|
3372|[Maximize the Number of Target Nodes After Connecting Trees I](./solutions/3372-maximize-the-number-of-target-nodes-after-connecting-trees-i.js)|Medium|
3373|[Maximize the Number of Target Nodes After Connecting Trees II](./solutions/3373-maximize-the-number-of-target-nodes-after-connecting-trees-ii.js)|Hard|
diff --git a/solutions/3359-find-sorted-submatrices-with-maximum-element-at-most-k.js b/solutions/3359-find-sorted-submatrices-with-maximum-element-at-most-k.js
new file mode 100644
index 00000000..666abb66
--- /dev/null
+++ b/solutions/3359-find-sorted-submatrices-with-maximum-element-at-most-k.js
@@ -0,0 +1,60 @@
+/**
+ * 3359. Find Sorted Submatrices With Maximum Element at Most K
+ * https://leetcode.com/problems/find-sorted-submatrices-with-maximum-element-at-most-k/
+ * Difficulty: Hard
+ *
+ * You are given a 2D matrix grid of size m x n. You are also given a non-negative integer k.
+ *
+ * Return the number of submatrices of grid that satisfy the following conditions:
+ * - The maximum element in the submatrix less than or equal to k.
+ * - Each row in the submatrix is sorted in non-increasing order.
+ *
+ * A submatrix (x1, y1, x2, y2) is a matrix that forms by choosing all cells grid[x][y]
+ * where x1 <= x <= x2 and y1 <= y <= y2.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @param {number} k
+ * @return {number}
+ */
+var countSubmatrices = function(grid, k) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const groups = new Array(cols).fill().map(() => []);
+ const sums = new Array(cols).fill(0);
+ let result = 0;
+
+ for (let row = 0; row < rows; row++) {
+ const rowLengths = new Array(cols).fill(0);
+
+ for (let col = 0; col < cols; col++) {
+ if (grid[row][col] <= k) {
+ rowLengths[col] = (col > 0 && grid[row][col - 1] >= grid[row][col])
+ ? rowLengths[col - 1] + 1
+ : 1;
+ let lengthCount = 1;
+ const stack = groups[col];
+
+ while (stack.length > 0 && stack[stack.length - 1][0] > rowLengths[col]) {
+ const [stackLength, stackCount] = stack.pop();
+ lengthCount += stackCount;
+ sums[col] -= stackLength * stackCount;
+ }
+
+ if (stack.length === 0 || stack[stack.length - 1][0] !== rowLengths[col]) {
+ stack.push([rowLengths[col], 0]);
+ }
+
+ stack[stack.length - 1][1] += lengthCount;
+ sums[col] += rowLengths[col] * lengthCount;
+ result += sums[col];
+ } else {
+ groups[col].length = 0;
+ sums[col] = 0;
+ }
+ }
+ }
+
+ return result;
+};
From b74ca4169765a45f08984664c611958d26f5db08 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 20 Jul 2025 23:58:34 -0500
Subject: [PATCH 905/994] Add solution #3369
---
README.md | 1 +
...3369-design-an-array-statistics-tracker.js | 139 ++++++++++++++++++
2 files changed, 140 insertions(+)
create mode 100644 solutions/3369-design-an-array-statistics-tracker.js
diff --git a/README.md b/README.md
index b954317f..c9ba71a4 100644
--- a/README.md
+++ b/README.md
@@ -2673,6 +2673,7 @@
3356|[Zero Array Transformation II](./solutions/3356-zero-array-transformation-ii.js)|Medium|
3359|[Find Sorted Submatrices With Maximum Element at Most K](./solutions/3359-find-sorted-submatrices-with-maximum-element-at-most-k.js)|Hard|
3362|[Zero Array Transformation III](./solutions/3362-zero-array-transformation-iii.js)|Medium|
+3369|[Design an Array Statistics Tracker](./solutions/3369-design-an-array-statistics-tracker.js)|Hard|
3372|[Maximize the Number of Target Nodes After Connecting Trees I](./solutions/3372-maximize-the-number-of-target-nodes-after-connecting-trees-i.js)|Medium|
3373|[Maximize the Number of Target Nodes After Connecting Trees II](./solutions/3373-maximize-the-number-of-target-nodes-after-connecting-trees-ii.js)|Hard|
3375|[Minimum Operations to Make Array Values Equal to K](./solutions/3375-minimum-operations-to-make-array-values-equal-to-k.js)|Easy|
diff --git a/solutions/3369-design-an-array-statistics-tracker.js b/solutions/3369-design-an-array-statistics-tracker.js
new file mode 100644
index 00000000..4cbeec69
--- /dev/null
+++ b/solutions/3369-design-an-array-statistics-tracker.js
@@ -0,0 +1,139 @@
+/**
+ * 3369. Design an Array Statistics Tracker
+ * https://leetcode.com/problems/design-an-array-statistics-tracker/
+ * Difficulty: Hard
+ *
+ * Design a data structure that keeps track of the values in it and answers some queries regarding
+ * their mean, median, and mode.
+ *
+ * Implement the StatisticsTracker class.
+ * - StatisticsTracker(): Initialize the StatisticsTracker object with an empty array.
+ * - void addNumber(int number): Add number to the data structure.
+ * - void removeFirstAddedNumber(): Remove the earliest added number from the data structure.
+ * - int getMean(): Return the floored mean of the numbers in the data structure.
+ * - int getMedian(): Return the median of the numbers in the data structure.
+ * - int getMode(): Return the mode of the numbers in the data structure. If there are multiple
+ * modes, return the smallest one.
+ *
+ * Note:
+ * - The mean of an array is the sum of all the values divided by the number of values in the array.
+ * - The median of an array is the middle element of the array when it is sorted in non-decreasing
+ * order. If there are two choices for a median, the larger of the two values is taken.
+ * - The mode of an array is the element that appears most often in the array.
+ */
+
+var StatisticsTracker = function() {
+ this.deque = [];
+ this.count = new Map();
+ this.frequencyHeap = new PriorityQueue((a, b) => {
+ if (a[0] !== b[0]) return b[0] - a[0];
+ return a[1] - b[1];
+ });
+ this.total = 0;
+
+ this.smallHeap = new PriorityQueue((a, b) => b - a);
+ this.largeHeap = new PriorityQueue((a, b) => a - b);
+ this.largeRemove = new Map();
+ this.smallRemove = new Map();
+ this.balance = 0;
+};
+
+/**
+ * @param {number} number
+ * @return {void}
+ */
+StatisticsTracker.prototype.addNumber = function(number) {
+ this.deque.push(number);
+ this.total += number;
+
+ const currentCount = this.count.get(number) || 0;
+ this.count.set(number, currentCount + 1);
+ this.frequencyHeap.enqueue([this.count.get(number), number]);
+
+ if (this.largeHeap.isEmpty() || number >= this.largeHeap.front()) {
+ this.largeHeap.enqueue(number);
+ this.balance += 1;
+ } else {
+ this.smallHeap.enqueue(number);
+ this.balance -= 1;
+ }
+
+ this.keepBalance();
+};
+
+/**
+ * @return {void}
+ */
+StatisticsTracker.prototype.removeFirstAddedNumber = function() {
+ const value = this.deque.shift();
+
+ const currentCount = this.count.get(value);
+ this.count.set(value, currentCount - 1);
+ if (this.count.get(value) > 0) {
+ this.frequencyHeap.enqueue([this.count.get(value), value]);
+ }
+
+ this.total -= value;
+
+ if (!this.largeHeap.isEmpty() && value >= this.largeHeap.front()) {
+ this.largeRemove.set(value, (this.largeRemove.get(value) || 0) + 1);
+ this.balance -= 1;
+ } else {
+ this.smallRemove.set(value, (this.smallRemove.get(value) || 0) + 1);
+ this.balance += 1;
+ }
+
+ this.keepBalance();
+};
+
+/**
+ * @return {void}
+ */
+StatisticsTracker.prototype.keepBalance = function() {
+ if (this.balance > 1) {
+ this.smallHeap.enqueue(this.largeHeap.dequeue());
+ this.balance -= 2;
+ }
+ if (this.balance < 0) {
+ this.largeHeap.enqueue(this.smallHeap.dequeue());
+ this.balance += 2;
+ }
+
+ while (!this.smallHeap.isEmpty() && (this.smallRemove.get(this.smallHeap.front()) || 0) > 0) {
+ const removed = this.smallHeap.dequeue();
+ this.smallRemove.set(removed, this.smallRemove.get(removed) - 1);
+ }
+
+ while (!this.largeHeap.isEmpty() && (this.largeRemove.get(this.largeHeap.front()) || 0) > 0) {
+ const removed = this.largeHeap.dequeue();
+ this.largeRemove.set(removed, this.largeRemove.get(removed) - 1);
+ }
+};
+
+/**
+ * @return {number}
+ */
+StatisticsTracker.prototype.getMean = function() {
+ return Math.floor(this.total / this.deque.length);
+};
+
+/**
+ * @return {number}
+ */
+StatisticsTracker.prototype.getMedian = function() {
+ return this.largeHeap.front();
+};
+
+/**
+ * @return {number}
+ */
+StatisticsTracker.prototype.getMode = function() {
+ while (!this.frequencyHeap.isEmpty()) {
+ const [frequency, value] = this.frequencyHeap.front();
+ if (this.count.get(value) === frequency) {
+ return value;
+ } else {
+ this.frequencyHeap.dequeue();
+ }
+ }
+};
From 2903ccff693e09dde75bf80aa26b09ea8eee7211 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 21 Jul 2025 00:01:59 -0500
Subject: [PATCH 906/994] Add solution #3383
---
README.md | 1 +
...3383-minimum-runes-to-add-to-cast-spell.js | 95 +++++++++++++++++++
2 files changed, 96 insertions(+)
create mode 100644 solutions/3383-minimum-runes-to-add-to-cast-spell.js
diff --git a/README.md b/README.md
index c9ba71a4..81892fa8 100644
--- a/README.md
+++ b/README.md
@@ -2677,6 +2677,7 @@
3372|[Maximize the Number of Target Nodes After Connecting Trees I](./solutions/3372-maximize-the-number-of-target-nodes-after-connecting-trees-i.js)|Medium|
3373|[Maximize the Number of Target Nodes After Connecting Trees II](./solutions/3373-maximize-the-number-of-target-nodes-after-connecting-trees-ii.js)|Hard|
3375|[Minimum Operations to Make Array Values Equal to K](./solutions/3375-minimum-operations-to-make-array-values-equal-to-k.js)|Easy|
+3383|[Minimum Runes to Add to Cast Spell](./solutions/3383-minimum-runes-to-add-to-cast-spell.js)|Hard|
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|
3396|[Minimum Number of Operations to Make Elements in Array Distinct](./solutions/3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy|
diff --git a/solutions/3383-minimum-runes-to-add-to-cast-spell.js b/solutions/3383-minimum-runes-to-add-to-cast-spell.js
new file mode 100644
index 00000000..c03f08ee
--- /dev/null
+++ b/solutions/3383-minimum-runes-to-add-to-cast-spell.js
@@ -0,0 +1,95 @@
+/**
+ * 3383. Minimum Runes to Add to Cast Spell
+ * https://leetcode.com/problems/minimum-runes-to-add-to-cast-spell/
+ * Difficulty: Hard
+ *
+ * Alice has just graduated from wizard school, and wishes to cast a magic spell to celebrate.
+ * The magic spell contains certain focus points where magic needs to be concentrated, and some
+ * of these focus points contain magic crystals which serve as the spell's energy source. Focus
+ * points can be linked through directed runes, which channel magic flow from one focus point
+ * to another.
+ *
+ * You are given a integer n denoting the number of focus points and an array of integers crystals
+ * where crystals[i] indicates a focus point which holds a magic crystal. You are also given two
+ * integer arrays flowFrom and flowTo, which represent the existing directed runes. The ith rune
+ * allows magic to freely flow from focus point flowFrom[i] to focus point flowTo[i].
+ *
+ * You need to find the number of directed runes Alice must add to her spell, such that each
+ * focus point either:
+ * - Contains a magic crystal.
+ * - Receives magic flow from another focus point.
+ *
+ * Return the minimum number of directed runes that she should add.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[]} crystals
+ * @param {number[]} flowFrom
+ * @param {number[]} flowTo
+ * @return {number}
+ */
+var minRunesToAdd = function(n, crystals, flowFrom, flowTo) {
+ const graph = Array.from({ length: n }, () => []);
+ const reverseGraph = Array.from({ length: n }, () => []);
+
+ for (let i = 0; i < flowFrom.length; i++) {
+ graph[flowFrom[i]].push(flowTo[i]);
+ reverseGraph[flowTo[i]].push(flowFrom[i]);
+ }
+
+ const visited = new Array(n).fill(false);
+ const finishOrder = [];
+
+ const dfsFinish = (node) => {
+ if (visited[node]) return;
+ visited[node] = true;
+ for (const neighbor of graph[node]) {
+ dfsFinish(neighbor);
+ }
+ finishOrder.push(node);
+ };
+
+ for (let i = 0; i < n; i++) {
+ dfsFinish(i);
+ }
+
+ const componentId = new Array(n).fill(-1);
+ let componentCount = 0;
+
+ const dfsComponent = (node, id) => {
+ if (componentId[node] >= 0) return;
+ componentId[node] = id;
+ for (const neighbor of reverseGraph[node]) {
+ dfsComponent(neighbor, id);
+ }
+ };
+
+ for (let i = n - 1; i >= 0; i--) {
+ const node = finishOrder[i];
+ if (componentId[node] < 0) {
+ dfsComponent(node, componentCount++);
+ }
+ }
+
+ const hasIncoming = new Array(componentCount).fill(false);
+ for (let i = 0; i < flowFrom.length; i++) {
+ if (componentId[flowFrom[i]] !== componentId[flowTo[i]]) {
+ hasIncoming[componentId[flowTo[i]]] = true;
+ }
+ }
+
+ const hasCrystal = new Array(componentCount).fill(false);
+ for (const crystal of crystals) {
+ hasCrystal[componentId[crystal]] = true;
+ }
+
+ let result = 0;
+ for (let i = 0; i < componentCount; i++) {
+ if (!hasIncoming[i] && !hasCrystal[i]) {
+ result++;
+ }
+ }
+
+ return result;
+};
From 3f64b5101230c8daab181dcd68292ed9ab713e76 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 21 Jul 2025 23:54:44 -0500
Subject: [PATCH 907/994] Add solution #3385
---
README.md | 1 +
.../3385-minimum-time-to-break-locks-ii.js | 88 +++++++++++++++++++
2 files changed, 89 insertions(+)
create mode 100644 solutions/3385-minimum-time-to-break-locks-ii.js
diff --git a/README.md b/README.md
index 81892fa8..eeb3610b 100644
--- a/README.md
+++ b/README.md
@@ -2678,6 +2678,7 @@
3373|[Maximize the Number of Target Nodes After Connecting Trees II](./solutions/3373-maximize-the-number-of-target-nodes-after-connecting-trees-ii.js)|Hard|
3375|[Minimum Operations to Make Array Values Equal to K](./solutions/3375-minimum-operations-to-make-array-values-equal-to-k.js)|Easy|
3383|[Minimum Runes to Add to Cast Spell](./solutions/3383-minimum-runes-to-add-to-cast-spell.js)|Hard|
+3385|[Minimum Time to Break Locks II](./solutions/3385-minimum-time-to-break-locks-ii.js)|Hard|
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|
3396|[Minimum Number of Operations to Make Elements in Array Distinct](./solutions/3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy|
diff --git a/solutions/3385-minimum-time-to-break-locks-ii.js b/solutions/3385-minimum-time-to-break-locks-ii.js
new file mode 100644
index 00000000..24541298
--- /dev/null
+++ b/solutions/3385-minimum-time-to-break-locks-ii.js
@@ -0,0 +1,88 @@
+/**
+ * 3385. Minimum Time to Break Locks II
+ * https://leetcode.com/problems/minimum-time-to-break-locks-ii/
+ * Difficulty: Hard
+ *
+ * Bob is stuck in a dungeon and must break n locks, each requiring some amount of energy
+ * to break. The required energy for each lock is stored in an array called strength where
+ * strength[i] indicates the energy needed to break the ith lock.
+ *
+ * To break a lock, Bob uses a sword with the following characteristics:
+ * - The initial energy of the sword is 0.
+ * - The initial factor X by which the energy of the sword increases is 1.
+ * - Every minute, the energy of the sword increases by the current factor X.
+ * - To break the ith lock, the energy of the sword must reach at least strength[i].
+ * - After breaking a lock, the energy of the sword resets to 0, and the factor X increases by 1.
+ *
+ * Your task is to determine the minimum time in minutes required for Bob to break all n locks
+ * and escape the dungeon.
+ *
+ * Return the minimum time required for Bob to break all n locks.
+ */
+
+/**
+ * @param {number[]} strength
+ * @return {number}
+ */
+var findMinimumTime = function(strength) {
+ const n = strength.length;
+ const cost = Array.from({ length: n + 1 }, () => new Array(n + 1).fill(0));
+
+ for (let i = 0; i < n; i++) {
+ for (let j = 0; j < n; j++) {
+ cost[i + 1][j + 1] = Math.floor((strength[i] + j) / (j + 1));
+ }
+ }
+
+ const rowPotential = new Array(n + 1).fill(0);
+ const colPotential = new Array(n + 1).fill(0);
+ const assignment = new Array(n + 1).fill(0);
+ const parent = new Array(n + 1).fill(0);
+
+ for (let row = 1; row <= n; row++) {
+ assignment[0] = row;
+ let col = 0;
+ const minCol = new Array(n + 1).fill(Number.MAX_SAFE_INTEGER);
+ const visited = new Array(n + 1).fill(false);
+
+ do {
+ visited[col] = true;
+ const currentRow = assignment[col];
+ let delta = Number.MAX_SAFE_INTEGER;
+ let nextCol;
+
+ for (let j = 1; j <= n; j++) {
+ if (!visited[j]) {
+ const reducedCost = cost[currentRow][j] - rowPotential[currentRow] - colPotential[j];
+ if (reducedCost < minCol[j]) {
+ minCol[j] = reducedCost;
+ parent[j] = col;
+ }
+ if (minCol[j] < delta) {
+ delta = minCol[j];
+ nextCol = j;
+ }
+ }
+ }
+
+ for (let j = 0; j <= n; j++) {
+ if (visited[j]) {
+ rowPotential[assignment[j]] += delta;
+ colPotential[j] -= delta;
+ } else {
+ minCol[j] -= delta;
+ }
+ }
+
+ col = nextCol;
+ } while (assignment[col] !== 0);
+
+ do {
+ const prevCol = parent[col];
+ assignment[col] = assignment[prevCol];
+ col = prevCol;
+ } while (col);
+ }
+
+ return -colPotential[0];
+};
From 40ac182fcc6191be8fe2c9588e5071fce8d4d18b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 21 Jul 2025 23:58:40 -0500
Subject: [PATCH 908/994] Add solution #3400
---
README.md | 1 +
...-of-matching-indices-after-right-shifts.js | 37 +++++++++++++++++++
2 files changed, 38 insertions(+)
create mode 100644 solutions/3400-maximum-number-of-matching-indices-after-right-shifts.js
diff --git a/README.md b/README.md
index eeb3610b..096664dd 100644
--- a/README.md
+++ b/README.md
@@ -2683,6 +2683,7 @@
3394|[Check if Grid can be Cut into Sections](./solutions/3394-check-if-grid-can-be-cut-into-sections.js)|Medium|
3396|[Minimum Number of Operations to Make Elements in Array Distinct](./solutions/3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy|
3397|[Maximum Number of Distinct Elements After Operations](./solutions/3397-maximum-number-of-distinct-elements-after-operations.js)|Medium|
+3400|[Maximum Number of Matching Indices After Right Shifts](./solutions/3400-maximum-number-of-matching-indices-after-right-shifts.js)|Medium|
3402|[Minimum Operations to Make Columns Strictly Increasing](./solutions/3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy|
3403|[Find the Lexicographically Largest String From the Box I](./solutions/3403-find-the-lexicographically-largest-string-from-the-box-i.js)|Medium|
3405|[Count the Number of Arrays with K Matching Adjacent Elements](./solutions/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.js)|Hard|
diff --git a/solutions/3400-maximum-number-of-matching-indices-after-right-shifts.js b/solutions/3400-maximum-number-of-matching-indices-after-right-shifts.js
new file mode 100644
index 00000000..6d510880
--- /dev/null
+++ b/solutions/3400-maximum-number-of-matching-indices-after-right-shifts.js
@@ -0,0 +1,37 @@
+/**
+ * 3400. Maximum Number of Matching Indices After Right Shifts
+ * https://leetcode.com/problems/maximum-number-of-matching-indices-after-right-shifts/
+ * Difficulty: Medium
+ *
+ * You are given two integer arrays, nums1 and nums2, of the same length.
+ *
+ * An index i is considered matching if nums1[i] == nums2[i].
+ *
+ * Return the maximum number of matching indices after performing any number of right shifts
+ * on nums1.
+ *
+ * A right shift is defined as shifting the element at index i to index (i + 1) % n, for
+ * all indices.
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @return {number}
+ */
+var maximumMatchingIndices = function(nums1, nums2) {
+ const n = nums1.length;
+ let result = 0;
+
+ for (let shift = 0; shift < n; shift++) {
+ let currentMatches = 0;
+ for (let i = 0; i < n; i++) {
+ if (nums1[(i - shift + n) % n] === nums2[i]) {
+ currentMatches++;
+ }
+ }
+ result = Math.max(result, currentMatches);
+ }
+
+ return result;
+};
From 441383a0cae0d002baab63848d040ccdd5d753bc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 22 Jul 2025 23:47:13 -0500
Subject: [PATCH 909/994] Add solution #3391
---
README.md | 1 +
...ry-matrix-with-efficient-layer-tracking.js | 65 +++++++++++++++++++
2 files changed, 66 insertions(+)
create mode 100644 solutions/3391-design-a-3d-binary-matrix-with-efficient-layer-tracking.js
diff --git a/README.md b/README.md
index 096664dd..38470fa1 100644
--- a/README.md
+++ b/README.md
@@ -2679,6 +2679,7 @@
3375|[Minimum Operations to Make Array Values Equal to K](./solutions/3375-minimum-operations-to-make-array-values-equal-to-k.js)|Easy|
3383|[Minimum Runes to Add to Cast Spell](./solutions/3383-minimum-runes-to-add-to-cast-spell.js)|Hard|
3385|[Minimum Time to Break Locks II](./solutions/3385-minimum-time-to-break-locks-ii.js)|Hard|
+3391|[Design a 3D Binary Matrix with Efficient Layer Tracking](./solutions/3391-design-a-3d-binary-matrix-with-efficient-layer-tracking.js)|Medium|
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|
3396|[Minimum Number of Operations to Make Elements in Array Distinct](./solutions/3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy|
diff --git a/solutions/3391-design-a-3d-binary-matrix-with-efficient-layer-tracking.js b/solutions/3391-design-a-3d-binary-matrix-with-efficient-layer-tracking.js
new file mode 100644
index 00000000..f24ee5f1
--- /dev/null
+++ b/solutions/3391-design-a-3d-binary-matrix-with-efficient-layer-tracking.js
@@ -0,0 +1,65 @@
+/**
+ * 3391. Design a 3D Binary Matrix with Efficient Layer Tracking
+ * https://leetcode.com/problems/design-a-3d-binary-matrix-with-efficient-layer-tracking/
+ * Difficulty: Medium
+ *
+ * You are given a n x n x n binary 3D array matrix.
+ *
+ * Implement the Matrix3D class:
+ * - Matrix3D(int n) Initializes the object with the 3D binary array matrix, where all elements
+ * are initially set to 0.
+ * - void setCell(int x, int y, int z) Sets the value at matrix[x][y][z] to 1.
+ * - void unsetCell(int x, int y, int z) Sets the value at matrix[x][y][z] to 0.
+ * - int largestMatrix() Returns the index x where matrix[x] contains the most number of 1's.
+ * If there are multiple such indices, return the largest x.
+ */
+
+/**
+ * @param {number} n
+ */
+var Matrix3D = function(n) {
+ this.n = n;
+ this.matrix = new Set();
+ this.layerCounts = new Array(n).fill(0);
+};
+
+/**
+ * @param {number} x
+ * @param {number} y
+ * @param {number} z
+ * @return {void}
+ */
+Matrix3D.prototype.setCell = function(x, y, z) {
+ const key = `${x},${y},${z}`;
+ if (!this.matrix.has(key)) {
+ this.matrix.add(key);
+ this.layerCounts[x]++;
+ }
+};
+
+/**
+ * @param {number} x
+ * @param {number} y
+ * @param {number} z
+ * @return {void}
+ */
+Matrix3D.prototype.unsetCell = function(x, y, z) {
+ const key = `${x},${y},${z}`;
+ if (this.matrix.has(key)) {
+ this.matrix.delete(key);
+ this.layerCounts[x]--;
+ }
+};
+
+/**
+ * @return {number}
+ */
+Matrix3D.prototype.largestMatrix = function() {
+ const maxCount = Math.max(...this.layerCounts);
+ for (let i = this.n - 1; i >= 0; i--) {
+ if (this.layerCounts[i] === maxCount) {
+ return i;
+ }
+ }
+ return this.n - 1;
+};
From 16f7fa795af34f95cda919288238955bc3f6e6ee Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 22 Jul 2025 23:49:25 -0500
Subject: [PATCH 910/994] Add solution #3406
---
README.md | 1 +
...phically-largest-string-from-the-box-ii.js | 52 +++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 solutions/3406-find-the-lexicographically-largest-string-from-the-box-ii.js
diff --git a/README.md b/README.md
index 38470fa1..6622541f 100644
--- a/README.md
+++ b/README.md
@@ -2688,6 +2688,7 @@
3402|[Minimum Operations to Make Columns Strictly Increasing](./solutions/3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy|
3403|[Find the Lexicographically Largest String From the Box I](./solutions/3403-find-the-lexicographically-largest-string-from-the-box-i.js)|Medium|
3405|[Count the Number of Arrays with K Matching Adjacent Elements](./solutions/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.js)|Hard|
+3406|[Find the Lexicographically Largest String From the Box II](./solutions/3406-find-the-lexicographically-largest-string-from-the-box-ii.js)|Hard|
3423|[Maximum Difference Between Adjacent Elements in a Circular Array](./solutions/3423-maximum-difference-between-adjacent-elements-in-a-circular-array.js)|Easy|
3439|[Reschedule Meetings for Maximum Free Time I](./solutions/3439-reschedule-meetings-for-maximum-free-time-i.js)|Medium|
3440|[Reschedule Meetings for Maximum Free Time II](./solutions/3440-reschedule-meetings-for-maximum-free-time-ii.js)|Medium|
diff --git a/solutions/3406-find-the-lexicographically-largest-string-from-the-box-ii.js b/solutions/3406-find-the-lexicographically-largest-string-from-the-box-ii.js
new file mode 100644
index 00000000..86021b16
--- /dev/null
+++ b/solutions/3406-find-the-lexicographically-largest-string-from-the-box-ii.js
@@ -0,0 +1,52 @@
+/**
+ * 3406. Find the Lexicographically Largest String From the Box II
+ * https://leetcode.com/problems/find-the-lexicographically-largest-string-from-the-box-ii/
+ * Difficulty: Hard
+ *
+ * You are given a string word, and an integer numFriends.
+ *
+ * Alice is organizing a game for her numFriends friends. There are multiple rounds in the game,
+ * where in each round:
+ * - word is split into numFriends non-empty strings, such that no previous round has had the
+ * exact same split.
+ * - All the split words are put into a box.
+ *
+ * Find the lexicographically largest string from the box after all the rounds are finished.
+ *
+ * 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.
+ *
+ * If the first min(a.length, b.length) characters do not differ, then the shorter string is the
+ * lexicographically smaller one.
+ */
+
+/**
+ * @param {string} word
+ * @param {number} numFriends
+ * @return {string}
+ */
+var answerString = function(word, numFriends) {
+ if (numFriends === 1) return word;
+ const n = word.length;
+ const maxLength = n - numFriends + 1;
+
+ const pairs = [];
+ for (let i = 0; i < n - 1; i++) {
+ pairs.push(word[i] + word[i + 1]);
+ }
+ const maxPair = pairs.reduce((a, b) => a > b ? a : b);
+ let result = word[n - 1];
+ let index = -1;
+
+ while (index < n) {
+ index = word.indexOf(maxPair, index + 1);
+ if (index === -1) break;
+ const candidate = word.substring(index, index + maxLength);
+ if (candidate > result) {
+ result = candidate;
+ }
+ }
+
+ return result;
+};
From 0d04ea5cca70ca493efd98490a87b02e2870ca85 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 23 Jul 2025 23:45:24 -0500
Subject: [PATCH 911/994] Add solution #3416
---
README.md | 1 +
...bsequences-with-a-unique-middle-mode-ii.js | 107 ++++++++++++++++++
2 files changed, 108 insertions(+)
create mode 100644 solutions/3416-subsequences-with-a-unique-middle-mode-ii.js
diff --git a/README.md b/README.md
index 6622541f..f3e03a0d 100644
--- a/README.md
+++ b/README.md
@@ -2689,6 +2689,7 @@
3403|[Find the Lexicographically Largest String From the Box I](./solutions/3403-find-the-lexicographically-largest-string-from-the-box-i.js)|Medium|
3405|[Count the Number of Arrays with K Matching Adjacent Elements](./solutions/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.js)|Hard|
3406|[Find the Lexicographically Largest String From the Box II](./solutions/3406-find-the-lexicographically-largest-string-from-the-box-ii.js)|Hard|
+3416|[Subsequences with a Unique Middle Mode II](./solutions/3416-subsequences-with-a-unique-middle-mode-ii.js)|Hard|
3423|[Maximum Difference Between Adjacent Elements in a Circular Array](./solutions/3423-maximum-difference-between-adjacent-elements-in-a-circular-array.js)|Easy|
3439|[Reschedule Meetings for Maximum Free Time I](./solutions/3439-reschedule-meetings-for-maximum-free-time-i.js)|Medium|
3440|[Reschedule Meetings for Maximum Free Time II](./solutions/3440-reschedule-meetings-for-maximum-free-time-ii.js)|Medium|
diff --git a/solutions/3416-subsequences-with-a-unique-middle-mode-ii.js b/solutions/3416-subsequences-with-a-unique-middle-mode-ii.js
new file mode 100644
index 00000000..154e3e73
--- /dev/null
+++ b/solutions/3416-subsequences-with-a-unique-middle-mode-ii.js
@@ -0,0 +1,107 @@
+/**
+ * 3416. Subsequences with a Unique Middle Mode II
+ * https://leetcode.com/problems/subsequences-with-a-unique-middle-mode-ii/
+ * Difficulty: Hard
+ *
+ * Given an integer array nums, find the number of subsequences of size 5 of nums with
+ * a unique middle mode.
+ *
+ * Since the answer may be very large, return it modulo 109 + 7.
+ *
+ * A mode of a sequence of numbers is defined as the element that appears the maximum number
+ * of times in the sequence.
+ *
+ * A sequence of numbers contains a unique mode if it has only one mode.
+ *
+ * A sequence of numbers seq of size 5 contains a unique middle mode if the middle element
+ * (seq[2]) is a unique mode.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var subsequencesWithMiddleMode = function(nums) {
+ const MOD = 1e9 + 7;
+ const HALF = (MOD + 1) / 2;
+ const [compressedNums, uniqueCount] = compress(nums);
+ const totalCounts = new Array(uniqueCount).fill(0);
+ compressedNums.forEach(id => totalCounts[id]++);
+
+ const result = countValid(compressedNums, totalCounts, true);
+ compressedNums.reverse();
+
+ return add(result, countValid(compressedNums, totalCounts, false));
+
+ function mul(x, y) {
+ return Number((BigInt(x) * BigInt(y)) % BigInt(MOD));
+ }
+
+ function add(x, y) {
+ return (x + y) % MOD;
+ }
+
+ function sub(x, y) {
+ return (x - y + MOD) % MOD;
+ }
+
+ function choose2(n) {
+ return mul(mul(n, n - 1), HALF);
+ }
+
+ function compress(arr) {
+ const valueMap = new Map();
+ let nextId = 0;
+ arr.forEach(val => !valueMap.has(val) && valueMap.set(val, nextId++));
+ return [arr.map(val => valueMap.get(val)), nextId];
+ }
+
+ function countValid(sequence, counts, includeEqual) {
+ const length = sequence.length;
+ const seenCounts = new Array(uniqueCount).fill(0);
+ let result = 0;
+ let squareSum = 0;
+ let weightedSum = 0;
+ let weightedSquareSum = 0;
+
+ counts.forEach(count => squareSum = add(squareSum, mul(count, count)));
+
+ for (let pos = 0; pos < length; pos++) {
+ const valueId = sequence[pos];
+ let remaining = counts[valueId] - seenCounts[valueId];
+ const newSquareSum = sub(squareSum, mul(remaining, remaining));
+ const newWeightedSum = sub(weightedSum, mul(remaining, seenCounts[valueId]));
+ const newWeightedSquareSum = sub(
+ weightedSquareSum,
+ mul(mul(remaining, remaining), seenCounts[valueId])
+ );
+ const suffixSize = length - pos - remaining;
+ const prefixSize = pos - seenCounts[valueId];
+
+ let contribution = mul(sub(mul(suffixSize, suffixSize), newSquareSum), prefixSize);
+ contribution = sub(contribution, mul(mul(2, suffixSize), newWeightedSum));
+ contribution = add(contribution, mul(2, newWeightedSquareSum));
+ contribution = mul(contribution, mul(seenCounts[valueId], HALF));
+ result = add(result, contribution);
+ result = add(result, mul(choose2(seenCounts[valueId]), choose2(suffixSize)));
+
+ remaining--;
+ result = add(result, mul(choose2(seenCounts[valueId]), mul(remaining, suffixSize)));
+
+ if (includeEqual) {
+ result = add(result, mul(mul(seenCounts[valueId], prefixSize), mul(remaining, suffixSize)));
+ result = add(result, mul(choose2(seenCounts[valueId]), choose2(remaining)));
+ }
+
+ seenCounts[valueId]++;
+ squareSum = add(newSquareSum, mul(remaining, remaining));
+ weightedSum = add(newWeightedSum, mul(remaining, seenCounts[valueId]));
+ weightedSquareSum = add(
+ newWeightedSquareSum,
+ mul(mul(remaining, remaining), seenCounts[valueId])
+ );
+ }
+
+ return result;
+ }
+};
From 94520479d903a20a0782eb29fa231ce6fed35887 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 23 Jul 2025 23:50:43 -0500
Subject: [PATCH 912/994] Add solution #3422
---
README.md | 1 +
...rations-to-make-subarray-elements-equal.js | 81 +++++++++++++++++++
2 files changed, 82 insertions(+)
create mode 100644 solutions/3422-minimum-operations-to-make-subarray-elements-equal.js
diff --git a/README.md b/README.md
index f3e03a0d..608345f5 100644
--- a/README.md
+++ b/README.md
@@ -2690,6 +2690,7 @@
3405|[Count the Number of Arrays with K Matching Adjacent Elements](./solutions/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.js)|Hard|
3406|[Find the Lexicographically Largest String From the Box II](./solutions/3406-find-the-lexicographically-largest-string-from-the-box-ii.js)|Hard|
3416|[Subsequences with a Unique Middle Mode II](./solutions/3416-subsequences-with-a-unique-middle-mode-ii.js)|Hard|
+3422|[Minimum Operations to Make Subarray Elements Equal](./solutions/3422-minimum-operations-to-make-subarray-elements-equal.js)|Medium|
3423|[Maximum Difference Between Adjacent Elements in a Circular Array](./solutions/3423-maximum-difference-between-adjacent-elements-in-a-circular-array.js)|Easy|
3439|[Reschedule Meetings for Maximum Free Time I](./solutions/3439-reschedule-meetings-for-maximum-free-time-i.js)|Medium|
3440|[Reschedule Meetings for Maximum Free Time II](./solutions/3440-reschedule-meetings-for-maximum-free-time-ii.js)|Medium|
diff --git a/solutions/3422-minimum-operations-to-make-subarray-elements-equal.js b/solutions/3422-minimum-operations-to-make-subarray-elements-equal.js
new file mode 100644
index 00000000..7ea4cb51
--- /dev/null
+++ b/solutions/3422-minimum-operations-to-make-subarray-elements-equal.js
@@ -0,0 +1,81 @@
+/**
+ * 3422. Minimum Operations to Make Subarray Elements Equal
+ * https://leetcode.com/problems/minimum-operations-to-make-subarray-elements-equal/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums and an integer k. You can perform the following operation
+ * any number of times:
+ * - Increase or decrease any element of nums by 1.
+ *
+ * Return the minimum number of operations required to ensure that at least one subarray of size
+ * k in nums has all elements equal.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var minOperations = function(nums, k) {
+ const n = nums.length;
+ const minHeap = new PriorityQueue((a, b) => a[0] < b[0] ? -1 : 1);
+ const maxHeap = new PriorityQueue((a, b) => a[0] > b[0] ? -1 : 1);
+ const maxHeapSize = Math.ceil(k / 2);
+ const minHeapSize = k - maxHeapSize;
+
+ let total = 0;
+ for (let i = 0; i < k; i++) {
+ total += nums[i];
+ maxHeap.enqueue([nums[i], i]);
+ }
+
+ let minSum = 0;
+ const minHeapIndices = new Set();
+ for (let i = 0; i < minHeapSize; i++) {
+ const [num, idx] = maxHeap.dequeue();
+ minSum += num;
+ minHeap.enqueue([num, idx]);
+ minHeapIndices.add(idx);
+ }
+
+ let maxSum = total - minSum;
+ let median = maxHeap.front()[0];
+ let result = Math.abs(median * maxHeapSize - maxSum) + Math.abs(minSum - median * minHeapSize);
+
+ for (let i = k; i < n; i++) {
+ const num = nums[i];
+ const leftOut = i - k;
+ total += num - nums[leftOut];
+
+ while (!minHeap.isEmpty() && minHeap.front()[1] <= leftOut) minHeap.dequeue();
+ while (!maxHeap.isEmpty() && maxHeap.front()[1] <= leftOut) maxHeap.dequeue();
+
+ if (minHeapIndices.has(leftOut)) {
+ minHeapIndices.delete(leftOut);
+ minSum -= nums[leftOut];
+ maxHeap.enqueue([num, i]);
+ const [newNum, newIdx] = maxHeap.dequeue();
+ minSum += newNum;
+ minHeap.enqueue([newNum, newIdx]);
+ minHeapIndices.add(newIdx);
+ } else {
+ minHeap.enqueue([num, i]);
+ minSum += num;
+ minHeapIndices.add(i);
+ const [newNum, newIdx] = minHeap.dequeue();
+ minHeapIndices.delete(newIdx);
+ minSum -= newNum;
+ maxHeap.enqueue([newNum, newIdx]);
+ }
+
+ maxSum = total - minSum;
+ while (!maxHeap.isEmpty() && maxHeap.front()[1] <= leftOut) maxHeap.dequeue();
+ median = maxHeap.front()[0];
+ result = Math.min(
+ result,
+ Math.abs(median * maxHeapSize - maxSum) + Math.abs(minSum - median * minHeapSize)
+ );
+ }
+
+ return result;
+};
From e5ca5ef795055646333fd8c6746302f29a5db6a0 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 23 Jul 2025 23:52:39 -0500
Subject: [PATCH 913/994] Add solution #3431
---
README.md | 1 +
...1-minimum-unlocked-indices-to-sort-nums.js | 44 +++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/3431-minimum-unlocked-indices-to-sort-nums.js
diff --git a/README.md b/README.md
index 608345f5..70372c7f 100644
--- a/README.md
+++ b/README.md
@@ -2692,6 +2692,7 @@
3416|[Subsequences with a Unique Middle Mode II](./solutions/3416-subsequences-with-a-unique-middle-mode-ii.js)|Hard|
3422|[Minimum Operations to Make Subarray Elements Equal](./solutions/3422-minimum-operations-to-make-subarray-elements-equal.js)|Medium|
3423|[Maximum Difference Between Adjacent Elements in a Circular Array](./solutions/3423-maximum-difference-between-adjacent-elements-in-a-circular-array.js)|Easy|
+3431|[Minimum Unlocked Indices to Sort Nums](./solutions/3431-minimum-unlocked-indices-to-sort-nums.js)|Medium|
3439|[Reschedule Meetings for Maximum Free Time I](./solutions/3439-reschedule-meetings-for-maximum-free-time-i.js)|Medium|
3440|[Reschedule Meetings for Maximum Free Time II](./solutions/3440-reschedule-meetings-for-maximum-free-time-ii.js)|Medium|
3442|[Maximum Difference Between Even and Odd Frequency I](./solutions/3442-maximum-difference-between-even-and-odd-frequency-i.js)|Easy|
diff --git a/solutions/3431-minimum-unlocked-indices-to-sort-nums.js b/solutions/3431-minimum-unlocked-indices-to-sort-nums.js
new file mode 100644
index 00000000..b36cc9b1
--- /dev/null
+++ b/solutions/3431-minimum-unlocked-indices-to-sort-nums.js
@@ -0,0 +1,44 @@
+/**
+ * 3431. Minimum Unlocked Indices to Sort Nums
+ * https://leetcode.com/problems/minimum-unlocked-indices-to-sort-nums/
+ * Difficulty: Medium
+ *
+ * You are given an array nums consisting of integers between 1 and 3, and a binary array
+ * locked of the same size.
+ *
+ * We consider nums sortable if it can be sorted using adjacent swaps, where a swap between
+ * two indices i and i + 1 is allowed if nums[i] - nums[i + 1] == 1 and locked[i] == 0.
+ *
+ * In one operation, you can unlock any index i by setting locked[i] to 0.
+ *
+ * Return the minimum number of operations needed to make nums sortable. If it is not possible
+ * to make nums sortable, return -1.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[]} locked
+ * @return {number}
+ */
+var minUnlockedIndices = function(nums, locked) {
+ let currentMax = 1;
+ let locks = 0;
+ let result = 0;
+
+ for (let i = 0; i < nums.length; i++) {
+ if (currentMax < nums[i]) {
+ currentMax = nums[i];
+ locks = 0;
+ }
+ if (nums[i] < currentMax) {
+ if (nums[i] + 1 < currentMax) {
+ return -1;
+ }
+ result += locks;
+ locks = 0;
+ }
+ locks += locked[i];
+ }
+
+ return result;
+};
From d12594ace519247ee22dfb63799abdbabe694ec7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 23 Jul 2025 23:54:16 -0500
Subject: [PATCH 914/994] Add solution #3437
---
README.md | 1 +
solutions/3437-permutations-iii.js | 48 ++++++++++++++++++++++++++++++
2 files changed, 49 insertions(+)
create mode 100644 solutions/3437-permutations-iii.js
diff --git a/README.md b/README.md
index 70372c7f..ec7677b1 100644
--- a/README.md
+++ b/README.md
@@ -2693,6 +2693,7 @@
3422|[Minimum Operations to Make Subarray Elements Equal](./solutions/3422-minimum-operations-to-make-subarray-elements-equal.js)|Medium|
3423|[Maximum Difference Between Adjacent Elements in a Circular Array](./solutions/3423-maximum-difference-between-adjacent-elements-in-a-circular-array.js)|Easy|
3431|[Minimum Unlocked Indices to Sort Nums](./solutions/3431-minimum-unlocked-indices-to-sort-nums.js)|Medium|
+3437|[Permutations III](./solutions/3437-permutations-iii.js)|Medium|
3439|[Reschedule Meetings for Maximum Free Time I](./solutions/3439-reschedule-meetings-for-maximum-free-time-i.js)|Medium|
3440|[Reschedule Meetings for Maximum Free Time II](./solutions/3440-reschedule-meetings-for-maximum-free-time-ii.js)|Medium|
3442|[Maximum Difference Between Even and Odd Frequency I](./solutions/3442-maximum-difference-between-even-and-odd-frequency-i.js)|Easy|
diff --git a/solutions/3437-permutations-iii.js b/solutions/3437-permutations-iii.js
new file mode 100644
index 00000000..ae3e4b8f
--- /dev/null
+++ b/solutions/3437-permutations-iii.js
@@ -0,0 +1,48 @@
+/**
+ * 3437. Permutations III
+ * https://leetcode.com/problems/permutations-iii/
+ * Difficulty: Medium
+ *
+ * Given an integer n, an alternating permutation is a permutation of the first n positive
+ * integers such that no two adjacent elements are both odd or both even.
+ *
+ * Return all such alternating permutations sorted in lexicographical order.
+ */
+
+/**
+ * @param {number} n
+ * @return {number[][]}
+ */
+var permute = function(n) {
+ const result = [];
+ const current = [];
+ const used = new Array(n + 1).fill(false);
+
+ backtrack(current, used, result, n);
+
+ return result;
+
+ function backtrack(current, used, result, n) {
+ if (current.length === n) {
+ result.push([...current]);
+ return;
+ }
+
+ for (let num = 1; num <= n; num++) {
+ if (used[num]) continue;
+
+ if (current.length > 0) {
+ const lastNum = current[current.length - 1];
+ if ((lastNum % 2 === 0 && num % 2 === 0) || (lastNum % 2 === 1 && num % 2 === 1)) {
+ continue;
+ }
+ }
+
+ current.push(num);
+ used[num] = true;
+ backtrack(current, used, result, n);
+ current.pop();
+ used[num] = false;
+ }
+ }
+};
From 08cfa78629de31178ae66bfb82320bcefb468d2e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 23 Jul 2025 23:55:52 -0500
Subject: [PATCH 915/994] Add solution #3450
---
README.md | 1 +
...3450-maximum-students-on-a-single-bench.js | 37 +++++++++++++++++++
2 files changed, 38 insertions(+)
create mode 100644 solutions/3450-maximum-students-on-a-single-bench.js
diff --git a/README.md b/README.md
index ec7677b1..aa67d2b7 100644
--- a/README.md
+++ b/README.md
@@ -2699,6 +2699,7 @@
3442|[Maximum Difference Between Even and Odd Frequency I](./solutions/3442-maximum-difference-between-even-and-odd-frequency-i.js)|Easy|
3443|[Maximum Manhattan Distance After K Changes](./solutions/3443-maximum-manhattan-distance-after-k-changes.js)|Medium|
3445|[Maximum Difference Between Even and Odd Frequency II](./solutions/3445-maximum-difference-between-even-and-odd-frequency-ii.js)|Hard|
+3450|[Maximum Students on a Single Bench](./solutions/3450-maximum-students-on-a-single-bench.js)|Easy|
3452|[Sum of Good Numbers](./solutions/3452-sum-of-good-numbers.js)|Easy|
3461|[Check If Digits Are Equal in String After Operations I](./solutions/3461-check-if-digits-are-equal-in-string-after-operations-i.js)|Easy|
3462|[Maximum Sum With at Most K Elements](./solutions/3462-maximum-sum-with-at-most-k-elements.js)|Medium|
diff --git a/solutions/3450-maximum-students-on-a-single-bench.js b/solutions/3450-maximum-students-on-a-single-bench.js
new file mode 100644
index 00000000..34d3af04
--- /dev/null
+++ b/solutions/3450-maximum-students-on-a-single-bench.js
@@ -0,0 +1,37 @@
+/**
+ * 3450. Maximum Students on a Single Bench
+ * https://leetcode.com/problems/maximum-students-on-a-single-bench/
+ * Difficulty: Easy
+ *
+ * You are given a 2D integer array of student data students, where
+ * students[i] = [student_id, bench_id] represents that student student_id is
+ * sitting on the bench bench_id.
+ *
+ * Return the maximum number of unique students sitting on any single bench. If no
+ * students are present, return 0.
+ *
+ * Note: A student can appear multiple times on the same bench in the input, but
+ * they should be counted only once per bench.
+ */
+
+/**
+ * @param {number[][]} students
+ * @return {number}
+ */
+var maxStudentsOnBench = function(students) {
+ const map = new Map();
+
+ for (const [studentId, benchId] of students) {
+ if (!map.has(benchId)) {
+ map.set(benchId, new Set());
+ }
+ map.get(benchId).add(studentId);
+ }
+
+ let result = 0;
+ for (const studentSet of map.values()) {
+ result = Math.max(result, studentSet.size);
+ }
+
+ return result;
+};
From d5230fb45f1af7ed86aca31cec9409dbabdd393c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 23 Jul 2025 23:58:25 -0500
Subject: [PATCH 916/994] Add solution #3460
---
README.md | 1 +
...common-prefix-after-at-most-one-removal.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/3460-longest-common-prefix-after-at-most-one-removal.js
diff --git a/README.md b/README.md
index aa67d2b7..c89f4b53 100644
--- a/README.md
+++ b/README.md
@@ -2701,6 +2701,7 @@
3445|[Maximum Difference Between Even and Odd Frequency II](./solutions/3445-maximum-difference-between-even-and-odd-frequency-ii.js)|Hard|
3450|[Maximum Students on a Single Bench](./solutions/3450-maximum-students-on-a-single-bench.js)|Easy|
3452|[Sum of Good Numbers](./solutions/3452-sum-of-good-numbers.js)|Easy|
+3460|[Longest Common Prefix After at Most One Removal](./solutions/3460-longest-common-prefix-after-at-most-one-removal.js)|Medium|
3461|[Check If Digits Are Equal in String After Operations I](./solutions/3461-check-if-digits-are-equal-in-string-after-operations-i.js)|Easy|
3462|[Maximum Sum With at Most K Elements](./solutions/3462-maximum-sum-with-at-most-k-elements.js)|Medium|
3463|[Check If Digits Are Equal in String After Operations II](./solutions/3463-check-if-digits-are-equal-in-string-after-operations-ii.js)|Hard|
diff --git a/solutions/3460-longest-common-prefix-after-at-most-one-removal.js b/solutions/3460-longest-common-prefix-after-at-most-one-removal.js
new file mode 100644
index 00000000..6caf272b
--- /dev/null
+++ b/solutions/3460-longest-common-prefix-after-at-most-one-removal.js
@@ -0,0 +1,39 @@
+/**
+ * 3460. Longest Common Prefix After at Most One Removal
+ * https://leetcode.com/problems/longest-common-prefix-after-at-most-one-removal/
+ * Difficulty: Medium
+ *
+ * You are given two strings s and t.
+ *
+ * Return the length of the longest common prefix between s and t after removing at most
+ * one character from s.
+ *
+ * Note: s can be left without any removal.
+ */
+
+/**
+ * @param {string} s
+ * @param {string} t
+ * @return {number}
+ */
+var longestCommonPrefix = function(s, t) {
+ let i = 0;
+ let j = 0;
+ let result = 0;
+ let isRemoved = false;
+
+ while (i < s.length && j < t.length) {
+ if (s[i] === t[j]) {
+ i++;
+ j++;
+ result++;
+ } else if (isRemoved) {
+ return result;
+ } else {
+ isRemoved = true;
+ i++;
+ }
+ }
+
+ return result;
+};
From a853864328d4ba01fda3bd875f211e34fd84518e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 24 Jul 2025 00:42:54 -0500
Subject: [PATCH 917/994] Add solution #3466
---
README.md | 3 +-
solutions/3466-maximum-coin-collection.js | 50 +++++++++++++++++++++++
2 files changed, 52 insertions(+), 1 deletion(-)
create mode 100644 solutions/3466-maximum-coin-collection.js
diff --git a/README.md b/README.md
index c89f4b53..808187f6 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 2,650+ LeetCode solutions in JavaScript
+# 2,700+ LeetCode solutions in JavaScript
[https://leetcodejavascript.com](https://leetcodejavascript.com)
@@ -2706,6 +2706,7 @@
3462|[Maximum Sum With at Most K Elements](./solutions/3462-maximum-sum-with-at-most-k-elements.js)|Medium|
3463|[Check If Digits Are Equal in String After Operations II](./solutions/3463-check-if-digits-are-equal-in-string-after-operations-ii.js)|Hard|
3464|[Maximize the Distance Between Points on a Square](./solutions/3464-maximize-the-distance-between-points-on-a-square.js)|Hard|
+3466|[Maximum Coin Collection](./solutions/3466-maximum-coin-collection.js)|Medium|
## License
diff --git a/solutions/3466-maximum-coin-collection.js b/solutions/3466-maximum-coin-collection.js
new file mode 100644
index 00000000..06763a94
--- /dev/null
+++ b/solutions/3466-maximum-coin-collection.js
@@ -0,0 +1,50 @@
+/**
+ * 3466. Maximum Coin Collection
+ * https://leetcode.com/problems/maximum-coin-collection/
+ * Difficulty: Medium
+ *
+ * Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays,
+ * lane1 and lane2, where the value at the ith index represents the number of coins he gains
+ * or loses in the ith mile in that lane.
+ * - If Mario is in lane 1 at mile i and lane1[i] > 0, Mario gains lane1[i] coins.
+ * - If Mario is in lane 1 at mile i and lane1[i] < 0, Mario pays a toll and loses abs(lane1[i])
+ * coins.
+ * - The same rules apply for lane2.
+ *
+ * Mario can enter the freeway anywhere and exit anytime after traveling at least one mile. Mario
+ * always enters the freeway on lane 1 but can switch lanes at most 2 times.
+ *
+ * A lane switch is when Mario goes from lane 1 to lane 2 or vice versa.
+ *
+ * Return the maximum number of coins Mario can earn after performing at most 2 lane switches.
+ *
+ * Note: Mario can switch lanes immediately upon entering or just before exiting the freeway.
+ */
+
+/**
+ * @param {number[]} lane1
+ * @param {number[]} lane2
+ * @return {number}
+ */
+var maxCoins = function(lane1, lane2) {
+ const n = lane1.length;
+ const dp = new Array(n).fill().map(() => new Array(2).fill().map(() => new Array(3).fill(0)));
+
+ dp[0][0][2] = lane1[0];
+ dp[0][0][0] = lane1[0];
+ dp[0][1][1] = lane2[0];
+
+ let result = Math.max(dp[0][0][2], dp[0][1][1]);
+ for (let i = 1; i < n; i++) {
+ dp[i][0][0] = Math.max(dp[i - 1][0][0], dp[i - 1][1][1]) + lane1[i];
+
+ dp[i][0][2] = Math.max(dp[i - 1][0][2] + lane1[i], lane1[i]);
+
+ dp[i][1][1] = Math.max(Math.max(dp[i - 1][0][2], dp[i - 1][1][1]), 0) + lane2[i];
+
+ const currentMax = Math.max(Math.max(dp[i][0][0], dp[i][0][2]), dp[i][1][1]);
+ result = Math.max(result, currentMax);
+ }
+
+ return result;
+};
From d889cf399fd6d89b6df2eda7204ff8f7da0a6524 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 24 Jul 2025 00:44:48 -0500
Subject: [PATCH 918/994] Add solution #3476
---
README.md | 1 +
...76-maximize-profit-from-task-assignment.js | 57 +++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/3476-maximize-profit-from-task-assignment.js
diff --git a/README.md b/README.md
index 808187f6..661fa22d 100644
--- a/README.md
+++ b/README.md
@@ -2707,6 +2707,7 @@
3463|[Check If Digits Are Equal in String After Operations II](./solutions/3463-check-if-digits-are-equal-in-string-after-operations-ii.js)|Hard|
3464|[Maximize the Distance Between Points on a Square](./solutions/3464-maximize-the-distance-between-points-on-a-square.js)|Hard|
3466|[Maximum Coin Collection](./solutions/3466-maximum-coin-collection.js)|Medium|
+3476|[Maximize Profit from Task Assignment](./solutions/3476-maximize-profit-from-task-assignment.js)|Medium|
## License
diff --git a/solutions/3476-maximize-profit-from-task-assignment.js b/solutions/3476-maximize-profit-from-task-assignment.js
new file mode 100644
index 00000000..c7212ce7
--- /dev/null
+++ b/solutions/3476-maximize-profit-from-task-assignment.js
@@ -0,0 +1,57 @@
+/**
+ * 3476. Maximize Profit from Task Assignment
+ * https://leetcode.com/problems/maximize-profit-from-task-assignment/
+ * Difficulty: Medium
+ *
+ * You are given an integer array workers, where workers[i] represents the skill level of
+ * the ith worker. You are also given a 2D integer array tasks, where:
+ * - tasks[i][0] represents the skill requirement needed to complete the task.
+ * - tasks[i][1] represents the profit earned from completing the task.
+ *
+ * Each worker can complete at most one task, and they can only take a task if their skill
+ * level is equal to the task's skill requirement. An additional worker joins today who can
+ * take up any task, regardless of the skill requirement.
+ *
+ * Return the maximum total profit that can be earned by optimally assigning the tasks to
+ * the workers.
+ */
+
+/**
+ * @param {number[]} workers
+ * @param {number[][]} tasks
+ * @return {number}
+ */
+var maxProfit = function(workers, tasks) {
+ const map = new Map();
+
+ for (const [skill, profit] of tasks) {
+ if (!map.has(skill)) {
+ map.set(skill, []);
+ }
+ map.get(skill).push(profit);
+ }
+
+ for (const [skill, profits] of map) {
+ profits.sort((a, b) => b - a);
+ }
+
+ let totalProfit = 0;
+
+ for (const worker of workers) {
+ if (map.has(worker) && map.get(worker).length > 0) {
+ totalProfit += map.get(worker).shift();
+ if (map.get(worker).length === 0) {
+ map.delete(worker);
+ }
+ }
+ }
+
+ let maxRemainingProfit = 0;
+ for (const profits of map.values()) {
+ if (profits.length > 0) {
+ maxRemainingProfit = Math.max(maxRemainingProfit, profits[0]);
+ }
+ }
+
+ return totalProfit + maxRemainingProfit;
+};
From 3e3be10fd0e6ce498a0a24ee896e1ea6d3d3f49d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 24 Jul 2025 00:48:59 -0500
Subject: [PATCH 919/994] Add solution #3481
---
README.md | 1 +
solutions/3481-apply-substitutions.js | 35 +++++++++++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/3481-apply-substitutions.js
diff --git a/README.md b/README.md
index 661fa22d..85f51bbf 100644
--- a/README.md
+++ b/README.md
@@ -2708,6 +2708,7 @@
3464|[Maximize the Distance Between Points on a Square](./solutions/3464-maximize-the-distance-between-points-on-a-square.js)|Hard|
3466|[Maximum Coin Collection](./solutions/3466-maximum-coin-collection.js)|Medium|
3476|[Maximize Profit from Task Assignment](./solutions/3476-maximize-profit-from-task-assignment.js)|Medium|
+3481|[Apply Substitutions](./solutions/3481-apply-substitutions.js)|Medium|
## License
diff --git a/solutions/3481-apply-substitutions.js b/solutions/3481-apply-substitutions.js
new file mode 100644
index 00000000..92981c97
--- /dev/null
+++ b/solutions/3481-apply-substitutions.js
@@ -0,0 +1,35 @@
+/**
+ * 3481. Apply Substitutions
+ * https://leetcode.com/problems/apply-substitutions/
+ * Difficulty: Medium
+ *
+ * You are given a replacements mapping and a text string that may contain placeholders
+ * formatted as %var%, where each var corresponds to a key in the replacements mapping.
+ * Each replacement value may itself contain one or more such placeholders. Each placeholder
+ * is replaced by the value associated with its corresponding replacement key.
+ *
+ * Return the fully substituted text string which does not contain any placeholders.
+ */
+
+/**
+ * @param {string[][]} replacements
+ * @param {string} text
+ * @return {string}
+ */
+var applySubstitutions = function(replacements, text) {
+ const replacementMap = new Map(replacements);
+ const cache = new Map();
+
+ return text.replace(/%([A-Z])%/g, (match, key) => helper(key));
+
+ function helper(key) {
+ if (cache.has(key)) {
+ return cache.get(key);
+ }
+
+ const value = replacementMap.get(key);
+ const result = value.replace(/%([A-Z])%/g, (match, innerKey) => helper(innerKey));
+ cache.set(key, result);
+ return result;
+ }
+};
From 7841200d95011e9ff8bdfb259efcf9229a82f018 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 24 Jul 2025 00:49:52 -0500
Subject: [PATCH 920/994] Add solution #3491
---
README.md | 1 +
solutions/3491-phone-number-prefix.js | 24 ++++++++++++++++++++++++
2 files changed, 25 insertions(+)
create mode 100644 solutions/3491-phone-number-prefix.js
diff --git a/README.md b/README.md
index 85f51bbf..3c2258d9 100644
--- a/README.md
+++ b/README.md
@@ -2709,6 +2709,7 @@
3466|[Maximum Coin Collection](./solutions/3466-maximum-coin-collection.js)|Medium|
3476|[Maximize Profit from Task Assignment](./solutions/3476-maximize-profit-from-task-assignment.js)|Medium|
3481|[Apply Substitutions](./solutions/3481-apply-substitutions.js)|Medium|
+3491|[Phone Number Prefix](./solutions/3491-phone-number-prefix.js)|Easy|
## License
diff --git a/solutions/3491-phone-number-prefix.js b/solutions/3491-phone-number-prefix.js
new file mode 100644
index 00000000..b968be0f
--- /dev/null
+++ b/solutions/3491-phone-number-prefix.js
@@ -0,0 +1,24 @@
+/**
+ * 3491. Phone Number Prefix
+ * https://leetcode.com/problems/phone-number-prefix/
+ * Difficulty: Easy
+ *
+ * You are given a string array numbers that represents phone numbers. Return true if no phone
+ * number is a prefix of any other phone number; otherwise, return false.
+ */
+
+/**
+ * @param {string[]} numbers
+ * @return {boolean}
+ */
+var phonePrefix = function(numbers) {
+ numbers.sort();
+
+ for (let i = 0; i < numbers.length - 1; i++) {
+ if (numbers[i + 1].startsWith(numbers[i])) {
+ return false;
+ }
+ }
+
+ return true;
+};
From 00dc9df50878305a09a2c27480e3b8ca897893ae Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 24 Jul 2025 00:52:02 -0500
Subject: [PATCH 921/994] Add solution #3496
---
README.md | 1 +
...496-maximize-score-after-pair-deletions.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/3496-maximize-score-after-pair-deletions.js
diff --git a/README.md b/README.md
index 3c2258d9..e4326f1f 100644
--- a/README.md
+++ b/README.md
@@ -2710,6 +2710,7 @@
3476|[Maximize Profit from Task Assignment](./solutions/3476-maximize-profit-from-task-assignment.js)|Medium|
3481|[Apply Substitutions](./solutions/3481-apply-substitutions.js)|Medium|
3491|[Phone Number Prefix](./solutions/3491-phone-number-prefix.js)|Easy|
+3496|[Maximize Score After Pair Deletions](./solutions/3496-maximize-score-after-pair-deletions.js)|Medium|
## License
diff --git a/solutions/3496-maximize-score-after-pair-deletions.js b/solutions/3496-maximize-score-after-pair-deletions.js
new file mode 100644
index 00000000..4a5b10f8
--- /dev/null
+++ b/solutions/3496-maximize-score-after-pair-deletions.js
@@ -0,0 +1,34 @@
+/**
+ * 3496. Maximize Score After Pair Deletions
+ * https://leetcode.com/problems/maximize-score-after-pair-deletions/
+ * Difficulty: Medium
+ *
+ * You are given an array of integers nums. You must repeatedly perform one of the following
+ * operations while the array has more than two elements:
+ * - Remove the first two elements.
+ * - Remove the last two elements.
+ * - Remove the first and last element.
+ *
+ * For each operation, add the sum of the removed elements to your total score.
+ *
+ * Return the maximum possible score you can achieve.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maxScore = function(nums) {
+ const n = nums.length;
+ const totalSum = nums.reduce((sum, num) => sum + num, 0);
+
+ if (n % 2 === 1) {
+ return totalSum - Math.min(...nums);
+ } else {
+ let minPairSum = Infinity;
+ for (let i = 0; i < n - 1; i++) {
+ minPairSum = Math.min(minPairSum, nums[i] + nums[i + 1]);
+ }
+ return totalSum - minPairSum;
+ }
+};
From eb4cf1c3a572223477c97277164d2cd072ea8acc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 24 Jul 2025 22:48:57 -0500
Subject: [PATCH 922/994] Add solution #3487
---
README.md | 1 +
...imum-unique-subarray-sum-after-deletion.js | 29 +++++++++++++++++++
2 files changed, 30 insertions(+)
create mode 100644 solutions/3487-maximum-unique-subarray-sum-after-deletion.js
diff --git a/README.md b/README.md
index e4326f1f..e190491f 100644
--- a/README.md
+++ b/README.md
@@ -2709,6 +2709,7 @@
3466|[Maximum Coin Collection](./solutions/3466-maximum-coin-collection.js)|Medium|
3476|[Maximize Profit from Task Assignment](./solutions/3476-maximize-profit-from-task-assignment.js)|Medium|
3481|[Apply Substitutions](./solutions/3481-apply-substitutions.js)|Medium|
+3487|[Maximum Unique Subarray Sum After Deletion](./solutions/3487-maximum-unique-subarray-sum-after-deletion.js)|Easy|
3491|[Phone Number Prefix](./solutions/3491-phone-number-prefix.js)|Easy|
3496|[Maximize Score After Pair Deletions](./solutions/3496-maximize-score-after-pair-deletions.js)|Medium|
diff --git a/solutions/3487-maximum-unique-subarray-sum-after-deletion.js b/solutions/3487-maximum-unique-subarray-sum-after-deletion.js
new file mode 100644
index 00000000..52d0449c
--- /dev/null
+++ b/solutions/3487-maximum-unique-subarray-sum-after-deletion.js
@@ -0,0 +1,29 @@
+/**
+ * 3487. Maximum Unique Subarray Sum After Deletion
+ * https://leetcode.com/problems/maximum-unique-subarray-sum-after-deletion/
+ * Difficulty: Easy
+ *
+ * You are given an integer array nums.
+ *
+ * You are allowed to delete any number of elements from nums without making it empty.
+ * After performing the deletions, select a subarray of nums such that:
+ * 1. All elements in the subarray are unique.
+ * 2. The sum of the elements in the subarray is maximized.
+ *
+ * Return the maximum sum of such a subarray.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maxSum = function(nums) {
+ const uniqueValues = [...new Set(nums)];
+ const positiveValues = uniqueValues.filter(val => val > 0);
+
+ if (positiveValues.length === 0) {
+ return Math.max(...uniqueValues);
+ }
+
+ return positiveValues.reduce((sum, val) => sum + val, 0);
+};
From 75c5075dc266ebe912b3836cf4d84b93797c5cb3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 24 Jul 2025 23:50:16 -0500
Subject: [PATCH 923/994] Add solution #3506
---
README.md | 1 +
...required-to-eliminate-bacterial-strains.js | 54 +++++++++++++++++++
2 files changed, 55 insertions(+)
create mode 100644 solutions/3506-find-time-required-to-eliminate-bacterial-strains.js
diff --git a/README.md b/README.md
index e190491f..529c639b 100644
--- a/README.md
+++ b/README.md
@@ -2712,6 +2712,7 @@
3487|[Maximum Unique Subarray Sum After Deletion](./solutions/3487-maximum-unique-subarray-sum-after-deletion.js)|Easy|
3491|[Phone Number Prefix](./solutions/3491-phone-number-prefix.js)|Easy|
3496|[Maximize Score After Pair Deletions](./solutions/3496-maximize-score-after-pair-deletions.js)|Medium|
+3506|[Find Time Required to Eliminate Bacterial Strains](./solutions/3506-find-time-required-to-eliminate-bacterial-strains.js)|Hard|
## License
diff --git a/solutions/3506-find-time-required-to-eliminate-bacterial-strains.js b/solutions/3506-find-time-required-to-eliminate-bacterial-strains.js
new file mode 100644
index 00000000..fa080b4b
--- /dev/null
+++ b/solutions/3506-find-time-required-to-eliminate-bacterial-strains.js
@@ -0,0 +1,54 @@
+/**
+ * 3506. Find Time Required to Eliminate Bacterial Strains
+ * https://leetcode.com/problems/find-time-required-to-eliminate-bacterial-strains/
+ * Difficulty: Hard
+ *
+ * You are given an integer array timeReq and an integer splitTime.
+ *
+ * In the microscopic world of the human body, the immune system faces an extraordinary
+ * challenge: combatting a rapidly multiplying bacterial colony that threatens the body's survival.
+ *
+ * Initially, only one white blood cell (WBC) is deployed to eliminate the bacteria. However, the
+ * lone WBC quickly realizes it cannot keep up with the bacterial growth rate.
+ *
+ * The WBC devises a clever strategy to fight the bacteria:
+ * - The ith bacterial strain takes timeReq[i] units of time to be eliminated.
+ * - A single WBC can eliminate only one bacterial strain. Afterwards, the WBC is exhausted and
+ * cannot perform any other tasks.
+ * - A WBC can split itself into two WBCs, but this requires splitTime units of time. Once split,
+ * the two WBCs can work in parallel on eliminating the bacteria.
+ * - Only one WBC can work on a single bacterial strain. Multiple WBCs cannot attack one strain
+ * in parallel.
+ *
+ * You must determine the minimum time required to eliminate all the bacterial strains.
+ *
+ * Note that the bacterial strains can be eliminated in any order.
+ */
+
+/**
+ * @param {number[]} timeReq
+ * @param {number} splitTime
+ * @return {number}
+ */
+var minEliminationTime = function(timeReq, splitTime) {
+ const heap = new PriorityQueue((a, b) => a - b);
+
+ for (const time of timeReq) {
+ heap.enqueue(time);
+ }
+
+ heap.dequeue();
+
+ let result = 0;
+ while (!heap.isEmpty()) {
+ const bacteria = splitTime + heap.dequeue();
+ if (!heap.isEmpty()) {
+ heap.enqueue(bacteria);
+ result = heap.dequeue();
+ } else {
+ result = bacteria;
+ }
+ }
+
+ return result;
+};
From 1c8473f68bebb32628f616a20affb6c8edba0c36 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 24 Jul 2025 23:51:59 -0500
Subject: [PATCH 924/994] Add solution #3511
---
README.md | 1 +
solutions/3511-make-a-positive-array.js | 35 +++++++++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/3511-make-a-positive-array.js
diff --git a/README.md b/README.md
index 529c639b..61e7f745 100644
--- a/README.md
+++ b/README.md
@@ -2713,6 +2713,7 @@
3491|[Phone Number Prefix](./solutions/3491-phone-number-prefix.js)|Easy|
3496|[Maximize Score After Pair Deletions](./solutions/3496-maximize-score-after-pair-deletions.js)|Medium|
3506|[Find Time Required to Eliminate Bacterial Strains](./solutions/3506-find-time-required-to-eliminate-bacterial-strains.js)|Hard|
+3511|[Make a Positive Array](./solutions/3511-make-a-positive-array.js)|Medium|
## License
diff --git a/solutions/3511-make-a-positive-array.js b/solutions/3511-make-a-positive-array.js
new file mode 100644
index 00000000..7432eb8f
--- /dev/null
+++ b/solutions/3511-make-a-positive-array.js
@@ -0,0 +1,35 @@
+/**
+ * 3511. Make a Positive Array
+ * https://leetcode.com/problems/make-a-positive-array/
+ * Difficulty: Medium
+ *
+ * You are given an array nums. An array is considered positive if the sum of all numbers in
+ * each subarray with more than two elements is positive.
+ *
+ * You can perform the following operation any number of times:
+ * - Replace one element in nums with any integer between -1018 and 1018.
+ *
+ * Find the minimum number of operations needed to make nums positive.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var makeArrayPositive = function(nums) {
+ let result = 0;
+ let lowestSum = nums[0] + nums[1];
+
+ for (let i = 2; i < nums.length; i++) {
+ const currentValue = nums[i];
+ const currentTriplet = currentValue + nums[i - 1] + nums[i - 2];
+ lowestSum = Math.min(lowestSum + currentValue, currentTriplet);
+
+ if (lowestSum <= 0) {
+ nums[i] = lowestSum = 10 ** 18;
+ result++;
+ }
+ }
+
+ return result;
+};
From 7cb4382a14c46c87f2f09f6648547f396141f9e4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 24 Jul 2025 23:54:41 -0500
Subject: [PATCH 925/994] Add solution #3520
---
README.md | 1 +
...mum-threshold-for-inversion-pairs-count.js | 80 +++++++++++++++++++
2 files changed, 81 insertions(+)
create mode 100644 solutions/3520-minimum-threshold-for-inversion-pairs-count.js
diff --git a/README.md b/README.md
index 61e7f745..4753e5d1 100644
--- a/README.md
+++ b/README.md
@@ -2714,6 +2714,7 @@
3496|[Maximize Score After Pair Deletions](./solutions/3496-maximize-score-after-pair-deletions.js)|Medium|
3506|[Find Time Required to Eliminate Bacterial Strains](./solutions/3506-find-time-required-to-eliminate-bacterial-strains.js)|Hard|
3511|[Make a Positive Array](./solutions/3511-make-a-positive-array.js)|Medium|
+3520|[Minimum Threshold for Inversion Pairs Count](./solutions/3520-minimum-threshold-for-inversion-pairs-count.js)|Medium|
## License
diff --git a/solutions/3520-minimum-threshold-for-inversion-pairs-count.js b/solutions/3520-minimum-threshold-for-inversion-pairs-count.js
new file mode 100644
index 00000000..a4ea8692
--- /dev/null
+++ b/solutions/3520-minimum-threshold-for-inversion-pairs-count.js
@@ -0,0 +1,80 @@
+/**
+ * 3520. Minimum Threshold for Inversion Pairs Count
+ * https://leetcode.com/problems/minimum-threshold-for-inversion-pairs-count/
+ * Difficulty: Medium
+ *
+ * You are given an array of integers nums and an integer k.
+ *
+ * An inversion pair with a threshold x is defined as a pair of indices (i, j) such that:
+ * - i < j
+ * - nums[i] > nums[j]
+ * - The difference between the two numbers is at most x (i.e. nums[i] - nums[j] <= x).
+ *
+ * Your task is to determine the minimum integer min_threshold such that there are at least
+ * k inversion pairs with threshold min_threshold.
+ *
+ * If no such integer exists, return -1.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var minThreshold = function(nums, k) {
+ const maxThreshold = Math.max(...nums) - Math.min(...nums) + 1;
+
+ if (!countInversions(maxThreshold)) return -1;
+
+ let left = 0;
+ let right = maxThreshold;
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (countInversions(mid)) {
+ right = mid;
+ } else {
+ left = mid + 1;
+ }
+ }
+
+ return left;
+
+ function binarySearchLeft(arr, target) {
+ let left = 0;
+ let right = arr.length;
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (arr[mid] < target) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+ return left;
+ }
+
+ function insertSorted(arr, val) {
+ const index = binarySearchLeft(arr, val);
+ arr.splice(index, 0, val);
+ }
+
+ function countInversions(threshold) {
+ let count = 0;
+ const sortedList = [];
+
+ for (let i = nums.length - 1; i >= 0; i--) {
+ const num = nums[i];
+ const leftBound = num - threshold;
+ const rightBound = num;
+ const leftIndex = binarySearchLeft(sortedList, leftBound);
+ const rightIndex = binarySearchLeft(sortedList, rightBound);
+
+ count += rightIndex - leftIndex;
+ if (count >= k) return true;
+
+ insertSorted(sortedList, num);
+ }
+
+ return false;
+ }
+};
From eecde5179aea7e03e37ec99702485deaef85d4c1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 25 Jul 2025 00:14:05 -0500
Subject: [PATCH 926/994] Add solution #3535
---
README.md | 1 +
solutions/3535-unit-conversion-ii.js | 87 ++++++++++++++++++++++++++++
2 files changed, 88 insertions(+)
create mode 100644 solutions/3535-unit-conversion-ii.js
diff --git a/README.md b/README.md
index 4753e5d1..c2e37859 100644
--- a/README.md
+++ b/README.md
@@ -2715,6 +2715,7 @@
3506|[Find Time Required to Eliminate Bacterial Strains](./solutions/3506-find-time-required-to-eliminate-bacterial-strains.js)|Hard|
3511|[Make a Positive Array](./solutions/3511-make-a-positive-array.js)|Medium|
3520|[Minimum Threshold for Inversion Pairs Count](./solutions/3520-minimum-threshold-for-inversion-pairs-count.js)|Medium|
+3535|[Unit Conversion II](./solutions/3535-unit-conversion-ii.js)|Medium|
## License
diff --git a/solutions/3535-unit-conversion-ii.js b/solutions/3535-unit-conversion-ii.js
new file mode 100644
index 00000000..18444a36
--- /dev/null
+++ b/solutions/3535-unit-conversion-ii.js
@@ -0,0 +1,87 @@
+/**
+ * 3535. Unit Conversion II
+ * https://leetcode.com/problems/unit-conversion-ii/
+ * Difficulty: Medium
+ *
+ * There are n types of units indexed from 0 to n - 1.
+ *
+ * You are given a 2D integer array conversions of length n - 1, where
+ * conversions[i] = [sourceUniti, targetUniti, conversionFactori]. This indicates
+ * that a single unit of type sourceUniti is equivalent to conversionFactori units
+ * of type targetUniti.
+ *
+ * You are also given a 2D integer array queries of length q, where queries[i] = [unitAi, unitBi].
+ *
+ * Return an array answer of length q where answer[i] is the number of units of type unitBi
+ * equivalent to 1 unit of type unitAi, and can be represented as p/q where p and q are coprime.
+ * Return each answer[i] as pq-1 modulo 109 + 7, where q-1 represents the multiplicative inverse
+ * of q modulo 109 + 7.
+ */
+
+/**
+ * @param {number[][]} conversions
+ * @param {number[][]} queries
+ * @return {number[]}
+ */
+var queryConversions = function(conversions, queries) {
+ const n = conversions.length + 1;
+ const adj = Array.from({ length: n }, () => []);
+ const convMap = new Map();
+ for (const [s, t, f] of conversions) {
+ adj[s].push(t);
+ adj[t].push(s);
+ convMap.set(`${s}-${t}`, BigInt(f));
+ }
+ const MOD = 1000000007n;
+ const ratio = new Array(n).fill(0n);
+ ratio[0] = 1n;
+ const visited = new Array(n).fill(false);
+ visited[0] = true;
+ const queue = [0];
+ let queueIndex = 0;
+ while (queueIndex < queue.length) {
+ const current = queue[queueIndex++];
+ for (const neighbor of adj[current]) {
+ if (visited[neighbor]) continue;
+ visited[neighbor] = true;
+ queue.push(neighbor);
+ const forwardKey = `${current}-${neighbor}`;
+ if (convMap.has(forwardKey)) {
+ const factor = convMap.get(forwardKey);
+ ratio[neighbor] = (ratio[current] * factor) % MOD;
+ } else {
+ const backwardKey = `${neighbor}-${current}`;
+ const factor = convMap.get(backwardKey);
+ const inverseFactor = modInverse(factor, MOD);
+ ratio[neighbor] = (ratio[current] * inverseFactor) % MOD;
+ }
+ }
+ }
+ const result = [];
+ for (const [unitA, unitB] of queries) {
+ const ratioA = ratio[unitA];
+ const ratioB = ratio[unitB];
+ const inverseRatioA = modInverse(ratioA, MOD);
+ const conversion = (ratioB * inverseRatioA) % MOD;
+ result.push(Number(conversion));
+ }
+
+ return result;
+
+ function modPow(base, exponent, modulus) {
+ let result = 1n;
+ base %= modulus;
+ while (exponent > 0n) {
+ if (exponent % 2n === 1n) {
+ result = (result * base) % modulus;
+ }
+ base = (base * base) % modulus;
+ exponent /= 2n;
+ }
+ return result;
+ }
+
+ function modInverse(value, modulus) {
+ return modPow(value, modulus - 2n, modulus);
+ }
+};
From 2003f8e5eb42eedcf875a251f441489a56b8c767 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 25 Jul 2025 00:16:38 -0500
Subject: [PATCH 927/994] Add solution #1942
---
README.md | 1 +
...number-of-the-smallest-unoccupied-chair.js | 62 +++++++++++++++++++
2 files changed, 63 insertions(+)
create mode 100644 solutions/1942-the-number-of-the-smallest-unoccupied-chair.js
diff --git a/README.md b/README.md
index c2e37859..29bfb812 100644
--- a/README.md
+++ b/README.md
@@ -1763,6 +1763,7 @@
1938|[Maximum Genetic Difference Query](./solutions/1938-maximum-genetic-difference-query.js)|Hard|
1940|[Longest Common Subsequence Between Sorted Arrays](./solutions/1940-longest-common-subsequence-between-sorted-arrays.js)|Medium|
1941|[Check if All Characters Have Equal Number of Occurrences](./solutions/1941-check-if-all-characters-have-equal-number-of-occurrences.js)|Easy|
+1942|[The Number of the Smallest Unoccupied Chair](./solutions/1942-the-number-of-the-smallest-unoccupied-chair.js)|Medium|
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|
diff --git a/solutions/1942-the-number-of-the-smallest-unoccupied-chair.js b/solutions/1942-the-number-of-the-smallest-unoccupied-chair.js
new file mode 100644
index 00000000..bac12d08
--- /dev/null
+++ b/solutions/1942-the-number-of-the-smallest-unoccupied-chair.js
@@ -0,0 +1,62 @@
+/**
+ * 1942. The Number of the Smallest Unoccupied Chair
+ * https://leetcode.com/problems/the-number-of-the-smallest-unoccupied-chair/
+ * Difficulty: Medium
+ *
+ * There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite
+ * number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at
+ * the party, they sit on the unoccupied chair with the smallest number.
+ * - For example, if chairs 0, 1, and 5 are occupied when a friend comes, they will sit on chair
+ * number 2.
+ *
+ * When a friend leaves the party, their chair becomes unoccupied at the moment they leave.
+ * If another friend arrives at that same moment, they can sit in that chair.
+ *
+ * You are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi],
+ * indicating the arrival and leaving times of the ith friend respectively, and an integer
+ * targetFriend. All arrival times are distinct.
+ *
+ * Return the chair number that the friend numbered targetFriend will sit on.
+ */
+
+/**
+ * @param {number[][]} times
+ * @param {number} targetFriend
+ * @return {number}
+ */
+var smallestChair = function(times, targetFriend) {
+ const events = [];
+
+ for (let i = 0; i < times.length; i++) {
+ events.push([times[i][0], 'arrive', i]);
+ events.push([times[i][1], 'leave', i]);
+ }
+
+ events.sort((a, b) => a[0] - b[0] || (a[1] === 'leave' ? -1 : 1));
+
+ const availableChairs = [];
+ const occupiedChairs = new Map();
+ let nextChair = 0;
+
+ for (const [time, eventType, friendId] of events) {
+ if (eventType === 'leave') {
+ const chairNumber = occupiedChairs.get(friendId);
+ occupiedChairs.delete(friendId);
+ availableChairs.push(chairNumber);
+ availableChairs.sort((a, b) => a - b);
+ } else {
+ let assignedChair;
+ if (availableChairs.length > 0) {
+ assignedChair = availableChairs.shift();
+ } else {
+ assignedChair = nextChair++;
+ }
+
+ occupiedChairs.set(friendId, assignedChair);
+
+ if (friendId === targetFriend) {
+ return assignedChair;
+ }
+ }
+ }
+};
From e437f0f659b16ee288562973fdf1679dc7cf85f6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 25 Jul 2025 00:18:42 -0500
Subject: [PATCH 928/994] Add solution #1962
---
README.md | 1 +
...962-remove-stones-to-minimize-the-total.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/1962-remove-stones-to-minimize-the-total.js
diff --git a/README.md b/README.md
index 29bfb812..e9bbf66a 100644
--- a/README.md
+++ b/README.md
@@ -1781,6 +1781,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|
+1962|[Remove Stones to Minimize the Total](./solutions/1962-remove-stones-to-minimize-the-total.js)|Medium|
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|
1966|[Binary Searchable Numbers in an Unsorted Array](./solutions/1966-binary-searchable-numbers-in-an-unsorted-array.js)|Medium|
diff --git a/solutions/1962-remove-stones-to-minimize-the-total.js b/solutions/1962-remove-stones-to-minimize-the-total.js
new file mode 100644
index 00000000..40535ad8
--- /dev/null
+++ b/solutions/1962-remove-stones-to-minimize-the-total.js
@@ -0,0 +1,39 @@
+/**
+ * 1962. Remove Stones to Minimize the Total
+ * https://leetcode.com/problems/remove-stones-to-minimize-the-total/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array piles, where piles[i] represents the number
+ * of stones in the ith pile, and an integer k. You should apply the following operation
+ * exactly k times:
+ * - Choose any piles[i] and remove ceil(piles[i] / 2) stones from it.
+ *
+ * Notice that you can apply the operation on the same pile more than once.
+ *
+ * Return the minimum possible total number of stones remaining after applying the k operations.
+ *
+ * ceil(x) is the smallest integer that is greater than or equal to x (i.e., rounds x up).
+ */
+
+/**
+ * @param {number[]} piles
+ * @param {number} k
+ * @return {number}
+ */
+var minStoneSum = function(piles, k) {
+ const maxHeap = new PriorityQueue((a, b) => b - a);
+ let result = 0;
+
+ for (const pile of piles) {
+ maxHeap.enqueue(pile);
+ result += pile;
+ }
+
+ while (k-- > 0) {
+ const largest = maxHeap.dequeue();
+ maxHeap.enqueue(largest - Math.floor(largest / 2));
+ result -= Math.floor(largest / 2);
+ }
+
+ return result;
+};
From d19a16e7c39cf4f0e9c6da6ac2e4355b7a6b3f4d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 25 Jul 2025 00:23:12 -0500
Subject: [PATCH 929/994] Add solution #2034
---
README.md | 1 +
solutions/2034-stock-price-fluctuation.js | 82 +++++++++++++++++++++++
2 files changed, 83 insertions(+)
create mode 100644 solutions/2034-stock-price-fluctuation.js
diff --git a/README.md b/README.md
index e9bbf66a..a8643dab 100644
--- a/README.md
+++ b/README.md
@@ -1844,6 +1844,7 @@
2031|[Count Subarrays With More Ones Than Zeros](./solutions/2031-count-subarrays-with-more-ones-than-zeros.js)|Medium|
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|
+2034|[Stock Price Fluctuation](./solutions/2034-stock-price-fluctuation.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|
2036|[Maximum Alternating Subarray Sum](./solutions/2036-maximum-alternating-subarray-sum.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/2034-stock-price-fluctuation.js b/solutions/2034-stock-price-fluctuation.js
new file mode 100644
index 00000000..ad4050da
--- /dev/null
+++ b/solutions/2034-stock-price-fluctuation.js
@@ -0,0 +1,82 @@
+/**
+ * 2034. Stock Price Fluctuation
+ * https://leetcode.com/problems/stock-price-fluctuation/
+ * Difficulty: Medium
+ *
+ * You are given a stream of records about a particular stock. Each record contains a timestamp
+ * and the corresponding price of the stock at that timestamp.
+ *
+ * Unfortunately due to the volatile nature of the stock market, the records do not come in order.
+ * Even worse, some records may be incorrect. Another record with the same timestamp may appear
+ * later in the stream correcting the price of the previous wrong record.
+ *
+ * Design an algorithm that:
+ * - Updates the price of the stock at a particular timestamp, correcting the price from any
+ * previous records at the timestamp.
+ * - Finds the latest price of the stock based on the current records. The latest price is the
+ * price at the latest timestamp recorded.
+ * - Finds the maximum price the stock has been based on the current records.
+ * - Finds the minimum price the stock has been based on the current records.
+ *
+ * Implement the StockPrice class:
+ * - StockPrice() Initializes the object with no price records.
+ * - void update(int timestamp, int price) Updates the price of the stock at the given timestamp.
+ * - int current() Returns the latest price of the stock.
+ * - int maximum() Returns the maximum price of the stock.
+ * - int minimum() Returns the minimum price of the stock.
+ */
+
+var StockPrice = function() {
+ this.timestamps = new Map();
+ this.highestTimestamp = 0;
+ this.minHeap = new PriorityQueue((a, b) => a[0] - b[0]);
+ this.maxHeap = new PriorityQueue((a, b) => b[0] - a[0]);
+};
+
+/**
+ * @param {number} timestamp
+ * @param {number} price
+ * @return {void}
+ */
+StockPrice.prototype.update = function(timestamp, price) {
+ this.timestamps.set(timestamp, price);
+ this.highestTimestamp = Math.max(this.highestTimestamp, timestamp);
+
+ this.minHeap.enqueue([price, timestamp]);
+ this.maxHeap.enqueue([price, timestamp]);
+};
+
+/**
+ * @return {number}
+ */
+StockPrice.prototype.current = function() {
+ return this.timestamps.get(this.highestTimestamp);
+};
+
+/**
+ * @return {number}
+ */
+StockPrice.prototype.maximum = function() {
+ let [currPrice, timestamp] = this.maxHeap.dequeue();
+
+ while (currPrice !== this.timestamps.get(timestamp)) {
+ [currPrice, timestamp] = this.maxHeap.dequeue();
+ }
+
+ this.maxHeap.enqueue([currPrice, timestamp]);
+ return currPrice;
+};
+
+/**
+ * @return {number}
+ */
+StockPrice.prototype.minimum = function() {
+ let [currPrice, timestamp] = this.minHeap.dequeue();
+
+ while (currPrice !== this.timestamps.get(timestamp)) {
+ [currPrice, timestamp] = this.minHeap.dequeue();
+ }
+
+ this.minHeap.enqueue([currPrice, timestamp]);
+ return currPrice;
+};
From 33c42ad472bd888d6e0ca5ca57894590945bb057 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 25 Jul 2025 00:24:50 -0500
Subject: [PATCH 930/994] Add solution #2054
---
README.md | 1 +
.../2054-two-best-non-overlapping-events.js | 58 +++++++++++++++++++
2 files changed, 59 insertions(+)
create mode 100644 solutions/2054-two-best-non-overlapping-events.js
diff --git a/README.md b/README.md
index a8643dab..e7e85223 100644
--- a/README.md
+++ b/README.md
@@ -1862,6 +1862,7 @@
2050|[Parallel Courses III](./solutions/2050-parallel-courses-iii.js)|Hard|
2052|[Minimum Cost to Separate Sentence Into Rows](./solutions/2052-minimum-cost-to-separate-sentence-into-rows.js)|Medium|
2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium|
+2054|[Two Best Non-Overlapping Events](./solutions/2054-two-best-non-overlapping-events.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|
diff --git a/solutions/2054-two-best-non-overlapping-events.js b/solutions/2054-two-best-non-overlapping-events.js
new file mode 100644
index 00000000..7cc0083d
--- /dev/null
+++ b/solutions/2054-two-best-non-overlapping-events.js
@@ -0,0 +1,58 @@
+/**
+ * 2054. Two Best Non-Overlapping Events
+ * https://leetcode.com/problems/two-best-non-overlapping-events/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed 2D integer array of events where
+ * events[i] = [startTimei, endTimei, valuei]. The ith event starts at
+ * startTimei and ends at endTimei, and if you attend this event, you will
+ * receive a value of valuei. You can choose at most two non-overlapping
+ * events to attend such that the sum of their values is maximized.
+ *
+ * Return this maximum sum.
+ *
+ * Note that the start time and end time is inclusive: that is, you cannot
+ * attend two events where one of them starts and the other ends at the
+ * same time. More specifically, if you attend an event with end time t,
+ * the next event must start at or after t + 1.
+ */
+
+/**
+ * @param {number[][]} events
+ * @return {number}
+ */
+var maxTwoEvents = function(events) {
+ events.sort((a, b) => a[1] - b[1]);
+
+ const maxValueUpTo = new Array(events.length);
+ maxValueUpTo[0] = events[0][2];
+
+ for (let i = 1; i < events.length; i++) {
+ maxValueUpTo[i] = Math.max(maxValueUpTo[i - 1], events[i][2]);
+ }
+
+ let result = 0;
+ for (let i = 0; i < events.length; i++) {
+ const [start, end, value] = events[i];
+ result = Math.max(result, value);
+
+ let left = 0;
+ let right = i - 1;
+ let bestIndex = -1;
+ while (left <= right) {
+ const mid = Math.floor((left + right) / 2);
+ if (events[mid][1] < start) {
+ bestIndex = mid;
+ left = mid + 1;
+ } else {
+ right = mid - 1;
+ }
+ }
+
+ if (bestIndex !== -1) {
+ result = Math.max(result, value + maxValueUpTo[bestIndex]);
+ }
+ }
+
+ return result;
+};
From 678bf3fc38fec7dcb3c2cbc961883072727c0968 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 25 Jul 2025 00:26:13 -0500
Subject: [PATCH 931/994] Add solution #2073
---
README.md | 1 +
solutions/2073-time-needed-to-buy-tickets.js | 39 ++++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/2073-time-needed-to-buy-tickets.js
diff --git a/README.md b/README.md
index e7e85223..66fb282c 100644
--- a/README.md
+++ b/README.md
@@ -1879,6 +1879,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|
+2073|[Time Needed to Buy Tickets](./solutions/2073-time-needed-to-buy-tickets.js)|Easy|
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|
diff --git a/solutions/2073-time-needed-to-buy-tickets.js b/solutions/2073-time-needed-to-buy-tickets.js
new file mode 100644
index 00000000..5feb01ff
--- /dev/null
+++ b/solutions/2073-time-needed-to-buy-tickets.js
@@ -0,0 +1,39 @@
+/**
+ * 2073. Time Needed to Buy Tickets
+ * https://leetcode.com/problems/time-needed-to-buy-tickets/
+ * Difficulty: Easy
+ *
+ * There are n people in a line queuing to buy tickets, where the 0th person is at the front
+ * of the line and the (n - 1)th person is at the back of the line.
+ *
+ * You are given a 0-indexed integer array tickets of length n where the number of tickets
+ * that the ith person would like to buy is tickets[i].
+ *
+ * Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a
+ * time and has to go back to the end of the line (which happens instantaneously) in order
+ * to buy more tickets. If a person does not have any tickets left to buy, the person will
+ * leave the line.
+ *
+ * Return the time taken for the person initially at position k (0-indexed) to finish buying
+ * tickets.
+ */
+
+/**
+ * @param {number[]} tickets
+ * @param {number} k
+ * @return {number}
+ */
+var timeRequiredToBuy = function(tickets, k) {
+ const target = tickets[k];
+ let result = 0;
+
+ for (let i = 0; i < tickets.length; i++) {
+ if (i <= k) {
+ result += Math.min(tickets[i], target);
+ } else {
+ result += Math.min(tickets[i], target - 1);
+ }
+ }
+
+ return result;
+};
From 6ea82d4fdedeead35477f32bcd4ca0ff45938918 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 26 Jul 2025 11:26:57 -0500
Subject: [PATCH 932/994] Add solution #3480
---
README.md | 1 +
...ays-after-removing-one-conflicting-pair.js | 49 +++++++++++++++++++
2 files changed, 50 insertions(+)
create mode 100644 solutions/3480-maximize-subarrays-after-removing-one-conflicting-pair.js
diff --git a/README.md b/README.md
index 66fb282c..99f01280 100644
--- a/README.md
+++ b/README.md
@@ -2713,6 +2713,7 @@
3464|[Maximize the Distance Between Points on a Square](./solutions/3464-maximize-the-distance-between-points-on-a-square.js)|Hard|
3466|[Maximum Coin Collection](./solutions/3466-maximum-coin-collection.js)|Medium|
3476|[Maximize Profit from Task Assignment](./solutions/3476-maximize-profit-from-task-assignment.js)|Medium|
+3480|[Maximize Subarrays After Removing One Conflicting Pair](./solutions/3480-maximize-subarrays-after-removing-one-conflicting-pair.js)|Hard|
3481|[Apply Substitutions](./solutions/3481-apply-substitutions.js)|Medium|
3487|[Maximum Unique Subarray Sum After Deletion](./solutions/3487-maximum-unique-subarray-sum-after-deletion.js)|Easy|
3491|[Phone Number Prefix](./solutions/3491-phone-number-prefix.js)|Easy|
diff --git a/solutions/3480-maximize-subarrays-after-removing-one-conflicting-pair.js b/solutions/3480-maximize-subarrays-after-removing-one-conflicting-pair.js
new file mode 100644
index 00000000..068940ff
--- /dev/null
+++ b/solutions/3480-maximize-subarrays-after-removing-one-conflicting-pair.js
@@ -0,0 +1,49 @@
+/**
+ * 3480. Maximize Subarrays After Removing One Conflicting Pair
+ * https://leetcode.com/problems/maximize-subarrays-after-removing-one-conflicting-pair/
+ * Difficulty: Hard
+ *
+ * You are given an integer n which represents an array nums containing the numbers from
+ * 1 to n in order. Additionally, you are given a 2D array conflictingPairs, where
+ * conflictingPairs[i] = [a, b] indicates that a and b form a conflicting pair.
+ *
+ * Remove exactly one element from conflictingPairs. Afterward, count the number of
+ * non-empty subarrays of nums which do not contain both a and b for any remaining
+ * conflicting pair [a, b].
+ *
+ * Return the maximum number of subarrays possible after removing exactly one conflicting pair.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} conflictingPairs
+ * @return {number}
+ */
+var maxSubarrays = function(n, conflictingPairs) {
+ const right = Array.from({ length: n + 1 }, () => []);
+
+ for (const [a, b] of conflictingPairs) {
+ right[Math.max(a, b)].push(Math.min(a, b));
+ }
+
+ let left = [0, 0];
+ let total = 0;
+ const bonus = new Array(n + 1).fill(0);
+ for (let r = 1; r <= n; r++) {
+ for (const l of right[r]) {
+ if (l > left[0]) {
+ left = [l, left[0]];
+ } else if (l > left[1]) {
+ left = [left[0], l];
+ }
+ }
+
+ total += r - left[0];
+
+ if (left[0] > 0) {
+ bonus[left[0]] += left[0] - left[1];
+ }
+ }
+
+ return total + Math.max(...bonus);
+};
From 5b823b033189128dd0862d88f9bb27ed2c655b85 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 26 Jul 2025 11:34:06 -0500
Subject: [PATCH 933/994] Add solution #2102
---
README.md | 1 +
.../2102-sequentially-ordinal-rank-tracker.js | 53 +++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 solutions/2102-sequentially-ordinal-rank-tracker.js
diff --git a/README.md b/README.md
index 99f01280..33dd1fd9 100644
--- a/README.md
+++ b/README.md
@@ -1906,6 +1906,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|
+2102|[Sequentially Ordinal Rank Tracker](./solutions/2102-sequentially-ordinal-rank-tracker.js)|Hard|
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|
diff --git a/solutions/2102-sequentially-ordinal-rank-tracker.js b/solutions/2102-sequentially-ordinal-rank-tracker.js
new file mode 100644
index 00000000..3f83c39c
--- /dev/null
+++ b/solutions/2102-sequentially-ordinal-rank-tracker.js
@@ -0,0 +1,53 @@
+/**
+ * 2102. Sequentially Ordinal Rank Tracker
+ * https://leetcode.com/problems/sequentially-ordinal-rank-tracker/
+ * Difficulty: Hard
+ *
+ * A scenic location is represented by its name and attractiveness score, where name is a unique
+ * string among all locations and score is an integer. Locations can be ranked from the best to
+ * the worst. The higher the score, the better the location. If the scores of two locations are
+ * equal, then the location with the lexicographically smaller name is better.
+ *
+ * You are building a system that tracks the ranking of locations with the system initially
+ * starting with no locations. It supports:
+ * - Adding scenic locations, one at a time.
+ * - Querying the ith best location of all locations already added, where i is the number of
+ * times the system has been queried (including the current query).
+ * - For example, when the system is queried for the 4th time, it returns the 4th best location
+ * of all locations already added.
+ *
+ * Note that the test data are generated so that at any time, the number of queries does not
+ * exceed the number of locations added to the system.
+ *
+ * Implement the SORTracker class:
+ * - SORTracker() Initializes the tracker system.
+ * - void add(string name, int score) Adds a scenic location with name and score to the system.
+ * - string get() Queries and returns the ith best location, where i is the number of times this
+ * method has been invoked (including this invocation).
+ */
+
+var SORTracker = function() {
+ this.count = 0;
+ this.minHeap = new PriorityQueue((a, b) => a[0] - b[0] || b[1].localeCompare(a[1]));
+ this.maxHeap = new PriorityQueue((a, b) => b[0] - a[0] || a[1].localeCompare(b[1]));
+};
+
+/**
+ * @param {string} name
+ * @param {number} score
+ * @return {void}
+ */
+SORTracker.prototype.add = function(name, score) {
+ this.minHeap.enqueue([score, name]);
+ this.maxHeap.enqueue(this.minHeap.dequeue());
+};
+
+/**
+ * @return {string}
+ */
+SORTracker.prototype.get = function() {
+ const maxElement = this.maxHeap.dequeue();
+ this.minHeap.enqueue(maxElement);
+
+ return maxElement[1];
+};
From c05bdcaf021400c1aed0725195c309a5e1aa36a4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 26 Jul 2025 11:37:05 -0500
Subject: [PATCH 934/994] Add solution #2146
---
README.md | 1 +
...ghest-ranked-items-within-a-price-range.js | 79 +++++++++++++++++++
2 files changed, 80 insertions(+)
create mode 100644 solutions/2146-k-highest-ranked-items-within-a-price-range.js
diff --git a/README.md b/README.md
index 33dd1fd9..de1de1d4 100644
--- a/README.md
+++ b/README.md
@@ -1947,6 +1947,7 @@
2143|[Choose Numbers From Two Arrays in Range](./solutions/2143-choose-numbers-from-two-arrays-in-range.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|
+2146|[K Highest Ranked Items Within a Price Range](./solutions/2146-k-highest-ranked-items-within-a-price-range.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|
diff --git a/solutions/2146-k-highest-ranked-items-within-a-price-range.js b/solutions/2146-k-highest-ranked-items-within-a-price-range.js
new file mode 100644
index 00000000..b0e9db12
--- /dev/null
+++ b/solutions/2146-k-highest-ranked-items-within-a-price-range.js
@@ -0,0 +1,79 @@
+/**
+ * 2146. K Highest Ranked Items Within a Price Range
+ * https://leetcode.com/problems/k-highest-ranked-items-within-a-price-range/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the
+ * items in a shop. The integers in the grid represent the following:
+ * - 0 represents a wall that you cannot pass through.
+ * - 1 represents an empty cell that you can freely move to and from.
+ *
+ * All other positive integers represent the price of an item in that cell. You may also freely
+ * move to and from these item cells.
+ *
+ * It takes 1 step to travel between adjacent grid cells.
+ *
+ * You are also given integer arrays pricing and start where pricing = [low, high] and
+ * start = [row, col] indicates that you start at the position (row, col) and are interested
+ * only in items with a price in the range of [low, high] (inclusive). You are further given
+ * an integer k.
+ *
+ * You are interested in the positions of the k highest-ranked items whose prices are within
+ * the given price range. The rank is determined by the first of these criteria that is different:
+ * 1. Distance, defined as the length of the shortest path from the start (shorter distance has
+ * a higher rank).
+ * 2. Price (lower price has a higher rank, but it must be in the price range).
+ * 3. The row number (smaller row number has a higher rank).
+ * 4. The column number (smaller column number has a higher rank).
+ *
+ * Return the k highest-ranked items within the price range sorted by their rank (highest to
+ * lowest). If there are fewer than k reachable items within the price range, return all of them.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @param {number[]} pricing
+ * @param {number[]} start
+ * @param {number} k
+ * @return {number[][]}
+ */
+var highestRankedKItems = function(grid, pricing, start, k) {
+ const [rows, cols] = [grid.length, grid[0].length];
+ const [low, high] = pricing;
+ const [startRow, startCol] = start;
+ const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]];
+ const queue = [[startRow, startCol, 0]];
+ const visited = new Set();
+ visited.add(`${startRow},${startCol}`);
+ const validItems = [];
+
+ while (queue.length > 0) {
+ const [row, col, distance] = queue.shift();
+ const price = grid[row][col];
+
+ if (price >= low && price <= high) {
+ validItems.push([distance, price, row, col]);
+ }
+
+ for (const [dr, dc] of directions) {
+ const newRow = row + dr;
+ const newCol = col + dc;
+ const key = `${newRow},${newCol}`;
+
+ if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols
+ && grid[newRow][newCol] > 0 && !visited.has(key)) {
+ visited.add(key);
+ queue.push([newRow, newCol, distance + 1]);
+ }
+ }
+ }
+
+ validItems.sort((a, b) => {
+ if (a[0] !== b[0]) return a[0] - b[0];
+ if (a[1] !== b[1]) return a[1] - b[1];
+ if (a[2] !== b[2]) return a[2] - b[2];
+ return a[3] - b[3];
+ });
+
+ return validItems.slice(0, k).map(item => [item[2], item[3]]);
+};
From ba18ec578f8cd7033bdff810883e3f388b17aae7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 26 Jul 2025 11:38:17 -0500
Subject: [PATCH 935/994] Add solution #2182
---
README.md | 1 +
...2182-construct-string-with-repeat-limit.js | 60 +++++++++++++++++++
2 files changed, 61 insertions(+)
create mode 100644 solutions/2182-construct-string-with-repeat-limit.js
diff --git a/README.md b/README.md
index de1de1d4..fc426eed 100644
--- a/README.md
+++ b/README.md
@@ -1979,6 +1979,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|
+2182|[Construct String With Repeat Limit](./solutions/2182-construct-string-with-repeat-limit.js)|Medium|
2183|[Count Array Pairs Divisible by K](./solutions/2183-count-array-pairs-divisible-by-k.js)|Hard|
2184|[Number of Ways to Build Sturdy Brick Wall](./solutions/2184-number-of-ways-to-build-sturdy-brick-wall.js)|Medium|
2185|[Counting Words With a Given Prefix](./solutions/2185-counting-words-with-a-given-prefix.js)|Easy|
diff --git a/solutions/2182-construct-string-with-repeat-limit.js b/solutions/2182-construct-string-with-repeat-limit.js
new file mode 100644
index 00000000..15896132
--- /dev/null
+++ b/solutions/2182-construct-string-with-repeat-limit.js
@@ -0,0 +1,60 @@
+/**
+ * 2182. Construct String With Repeat Limit
+ * https://leetcode.com/problems/construct-string-with-repeat-limit/
+ * Difficulty: Medium
+ *
+ * You are given a string s and an integer repeatLimit. Construct a new string
+ * repeatLimitedString using the characters of s such that no letter appears more than
+ * repeatLimit times in a row. You do not have to use all characters from s.
+ *
+ * Return the lexicographically largest repeatLimitedString possible.
+ *
+ * A string a is lexicographically larger than a string b if in the first position where
+ * a and b differ, string a has a letter that appears later in the alphabet than the
+ * corresponding letter in b. If the first min(a.length, b.length) characters do not differ,
+ * then the longer string is the lexicographically larger one.
+ */
+
+/**
+ * @param {string} s
+ * @param {number} repeatLimit
+ * @return {string}
+ */
+var repeatLimitedString = function(s, repeatLimit) {
+ const frequency = new Array(26).fill(0);
+ for (const char of s) {
+ frequency[char.charCodeAt(0) - 97]++;
+ }
+
+ const result = [];
+ let currentChar = 25;
+
+ while (currentChar >= 0) {
+ if (frequency[currentChar] === 0) {
+ currentChar--;
+ continue;
+ }
+
+ const useCount = Math.min(frequency[currentChar], repeatLimit);
+ for (let i = 0; i < useCount; i++) {
+ result.push(String.fromCharCode(currentChar + 97));
+ }
+ frequency[currentChar] -= useCount;
+
+ if (frequency[currentChar] > 0) {
+ let nextChar = currentChar - 1;
+ while (nextChar >= 0 && frequency[nextChar] === 0) {
+ nextChar--;
+ }
+
+ if (nextChar < 0) break;
+
+ result.push(String.fromCharCode(nextChar + 97));
+ frequency[nextChar]--;
+ } else {
+ currentChar--;
+ }
+ }
+
+ return result.join('');
+};
From 16da511649f2ad0738031f9411ef8989ccfbbde4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 26 Jul 2025 12:14:09 -0500
Subject: [PATCH 936/994] Add solution #2208
---
README.md | 1 +
...8-minimum-operations-to-halve-array-sum.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/2208-minimum-operations-to-halve-array-sum.js
diff --git a/README.md b/README.md
index fc426eed..1ca4fb08 100644
--- a/README.md
+++ b/README.md
@@ -2003,6 +2003,7 @@
2204|[Distance to a Cycle in Undirected Graph](./solutions/2204-distance-to-a-cycle-in-undirected-graph.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|
+2208|[Minimum Operations to Halve Array Sum](./solutions/2208-minimum-operations-to-halve-array-sum.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|
diff --git a/solutions/2208-minimum-operations-to-halve-array-sum.js b/solutions/2208-minimum-operations-to-halve-array-sum.js
new file mode 100644
index 00000000..dffd4cd0
--- /dev/null
+++ b/solutions/2208-minimum-operations-to-halve-array-sum.js
@@ -0,0 +1,39 @@
+/**
+ * 2208. Minimum Operations to Halve Array Sum
+ * https://leetcode.com/problems/minimum-operations-to-halve-array-sum/
+ * Difficulty: Medium
+ *
+ * You are given an array nums of positive integers. In one operation, you can choose any
+ * number from nums and reduce it to exactly half the number. (Note that you may choose
+ * this reduced number in future operations.)
+ *
+ * Return the minimum number of operations to reduce the sum of nums by at least half.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var halveArray = function(nums) {
+ const pq = new PriorityQueue((a, b) => b - a);
+ let totalSum = 0;
+
+ for (const num of nums) {
+ pq.enqueue(num);
+ totalSum += num;
+ }
+
+ const target = totalSum / 2;
+ let reducedSum = 0;
+ let result = 0;
+
+ while (reducedSum < target) {
+ const largest = pq.dequeue();
+ const halved = largest / 2;
+ reducedSum += halved;
+ pq.enqueue(halved);
+ result++;
+ }
+
+ return result;
+};
From 23e5ba736dd4d30f875201cb40a323f9e328527f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 27 Jul 2025 18:41:12 -0500
Subject: [PATCH 937/994] Add solution #2231
---
README.md | 1 +
...gest-number-after-digit-swaps-by-parity.js | 45 +++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/2231-largest-number-after-digit-swaps-by-parity.js
diff --git a/README.md b/README.md
index 1ca4fb08..28e4a373 100644
--- a/README.md
+++ b/README.md
@@ -2024,6 +2024,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|
2229|[Check if an Array Is Consecutive](./solutions/2229-check-if-an-array-is-consecutive.js)|Easy|
+2231|[Largest Number After Digit Swaps by Parity](./solutions/2231-largest-number-after-digit-swaps-by-parity.js)|Easy|
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|
diff --git a/solutions/2231-largest-number-after-digit-swaps-by-parity.js b/solutions/2231-largest-number-after-digit-swaps-by-parity.js
new file mode 100644
index 00000000..c7b43b77
--- /dev/null
+++ b/solutions/2231-largest-number-after-digit-swaps-by-parity.js
@@ -0,0 +1,45 @@
+/**
+ * 2231. Largest Number After Digit Swaps by Parity
+ * https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/
+ * Difficulty: Easy
+ *
+ * You are given a positive integer num. You may swap any two digits of num that have the
+ * same parity (i.e. both odd digits or both even digits).
+ *
+ * Return the largest possible value of num after any number of swaps.
+ */
+
+/**
+ * @param {number} num
+ * @return {number}
+ */
+var largestInteger = function(num) {
+ const digits = num.toString().split('').map(Number);
+ const evenDigits = [];
+ const oddDigits = [];
+
+ for (const digit of digits) {
+ if (digit % 2 === 0) {
+ evenDigits.push(digit);
+ } else {
+ oddDigits.push(digit);
+ }
+ }
+
+ evenDigits.sort((a, b) => b - a);
+ oddDigits.sort((a, b) => b - a);
+
+ let evenIndex = 0;
+ let oddIndex = 0;
+ const result = [];
+
+ for (const digit of digits) {
+ if (digit % 2 === 0) {
+ result.push(evenDigits[evenIndex++]);
+ } else {
+ result.push(oddDigits[oddIndex++]);
+ }
+ }
+
+ return parseInt(result.join(''), 10);
+};
From 9ad7f5fbcf6f9de4ff29d5e68a74796e92e10a1c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 27 Jul 2025 23:43:02 -0500
Subject: [PATCH 938/994] Add solution #2233
---
README.md | 1 +
...2233-maximum-product-after-k-increments.js | 38 +++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2233-maximum-product-after-k-increments.js
diff --git a/README.md b/README.md
index 28e4a373..01293c2a 100644
--- a/README.md
+++ b/README.md
@@ -2026,6 +2026,7 @@
2229|[Check if an Array Is Consecutive](./solutions/2229-check-if-an-array-is-consecutive.js)|Easy|
2231|[Largest Number After Digit Swaps by Parity](./solutions/2231-largest-number-after-digit-swaps-by-parity.js)|Easy|
2232|[Minimize Result by Adding Parentheses to Expression](./solutions/2232-minimize-result-by-adding-parentheses-to-expression.js)|Medium|
+2233|[Maximum Product After K Increments](./solutions/2233-maximum-product-after-k-increments.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|
diff --git a/solutions/2233-maximum-product-after-k-increments.js b/solutions/2233-maximum-product-after-k-increments.js
new file mode 100644
index 00000000..2b1b61b0
--- /dev/null
+++ b/solutions/2233-maximum-product-after-k-increments.js
@@ -0,0 +1,38 @@
+/**
+ * 2233. Maximum Product After K Increments
+ * https://leetcode.com/problems/maximum-product-after-k-increments/
+ * Difficulty: Medium
+ *
+ * You are given an array of non-negative integers nums and an integer k. In one operation,
+ * you may choose any element from nums and increment it by 1.
+ *
+ * Return the maximum product of nums after at most k operations. Since the answer may be
+ * very large, return it modulo 109 + 7. Note that you should maximize the product before
+ * taking the modulo.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var maximumProduct = function(nums, k) {
+ const MOD = 1e9 + 7;
+ const minHeap = new PriorityQueue((a, b) => a - b);
+
+ for (const num of nums) {
+ minHeap.enqueue(num);
+ }
+
+ for (let i = 0; i < k; i++) {
+ const smallest = minHeap.dequeue();
+ minHeap.enqueue(smallest + 1);
+ }
+
+ let result = 1;
+ while (!minHeap.isEmpty()) {
+ result = (result * minHeap.dequeue()) % MOD;
+ }
+
+ return result;
+};
From 3adfc2a31c78b7a822fd40e617cfe0802149c920 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sun, 27 Jul 2025 23:54:28 -0500
Subject: [PATCH 939/994] Add solution #2276
---
README.md | 1 +
solutions/2276-count-integers-in-intervals.js | 80 +++++++++++++++++++
2 files changed, 81 insertions(+)
create mode 100644 solutions/2276-count-integers-in-intervals.js
diff --git a/README.md b/README.md
index 01293c2a..4a549cb0 100644
--- a/README.md
+++ b/README.md
@@ -2066,6 +2066,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|
+2276|[Count Integers in Intervals](./solutions/2276-count-integers-in-intervals.js)|Hard|
2277|[Closest Node to Path in Tree](./solutions/2277-closest-node-to-path-in-tree.js)|Hard|
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|
diff --git a/solutions/2276-count-integers-in-intervals.js b/solutions/2276-count-integers-in-intervals.js
new file mode 100644
index 00000000..1db3160b
--- /dev/null
+++ b/solutions/2276-count-integers-in-intervals.js
@@ -0,0 +1,80 @@
+/**
+ * 2276. Count Integers in Intervals
+ * https://leetcode.com/problems/count-integers-in-intervals/
+ * Difficulty: Hard
+ *
+ * Given an empty set of intervals, implement a data structure that can:
+ * - Add an interval to the set of intervals.
+ * - Count the number of integers that are present in at least one interval.
+ *
+ * Implement the CountIntervals class:
+ * - CountIntervals() Initializes the object with an empty set of intervals.
+ * - void add(int left, int right) Adds the interval [left, right] to the set of intervals.
+ * - int count() Returns the number of integers that are present in at least one interval.
+ *
+ * Note that an interval [left, right] denotes all the integers x where left <= x <= right.
+ */
+
+var CountIntervals = function() {
+ this.coverage = 0;
+ this.intervals = [[-Infinity, -Infinity], [Infinity, Infinity]];
+};
+
+/**
+ * @param {number} left
+ * @param {number} right
+ * @return {void}
+ */
+CountIntervals.prototype.add = function(left, right) {
+ function bisectLeft(arr, target) {
+ let low = 0;
+ let high = arr.length;
+ while (low < high) {
+ const mid = Math.floor((low + high) / 2);
+ if (arr[mid][0] < target) {
+ low = mid + 1;
+ } else {
+ high = mid;
+ }
+ }
+ return low;
+ }
+
+ function bisectRight(arr, target) {
+ let low = 0;
+ let high = arr.length;
+ while (low < high) {
+ const mid = Math.floor((low + high) / 2);
+ if (arr[mid][0] <= target) {
+ low = mid + 1;
+ } else {
+ high = mid;
+ }
+ }
+ return low;
+ }
+
+ let li = bisectLeft(this.intervals, left - 1);
+ if (this.intervals[li - 1][1] >= left - 1) {
+ li -= 1;
+ }
+
+ const lval = Math.min(this.intervals[li][0], left);
+ const ri = bisectRight(this.intervals, right + 1);
+ const rval = Math.max(this.intervals[ri - 1][1], right);
+
+ let toDelete = 0;
+ for (let i = li; i < ri; i++) {
+ toDelete += this.intervals[i][1] - this.intervals[i][0] + 1;
+ }
+
+ this.coverage += rval - lval + 1 - toDelete;
+ this.intervals.splice(li, ri - li, [lval, rval]);
+};
+
+/**
+ * @return {number}
+ */
+CountIntervals.prototype.count = function() {
+ return this.coverage;
+};
From 931ef01dfa69376d57b4d7b328c53e061fc09f3d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 28 Jul 2025 23:31:29 -0500
Subject: [PATCH 940/994] Add solution #2281
---
README.md | 1 +
.../2281-sum-of-total-strength-of-wizards.js | 82 +++++++++++++++++++
2 files changed, 83 insertions(+)
create mode 100644 solutions/2281-sum-of-total-strength-of-wizards.js
diff --git a/README.md b/README.md
index 4a549cb0..cd07f3fd 100644
--- a/README.md
+++ b/README.md
@@ -2071,6 +2071,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|
2280|[Minimum Lines to Represent a Line Chart](./solutions/2280-minimum-lines-to-represent-a-line-chart.js)|Medium|
+2281|[Sum of Total Strength of Wizards](./solutions/2281-sum-of-total-strength-of-wizards.js)|Hard|
2282|[Number of People That Can Be Seen in a Grid](./solutions/2282-number-of-people-that-can-be-seen-in-a-grid.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|
diff --git a/solutions/2281-sum-of-total-strength-of-wizards.js b/solutions/2281-sum-of-total-strength-of-wizards.js
new file mode 100644
index 00000000..8d477c20
--- /dev/null
+++ b/solutions/2281-sum-of-total-strength-of-wizards.js
@@ -0,0 +1,82 @@
+/**
+ * 2281. Sum of Total Strength of Wizards
+ * https://leetcode.com/problems/sum-of-total-strength-of-wizards/
+ * Difficulty: Hard
+ *
+ * As the ruler of a kingdom, you have an army of wizards at your command.
+ *
+ * You are given a 0-indexed integer array strength, where strength[i] denotes the strength
+ * of the ith wizard. For a contiguous group of wizards (i.e. the wizards' strengths form
+ * a subarray of strength), the total strength is defined as the product of the following
+ * two values:
+ * - The strength of the weakest wizard in the group.
+ * - The total of all the individual strengths of the wizards in the group.
+ *
+ * Return the sum of the total strengths of all contiguous groups of wizards. Since the answer
+ * may be very large, return it modulo 109 + 7.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} strength
+ * @return {number}
+ */
+var totalStrength = function(strength) {
+ const n = strength.length;
+ const mod = BigInt(1e9 + 7);
+ const left = new Array(n).fill(-1);
+ const right = new Array(n).fill(n);
+
+ const stack = [];
+
+ for (let i = 0; i < n; ++i) {
+ while (stack.length > 0 && strength[stack[stack.length - 1]] >= strength[i]) {
+ stack.pop();
+ }
+ if (stack.length > 0) {
+ left[i] = stack[stack.length - 1];
+ }
+ stack.push(i);
+ }
+
+ stack.length = 0;
+
+ for (let i = n - 1; i >= 0; --i) {
+ while (stack.length > 0 && strength[stack[stack.length - 1]] > strength[i]) {
+ stack.pop();
+ }
+ if (stack.length > 0) {
+ right[i] = stack[stack.length - 1];
+ }
+ stack.push(i);
+ }
+
+ const prefixSum = new Array(n + 1).fill(0n);
+ for (let i = 0; i < n; ++i) {
+ prefixSum[i + 1] = (prefixSum[i] + BigInt(strength[i])) % mod;
+ }
+
+ const prefixSumOfPrefixSum = new Array(n + 2).fill(0n);
+ for (let i = 0; i < n + 1; ++i) {
+ prefixSumOfPrefixSum[i + 1] = (prefixSumOfPrefixSum[i] + prefixSum[i]) % mod;
+ }
+
+ let result = 0n;
+ for (let i = 0; i < n; ++i) {
+ const value = BigInt(strength[i]);
+ const l = left[i] + 1;
+ const r = right[i] - 1;
+ const leftSum = (prefixSumOfPrefixSum[i + 1] - prefixSumOfPrefixSum[l] + mod) % mod;
+ const rightSum = (prefixSumOfPrefixSum[r + 2] - prefixSumOfPrefixSum[i + 1] + mod) % mod;
+ const leftCount = BigInt(i - l + 1);
+ const rightCount = BigInt(r - i + 1);
+ const leftPart = (rightSum * leftCount) % mod;
+ const rightPart = (leftSum * rightCount) % mod;
+ const contribution = (value * ((leftPart - rightPart + mod) % mod)) % mod;
+
+ result = (result + contribution) % mod;
+ }
+
+ return Number(result);
+};
From 15258867b1c7dee8cfc71ab2053f6ac60089d68e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 28 Jul 2025 23:32:49 -0500
Subject: [PATCH 941/994] Add solution #2285
---
README.md | 1 +
.../2285-maximum-total-importance-of-roads.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/2285-maximum-total-importance-of-roads.js
diff --git a/README.md b/README.md
index cd07f3fd..5d942b13 100644
--- a/README.md
+++ b/README.md
@@ -2075,6 +2075,7 @@
2282|[Number of People That Can Be Seen in a Grid](./solutions/2282-number-of-people-that-can-be-seen-in-a-grid.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|
+2285|[Maximum Total Importance of Roads](./solutions/2285-maximum-total-importance-of-roads.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|
2291|[Maximum Profit From Trading Stocks](./solutions/2291-maximum-profit-from-trading-stocks.js)|Medium|
diff --git a/solutions/2285-maximum-total-importance-of-roads.js b/solutions/2285-maximum-total-importance-of-roads.js
new file mode 100644
index 00000000..47964c64
--- /dev/null
+++ b/solutions/2285-maximum-total-importance-of-roads.js
@@ -0,0 +1,42 @@
+/**
+ * 2285. Maximum Total Importance of Roads
+ * https://leetcode.com/problems/maximum-total-importance-of-roads/
+ * Difficulty: Medium
+ *
+ * You are given an integer n denoting the number of cities in a country. The cities are
+ * numbered from 0 to n - 1.
+ *
+ * You are also given a 2D integer array roads where roads[i] = [ai, bi] denotes that there
+ * exists a bidirectional road connecting cities ai and bi.
+ *
+ * You need to assign each city with an integer value from 1 to n, where each value can
+ * only be used once. The importance of a road is then defined as the sum of the values
+ * of the two cities it connects.
+ *
+ * Return the maximum total importance of all roads possible after assigning the values
+ * optimally.
+ */
+
+/**
+ * @param {number} n
+ * @param {number[][]} roads
+ * @return {number}
+ */
+var maximumImportance = function(n, roads) {
+ const degrees = new Array(n).fill(0);
+
+ for (const [a, b] of roads) {
+ degrees[a]++;
+ degrees[b]++;
+ }
+
+ const cities = Array.from({ length: n }, (_, i) => i);
+ cities.sort((a, b) => degrees[b] - degrees[a]);
+
+ let result = 0;
+ for (let i = 0; i < n; i++) {
+ result += degrees[cities[i]] * (n - i);
+ }
+
+ return result;
+};
From 683fba6a55292691a60763a80333da462e7b17f7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 28 Jul 2025 23:41:17 -0500
Subject: [PATCH 942/994] Add solution #2286
---
README.md | 1 +
.../2286-booking-concert-tickets-in-groups.js | 184 ++++++++++++++++++
2 files changed, 185 insertions(+)
create mode 100644 solutions/2286-booking-concert-tickets-in-groups.js
diff --git a/README.md b/README.md
index 5d942b13..2cc29f70 100644
--- a/README.md
+++ b/README.md
@@ -2076,6 +2076,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|
2285|[Maximum Total Importance of Roads](./solutions/2285-maximum-total-importance-of-roads.js)|Medium|
+2286|[Booking Concert Tickets in Groups](./solutions/2286-booking-concert-tickets-in-groups.js)|Hard|
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|
2291|[Maximum Profit From Trading Stocks](./solutions/2291-maximum-profit-from-trading-stocks.js)|Medium|
diff --git a/solutions/2286-booking-concert-tickets-in-groups.js b/solutions/2286-booking-concert-tickets-in-groups.js
new file mode 100644
index 00000000..4e85bb43
--- /dev/null
+++ b/solutions/2286-booking-concert-tickets-in-groups.js
@@ -0,0 +1,184 @@
+/**
+ * 2286. Booking Concert Tickets in Groups
+ * https://leetcode.com/problems/booking-concert-tickets-in-groups/
+ * Difficulty: Hard
+ *
+ * A concert hall has n rows numbered from 0 to n - 1, each with m seats, numbered from
+ * 0 to m - 1. You need to design a ticketing system that can allocate seats in the following cases:
+ * - If a group of k spectators can sit together in a row.
+ * - If every member of a group of k spectators can get a seat. They may or may not sit together.
+ *
+ * Note that the spectators are very picky. Hence:
+ * - They will book seats only if each member of their group can get a seat with row number less
+ * than or equal to maxRow. maxRow can vary from group to group.
+ * - In case there are multiple rows to choose from, the row with the smallest number is chosen.
+ * If there are multiple seats to choose in the same row, the seat with the smallest number is
+ * chosen.
+ *
+ * Implement the BookMyShow class:
+ * - BookMyShow(int n, int m) Initializes the object with n as number of rows and m as number of
+ * seats per row.
+ * - int[] gather(int k, int maxRow) Returns an array of length 2 denoting the row and seat number
+ * (respectively) of the first seat being allocated to the k members of the group, who must sit
+ * together. In other words, it returns the smallest possible r and c such that all [c, c + k - 1]
+ * seats are valid and empty in row r, and r <= maxRow. Returns [] in case it is not possible to
+ * allocate seats to the group.
+ * - boolean scatter(int k, int maxRow) Returns true if all k members of the group can be allocated
+ * seats in rows 0 to maxRow, who may or may not sit together. If the seats can be allocated, it
+ * allocates k seats to the group with the smallest row numbers, and the smallest possible seat
+ * numbers in each row. Otherwise, returns false.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} m
+ */
+var BookMyShow = function(n, m) {
+ this.n = n;
+ this.m = m;
+
+ let size = 1;
+ while (size < n * 2) {
+ size <<= 1;
+ }
+ this.segmentTree = new Array(size).fill(0).map(() => [0, 0]);
+
+ this.build(0, 0, n - 1);
+};
+
+/**
+ * @param {number} k
+ * @param {number} maxRow
+ * @return {number[]}
+ */
+BookMyShow.prototype.gather = function(k, maxRow) {
+ const result = this.queryMax(0, 0, this.n - 1, k, maxRow);
+ if (result.length) {
+ this.updateMax(0, 0, this.n - 1, result[0], k);
+ }
+ return result;
+};
+
+/**
+ * @param {number} k
+ * @param {number} maxRow
+ * @return {boolean}
+ */
+BookMyShow.prototype.scatter = function(k, maxRow) {
+ const totalAvailable = this.querySum(0, 0, this.n - 1, maxRow);
+ const canScatter = totalAvailable >= k;
+ if (canScatter) {
+ this.updateSum(0, 0, this.n - 1, k, maxRow);
+ }
+ return canScatter;
+};
+
+/**
+ * @param {number} index
+ * @param {number} left
+ * @param {number} right
+ */
+BookMyShow.prototype.build = function(index, left, right) {
+ if (left === right) {
+ this.segmentTree[index] = [this.m, this.m];
+ return;
+ }
+ const mid = Math.floor((left + right) / 2);
+ this.segmentTree[index] = [this.m, (right - left + 1) * this.m];
+ this.build(2 * index + 1, left, mid);
+ this.build(2 * index + 2, mid + 1, right);
+};
+
+/**
+ * @param {number} index
+ * @param {number} left
+ * @param {number} right
+ * @param {number} k
+ * @param {number} maxRow
+ * @return {number[]}
+ */
+BookMyShow.prototype.queryMax = function(index, left, right, k, maxRow) {
+ if (left > maxRow) return [];
+ if (this.segmentTree[index][0] < k) return [];
+ if (left === right) {
+ return [left, this.m - this.segmentTree[index][0]];
+ }
+
+ const mid = Math.floor((left + right) / 2);
+ const leftResult = this.queryMax(2 * index + 1, left, mid, k, maxRow);
+ if (leftResult.length) return leftResult;
+ return this.queryMax(2 * index + 2, mid + 1, right, k, maxRow);
+};
+
+/**
+ * @param {number} index
+ * @param {number} left
+ * @param {number} right
+ * @param {number} row
+ * @param {number} k
+ */
+BookMyShow.prototype.updateMax = function(index, left, right, row, k) {
+ if (left > row || right < row) return;
+ if (left === right) {
+ this.segmentTree[index][0] -= k;
+ this.segmentTree[index][1] -= k;
+ return;
+ }
+
+ const mid = Math.floor((left + right) / 2);
+ this.segmentTree[index][1] -= k;
+ this.updateMax(2 * index + 1, left, mid, row, k);
+ this.updateMax(2 * index + 2, mid + 1, right, row, k);
+ this.segmentTree[index][0] = Math.max(
+ this.segmentTree[2 * index + 1][0],
+ this.segmentTree[2 * index + 2][0]
+ );
+};
+
+/**
+ * @param {number} index
+ * @param {number} left
+ * @param {number} right
+ * @param {number} maxRow
+ * @return {number}
+ */
+BookMyShow.prototype.querySum = function(index, left, right, maxRow) {
+ if (left > maxRow) return 0;
+ if (right <= maxRow) return this.segmentTree[index][1];
+
+ const mid = Math.floor((left + right) / 2);
+ return this.querySum(2 * index + 1, left, mid, maxRow)
+ + this.querySum(2 * index + 2, mid + 1, right, maxRow);
+};
+
+/**
+ * @param {number} index
+ * @param {number} left
+ * @param {number} right
+ * @param {number} k
+ * @param {number} maxRow
+ */
+BookMyShow.prototype.updateSum = function(index, left, right, k, maxRow) {
+ if (left > maxRow) return;
+ if (left === right) {
+ this.segmentTree[index][0] -= k;
+ this.segmentTree[index][1] -= k;
+ return;
+ }
+
+ const mid = Math.floor((left + right) / 2);
+ this.segmentTree[index][1] -= k;
+
+ if (mid + 1 > maxRow || this.segmentTree[2 * index + 1][1] >= k) {
+ this.updateSum(2 * index + 1, left, mid, k, maxRow);
+ } else {
+ const leftSum = this.segmentTree[2 * index + 1][1];
+ this.updateSum(2 * index + 1, left, mid, leftSum, maxRow);
+ this.updateSum(2 * index + 2, mid + 1, right, k - leftSum, maxRow);
+ }
+
+ this.segmentTree[index][0] = Math.max(
+ this.segmentTree[2 * index + 1][0],
+ this.segmentTree[2 * index + 2][0]
+ );
+};
From 89f859e5c07fcd5b5aba4f5baa277beb5cb9f18c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 28 Jul 2025 23:42:30 -0500
Subject: [PATCH 943/994] Add solution #2289
---
README.md | 1 +
...2289-steps-to-make-array-non-decreasing.js | 32 +++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 solutions/2289-steps-to-make-array-non-decreasing.js
diff --git a/README.md b/README.md
index 2cc29f70..075729bd 100644
--- a/README.md
+++ b/README.md
@@ -2079,6 +2079,7 @@
2286|[Booking Concert Tickets in Groups](./solutions/2286-booking-concert-tickets-in-groups.js)|Hard|
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|
+2289|[Steps to Make Array Non-decreasing](./solutions/2289-steps-to-make-array-non-decreasing.js)|Medium|
2291|[Maximum Profit From Trading Stocks](./solutions/2291-maximum-profit-from-trading-stocks.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|
diff --git a/solutions/2289-steps-to-make-array-non-decreasing.js b/solutions/2289-steps-to-make-array-non-decreasing.js
new file mode 100644
index 00000000..8556f9a2
--- /dev/null
+++ b/solutions/2289-steps-to-make-array-non-decreasing.js
@@ -0,0 +1,32 @@
+/**
+ * 2289. Steps to Make Array Non-decreasing
+ * https://leetcode.com/problems/steps-to-make-array-non-decreasing/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array nums. In one step, remove all elements nums[i]
+ * where nums[i - 1] > nums[i] for all 0 < i < nums.length.
+ *
+ * Return the number of steps performed until nums becomes a non-decreasing array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var totalSteps = function(nums) {
+ const n = nums.length;
+ const stack = [];
+ const steps = new Array(n).fill(0);
+ let result = 0;
+
+ for (let i = n - 1; i >= 0; i--) {
+ while (stack.length && nums[i] > nums[stack[stack.length - 1]]) {
+ const j = stack.pop();
+ steps[i] = Math.max(steps[i] + 1, steps[j]);
+ }
+ result = Math.max(result, steps[i]);
+ stack.push(i);
+ }
+
+ return result;
+};
From e085979dfc7885fa4cdef761fa48f4d5c45f5cf9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 29 Jul 2025 23:42:57 -0500
Subject: [PATCH 944/994] Add solution #2290
---
README.md | 1 +
...inimum-obstacle-removal-to-reach-corner.js | 60 +++++++++++++++++++
2 files changed, 61 insertions(+)
create mode 100644 solutions/2290-minimum-obstacle-removal-to-reach-corner.js
diff --git a/README.md b/README.md
index 075729bd..b6bc06ed 100644
--- a/README.md
+++ b/README.md
@@ -2080,6 +2080,7 @@
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|
2289|[Steps to Make Array Non-decreasing](./solutions/2289-steps-to-make-array-non-decreasing.js)|Medium|
+2290|[Minimum Obstacle Removal to Reach Corner](./solutions/2290-minimum-obstacle-removal-to-reach-corner.js)|Hard|
2291|[Maximum Profit From Trading Stocks](./solutions/2291-maximum-profit-from-trading-stocks.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|
diff --git a/solutions/2290-minimum-obstacle-removal-to-reach-corner.js b/solutions/2290-minimum-obstacle-removal-to-reach-corner.js
new file mode 100644
index 00000000..c1559b8d
--- /dev/null
+++ b/solutions/2290-minimum-obstacle-removal-to-reach-corner.js
@@ -0,0 +1,60 @@
+/**
+ * 2290. Minimum Obstacle Removal to Reach Corner
+ * https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner/
+ * Difficulty: Hard
+ *
+ * You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values:
+ * - 0 represents an empty cell,
+ * - 1 represents an obstacle that may be removed.
+ *
+ * You can move up, down, left, or right from and to an empty cell.
+ *
+ * Return the minimum number of obstacles to remove so you can move from the upper left corner
+ * (0, 0) to the lower right corner (m - 1, n - 1).
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var minimumObstacles = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]];
+ const dp = new Array(rows).fill().map(() => new Array(cols).fill(Number.MAX_SAFE_INTEGER));
+ const queue = [[0, 0, 0]];
+ let result = rows * cols + 1;
+
+ while (queue.length > 0) {
+ const levelSize = queue.length;
+ for (let l = 0; l < levelSize; l++) {
+ const [i, j, cost] = queue.shift();
+
+ if (i === rows - 1 && j === cols - 1) {
+ result = Math.min(result, cost);
+ continue;
+ }
+
+ if (cost > dp[i][j]) {
+ continue;
+ }
+
+ for (const [dx, dy] of directions) {
+ const newI = i + dx;
+ const newJ = j + dy;
+
+ if (isValid(newI, newJ, cost)) {
+ queue.push([newI, newJ, dp[newI][newJ]]);
+ }
+ }
+ }
+ }
+
+ return result;
+
+ function isValid(i, j, cost) {
+ const valid = i >= 0 && j >= 0 && i < rows && j < cols && dp[i][j] > cost + grid[i][j];
+ if (valid) dp[i][j] = cost + grid[i][j];
+ return valid;
+ }
+};
From cfc9ecb818164228528b56cba68a90700750a706 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 29 Jul 2025 23:44:12 -0500
Subject: [PATCH 945/994] Add solution #2310
---
README.md | 1 +
.../2310-sum-of-numbers-with-units-digit-k.js | 33 +++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 solutions/2310-sum-of-numbers-with-units-digit-k.js
diff --git a/README.md b/README.md
index b6bc06ed..34c73a0c 100644
--- a/README.md
+++ b/README.md
@@ -2097,6 +2097,7 @@
2306|[Naming a Company](./solutions/2306-naming-a-company.js)|Hard|
2307|[Check for Contradictions in Equations](./solutions/2307-check-for-contradictions-in-equations.js)|Hard|
2309|[Greatest English Letter in Upper and Lower Case](./solutions/2309-greatest-english-letter-in-upper-and-lower-case.js)|Easy|
+2310|[Sum of Numbers With Units Digit K](./solutions/2310-sum-of-numbers-with-units-digit-k.js)|Medium|
2311|[Longest Binary Subsequence Less Than or Equal to K](./solutions/2311-longest-binary-subsequence-less-than-or-equal-to-k.js)|Medium|
2312|[Selling Pieces of Wood](./solutions/2312-selling-pieces-of-wood.js)|Hard|
2313|[Minimum Flips in Binary Tree to Get Result](./solutions/2313-minimum-flips-in-binary-tree-to-get-result.js)|Hard|
diff --git a/solutions/2310-sum-of-numbers-with-units-digit-k.js b/solutions/2310-sum-of-numbers-with-units-digit-k.js
new file mode 100644
index 00000000..edf6abeb
--- /dev/null
+++ b/solutions/2310-sum-of-numbers-with-units-digit-k.js
@@ -0,0 +1,33 @@
+/**
+ * 2310. Sum of Numbers With Units Digit K
+ * https://leetcode.com/problems/sum-of-numbers-with-units-digit-k/
+ * Difficulty: Medium
+ *
+ * Given two integers num and k, consider a set of positive integers with the following properties:
+ * - The units digit of each integer is k.
+ * - The sum of the integers is num.
+ *
+ * Return the minimum possible size of such a set, or -1 if no such set exists.
+ *
+ * Note:
+ * - The set can contain multiple instances of the same integer, and the sum of an empty set is
+ * considered 0.
+ * - The units digit of a number is the rightmost digit of the number.
+ */
+
+/**
+ * @param {number} num
+ * @param {number} k
+ * @return {number}
+ */
+var minimumNumbers = function(num, k) {
+ if (num === 0) return 0;
+
+ for (let count = 1; count <= 10; count++) {
+ if ((count * k) % 10 === num % 10 && count * k <= num) {
+ return count;
+ }
+ }
+
+ return -1;
+};
From 217e147183af6d80baea7a46bbc2b33b5279512a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 29 Jul 2025 23:45:18 -0500
Subject: [PATCH 946/994] Add solution #2327
---
README.md | 1 +
...2327-number-of-people-aware-of-a-secret.js | 43 +++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/2327-number-of-people-aware-of-a-secret.js
diff --git a/README.md b/README.md
index 34c73a0c..3977950e 100644
--- a/README.md
+++ b/README.md
@@ -2112,6 +2112,7 @@
2323|[Find Minimum Time to Finish All Jobs II](./solutions/2323-find-minimum-time-to-finish-all-jobs-ii.js)|Medium|
2325|[Decode the Message](./solutions/2325-decode-the-message.js)|Easy|
2326|[Spiral Matrix IV](./solutions/2326-spiral-matrix-iv.js)|Medium|
+2327|[Number of People Aware of a Secret](./solutions/2327-number-of-people-aware-of-a-secret.js)|Medium|
2328|[Number of Increasing Paths in a Grid](./solutions/2328-number-of-increasing-paths-in-a-grid.js)|Hard|
2330|[Valid Palindrome IV](./solutions/2330-valid-palindrome-iv.js)|Medium|
2331|[Evaluate Boolean Binary Tree](./solutions/2331-evaluate-boolean-binary-tree.js)|Easy|
diff --git a/solutions/2327-number-of-people-aware-of-a-secret.js b/solutions/2327-number-of-people-aware-of-a-secret.js
new file mode 100644
index 00000000..513c9eaf
--- /dev/null
+++ b/solutions/2327-number-of-people-aware-of-a-secret.js
@@ -0,0 +1,43 @@
+/**
+ * 2327. Number of People Aware of a Secret
+ * https://leetcode.com/problems/number-of-people-aware-of-a-secret/
+ * Difficulty: Medium
+ *
+ * On day 1, one person discovers a secret.
+ *
+ * You are given an integer delay, which means that each person will share the secret with a new
+ * person every day, starting from delay days after discovering the secret. You are also given
+ * an integer forget, which means that each person will forget the secret forget days after
+ * discovering it. A person cannot share the secret on the same day they forgot it, or on any
+ * day afterwards.
+ *
+ * Given an integer n, return the number of people who know the secret at the end of day n.
+ * Since the answer may be very large, return it modulo 109 + 7.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} delay
+ * @param {number} forget
+ * @return {number}
+ */
+var peopleAwareOfSecret = function(n, delay, forget) {
+ const MOD = 1e9 + 7;
+ const dp = new Array(n + 1).fill(0);
+ dp[1] = 1;
+
+ for (let day = 1; day <= n; day++) {
+ if (dp[day] === 0) continue;
+
+ for (let shareDay = day + delay; shareDay < day + forget && shareDay <= n; shareDay++) {
+ dp[shareDay] = (dp[shareDay] + dp[day]) % MOD;
+ }
+ }
+
+ let result = 0;
+ for (let day = Math.max(1, n - forget + 1); day <= n; day++) {
+ result = (result + dp[day]) % MOD;
+ }
+
+ return result;
+};
From 9cf0157155459b7391dd569faba7c14b142bd8c1 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 30 Jul 2025 23:53:58 -0500
Subject: [PATCH 947/994] Add solution #2335
---
README.md | 1 +
...335-minimum-amount-of-time-to-fill-cups.js | 21 +++++++++++++++++++
2 files changed, 22 insertions(+)
create mode 100644 solutions/2335-minimum-amount-of-time-to-fill-cups.js
diff --git a/README.md b/README.md
index 3977950e..a7d6e6b1 100644
--- a/README.md
+++ b/README.md
@@ -2117,6 +2117,7 @@
2330|[Valid Palindrome IV](./solutions/2330-valid-palindrome-iv.js)|Medium|
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|
+2335|[Minimum Amount of Time to Fill Cups](./solutions/2335-minimum-amount-of-time-to-fill-cups.js)|Easy|
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|
diff --git a/solutions/2335-minimum-amount-of-time-to-fill-cups.js b/solutions/2335-minimum-amount-of-time-to-fill-cups.js
new file mode 100644
index 00000000..e808dd25
--- /dev/null
+++ b/solutions/2335-minimum-amount-of-time-to-fill-cups.js
@@ -0,0 +1,21 @@
+/**
+ * 2335. Minimum Amount of Time to Fill Cups
+ * https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/
+ * Difficulty: Easy
+ *
+ * You have a water dispenser that can dispense cold, warm, and hot water. Every second, you
+ * can either fill up 2 cups with different types of water, or 1 cup of any type of water.
+ *
+ * You are given a 0-indexed integer array amount of length 3 where amount[0], amount[1], and
+ * amount[2] denote the number of cold, warm, and hot water cups you need to fill respectively.
+ * Return the minimum number of seconds needed to fill up all the cups.
+ */
+
+/**
+ * @param {number[]} amount
+ * @return {number}
+ */
+var fillCups = function(amount) {
+ const [a, b, c] = amount.sort((x, y) => y - x);
+ return Math.max(a, Math.ceil((a + b + c) / 2));
+};
From 3797e1e9bc339d3d4e1f98151f625c12e56eca29 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 31 Jul 2025 22:43:05 -0500
Subject: [PATCH 948/994] Add solution #2332
---
README.md | 1 +
.../2332-the-latest-time-to-catch-a-bus.js | 64 +++++++++++++++++++
2 files changed, 65 insertions(+)
create mode 100644 solutions/2332-the-latest-time-to-catch-a-bus.js
diff --git a/README.md b/README.md
index a7d6e6b1..b9271b5b 100644
--- a/README.md
+++ b/README.md
@@ -2116,6 +2116,7 @@
2328|[Number of Increasing Paths in a Grid](./solutions/2328-number-of-increasing-paths-in-a-grid.js)|Hard|
2330|[Valid Palindrome IV](./solutions/2330-valid-palindrome-iv.js)|Medium|
2331|[Evaluate Boolean Binary Tree](./solutions/2331-evaluate-boolean-binary-tree.js)|Easy|
+2332|[The Latest Time to Catch a Bus](./solutions/2332-the-latest-time-to-catch-a-bus.js)|Medium|
2334|[Subarray With Elements Greater Than Varying Threshold](./solutions/2334-subarray-with-elements-greater-than-varying-threshold.js)|Hard|
2335|[Minimum Amount of Time to Fill Cups](./solutions/2335-minimum-amount-of-time-to-fill-cups.js)|Easy|
2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2332-the-latest-time-to-catch-a-bus.js b/solutions/2332-the-latest-time-to-catch-a-bus.js
new file mode 100644
index 00000000..2354e722
--- /dev/null
+++ b/solutions/2332-the-latest-time-to-catch-a-bus.js
@@ -0,0 +1,64 @@
+/**
+ * 2332. The Latest Time to Catch a Bus
+ * https://leetcode.com/problems/the-latest-time-to-catch-a-bus/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed integer array buses of length n, where buses[i] represents the
+ * departure time of the ith bus. You are also given a 0-indexed integer array passengers of
+ * length m, where passengers[j] represents the arrival time of the jth passenger. All bus
+ * departure times are unique. All passenger arrival times are unique.
+ *
+ * You are given an integer capacity, which represents the maximum number of passengers that
+ * can get on each bus.
+ *
+ * When a passenger arrives, they will wait in line for the next available bus. You can get
+ * on a bus that departs at x minutes if you arrive at y minutes where y <= x, and the bus
+ * is not full. Passengers with the earliest arrival times get on the bus first.
+ *
+ * More formally when a bus arrives, either:
+ * - If capacity or fewer passengers are waiting for a bus, they will all get on the bus, or
+ * - The capacity passengers with the earliest arrival times will get on the bus.
+ *
+ * Return the latest time you may arrive at the bus station to catch a bus. You cannot arrive
+ * at the same time as another passenger.
+ *
+ * Note: The arrays buses and passengers are not necessarily sorted.
+ */
+
+/**
+ * @param {number[]} buses
+ * @param {number[]} passengers
+ * @param {number} capacity
+ * @return {number}
+ */
+var latestTimeCatchTheBus = function(buses, passengers, capacity) {
+ buses.sort((a, b) => a - b);
+ passengers.sort((a, b) => a - b);
+
+ let passengerIndex = 0;
+ let lastBusPassengers = [];
+ for (const busTime of buses) {
+ const currentBusPassengers = [];
+
+ while (passengerIndex < passengers.length && passengers[passengerIndex] <= busTime
+ && currentBusPassengers.length < capacity) {
+ currentBusPassengers.push(passengers[passengerIndex]);
+ passengerIndex++;
+ }
+
+ lastBusPassengers = currentBusPassengers;
+ }
+
+ const lastBusTime = buses[buses.length - 1];
+ let latestTime = lastBusTime;
+ if (lastBusPassengers.length === capacity) {
+ latestTime = lastBusPassengers[lastBusPassengers.length - 1] - 1;
+ }
+
+ const passengerSet = new Set(passengers);
+ while (passengerSet.has(latestTime)) {
+ latestTime--;
+ }
+
+ return latestTime;
+};
From f92585bb8b145037ee8956444bc332bcc9fb921f Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 31 Jul 2025 22:46:28 -0500
Subject: [PATCH 949/994] Add solution #2333
---
README.md | 1 +
.../2333-minimum-sum-of-squared-difference.js | 84 +++++++++++++++++++
2 files changed, 85 insertions(+)
create mode 100644 solutions/2333-minimum-sum-of-squared-difference.js
diff --git a/README.md b/README.md
index b9271b5b..0489bdc1 100644
--- a/README.md
+++ b/README.md
@@ -2117,6 +2117,7 @@
2330|[Valid Palindrome IV](./solutions/2330-valid-palindrome-iv.js)|Medium|
2331|[Evaluate Boolean Binary Tree](./solutions/2331-evaluate-boolean-binary-tree.js)|Easy|
2332|[The Latest Time to Catch a Bus](./solutions/2332-the-latest-time-to-catch-a-bus.js)|Medium|
+2333|[Minimum Sum of Squared Difference](./solutions/2333-minimum-sum-of-squared-difference.js)|Medium|
2334|[Subarray With Elements Greater Than Varying Threshold](./solutions/2334-subarray-with-elements-greater-than-varying-threshold.js)|Hard|
2335|[Minimum Amount of Time to Fill Cups](./solutions/2335-minimum-amount-of-time-to-fill-cups.js)|Easy|
2336|[Smallest Number in Infinite Set](./solutions/2336-smallest-number-in-infinite-set.js)|Medium|
diff --git a/solutions/2333-minimum-sum-of-squared-difference.js b/solutions/2333-minimum-sum-of-squared-difference.js
new file mode 100644
index 00000000..4616d586
--- /dev/null
+++ b/solutions/2333-minimum-sum-of-squared-difference.js
@@ -0,0 +1,84 @@
+/**
+ * 2333. Minimum Sum of Squared Difference
+ * https://leetcode.com/problems/minimum-sum-of-squared-difference/
+ * Difficulty: Medium
+ *
+ * You are given two positive 0-indexed integer arrays nums1 and nums2, both of length n.
+ *
+ * The sum of squared difference of arrays nums1 and nums2 is defined as the sum of
+ * (nums1[i] - nums2[i])2 for each 0 <= i < n.
+ *
+ * You are also given two positive integers k1 and k2. You can modify any of the elements
+ * of nums1 by +1 or -1 at most k1 times. Similarly, you can modify any of the elements
+ * of nums2 by +1 or -1 at most k2 times.
+ *
+ * Return the minimum sum of squared difference after modifying array nums1 at most k1
+ * times and modifying array nums2 at most k2 times.
+ *
+ * Note: You are allowed to modify the array elements to become negative integers.
+ */
+
+/**
+ * @param {number[]} nums1
+ * @param {number[]} nums2
+ * @param {number} k1
+ * @param {number} k2
+ * @return {number}
+ */
+var minSumSquareDiff = function(nums1, nums2, k1, k2) {
+ const n = nums1.length;
+ const frequencyMap = new Map();
+
+ for (let i = 0; i < n; i++) {
+ const diff = Math.abs(nums1[i] - nums2[i]);
+ frequencyMap.set(diff, (frequencyMap.get(diff) || 0) + 1);
+ }
+
+ let totalMoves = k1 + k2;
+ const maxHeap = new PriorityQueue((a, b) => b[0] - a[0]);
+
+ for (const [value, count] of frequencyMap) {
+ if (value === 0) continue;
+ maxHeap.enqueue([value, count]);
+ }
+
+ while (!maxHeap.isEmpty() && totalMoves > 0) {
+ const [value, count] = maxHeap.dequeue();
+
+ if (maxHeap.isEmpty()) {
+ const moves = Math.min(totalMoves, count);
+ totalMoves -= moves;
+ const remainingCount = count - moves;
+
+ if (value - 1 > 0) {
+ maxHeap.enqueue([value - 1, moves]);
+ }
+ if (remainingCount > 0) {
+ maxHeap.enqueue([value, remainingCount]);
+ }
+ } else {
+ const moves = Math.min(totalMoves, count);
+ totalMoves -= moves;
+ const remainingCount = count - moves;
+
+ if (remainingCount > 0) {
+ maxHeap.enqueue([value, remainingCount]);
+ }
+
+ if (!maxHeap.isEmpty() && maxHeap.front()[0] === value - 1) {
+ const [nextValue, nextCount] = maxHeap.dequeue();
+ maxHeap.enqueue([nextValue, nextCount + moves]);
+ } else if (value - 1 > 0) {
+ maxHeap.enqueue([value - 1, moves]);
+ }
+ }
+ }
+
+ let result = 0;
+ while (!maxHeap.isEmpty()) {
+ const [value, count] = maxHeap.dequeue();
+ result += value * value * count;
+ }
+
+ return result;
+};
From 92869d76efe2b3978a4e2ddd38000b2dd6027430 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 31 Jul 2025 22:51:23 -0500
Subject: [PATCH 950/994] Add solution #2343
---
README.md | 1 +
.../2343-query-kth-smallest-trimmed-number.js | 61 +++++++++++++++++++
2 files changed, 62 insertions(+)
create mode 100644 solutions/2343-query-kth-smallest-trimmed-number.js
diff --git a/README.md b/README.md
index 0489bdc1..211d19a1 100644
--- a/README.md
+++ b/README.md
@@ -2126,6 +2126,7 @@
2340|[Minimum Adjacent Swaps to Make a Valid Array](./solutions/2340-minimum-adjacent-swaps-to-make-a-valid-array.js)|Medium|
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|
+2343|[Query Kth Smallest Trimmed Number](./solutions/2343-query-kth-smallest-trimmed-number.js)|Medium|
2345|[Finding the Number of Visible Mountains](./solutions/2345-finding-the-number-of-visible-mountains.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|
diff --git a/solutions/2343-query-kth-smallest-trimmed-number.js b/solutions/2343-query-kth-smallest-trimmed-number.js
new file mode 100644
index 00000000..1af6705b
--- /dev/null
+++ b/solutions/2343-query-kth-smallest-trimmed-number.js
@@ -0,0 +1,61 @@
+/**
+ * 2343. Query Kth Smallest Trimmed Number
+ * https://leetcode.com/problems/query-kth-smallest-trimmed-number/
+ * Difficulty: Medium
+ *
+ * You are given a 0-indexed array of strings nums, where each string is of equal length
+ * and consists of only digits.
+ *
+ * You are also given a 0-indexed 2D integer array queries where queries[i] = [ki, trimi].
+ * For each queries[i], you need to:
+ * - Trim each number in nums to its rightmost trimi digits.
+ * - Determine the index of the kith smallest trimmed number in nums. If two trimmed numbers
+ * are equal, the number with the lower index is considered to be smaller.
+ * - Reset each number in nums to its original length.
+ *
+ * Return an array answer of the same length as queries, where answer[i] is the answer to
+ * the ith query.
+ *
+ * Note:
+ * - To trim to the rightmost x digits means to keep removing the leftmost digit, until only
+ * x digits remain.
+ * - Strings in nums may contain leading zeros.
+ */
+
+/**
+ * @param {string[]} nums
+ * @param {number[][]} queries
+ * @return {number[]}
+ */
+var smallestTrimmedNumbers = function(nums, queries) {
+ if (nums.length === 0) return [];
+
+ const result = [];
+ const stringLength = nums[0].length;
+ let startIndex = 0;
+
+ const maxHeap = new PriorityQueue((a, b) => {
+ for (let i = startIndex; i < stringLength; i++) {
+ if (nums[a].charAt(i) !== nums[b].charAt(i)) {
+ return nums[b].charAt(i).charCodeAt(0) - nums[a].charAt(i).charCodeAt(0);
+ }
+ }
+ return b - a;
+ });
+
+ for (let i = 0; i < queries.length; i++) {
+ startIndex = stringLength - queries[i][1];
+ maxHeap.clear();
+
+ for (let j = 0; j < nums.length; j++) {
+ maxHeap.enqueue(j);
+ if (maxHeap.size() > queries[i][0]) {
+ maxHeap.dequeue();
+ }
+ }
+
+ result[i] = maxHeap.dequeue();
+ }
+
+ return result;
+};
From bb82cf56c9b135480a3be90a84cbcb6772233e2d Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 31 Jul 2025 22:52:38 -0500
Subject: [PATCH 951/994] Add solution #2344
---
README.md | 1 +
...nimum-deletions-to-make-array-divisible.js | 35 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/2344-minimum-deletions-to-make-array-divisible.js
diff --git a/README.md b/README.md
index 211d19a1..c283d605 100644
--- a/README.md
+++ b/README.md
@@ -2127,6 +2127,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|
2343|[Query Kth Smallest Trimmed Number](./solutions/2343-query-kth-smallest-trimmed-number.js)|Medium|
+2344|[Minimum Deletions to Make Array Divisible](./solutions/2344-minimum-deletions-to-make-array-divisible.js)|Hard|
2345|[Finding the Number of Visible Mountains](./solutions/2345-finding-the-number-of-visible-mountains.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|
diff --git a/solutions/2344-minimum-deletions-to-make-array-divisible.js b/solutions/2344-minimum-deletions-to-make-array-divisible.js
new file mode 100644
index 00000000..1d5ab870
--- /dev/null
+++ b/solutions/2344-minimum-deletions-to-make-array-divisible.js
@@ -0,0 +1,35 @@
+/**
+ * 2344. Minimum Deletions to Make Array Divisible
+ * https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/
+ * Difficulty: Hard
+ *
+ * You are given two positive integer arrays nums and numsDivide. You can delete any number
+ * of elements from nums.
+ *
+ * Return the minimum number of deletions such that the smallest element in nums divides
+ * all the elements of numsDivide. If this is not possible, return -1.
+ *
+ * Note that an integer x divides y if y % x == 0.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number[]} numsDivide
+ * @return {number}
+ */
+var minOperations = function(nums, numsDivide) {
+ const targetGcd = numsDivide.reduce(gcd);
+ nums.sort((a, b) => a - b);
+
+ for (let i = 0; i < nums.length; i++) {
+ if (targetGcd % nums[i] === 0) {
+ return i;
+ }
+ }
+
+ return -1;
+
+ function gcd(a, b) {
+ return b === 0 ? a : gcd(b, a % b);
+ }
+};
From f251ab7413b53e2fac805feed84e1458de075e7e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 1 Aug 2025 19:58:57 -0500
Subject: [PATCH 952/994] Add solution #2561
---
README.md | 1 +
solutions/2561-rearranging-fruits.js | 72 ++++++++++++++++++++++++++++
2 files changed, 73 insertions(+)
create mode 100644 solutions/2561-rearranging-fruits.js
diff --git a/README.md b/README.md
index c283d605..f7a2dc1b 100644
--- a/README.md
+++ b/README.md
@@ -2298,6 +2298,7 @@
2557|[Maximum Number of Integers to Choose From a Range II](./solutions/2557-maximum-number-of-integers-to-choose-from-a-range-ii.js)|Medium|
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|
+2561|[Rearranging Fruits](./solutions/2561-rearranging-fruits.js)|Hard|
2562|[Find the Array Concatenation Value](./solutions/2562-find-the-array-concatenation-value.js)|Easy|
2563|[Count the Number of Fair Pairs](./solutions/2563-count-the-number-of-fair-pairs.js)|Medium|
2566|[Maximum Difference by Remapping a Digit](./solutions/2566-maximum-difference-by-remapping-a-digit.js)|Easy|
diff --git a/solutions/2561-rearranging-fruits.js b/solutions/2561-rearranging-fruits.js
new file mode 100644
index 00000000..34cb159e
--- /dev/null
+++ b/solutions/2561-rearranging-fruits.js
@@ -0,0 +1,72 @@
+/**
+ * 2561. Rearranging Fruits
+ * https://leetcode.com/problems/rearranging-fruits/
+ * Difficulty: Hard
+ *
+ * You have two fruit baskets containing n fruits each. You are given two 0-indexed integer
+ * arrays basket1 and basket2 representing the cost of fruit in each basket. You want to
+ * make both baskets equal. To do so, you can use the following operation as many times as you want:
+ * - Chose two indices i and j, and swap the ith fruit of basket1 with the jth fruit of basket2.
+ * - The cost of the swap is min(basket1[i],basket2[j]).
+ *
+ * Two baskets are considered equal if sorting them according to the fruit cost makes them
+ * exactly the same baskets.
+ *
+ * Return the minimum cost to make both the baskets equal or -1 if impossible.
+ */
+
+/**
+ * @param {number[]} basket1
+ * @param {number[]} basket2
+ * @return {number}
+ */
+var minCost = function(basket1, basket2) {
+ const count1 = new Map();
+ const count2 = new Map();
+
+ for (const fruit of basket1) {
+ count1.set(fruit, (count1.get(fruit) || 0) + 1);
+ }
+
+ for (const fruit of basket2) {
+ count2.set(fruit, (count2.get(fruit) || 0) + 1);
+ }
+
+ const allFruits = new Set([...basket1, ...basket2]);
+ const excess1 = [];
+ const excess2 = [];
+ let minCost = Infinity;
+
+ for (const fruit of allFruits) {
+ const freq1 = count1.get(fruit) || 0;
+ const freq2 = count2.get(fruit) || 0;
+ const total = freq1 + freq2;
+
+ if (total % 2 !== 0) return -1;
+
+ minCost = Math.min(minCost, fruit);
+ const target = total / 2;
+
+ if (freq1 > target) {
+ for (let i = 0; i < freq1 - target; i++) {
+ excess1.push(fruit);
+ }
+ } else if (freq2 > target) {
+ for (let i = 0; i < freq2 - target; i++) {
+ excess2.push(fruit);
+ }
+ }
+ }
+
+ excess1.sort((a, b) => a - b);
+ excess2.sort((a, b) => b - a);
+
+ let result = 0;
+ for (let i = 0; i < excess1.length; i++) {
+ const directSwap = Math.min(excess1[i], excess2[i]);
+ const doubleSwap = 2 * minCost;
+ result += Math.min(directSwap, doubleSwap);
+ }
+
+ return result;
+};
From 2ac9f2b81099cfa5f912f2a02e80f4ccac7769dc Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 4 Aug 2025 21:35:53 -0500
Subject: [PATCH 953/994] Add solution #3477
---
README.md | 1 +
solutions/3477-fruits-into-baskets-ii.js | 45 ++++++++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/3477-fruits-into-baskets-ii.js
diff --git a/README.md b/README.md
index f7a2dc1b..61a41e15 100644
--- a/README.md
+++ b/README.md
@@ -2733,6 +2733,7 @@
3464|[Maximize the Distance Between Points on a Square](./solutions/3464-maximize-the-distance-between-points-on-a-square.js)|Hard|
3466|[Maximum Coin Collection](./solutions/3466-maximum-coin-collection.js)|Medium|
3476|[Maximize Profit from Task Assignment](./solutions/3476-maximize-profit-from-task-assignment.js)|Medium|
+3477|[Fruits Into Baskets II](./solutions/3477-fruits-into-baskets-ii.js)|Easy|
3480|[Maximize Subarrays After Removing One Conflicting Pair](./solutions/3480-maximize-subarrays-after-removing-one-conflicting-pair.js)|Hard|
3481|[Apply Substitutions](./solutions/3481-apply-substitutions.js)|Medium|
3487|[Maximum Unique Subarray Sum After Deletion](./solutions/3487-maximum-unique-subarray-sum-after-deletion.js)|Easy|
diff --git a/solutions/3477-fruits-into-baskets-ii.js b/solutions/3477-fruits-into-baskets-ii.js
new file mode 100644
index 00000000..c95cf785
--- /dev/null
+++ b/solutions/3477-fruits-into-baskets-ii.js
@@ -0,0 +1,45 @@
+/**
+ * 3477. Fruits Into Baskets II
+ * https://leetcode.com/problems/fruits-into-baskets-ii/
+ * Difficulty: Easy
+ *
+ * You are given two arrays of integers, fruits and baskets, each of length n, where
+ * fruits[i] represents the quantity of the ith type of fruit, and baskets[j] represents
+ * the capacity of the jth basket.
+ *
+ * From left to right, place the fruits according to these rules:
+ * - Each fruit type must be placed in the leftmost available basket with a capacity greater
+ * than or equal to the quantity of that fruit type.
+ * - Each basket can hold only one type of fruit.
+ * - If a fruit type cannot be placed in any basket, it remains unplaced.
+ *
+ * Return the number of fruit types that remain unplaced after all possible allocations are made.
+ */
+
+/**
+ * @param {number[]} fruits
+ * @param {number[]} baskets
+ * @return {number}
+ */
+var numOfUnplacedFruits = function(fruits, baskets) {
+ const availableBaskets = [...baskets];
+ let result = 0;
+
+ for (const fruitQuantity of fruits) {
+ let placed = false;
+
+ for (let i = 0; i < availableBaskets.length; i++) {
+ if (availableBaskets[i] >= fruitQuantity) {
+ availableBaskets[i] = 0;
+ placed = true;
+ break;
+ }
+ }
+
+ if (!placed) {
+ result++;
+ }
+ }
+
+ return result;
+};
From c03cab5e0b5c37cb21b89fa715a693f5bfe12c84 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 4 Aug 2025 21:41:07 -0500
Subject: [PATCH 954/994] Add solution #2353
---
README.md | 1 +
solutions/2353-design-a-food-rating-system.js | 82 +++++++++++++++++++
2 files changed, 83 insertions(+)
create mode 100644 solutions/2353-design-a-food-rating-system.js
diff --git a/README.md b/README.md
index 61a41e15..8b4bd20e 100644
--- a/README.md
+++ b/README.md
@@ -2135,6 +2135,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|
+2353|[Design a Food Rating System](./solutions/2353-design-a-food-rating-system.js)|Medium|
2354|[Number of Excellent Pairs](./solutions/2354-number-of-excellent-pairs.js)|Hard|
2355|[Maximum Number of Books You Can Take](./solutions/2355-maximum-number-of-books-you-can-take.js)|Hard|
2358|[Maximum Number of Groups Entering a Competition](./solutions/2358-maximum-number-of-groups-entering-a-competition.js)|Medium|
diff --git a/solutions/2353-design-a-food-rating-system.js b/solutions/2353-design-a-food-rating-system.js
new file mode 100644
index 00000000..e2e03f94
--- /dev/null
+++ b/solutions/2353-design-a-food-rating-system.js
@@ -0,0 +1,82 @@
+/**
+ * 2353. Design a Food Rating System
+ * https://leetcode.com/problems/design-a-food-rating-system/
+ * Difficulty: Medium
+ *
+ * Design a food rating system that can do the following:
+ * - Modify the rating of a food item listed in the system.
+ * - Return the highest-rated food item for a type of cuisine in the system.
+ *
+ * Implement the FoodRatings class:
+ * - FoodRatings(String[] foods, String[] cuisines, int[] ratings) Initializes the system.
+ * The food items are described by foods, cuisines and ratings, all of which have a length
+ * of n.
+ * - foods[i] is the name of the ith food,
+ * - cuisines[i] is the type of cuisine of the ith food, and
+ * - ratings[i] is the initial rating of the ith food.
+ * - void changeRating(String food, int newRating) Changes the rating of the food item with
+ * the name food.
+ * - String highestRated(String cuisine) Returns the name of the food item that has the
+ * highest rating for the given type of cuisine. If there is a tie, return the item with
+ * the lexicographically smaller name.
+ *
+ * Note that a string x is lexicographically smaller than string y if x comes before y in
+ * dictionary order, that is, either x is a prefix of y, or if i is the first position such
+ * that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.
+ */
+
+/**
+ * @param {string[]} foods
+ * @param {string[]} cuisines
+ * @param {number[]} ratings
+ */
+var FoodRatings = function(foods, cuisines, ratings) {
+ this.foodToCuisine = new Map();
+ this.foodToRating = new Map();
+ this.cuisineToFoods = new Map();
+
+ for (let i = 0; i < foods.length; i++) {
+ const food = foods[i];
+ const cuisine = cuisines[i];
+ const rating = ratings[i];
+
+ this.foodToCuisine.set(food, cuisine);
+ this.foodToRating.set(food, rating);
+
+ if (!this.cuisineToFoods.has(cuisine)) {
+ this.cuisineToFoods.set(cuisine, new PriorityQueue((a, b) => {
+ if (a.rating !== b.rating) return b.rating - a.rating;
+ return a.food.localeCompare(b.food);
+ }));
+ }
+
+ this.cuisineToFoods.get(cuisine).enqueue({ food, rating });
+ }
+};
+
+/**
+ * @param {string} food
+ * @param {number} newRating
+ * @return {void}
+ */
+FoodRatings.prototype.changeRating = function(food, newRating) {
+ const cuisine = this.foodToCuisine.get(food);
+ this.foodToRating.set(food, newRating);
+ this.cuisineToFoods.get(cuisine).enqueue({ food, rating: newRating });
+};
+
+/**
+ * @param {string} cuisine
+ * @return {string}
+ */
+FoodRatings.prototype.highestRated = function(cuisine) {
+ const heap = this.cuisineToFoods.get(cuisine);
+
+ while (!heap.isEmpty()) {
+ const top = heap.front();
+ if (this.foodToRating.get(top.food) === top.rating) {
+ return top.food;
+ }
+ heap.dequeue();
+ }
+};
From 1cfcf49532a4e0f65516084cea759324e6117991 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 4 Aug 2025 21:42:18 -0500
Subject: [PATCH 955/994] Add solution #2357
---
README.md | 1 +
...array-zero-by-subtracting-equal-amounts.js | 20 +++++++++++++++++++
2 files changed, 21 insertions(+)
create mode 100644 solutions/2357-make-array-zero-by-subtracting-equal-amounts.js
diff --git a/README.md b/README.md
index 8b4bd20e..ea143bfe 100644
--- a/README.md
+++ b/README.md
@@ -2138,6 +2138,7 @@
2353|[Design a Food Rating System](./solutions/2353-design-a-food-rating-system.js)|Medium|
2354|[Number of Excellent Pairs](./solutions/2354-number-of-excellent-pairs.js)|Hard|
2355|[Maximum Number of Books You Can Take](./solutions/2355-maximum-number-of-books-you-can-take.js)|Hard|
+2357|[Make Array Zero by Subtracting Equal Amounts](./solutions/2357-make-array-zero-by-subtracting-equal-amounts.js)|Easy|
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|
diff --git a/solutions/2357-make-array-zero-by-subtracting-equal-amounts.js b/solutions/2357-make-array-zero-by-subtracting-equal-amounts.js
new file mode 100644
index 00000000..63e08177
--- /dev/null
+++ b/solutions/2357-make-array-zero-by-subtracting-equal-amounts.js
@@ -0,0 +1,20 @@
+/**
+ * 2357. Make Array Zero by Subtracting Equal Amounts
+ * https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/
+ * Difficulty: Easy
+ *
+ * You are given a non-negative integer array nums. In one operation, you must:
+ * - Choose a positive integer x such that x is less than or equal to the smallest
+ * non-zero element in nums.
+ * - Subtract x from every positive element in nums.
+ *
+ * Return the minimum number of operations to make every element in nums equal to 0.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimumOperations = function(nums) {
+ return new Set(nums.filter(num => num > 0)).size;
+};
From 841d51c8f658c0f06d8d58faf9ba4fb88aed2709 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 4 Aug 2025 21:44:41 -0500
Subject: [PATCH 956/994] Add solution #2384
---
README.md | 1 +
solutions/2384-largest-palindromic-number.js | 50 ++++++++++++++++++++
2 files changed, 51 insertions(+)
create mode 100644 solutions/2384-largest-palindromic-number.js
diff --git a/README.md b/README.md
index ea143bfe..fd11c445 100644
--- a/README.md
+++ b/README.md
@@ -2162,6 +2162,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|
+2384|[Largest Palindromic Number](./solutions/2384-largest-palindromic-number.js)|Medium|
2385|[Amount of Time for Binary Tree to Be Infected](./solutions/2385-amount-of-time-for-binary-tree-to-be-infected.js)|Medium|
2387|[Median of a Row Wise Sorted Matrix](./solutions/2387-median-of-a-row-wise-sorted-matrix.js)|Medium|
2389|[Longest Subsequence With Limited Sum](./solutions/2389-longest-subsequence-with-limited-sum.js)|Easy|
diff --git a/solutions/2384-largest-palindromic-number.js b/solutions/2384-largest-palindromic-number.js
new file mode 100644
index 00000000..a06b86dc
--- /dev/null
+++ b/solutions/2384-largest-palindromic-number.js
@@ -0,0 +1,50 @@
+/**
+ * 2384. Largest Palindromic Number
+ * https://leetcode.com/problems/largest-palindromic-number/
+ * Difficulty: Medium
+ *
+ * You are given a string num consisting of digits only.
+ *
+ * Return the largest palindromic integer (in the form of a string) that can be formed
+ * using digits taken from num. It should not contain leading zeroes.
+ *
+ * Notes:
+ * - You do not need to use all the digits of num, but you must use at least one digit.
+ * - The digits can be reordered.
+ */
+
+/**
+ * @param {string} num
+ * @return {string}
+ */
+var largestPalindromic = function(num) {
+ const digitCount = new Array(10).fill(0);
+
+ for (const digit of num) {
+ digitCount[parseInt(digit, 10)]++;
+ }
+
+ let leftHalf = '';
+ let middle = '';
+ for (let digit = 9; digit >= 0; digit--) {
+ const count = digitCount[digit];
+ const pairs = Math.floor(count / 2);
+
+ if (digit === 0 && leftHalf === '') {
+ continue;
+ }
+
+ leftHalf += digit.toString().repeat(pairs);
+
+ if (count % 2 === 1 && middle === '') {
+ middle = digit.toString();
+ }
+ }
+
+ if (leftHalf === '' && middle === '') {
+ return '0';
+ }
+
+ const rightHalf = leftHalf.split('').reverse().join('');
+ return leftHalf + middle + rightHalf;
+};
From b7a7530010488d35bafeb9b69fe07dcc5ebec520 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 5 Aug 2025 23:44:42 -0500
Subject: [PATCH 957/994] Add solution #3479
---
README.md | 1 +
solutions/3479-fruits-into-baskets-iii.js | 68 +++++++++++++++++++++++
2 files changed, 69 insertions(+)
create mode 100644 solutions/3479-fruits-into-baskets-iii.js
diff --git a/README.md b/README.md
index fd11c445..45fa555d 100644
--- a/README.md
+++ b/README.md
@@ -2737,6 +2737,7 @@
3466|[Maximum Coin Collection](./solutions/3466-maximum-coin-collection.js)|Medium|
3476|[Maximize Profit from Task Assignment](./solutions/3476-maximize-profit-from-task-assignment.js)|Medium|
3477|[Fruits Into Baskets II](./solutions/3477-fruits-into-baskets-ii.js)|Easy|
+3479|[Fruits Into Baskets III](./solutions/3479-fruits-into-baskets-iii.js)|Medium|
3480|[Maximize Subarrays After Removing One Conflicting Pair](./solutions/3480-maximize-subarrays-after-removing-one-conflicting-pair.js)|Hard|
3481|[Apply Substitutions](./solutions/3481-apply-substitutions.js)|Medium|
3487|[Maximum Unique Subarray Sum After Deletion](./solutions/3487-maximum-unique-subarray-sum-after-deletion.js)|Easy|
diff --git a/solutions/3479-fruits-into-baskets-iii.js b/solutions/3479-fruits-into-baskets-iii.js
new file mode 100644
index 00000000..65daf446
--- /dev/null
+++ b/solutions/3479-fruits-into-baskets-iii.js
@@ -0,0 +1,68 @@
+/**
+ * 3479. Fruits Into Baskets III
+ * https://leetcode.com/problems/fruits-into-baskets-iii/
+ * Difficulty: Medium
+ *
+ * You are given two arrays of integers, fruits and baskets, each of length n, where fruits[i]
+ * represents the quantity of the ith type of fruit, and baskets[j] represents the capacity of
+ * the jth basket.
+ *
+ * From left to right, place the fruits according to these rules:
+ * - Each fruit type must be placed in the leftmost available basket with a capacity greater
+ * than or equal to the quantity of that fruit type.
+ * - Each basket can hold only one type of fruit.
+ * - If a fruit type cannot be placed in any basket, it remains unplaced.
+ *
+ * Return the number of fruit types that remain unplaced after all possible allocations are made.
+ */
+
+/**
+ * @param {number[]} fruits
+ * @param {number[]} baskets
+ * @return {number}
+ */
+var numOfUnplacedFruits = function(fruits, baskets) {
+ const n = fruits.length;
+ const bucketSize = Math.ceil(Math.sqrt(n));
+ const buckets = Array.from({ length: bucketSize }, () => []);
+
+ for (let i = 0; i < baskets.length; i++) {
+ const bucketIndex = Math.floor(i / bucketSize);
+ buckets[bucketIndex].push([baskets[i], i]);
+ }
+
+ for (const bucket of buckets) {
+ bucket.sort((a, b) => a[0] - b[0]);
+ }
+
+ let result = 0;
+ for (const fruitQuantity of fruits) {
+ let placed = false;
+
+ for (const bucket of buckets) {
+ if (bucket.length > 0 && bucket[bucket.length - 1][0] >= fruitQuantity) {
+ let chosenIndex = -1;
+ let minBasketIndex = Infinity;
+
+ for (let i = 0; i < bucket.length; i++) {
+ if (bucket[i][0] >= fruitQuantity && bucket[i][1] < minBasketIndex) {
+ chosenIndex = i;
+ minBasketIndex = bucket[i][1];
+ }
+ }
+
+ if (chosenIndex !== -1) {
+ bucket.splice(chosenIndex, 1);
+ placed = true;
+ break;
+ }
+ }
+ }
+
+ if (!placed) {
+ result++;
+ }
+ }
+
+ return result;
+};
From 7b7cd59ee7e1766d28de475b487748041a12cc2a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 6 Aug 2025 22:55:54 -0500
Subject: [PATCH 958/994] Add solution #3363
---
README.md | 1 +
...-the-maximum-number-of-fruits-collected.js | 84 +++++++++++++++++++
2 files changed, 85 insertions(+)
create mode 100644 solutions/3363-find-the-maximum-number-of-fruits-collected.js
diff --git a/README.md b/README.md
index 45fa555d..67482ea6 100644
--- a/README.md
+++ b/README.md
@@ -2701,6 +2701,7 @@
3356|[Zero Array Transformation II](./solutions/3356-zero-array-transformation-ii.js)|Medium|
3359|[Find Sorted Submatrices With Maximum Element at Most K](./solutions/3359-find-sorted-submatrices-with-maximum-element-at-most-k.js)|Hard|
3362|[Zero Array Transformation III](./solutions/3362-zero-array-transformation-iii.js)|Medium|
+3363|[Find the Maximum Number of Fruits Collected](./solutions/3363-find-the-maximum-number-of-fruits-collected.js)|Hard|
3369|[Design an Array Statistics Tracker](./solutions/3369-design-an-array-statistics-tracker.js)|Hard|
3372|[Maximize the Number of Target Nodes After Connecting Trees I](./solutions/3372-maximize-the-number-of-target-nodes-after-connecting-trees-i.js)|Medium|
3373|[Maximize the Number of Target Nodes After Connecting Trees II](./solutions/3373-maximize-the-number-of-target-nodes-after-connecting-trees-ii.js)|Hard|
diff --git a/solutions/3363-find-the-maximum-number-of-fruits-collected.js b/solutions/3363-find-the-maximum-number-of-fruits-collected.js
new file mode 100644
index 00000000..9e512715
--- /dev/null
+++ b/solutions/3363-find-the-maximum-number-of-fruits-collected.js
@@ -0,0 +1,84 @@
+/**
+ * 3363. Find the Maximum Number of Fruits Collected
+ * https://leetcode.com/problems/find-the-maximum-number-of-fruits-collected/
+ * Difficulty: Hard
+ *
+ * There is a game dungeon comprised of n x n rooms arranged in a grid.
+ *
+ * You are given a 2D array fruits of size n x n, where fruits[i][j] represents the number of fruits
+ * in the room (i, j). Three children will play in the game dungeon, with initial positions at the
+ * corner rooms (0, 0), (0, n - 1), and (n - 1, 0).
+ *
+ * The children will make exactly n - 1 moves according to the following rules to reach the
+ * room (n - 1, n - 1):
+ * - The child starting from (0, 0) must move from their current room (i, j) to one of the rooms
+ * (i + 1, j + 1), (i + 1, j), and (i, j + 1) if the target room exists.
+ * - The child starting from (0, n - 1) must move from their current room (i, j) to one of the rooms
+ * (i + 1, j - 1), (i + 1, j), and (i + 1, j + 1) if the target room exists.
+ * - The child starting from (n - 1, 0) must move from their current room (i, j) to one of the rooms
+ * (i - 1, j + 1), (i, j + 1), and (i + 1, j + 1) if the target room exists.
+ *
+ * When a child enters a room, they will collect all the fruits there. If two or more children
+ * enter the same room, only one child will collect the fruits, and the room will be emptied after
+ * they leave.
+ *
+ * Return the maximum number of fruits the children can collect from the dungeon.
+ */
+
+/**
+ * @param {number[][]} fruits
+ * @return {number}
+ */
+var maxCollectedFruits = function(fruits) {
+ const n = fruits.length;
+ const dp = Array(n).fill().map(() => Array(n).fill(-1));
+ const dp2 = Array(n).fill().map(() => Array(n).fill(-1));
+
+ let diagonalSum = 0;
+ for (let i = 0; i < n; i++) {
+ diagonalSum += fruits[i][i];
+ }
+
+ const child2Max = solveChild2(0, n - 1);
+ const child3Max = solveChild3(n - 1, 0);
+
+ return diagonalSum + child2Max + child3Max;
+
+ function solveChild2(row, col) {
+ if (row === n - 1 && col === n - 1) return 0;
+ if (row >= n || col < 0 || col >= n || row > col + 1) return -Infinity;
+ if (dp[row][col] !== -1) return dp[row][col];
+
+ const value = (row === col) ? 0 : fruits[row][col];
+ let maxNext = -Infinity;
+
+ for (const [dr, dc] of [[1, -1], [1, 0], [1, 1]]) {
+ const newRow = row + dr;
+ const newCol = col + dc;
+ if (newRow < n && newCol >= 0 && newCol < n) {
+ maxNext = Math.max(maxNext, solveChild2(newRow, newCol));
+ }
+ }
+
+ return dp[row][col] = value + maxNext;
+ }
+
+ function solveChild3(row, col) {
+ if (row === n - 1 && col === n - 1) return 0;
+ if (row < 0 || row >= n || col >= n || row + col < n - 1) return -Infinity;
+ if (dp2[row][col] !== -1) return dp2[row][col];
+
+ const value = (row === col) ? 0 : fruits[row][col];
+ let maxNext = -Infinity;
+
+ for (const [dr, dc] of [[-1, 1], [0, 1], [1, 1]]) {
+ const newRow = row + dr;
+ const newCol = col + dc;
+ if (newRow >= 0 && newRow < n && newCol < n) {
+ maxNext = Math.max(maxNext, solveChild3(newRow, newCol));
+ }
+ }
+
+ return dp2[row][col] = value + maxNext;
+ }
+};
From 4205115126ff931c7b68bc6dddf95fd844f5f962 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 7 Aug 2025 23:51:12 -0500
Subject: [PATCH 959/994] Add solution #2386
---
README.md | 1 +
solutions/2386-find-the-k-sum-of-an-array.js | 42 ++++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/2386-find-the-k-sum-of-an-array.js
diff --git a/README.md b/README.md
index 67482ea6..5ffc24c5 100644
--- a/README.md
+++ b/README.md
@@ -2164,6 +2164,7 @@
2383|[Minimum Hours of Training to Win a Competition](./solutions/2383-minimum-hours-of-training-to-win-a-competition.js)|Easy|
2384|[Largest Palindromic Number](./solutions/2384-largest-palindromic-number.js)|Medium|
2385|[Amount of Time for Binary Tree to Be Infected](./solutions/2385-amount-of-time-for-binary-tree-to-be-infected.js)|Medium|
+2386|[Find the K-Sum of an Array](./solutions/2386-find-the-k-sum-of-an-array.js)|Hard|
2387|[Median of a Row Wise Sorted Matrix](./solutions/2387-median-of-a-row-wise-sorted-matrix.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|
diff --git a/solutions/2386-find-the-k-sum-of-an-array.js b/solutions/2386-find-the-k-sum-of-an-array.js
new file mode 100644
index 00000000..c3f49e46
--- /dev/null
+++ b/solutions/2386-find-the-k-sum-of-an-array.js
@@ -0,0 +1,42 @@
+/**
+ * 2386. Find the K-Sum of an Array
+ * https://leetcode.com/problems/find-the-k-sum-of-an-array/
+ * Difficulty: Hard
+ *
+ * You are given an integer array nums and a positive integer k. You can choose any subsequence
+ * of the array and sum all of its elements together.
+ *
+ * We define the K-Sum of the array as the kth largest subsequence sum that can be obtained
+ * (not necessarily distinct).
+ *
+ * Return the K-Sum of the array.
+ *
+ * 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.
+ *
+ * Note that the empty subsequence is considered to have a sum of 0.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var kSum = function(nums, k) {
+ const maxSum = nums.reduce((sum, num) => sum + Math.max(0, num), 0);
+ const absoluteNums = nums.map(num => Math.abs(num)).sort((a, b) => a - b);
+ const maxHeap = new PriorityQueue((a, b) => a[0] - b[0]);
+ maxHeap.enqueue([-maxSum + absoluteNums[0], 0]);
+ let nextSum = -maxSum;
+
+ for (let iteration = 0; iteration < k - 1; iteration++) {
+ [nextSum, i] = maxHeap.dequeue();
+
+ if (i + 1 < absoluteNums.length) {
+ maxHeap.enqueue([nextSum - absoluteNums[i] + absoluteNums[i + 1], i + 1]);
+ maxHeap.enqueue([nextSum + absoluteNums[i + 1], i + 1]);
+ }
+ }
+
+ return -nextSum;
+};
From 8c1f6dc3aa967259243224a1bebf358876f9add3 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 11 Aug 2025 23:16:33 -0500
Subject: [PATCH 960/994] Add solution #2787
---
README.md | 1 +
...-to-express-an-integer-as-sum-of-powers.js | 37 +++++++++++++++++++
2 files changed, 38 insertions(+)
create mode 100644 solutions/2787-ways-to-express-an-integer-as-sum-of-powers.js
diff --git a/README.md b/README.md
index 5ffc24c5..f0c028bc 100644
--- a/README.md
+++ b/README.md
@@ -2463,6 +2463,7 @@
2782|[Number of Unique Categories](./solutions/2782-number-of-unique-categories.js)|Medium|
2784|[Check if Array is Good](./solutions/2784-check-if-array-is-good.js)|Easy|
2785|[Sort Vowels in a String](./solutions/2785-sort-vowels-in-a-string.js)|Medium|
+2787|[Ways to Express an Integer as Sum of Powers](./solutions/2787-ways-to-express-an-integer-as-sum-of-powers.js)|Medium|
2788|[Split Strings by Separator](./solutions/2788-split-strings-by-separator.js)|Easy|
2789|[Largest Element in an Array after Merge Operations](./solutions/2789-largest-element-in-an-array-after-merge-operations.js)|Medium|
2791|[Count Paths That Can Form a Palindrome in a Tree](./solutions/2791-count-paths-that-can-form-a-palindrome-in-a-tree.js)|Hard|
diff --git a/solutions/2787-ways-to-express-an-integer-as-sum-of-powers.js b/solutions/2787-ways-to-express-an-integer-as-sum-of-powers.js
new file mode 100644
index 00000000..240f2ec6
--- /dev/null
+++ b/solutions/2787-ways-to-express-an-integer-as-sum-of-powers.js
@@ -0,0 +1,37 @@
+/**
+ * 2787. Ways to Express an Integer as Sum of Powers
+ * https://leetcode.com/problems/ways-to-express-an-integer-as-sum-of-powers/
+ * Difficulty: Medium
+ *
+ * Given two positive integers n and x.
+ *
+ * Return the number of ways n can be expressed as the sum of the xth power of unique positive
+ * integers, in other words, the number of sets of unique integers [n1, n2, ..., nk] where
+ * n = n1x + n2x + ... + nkx.
+ *
+ * Since the result can be very large, return it modulo 109 + 7.
+ *
+ * For example, if n = 160 and x = 3, one way to express n is n = 23 + 33 + 53.
+ */
+
+/**
+ * @param {number} n
+ * @param {number} x
+ * @return {number}
+ */
+var numberOfWays = function(n, x) {
+ const MOD = 1e9 + 7;
+ const dp = new Array(n + 1).fill(0);
+ dp[0] = 1;
+
+ let power = 1;
+ while (Math.pow(power, x) <= n) {
+ const currentPower = Math.pow(power, x);
+ for (let sum = n; sum >= currentPower; sum--) {
+ dp[sum] = (dp[sum] + dp[sum - currentPower]) % MOD;
+ }
+ power++;
+ }
+
+ return dp[n];
+};
From 9fda52308e001c7914f7504c996f3b7b1404d686 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 14 Aug 2025 22:23:04 -0500
Subject: [PATCH 961/994] Add solution #2398
---
README.md | 1 +
...-maximum-number-of-robots-within-budget.js | 57 +++++++++++++++++++
2 files changed, 58 insertions(+)
create mode 100644 solutions/2398-maximum-number-of-robots-within-budget.js
diff --git a/README.md b/README.md
index f0c028bc..022ccf05 100644
--- a/README.md
+++ b/README.md
@@ -2174,6 +2174,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|
+2398|[Maximum Number of Robots Within Budget](./solutions/2398-maximum-number-of-robots-within-budget.js)|Hard|
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|
2402|[Meeting Rooms III](./solutions/2402-meeting-rooms-iii.js)|Hard|
diff --git a/solutions/2398-maximum-number-of-robots-within-budget.js b/solutions/2398-maximum-number-of-robots-within-budget.js
new file mode 100644
index 00000000..cdf88590
--- /dev/null
+++ b/solutions/2398-maximum-number-of-robots-within-budget.js
@@ -0,0 +1,57 @@
+/**
+ * 2398. Maximum Number of Robots Within Budget
+ * https://leetcode.com/problems/maximum-number-of-robots-within-budget/
+ * Difficulty: Hard
+ *
+ * You have n robots. You are given two 0-indexed integer arrays, chargeTimes and runningCosts,
+ * both of length n. The ith robot costs chargeTimes[i] units to charge and costs runningCosts[i]
+ * units to run. You are also given an integer budget.
+ *
+ * The total cost of running k chosen robots is equal to max(chargeTimes) + k * sum(runningCosts),
+ * where max(chargeTimes) is the largest charge cost among the k robots and sum(runningCosts) is
+ * the sum of running costs among the k robots.
+ *
+ * Return the maximum number of consecutive robots you can run such that the total cost does not
+ * exceed budget.
+ */
+
+/**
+ * @param {number[]} chargeTimes
+ * @param {number[]} runningCosts
+ * @param {number} budget
+ * @return {number}
+ */
+var maximumRobots = function(chargeTimes, runningCosts, budget) {
+ const n = chargeTimes.length;
+ let left = 0;
+ let result = 0;
+ let runningSum = 0;
+ const queue = [];
+
+ for (let right = 0; right < n; right++) {
+ runningSum += runningCosts[right];
+
+ while (queue.length > 0 && chargeTimes[queue[queue.length - 1]] <= chargeTimes[right]) {
+ queue.pop();
+ }
+ queue.push(right);
+
+ while (left <= right) {
+ const maxCharge = chargeTimes[queue[0]];
+ const totalCost = maxCharge + (right - left + 1) * runningSum;
+
+ if (totalCost <= budget) {
+ result = Math.max(result, right - left + 1);
+ break;
+ }
+
+ if (queue[0] === left) {
+ queue.shift();
+ }
+ runningSum -= runningCosts[left];
+ left++;
+ }
+ }
+
+ return result;
+};
From 1661e0a7536f65ec531ce497a8a472d62fafbf92 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 16 Aug 2025 08:21:14 -0500
Subject: [PATCH 962/994] Add solution #2400
---
README.md | 1 +
...-reach-a-position-after-exactly-k-steps.js | 49 +++++++++++++++++++
2 files changed, 50 insertions(+)
create mode 100644 solutions/2400-number-of-ways-to-reach-a-position-after-exactly-k-steps.js
diff --git a/README.md b/README.md
index 022ccf05..3f98cf3b 100644
--- a/README.md
+++ b/README.md
@@ -2176,6 +2176,7 @@
2397|[Maximum Rows Covered by Columns](./solutions/2397-maximum-rows-covered-by-columns.js)|Medium|
2398|[Maximum Number of Robots Within Budget](./solutions/2398-maximum-number-of-robots-within-budget.js)|Hard|
2399|[Check Distances Between Same Letters](./solutions/2399-check-distances-between-same-letters.js)|Easy|
+2400|[Number of Ways to Reach a Position After Exactly k Steps](./solutions/2400-number-of-ways-to-reach-a-position-after-exactly-k-steps.js)|Medium|
2401|[Longest Nice Subarray](./solutions/2401-longest-nice-subarray.js)|Medium|
2402|[Meeting Rooms III](./solutions/2402-meeting-rooms-iii.js)|Hard|
2403|[Minimum Time to Kill All Monsters](./solutions/2403-minimum-time-to-kill-all-monsters.js)|Hard|
diff --git a/solutions/2400-number-of-ways-to-reach-a-position-after-exactly-k-steps.js b/solutions/2400-number-of-ways-to-reach-a-position-after-exactly-k-steps.js
new file mode 100644
index 00000000..fa0c7186
--- /dev/null
+++ b/solutions/2400-number-of-ways-to-reach-a-position-after-exactly-k-steps.js
@@ -0,0 +1,49 @@
+/**
+ * 2400. Number of Ways to Reach a Position After Exactly k Steps
+ * https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/
+ * Difficulty: Medium
+ *
+ * You are given two positive integers startPos and endPos. Initially, you are standing at
+ * position startPos on an infinite number line. With one step, you can move either one position
+ * to the left, or one position to the right.
+ *
+ * Given a positive integer k, return the number of different ways to reach the position endPos
+ * starting from startPos, such that you perform exactly k steps. Since the answer may be very
+ * large, return it modulo 109 + 7.
+ *
+ * Two ways are considered different if the order of the steps made is not exactly the same.
+ *
+ * Note that the number line includes negative integers.
+ */
+
+/**
+ * @param {number} startPos
+ * @param {number} endPos
+ * @param {number} k
+ * @return {number}
+ */
+var numberOfWays = function(startPos, endPos, k) {
+ const MOD = 1e9 + 7;
+ const dp = new Array(3000).fill().map(() => new Array(k + 1).fill(-1));
+
+ return helper(startPos, endPos, k);
+
+ function helper(currentPos, targetPos, remainingSteps) {
+ if (currentPos === targetPos && remainingSteps === 0) {
+ return 1;
+ }
+ if (remainingSteps === 0) {
+ return 0;
+ }
+
+ const dpIndex = currentPos + 1000;
+ if (dp[dpIndex][remainingSteps] !== -1) {
+ return dp[dpIndex][remainingSteps];
+ }
+ const leftMove = helper(currentPos - 1, targetPos, remainingSteps - 1);
+ const rightMove = helper(currentPos + 1, targetPos, remainingSteps - 1);
+
+ dp[dpIndex][remainingSteps] = (leftMove + rightMove) % MOD;
+ return dp[dpIndex][remainingSteps];
+ }
+};
From ed613746c7b311eaff4eaf2de83b204f81328aaf Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 16 Aug 2025 08:22:34 -0500
Subject: [PATCH 963/994] Add solution #2406
---
README.md | 1 +
...intervals-into-minimum-number-of-groups.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/2406-divide-intervals-into-minimum-number-of-groups.js
diff --git a/README.md b/README.md
index 3f98cf3b..26278380 100644
--- a/README.md
+++ b/README.md
@@ -2182,6 +2182,7 @@
2403|[Minimum Time to Kill All Monsters](./solutions/2403-minimum-time-to-kill-all-monsters.js)|Hard|
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|
+2406|[Divide Intervals Into Minimum Number of Groups](./solutions/2406-divide-intervals-into-minimum-number-of-groups.js)|Medium|
2408|[Design SQL](./solutions/2408-design-sql.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|
diff --git a/solutions/2406-divide-intervals-into-minimum-number-of-groups.js b/solutions/2406-divide-intervals-into-minimum-number-of-groups.js
new file mode 100644
index 00000000..60b50fb3
--- /dev/null
+++ b/solutions/2406-divide-intervals-into-minimum-number-of-groups.js
@@ -0,0 +1,39 @@
+/**
+ * 2406. Divide Intervals Into Minimum Number of Groups
+ * https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/
+ * Difficulty: Medium
+ *
+ * You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents
+ * the inclusive interval [lefti, righti].
+ *
+ * You have to divide the intervals into one or more groups such that each interval is in
+ * exactly one group, and no two intervals that are in the same group intersect each other.
+ *
+ * Return the minimum number of groups you need to make.
+ *
+ * Two intervals intersect if there is at least one common number between them. For example,
+ * the intervals [1, 5] and [5, 8] intersect.
+ */
+
+/**
+ * @param {number[][]} intervals
+ * @return {number}
+ */
+var minGroups = function(intervals) {
+ const events = [];
+ for (const [start, end] of intervals) {
+ events.push([start, 1]);
+ events.push([end + 1, -1]);
+ }
+
+ events.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]);
+
+ let activeIntervals = 0;
+ let result = 0;
+ for (const [time, change] of events) {
+ activeIntervals += change;
+ result = Math.max(result, activeIntervals);
+ }
+
+ return result;
+};
From 551586c02b396d0695fa4156ab78b50e3789246e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 21 Aug 2025 21:58:32 -0500
Subject: [PATCH 964/994] Add solution #3195
---
README.md | 1 +
...nd-the-minimum-area-to-cover-all-ones-i.js | 36 +++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/3195-find-the-minimum-area-to-cover-all-ones-i.js
diff --git a/README.md b/README.md
index 26278380..aad36a6f 100644
--- a/README.md
+++ b/README.md
@@ -2667,6 +2667,7 @@
3183|[The Number of Ways to Make the Sum](./solutions/3183-the-number-of-ways-to-make-the-sum.js)|Medium|
3189|[Minimum Moves to Get a Peaceful Board](./solutions/3189-minimum-moves-to-get-a-peaceful-board.js)|Medium|
3191|[Minimum Operations to Make Binary Array Elements Equal to One I](./solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js)|Medium|
+3195|[Find the Minimum Area to Cover All Ones I](./solutions/3195-find-the-minimum-area-to-cover-all-ones-i.js)|Medium|
3199|[Count Triplets with Even XOR Set Bits I](./solutions/3199-count-triplets-with-even-xor-set-bits-i.js)|Easy|
3201|[Find the Maximum Length of Valid Subsequence I](./solutions/3201-find-the-maximum-length-of-valid-subsequence-i.js)|Medium|
3202|[Find the Maximum Length of Valid Subsequence II](./solutions/3202-find-the-maximum-length-of-valid-subsequence-ii.js)|Medium|
diff --git a/solutions/3195-find-the-minimum-area-to-cover-all-ones-i.js b/solutions/3195-find-the-minimum-area-to-cover-all-ones-i.js
new file mode 100644
index 00000000..d01d8c9c
--- /dev/null
+++ b/solutions/3195-find-the-minimum-area-to-cover-all-ones-i.js
@@ -0,0 +1,36 @@
+/**
+ * 3195. Find the Minimum Area to Cover All Ones I
+ * https://leetcode.com/problems/find-the-minimum-area-to-cover-all-ones-i/
+ * Difficulty: Medium
+ *
+ * You are given a 2D binary array grid. Find a rectangle with horizontal and vertical
+ * sides with the smallest area, such that all the 1's in grid lie inside this rectangle.
+ *
+ * Return the minimum possible area of the rectangle.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var minimumArea = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ let minRow = rows;
+ let maxRow = -1;
+ let minCol = cols;
+ let maxCol = -1;
+
+ for (let i = 0; i < rows; i++) {
+ for (let j = 0; j < cols; j++) {
+ if (grid[i][j] === 1) {
+ minRow = Math.min(minRow, i);
+ maxRow = Math.max(maxRow, i);
+ minCol = Math.min(minCol, j);
+ maxCol = Math.max(maxCol, j);
+ }
+ }
+ }
+
+ return (maxRow - minRow + 1) * (maxCol - minCol + 1);
+};
From e31fbf6197d009a38dca36f93e5a1f5dff9ad50c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 21 Aug 2025 22:02:12 -0500
Subject: [PATCH 965/994] Add solution #2500
---
README.md | 1 +
.../2500-delete-greatest-value-in-each-row.js | 38 +++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 solutions/2500-delete-greatest-value-in-each-row.js
diff --git a/README.md b/README.md
index aad36a6f..3e307f97 100644
--- a/README.md
+++ b/README.md
@@ -2264,6 +2264,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|
+2500|[Delete Greatest Value in Each Row](./solutions/2500-delete-greatest-value-in-each-row.js)|Easy|
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|
diff --git a/solutions/2500-delete-greatest-value-in-each-row.js b/solutions/2500-delete-greatest-value-in-each-row.js
new file mode 100644
index 00000000..68f0164f
--- /dev/null
+++ b/solutions/2500-delete-greatest-value-in-each-row.js
@@ -0,0 +1,38 @@
+/**
+ * 2500. Delete Greatest Value in Each Row
+ * https://leetcode.com/problems/delete-greatest-value-in-each-row/
+ * Difficulty: Easy
+ *
+ * You are given an m x n matrix grid consisting of positive integers.
+ *
+ * Perform the following operation until grid becomes empty:
+ * - Delete the element with the greatest value from each row. If multiple such elements exist,
+ * delete any of them.
+ * - Add the maximum of deleted elements to the answer.
+ *
+ * Note that the number of columns decreases by one after each operation.
+ *
+ * Return the answer after performing the operations described above.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var deleteGreatestValue = function(grid) {
+ for (const row of grid) {
+ row.sort((a, b) => a - b);
+ }
+
+ let result = 0;
+ const cols = grid[0].length;
+ for (let col = cols - 1; col >= 0; col--) {
+ let maxInColumn = 0;
+ for (let row = 0; row < grid.length; row++) {
+ maxInColumn = Math.max(maxInColumn, grid[row][col]);
+ }
+ result += maxInColumn;
+ }
+
+ return result;
+};
From 7f3e4b0dc0c70bef5c049aa346c6b1bbb88a600a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 21 Aug 2025 22:03:52 -0500
Subject: [PATCH 966/994] Add solution #2512
---
README.md | 1 +
solutions/2512-reward-top-k-students.js | 56 +++++++++++++++++++++++++
2 files changed, 57 insertions(+)
create mode 100644 solutions/2512-reward-top-k-students.js
diff --git a/README.md b/README.md
index 3e307f97..32b6afb2 100644
--- a/README.md
+++ b/README.md
@@ -2274,6 +2274,7 @@
2509|[Cycle Length Queries in a Tree](./solutions/2509-cycle-length-queries-in-a-tree.js)|Hard|
2510|[Check if There is a Path With Equal Number of 0's And 1's](./solutions/2510-check-if-there-is-a-path-with-equal-number-of-0s-and-1s.js)|Medium|
2511|[Maximum Enemy Forts That Can Be Captured](./solutions/2511-maximum-enemy-forts-that-can-be-captured.js)|Easy|
+2512|[Reward Top K Students](./solutions/2512-reward-top-k-students.js)|Medium|
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|
diff --git a/solutions/2512-reward-top-k-students.js b/solutions/2512-reward-top-k-students.js
new file mode 100644
index 00000000..d5c663f2
--- /dev/null
+++ b/solutions/2512-reward-top-k-students.js
@@ -0,0 +1,56 @@
+/**
+ * 2512. Reward Top K Students
+ * https://leetcode.com/problems/reward-top-k-students/
+ * Difficulty: Medium
+ *
+ * You are given two string arrays positive_feedback and negative_feedback, containing the words
+ * denoting positive and negative feedback, respectively. Note that no word is both positive and
+ * negative.
+ *
+ * Initially every student has 0 points. Each positive word in a feedback report increases the
+ * points of a student by 3, whereas each negative word decreases the points by 1.
+ *
+ * You are given n feedback reports, represented by a 0-indexed string array report and a
+ * 0-indexed integer array student_id, where student_id[i] represents the ID of the student
+ * who has received the feedback report report[i]. The ID of each student is unique.
+ *
+ * Given an integer k, return the top k students after ranking them in non-increasing order
+ * by their points. In case more than one student has the same points, the one with the lower
+ * ID ranks higher.
+ */
+
+/**
+ * @param {string[]} positive_feedback
+ * @param {string[]} negative_feedback
+ * @param {string[]} report
+ * @param {number[]} student_id
+ * @param {number} k
+ * @return {number[]}
+ */
+var topStudents = function(positive_feedback, negative_feedback, report, student_id, k) {
+ const positiveSet = new Set(positive_feedback);
+ const negativeSet = new Set(negative_feedback);
+ const studentScores = [];
+
+ for (let i = 0; i < report.length; i++) {
+ const words = report[i].split(' ');
+ let score = 0;
+
+ for (const word of words) {
+ if (positiveSet.has(word)) {
+ score += 3;
+ } else if (negativeSet.has(word)) {
+ score -= 1;
+ }
+ }
+
+ studentScores.push([student_id[i], score]);
+ }
+
+ studentScores.sort((a, b) => {
+ if (a[1] !== b[1]) return b[1] - a[1];
+ return a[0] - b[0];
+ });
+
+ return studentScores.slice(0, k).map(student => student[0]);
+};
From 83f58a3adbbcbea475b91b0c1e47c5d0c948f2a6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 21 Aug 2025 22:07:58 -0500
Subject: [PATCH 967/994] Add solution #2456
---
README.md | 3 +-
solutions/2456-most-popular-video-creator.js | 67 ++++++++++++++++++++
2 files changed, 69 insertions(+), 1 deletion(-)
create mode 100644 solutions/2456-most-popular-video-creator.js
diff --git a/README.md b/README.md
index 32b6afb2..aa1265e8 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# 2,700+ LeetCode solutions in JavaScript
+# 2,750+ LeetCode solutions in JavaScript
[https://leetcodejavascript.com](https://leetcodejavascript.com)
@@ -2227,6 +2227,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|
+2456|[Most Popular Video Creator](./solutions/2456-most-popular-video-creator.js)|Medium|
2458|[Height of Binary Tree After Subtree Removal Queries](./solutions/2458-height-of-binary-tree-after-subtree-removal-queries.js)|Hard|
2459|[Sort Array by Moving Items to Empty Space](./solutions/2459-sort-array-by-moving-items-to-empty-space.js)|Hard|
2460|[Apply Operations to an Array](./solutions/2460-apply-operations-to-an-array.js)|Easy|
diff --git a/solutions/2456-most-popular-video-creator.js b/solutions/2456-most-popular-video-creator.js
new file mode 100644
index 00000000..e41632d8
--- /dev/null
+++ b/solutions/2456-most-popular-video-creator.js
@@ -0,0 +1,67 @@
+/**
+ * 2456. Most Popular Video Creator
+ * https://leetcode.com/problems/most-popular-video-creator/
+ * Difficulty: Medium
+ *
+ * You are given two string arrays creators and ids, and an integer array views, all of length n.
+ * The ith video on a platform was created by creators[i], has an id of ids[i], and has views[i]
+ * views.
+ *
+ * The popularity of a creator is the sum of the number of views on all of the creator's videos.
+ * Find the creator with the highest popularity and the id of their most viewed video.
+ * - If multiple creators have the highest popularity, find all of them.
+ * - If multiple videos have the highest view count for a creator, find the lexicographically
+ * smallest id.
+ *
+ * Note: It is possible for different videos to have the same id, meaning that ids do not uniquely
+ * identify a video. For example, two videos with the same ID are considered as distinct videos
+ * with their own viewcount.
+ *
+ * Return a 2D array of strings answer where answer[i] = [creatorsi, idi] means that creatorsi
+ * has the highest popularity and idi is the id of their most popular video. The answer can be
+ * returned in any order.
+ */
+
+/**
+ * @param {string[]} creators
+ * @param {string[]} ids
+ * @param {number[]} views
+ * @return {string[][]}
+ */
+var mostPopularCreator = function(creators, ids, views) {
+ const map = new Map();
+
+ for (let i = 0; i < creators.length; i++) {
+ const creator = creators[i];
+ const videoId = ids[i];
+ const videoViews = views[i];
+
+ if (!map.has(creator)) {
+ map.set(creator, {
+ totalViews: 0,
+ mostViewedCount: -1,
+ mostViewedId: ''
+ });
+ }
+
+ const stats = map.get(creator);
+ stats.totalViews += videoViews;
+
+ if (videoViews > stats.mostViewedCount || (videoViews === stats.mostViewedCount
+ && videoId < stats.mostViewedId)) {
+ stats.mostViewedCount = videoViews;
+ stats.mostViewedId = videoId;
+ }
+ }
+
+ const maxViews = Math.max(...Array.from(map.values()).map(s => s.totalViews));
+
+ const result = [];
+ for (const [creator, stats] of map) {
+ if (stats.totalViews === maxViews) {
+ result.push([creator, stats.mostViewedId]);
+ }
+ }
+
+ return result;
+};
From 150bbdb4dd587786140a224962fd9892536f89be Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 22 Aug 2025 22:33:24 -0500
Subject: [PATCH 968/994] Add solution #3197
---
README.md | 1 +
...d-the-minimum-area-to-cover-all-ones-ii.js | 101 ++++++++++++++++++
2 files changed, 102 insertions(+)
create mode 100644 solutions/3197-find-the-minimum-area-to-cover-all-ones-ii.js
diff --git a/README.md b/README.md
index aa1265e8..eec7605b 100644
--- a/README.md
+++ b/README.md
@@ -2671,6 +2671,7 @@
3189|[Minimum Moves to Get a Peaceful Board](./solutions/3189-minimum-moves-to-get-a-peaceful-board.js)|Medium|
3191|[Minimum Operations to Make Binary Array Elements Equal to One I](./solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js)|Medium|
3195|[Find the Minimum Area to Cover All Ones I](./solutions/3195-find-the-minimum-area-to-cover-all-ones-i.js)|Medium|
+3197|[Find the Minimum Area to Cover All Ones II](./solutions/3197-find-the-minimum-area-to-cover-all-ones-ii.js)|Hard|
3199|[Count Triplets with Even XOR Set Bits I](./solutions/3199-count-triplets-with-even-xor-set-bits-i.js)|Easy|
3201|[Find the Maximum Length of Valid Subsequence I](./solutions/3201-find-the-maximum-length-of-valid-subsequence-i.js)|Medium|
3202|[Find the Maximum Length of Valid Subsequence II](./solutions/3202-find-the-maximum-length-of-valid-subsequence-ii.js)|Medium|
diff --git a/solutions/3197-find-the-minimum-area-to-cover-all-ones-ii.js b/solutions/3197-find-the-minimum-area-to-cover-all-ones-ii.js
new file mode 100644
index 00000000..49c88ebb
--- /dev/null
+++ b/solutions/3197-find-the-minimum-area-to-cover-all-ones-ii.js
@@ -0,0 +1,101 @@
+/**
+ * 3197. Find the Minimum Area to Cover All Ones II
+ * https://leetcode.com/problems/find-the-minimum-area-to-cover-all-ones-ii/
+ * Difficulty: Hard
+ *
+ * You are given a 2D binary array grid. You need to find 3 non-overlapping rectangles having
+ * non-zero areas with horizontal and vertical sides such that all the 1's in grid lie inside
+ * these rectangles.
+ *
+ * Return the minimum possible sum of the area of these rectangles.
+ *
+ * Note that the rectangles are allowed to touch.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number}
+ */
+var minimumSum = function(grid) {
+ const rows = grid.length;
+ const cols = grid[0].length;
+ let minSum = Infinity;
+
+ for (let i = 0; i < rows; i++) {
+ const area1 = calculateArea(0, i, 0, cols - 1);
+ for (let j = 0; j < cols; j++) {
+ const area2 = calculateArea(i + 1, rows - 1, 0, j);
+ const area3 = calculateArea(i + 1, rows - 1, j + 1, cols - 1);
+ minSum = Math.min(minSum, area1 + area2 + area3);
+ }
+ }
+
+ for (let j = 0; j < cols; j++) {
+ const area1 = calculateArea(0, rows - 1, 0, j);
+ for (let i = 0; i < rows; i++) {
+ const area2 = calculateArea(0, i, j + 1, cols - 1);
+ const area3 = calculateArea(i + 1, rows - 1, j + 1, cols - 1);
+ minSum = Math.min(minSum, area1 + area2 + area3);
+ }
+ }
+
+ for (let j = cols - 1; j >= 0; j--) {
+ const area1 = calculateArea(0, rows - 1, j + 1, cols - 1);
+ for (let i = 0; i < rows; i++) {
+ const area2 = calculateArea(0, i, 0, j);
+ const area3 = calculateArea(i + 1, rows - 1, 0, j);
+ minSum = Math.min(minSum, area1 + area2 + area3);
+ }
+ }
+
+ for (let i = rows - 1; i >= 0; i--) {
+ const area1 = calculateArea(i + 1, rows - 1, 0, cols - 1);
+ for (let j = 0; j < cols; j++) {
+ const area2 = calculateArea(0, i, 0, j);
+ const area3 = calculateArea(0, i, j + 1, cols - 1);
+ minSum = Math.min(minSum, area1 + area2 + area3);
+ }
+ }
+
+ for (let i = 0; i < rows; i++) {
+ for (let j = i + 1; j < rows; j++) {
+ const area1 = calculateArea(0, i, 0, cols - 1);
+ const area2 = calculateArea(i + 1, j, 0, cols - 1);
+ const area3 = calculateArea(j + 1, rows - 1, 0, cols - 1);
+ minSum = Math.min(minSum, area1 + area2 + area3);
+ }
+ }
+
+ for (let i = 0; i < cols; i++) {
+ for (let j = i + 1; j < cols; j++) {
+ const area1 = calculateArea(0, rows - 1, 0, i);
+ const area2 = calculateArea(0, rows - 1, i + 1, j);
+ const area3 = calculateArea(0, rows - 1, j + 1, cols - 1);
+ minSum = Math.min(minSum, area1 + area2 + area3);
+ }
+ }
+
+ return minSum;
+
+ function calculateArea(startRow, endRow, startCol, endCol) {
+ let minRow = Infinity;
+ let maxRow = -1;
+ let minCol = Infinity;
+ let maxCol = -1;
+ let found = false;
+
+ for (let i = startRow; i <= endRow; i++) {
+ for (let j = startCol; j <= endCol; j++) {
+ if (grid[i][j] === 1) {
+ minRow = Math.min(minRow, i);
+ maxRow = Math.max(maxRow, i);
+ minCol = Math.min(minCol, j);
+ maxCol = Math.max(maxCol, j);
+ found = true;
+ }
+ }
+ }
+
+ return found ? (maxRow - minRow + 1) * (maxCol - minCol + 1) : 0;
+ }
+};
From daf3e8bc305e60f5bb0144c5c905d5e9a543a305 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 26 Aug 2025 15:29:07 -0500
Subject: [PATCH 969/994] Add solution #3000
---
README.md | 1 +
...imum-area-of-longest-diagonal-rectangle.js | 34 +++++++++++++++++++
2 files changed, 35 insertions(+)
create mode 100644 solutions/3000-maximum-area-of-longest-diagonal-rectangle.js
diff --git a/README.md b/README.md
index eec7605b..da8b0819 100644
--- a/README.md
+++ b/README.md
@@ -2589,6 +2589,7 @@
2997|[Minimum Number of Operations to Make Array XOR Equal to K](./solutions/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k.js)|Medium|
2998|[Minimum Number of Operations to Make X and Y Equal](./solutions/2998-minimum-number-of-operations-to-make-x-and-y-equal.js)|Medium|
2999|[Count the Number of Powerful Integers](./solutions/2999-count-the-number-of-powerful-integers.js)|Hard|
+3000|[Maximum Area of Longest Diagonal Rectangle](./solutions/3000-maximum-area-of-longest-diagonal-rectangle.js)|Easy|
3002|[Maximum Size of a Set After Removals](./solutions/3002-maximum-size-of-a-set-after-removals.js)|Medium|
3004|[Maximum Subtree of the Same Color](./solutions/3004-maximum-subtree-of-the-same-color.js)|Medium|
3005|[Count Elements With Maximum Frequency](./solutions/3005-count-elements-with-maximum-frequency.js)|Easy|
diff --git a/solutions/3000-maximum-area-of-longest-diagonal-rectangle.js b/solutions/3000-maximum-area-of-longest-diagonal-rectangle.js
new file mode 100644
index 00000000..5cb6ed23
--- /dev/null
+++ b/solutions/3000-maximum-area-of-longest-diagonal-rectangle.js
@@ -0,0 +1,34 @@
+/**
+ * 3000. Maximum Area of Longest Diagonal Rectangle
+ * https://leetcode.com/problems/maximum-area-of-longest-diagonal-rectangle/
+ * Difficulty: Easy
+ *
+ * You are given a 2D 0-indexed integer array dimensions.
+ *
+ * For all indices i, 0 <= i < dimensions.length, dimensions[i][0] represents the length and
+ * dimensions[i][1] represents the width of the rectangle i.
+ *
+ * Return the area of the rectangle having the longest diagonal. If there are multiple rectangles
+ * with the longest diagonal, return the area of the rectangle having the maximum area.
+ */
+
+/**
+ * @param {number[][]} dimensions
+ * @return {number}
+ */
+var areaOfMaxDiagonal = function(dimensions) {
+ let maxDiagonal = 0;
+ let result = 0;
+
+ for (const [length, width] of dimensions) {
+ const diagonal = length * length + width * width;
+ const area = length * width;
+
+ if (diagonal > maxDiagonal || (diagonal === maxDiagonal && area > result)) {
+ maxDiagonal = diagonal;
+ result = area;
+ }
+ }
+
+ return result;
+};
From c7668498e947bb451f685a7dd6ea3ecfd8d995d4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 27 Aug 2025 22:17:22 -0500
Subject: [PATCH 970/994] Add solution #3446
---
README.md | 1 +
solutions/3446-sort-matrix-by-diagonals.js | 40 ++++++++++++++++++++++
2 files changed, 41 insertions(+)
create mode 100644 solutions/3446-sort-matrix-by-diagonals.js
diff --git a/README.md b/README.md
index da8b0819..462ba20b 100644
--- a/README.md
+++ b/README.md
@@ -2739,6 +2739,7 @@
3442|[Maximum Difference Between Even and Odd Frequency I](./solutions/3442-maximum-difference-between-even-and-odd-frequency-i.js)|Easy|
3443|[Maximum Manhattan Distance After K Changes](./solutions/3443-maximum-manhattan-distance-after-k-changes.js)|Medium|
3445|[Maximum Difference Between Even and Odd Frequency II](./solutions/3445-maximum-difference-between-even-and-odd-frequency-ii.js)|Hard|
+3446|[Sort Matrix by Diagonals](./solutions/3446-sort-matrix-by-diagonals.js)|Medium|
3450|[Maximum Students on a Single Bench](./solutions/3450-maximum-students-on-a-single-bench.js)|Easy|
3452|[Sum of Good Numbers](./solutions/3452-sum-of-good-numbers.js)|Easy|
3460|[Longest Common Prefix After at Most One Removal](./solutions/3460-longest-common-prefix-after-at-most-one-removal.js)|Medium|
diff --git a/solutions/3446-sort-matrix-by-diagonals.js b/solutions/3446-sort-matrix-by-diagonals.js
new file mode 100644
index 00000000..d4772686
--- /dev/null
+++ b/solutions/3446-sort-matrix-by-diagonals.js
@@ -0,0 +1,40 @@
+/**
+ * 3446. Sort Matrix by Diagonals
+ * https://leetcode.com/problems/sort-matrix-by-diagonals/
+ * Difficulty: Medium
+ *
+ * You are given an n x n square matrix of integers grid. Return the matrix such that:
+ * - The diagonals in the bottom-left triangle (including the middle diagonal) are sorted
+ * in non-increasing order.
+ * - The diagonals in the top-right triangle are sorted in non-decreasing order.
+ */
+
+/**
+ * @param {number[][]} grid
+ * @return {number[][]}
+ */
+var sortMatrix = function(grid) {
+ const n = grid.length;
+ const map = new Map();
+
+ for (let i = 0; i < n; i++) {
+ for (let j = 0; j < n; j++) {
+ const key = i - j;
+ if (!map.has(key)) {
+ map.set(key, key < 0
+ ? new PriorityQueue((a, b) => a - b)
+ : new PriorityQueue((a, b) => b - a));
+ }
+ map.get(key).enqueue(grid[i][j]);
+ }
+ }
+
+ for (let i = 0; i < n; i++) {
+ for (let j = 0; j < n; j++) {
+ const key = i - j;
+ grid[i][j] = map.get(key).dequeue();
+ }
+ }
+
+ return grid;
+};
From 39b4d3619045a20372f2cec8f2131831e836a030 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 29 Aug 2025 22:49:42 -0500
Subject: [PATCH 971/994] Add solution #2407
---
README.md | 1 +
.../2407-longest-increasing-subsequence-ii.js | 65 +++++++++++++++++++
2 files changed, 66 insertions(+)
create mode 100644 solutions/2407-longest-increasing-subsequence-ii.js
diff --git a/README.md b/README.md
index 462ba20b..18d215f2 100644
--- a/README.md
+++ b/README.md
@@ -2183,6 +2183,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|
2406|[Divide Intervals Into Minimum Number of Groups](./solutions/2406-divide-intervals-into-minimum-number-of-groups.js)|Medium|
+2407|[Longest Increasing Subsequence II](./solutions/2407-longest-increasing-subsequence-ii.js)|Hard|
2408|[Design SQL](./solutions/2408-design-sql.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|
diff --git a/solutions/2407-longest-increasing-subsequence-ii.js b/solutions/2407-longest-increasing-subsequence-ii.js
new file mode 100644
index 00000000..d30f3ae8
--- /dev/null
+++ b/solutions/2407-longest-increasing-subsequence-ii.js
@@ -0,0 +1,65 @@
+/**
+ * 2407. Longest Increasing Subsequence II
+ * https://leetcode.com/problems/longest-increasing-subsequence-ii/
+ * Difficulty: Hard
+ *
+ * You are given an integer array nums and an integer k.
+ *
+ * Find the longest subsequence of nums that meets the following requirements:
+ * - The subsequence is strictly increasing and
+ * - The difference between adjacent elements in the subsequence is at most k.
+ *
+ * Return the length of the longest subsequence that meets the requirements.
+ *
+ * A subsequence is an array that can be derived from another array by deleting some or
+ * no elements without changing the order of the remaining elements.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var lengthOfLIS = function(nums, k) {
+ const maxValue = Math.max(...nums);
+ const tree = new Array(4 * maxValue).fill(0);
+
+ for (const currentNum of nums) {
+ const rangeStart = Math.max(1, currentNum - k);
+ const rangeEnd = currentNum - 1;
+
+ const bestPreviousLength = rangeEnd >= rangeStart
+ ? queryRange(1, 1, maxValue, rangeStart, rangeEnd) : 0;
+ updatePosition(1, 1, maxValue, currentNum, bestPreviousLength + 1);
+ }
+
+ return queryRange(1, 1, maxValue, 1, maxValue);
+
+ function updatePosition(nodeIndex, treeStart, treeEnd, position, newLength) {
+ if (treeStart === treeEnd) {
+ tree[nodeIndex] = Math.max(tree[nodeIndex], newLength);
+ } else {
+ const treeMid = Math.floor((treeStart + treeEnd) / 2);
+ if (position <= treeMid) {
+ updatePosition(2 * nodeIndex, treeStart, treeMid, position, newLength);
+ } else {
+ updatePosition(2 * nodeIndex + 1, treeMid + 1, treeEnd, position, newLength);
+ }
+ tree[nodeIndex] = Math.max(tree[2 * nodeIndex], tree[2 * nodeIndex + 1]);
+ }
+ }
+
+ function queryRange(nodeIndex, treeStart, treeEnd, queryStart, queryEnd) {
+ if (queryEnd < treeStart || treeEnd < queryStart) {
+ return 0;
+ }
+ if (queryStart <= treeStart && treeEnd <= queryEnd) {
+ return tree[nodeIndex];
+ }
+ const mid = Math.floor((treeStart + treeEnd) / 2);
+ return Math.max(
+ queryRange(2 * nodeIndex, treeStart, mid, queryStart, queryEnd),
+ queryRange(2 * nodeIndex + 1, mid + 1, treeEnd, queryStart, queryEnd)
+ );
+ }
+};
From 5844ef087d27e99a4b0d1afcae54ee339cdaca56 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 3 Sep 2025 22:38:49 -0500
Subject: [PATCH 972/994] Add solution #3516
---
README.md | 1 +
solutions/3516-find-closest-person.js | 39 +++++++++++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/3516-find-closest-person.js
diff --git a/README.md b/README.md
index 18d215f2..05ea1e6e 100644
--- a/README.md
+++ b/README.md
@@ -2759,6 +2759,7 @@
3496|[Maximize Score After Pair Deletions](./solutions/3496-maximize-score-after-pair-deletions.js)|Medium|
3506|[Find Time Required to Eliminate Bacterial Strains](./solutions/3506-find-time-required-to-eliminate-bacterial-strains.js)|Hard|
3511|[Make a Positive Array](./solutions/3511-make-a-positive-array.js)|Medium|
+3516|[Find Closest Person](./solutions/3516-find-closest-person.js)|Easy|
3520|[Minimum Threshold for Inversion Pairs Count](./solutions/3520-minimum-threshold-for-inversion-pairs-count.js)|Medium|
3535|[Unit Conversion II](./solutions/3535-unit-conversion-ii.js)|Medium|
diff --git a/solutions/3516-find-closest-person.js b/solutions/3516-find-closest-person.js
new file mode 100644
index 00000000..973cb632
--- /dev/null
+++ b/solutions/3516-find-closest-person.js
@@ -0,0 +1,39 @@
+/**
+ * 3516. Find Closest Person
+ * https://leetcode.com/problems/find-closest-person/
+ * Difficulty: Easy
+ *
+ * You are given three integers x, y, and z, representing the positions of three people
+ * on a number line:
+ * - x is the position of Person 1.
+ * - y is the position of Person 2.
+ * - z is the position of Person 3, who does not move.
+ *
+ * Both Person 1 and Person 2 move toward Person 3 at the same speed.
+ *
+ * Determine which person reaches Person 3 first:
+ * - Return 1 if Person 1 arrives first.
+ * - Return 2 if Person 2 arrives first.
+ * - Return 0 if both arrive at the same time.
+ *
+ * Return the result accordingly.
+ */
+
+/**
+ * @param {number} x
+ * @param {number} y
+ * @param {number} z
+ * @return {number}
+ */
+var findClosest = function(x, y, z) {
+ const distancePerson1 = Math.abs(x - z);
+ const distancePerson2 = Math.abs(y - z);
+
+ if (distancePerson1 < distancePerson2) {
+ return 1;
+ } else if (distancePerson2 < distancePerson1) {
+ return 2;
+ } else {
+ return 0;
+ }
+};
From 64f2a6b36dbdb57c68eea687bf92d11240a4402b Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 4 Sep 2025 23:37:53 -0500
Subject: [PATCH 973/994] Add solution #2749
---
README.md | 1 +
...mum-operations-to-make-the-integer-zero.js | 43 +++++++++++++++++++
2 files changed, 44 insertions(+)
create mode 100644 solutions/2749-minimum-operations-to-make-the-integer-zero.js
diff --git a/README.md b/README.md
index 05ea1e6e..37cc2baa 100644
--- a/README.md
+++ b/README.md
@@ -2446,6 +2446,7 @@
2744|[Find Maximum Number of String Pairs](./solutions/2744-find-maximum-number-of-string-pairs.js)|Easy|
2745|[Construct the Longest New String](./solutions/2745-construct-the-longest-new-string.js)|Medium|
2748|[Number of Beautiful Pairs](./solutions/2748-number-of-beautiful-pairs.js)|Easy|
+2749|[Minimum Operations to Make the Integer Zero](./solutions/2749-minimum-operations-to-make-the-integer-zero.js)|Medium|
2751|[Robot Collisions](./solutions/2751-robot-collisions.js)|Hard|
2753|[Count Houses in a Circular Street II](./solutions/2753-count-houses-in-a-circular-street-ii.js)|Hard|
2754|[Bind Function to Context](./solutions/2754-bind-function-to-context.js)|Medium|
diff --git a/solutions/2749-minimum-operations-to-make-the-integer-zero.js b/solutions/2749-minimum-operations-to-make-the-integer-zero.js
new file mode 100644
index 00000000..c837f351
--- /dev/null
+++ b/solutions/2749-minimum-operations-to-make-the-integer-zero.js
@@ -0,0 +1,43 @@
+/**
+ * 2749. Minimum Operations to Make the Integer Zero
+ * https://leetcode.com/problems/minimum-operations-to-make-the-integer-zero/
+ * Difficulty: Medium
+ *
+ * You are given two integers num1 and num2.
+ *
+ * In one operation, you can choose integer i in the range [0, 60] and subtract 2i + num2 from num1.
+ *
+ * Return the integer denoting the minimum number of operations needed to make num1 equal to 0.
+ *
+ * If it is impossible to make num1 equal to 0, return -1.
+ */
+
+/**
+ * @param {number} num1
+ * @param {number} num2
+ * @return {number}
+ */
+var makeTheIntegerZero = function(num1, num2) {
+ for (let operations = 1; operations <= 60; operations++) {
+ const remaining = num1 - num2 * operations;
+
+ if (remaining < operations) {
+ return -1;
+ }
+
+ if (operations >= countBits(remaining)) {
+ return operations;
+ }
+ }
+
+ return -1;
+
+ function countBits(n) {
+ let count = 0;
+ while (n > 0) {
+ count += n & 1;
+ n = Math.floor(n / 2);
+ }
+ return count;
+ }
+};
From ca366ba84fe857b822e060972b690bc27b703da6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 5 Sep 2025 23:40:36 -0500
Subject: [PATCH 974/994] Add solution #3495
---
README.md | 1 +
...-operations-to-make-array-elements-zero.js | 44 +++++++++++++++++++
2 files changed, 45 insertions(+)
create mode 100644 solutions/3495-minimum-operations-to-make-array-elements-zero.js
diff --git a/README.md b/README.md
index 37cc2baa..6ec6e5d2 100644
--- a/README.md
+++ b/README.md
@@ -2757,6 +2757,7 @@
3481|[Apply Substitutions](./solutions/3481-apply-substitutions.js)|Medium|
3487|[Maximum Unique Subarray Sum After Deletion](./solutions/3487-maximum-unique-subarray-sum-after-deletion.js)|Easy|
3491|[Phone Number Prefix](./solutions/3491-phone-number-prefix.js)|Easy|
+3495|[Minimum Operations to Make Array Elements Zero](./solutions/3495-minimum-operations-to-make-array-elements-zero.js)|Hard|
3496|[Maximize Score After Pair Deletions](./solutions/3496-maximize-score-after-pair-deletions.js)|Medium|
3506|[Find Time Required to Eliminate Bacterial Strains](./solutions/3506-find-time-required-to-eliminate-bacterial-strains.js)|Hard|
3511|[Make a Positive Array](./solutions/3511-make-a-positive-array.js)|Medium|
diff --git a/solutions/3495-minimum-operations-to-make-array-elements-zero.js b/solutions/3495-minimum-operations-to-make-array-elements-zero.js
new file mode 100644
index 00000000..9d3967ff
--- /dev/null
+++ b/solutions/3495-minimum-operations-to-make-array-elements-zero.js
@@ -0,0 +1,44 @@
+/**
+ * 3495. Minimum Operations to Make Array Elements Zero
+ * https://leetcode.com/problems/minimum-operations-to-make-array-elements-zero/
+ * Difficulty: Hard
+ *
+ * You are given a 2D array queries, where queries[i] is of the form [l, r]. Each
+ * queries[i] defines an array of integers nums consisting of elements ranging
+ * from l to r, both inclusive.
+ *
+ * In one operation, you can:
+ * - Select two integers a and b from the array.
+ * - Replace them with floor(a / 4) and floor(b / 4).
+ *
+ * Your task is to determine the minimum number of operations required to reduce all
+ * elements of the array to zero for each query. Return the sum of the results for
+ * all queries.
+ */
+
+/**
+ * @param {number[][]} queries
+ * @return {number}
+ */
+var minOperations = function(queries) {
+ let result = 0;
+
+ for (const [start, end] of queries) {
+ let operationsNeeded = 0;
+
+ for (let depth = 1, previousBound = 1; depth < 17; depth++) {
+ const currentBound = previousBound * 4;
+ const intersectionLeft = Math.max(start, previousBound);
+ const intersectionRight = Math.min(end, currentBound - 1);
+
+ if (intersectionRight >= intersectionLeft) {
+ operationsNeeded += (intersectionRight - intersectionLeft + 1) * depth;
+ }
+ previousBound = currentBound;
+ }
+
+ result += Math.ceil(operationsNeeded / 2);
+ }
+
+ return result;
+};
From 18d24dd55c0b8e3d0be63ae8a59e96afd825f2f4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 12 Sep 2025 18:30:02 -0500
Subject: [PATCH 975/994] Add solution #3227
---
README.md | 1 +
solutions/3227-vowels-game-in-a-string.js | 35 +++++++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 solutions/3227-vowels-game-in-a-string.js
diff --git a/README.md b/README.md
index 6ec6e5d2..44e862d0 100644
--- a/README.md
+++ b/README.md
@@ -2683,6 +2683,7 @@
3215|[Count Triplets with Even XOR Set Bits II](./solutions/3215-count-triplets-with-even-xor-set-bits-ii.js)|Medium|
3221|[Maximum Array Hopping Score II](./solutions/3221-maximum-array-hopping-score-ii.js)|Medium|
3223|[Minimum Length of String After Operations](./solutions/3223-minimum-length-of-string-after-operations.js)|Medium|
+3227|[Vowels Game in a String](./solutions/3227-vowels-game-in-a-string.js)|Medium|
3231|[Minimum Number of Increasing Subsequence to Be Removed](./solutions/3231-minimum-number-of-increasing-subsequence-to-be-removed.js)|Hard|
3237|[Alt and Tab Simulation](./solutions/3237-alt-and-tab-simulation.js)|Medium|
3247|[Number of Subsequences with Odd Sum](./solutions/3247-number-of-subsequences-with-odd-sum.js)|Medium|
diff --git a/solutions/3227-vowels-game-in-a-string.js b/solutions/3227-vowels-game-in-a-string.js
new file mode 100644
index 00000000..15dfd693
--- /dev/null
+++ b/solutions/3227-vowels-game-in-a-string.js
@@ -0,0 +1,35 @@
+/**
+ * 3227. Vowels Game in a String
+ * https://leetcode.com/problems/vowels-game-in-a-string/
+ * Difficulty: Medium
+ *
+ * Alice and Bob are playing a game on a string.
+ *
+ * You are given a string s, Alice and Bob will take turns playing the following game where
+ * Alice starts first:
+ * - On Alice's turn, she has to remove any non-empty substring from s that contains an odd
+ * number of vowels.
+ * - On Bob's turn, he has to remove any non-empty substring from s that contains an even
+ * number of vowels.
+ *
+ * The first player who cannot make a move on their turn loses the game. We assume that both
+ * Alice and Bob play optimally.
+ *
+ * Return true if Alice wins the game, and false otherwise.
+ *
+ * The English vowels are: a, e, i, o, and u.
+ */
+
+/**
+ * @param {string} s
+ * @return {boolean}
+ */
+var doesAliceWin = function(s) {
+ const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
+ for (const char of s) {
+ if (vowels.has(char)) {
+ return true;
+ }
+ }
+ return false;
+};
From 600214dd661b9fd9ac0df374d0a49ea327af86c6 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 13 Sep 2025 16:18:27 -0500
Subject: [PATCH 976/994] Add solution #3541
---
README.md | 1 +
...-find-most-frequent-vowel-and-consonant.js | 42 +++++++++++++++++++
2 files changed, 43 insertions(+)
create mode 100644 solutions/3541-find-most-frequent-vowel-and-consonant.js
diff --git a/README.md b/README.md
index 44e862d0..487ba7de 100644
--- a/README.md
+++ b/README.md
@@ -2765,6 +2765,7 @@
3516|[Find Closest Person](./solutions/3516-find-closest-person.js)|Easy|
3520|[Minimum Threshold for Inversion Pairs Count](./solutions/3520-minimum-threshold-for-inversion-pairs-count.js)|Medium|
3535|[Unit Conversion II](./solutions/3535-unit-conversion-ii.js)|Medium|
+3541|[Find Most Frequent Vowel and Consonant](./solutions/3541-find-most-frequent-vowel-and-consonant.js)|Easy|
## License
diff --git a/solutions/3541-find-most-frequent-vowel-and-consonant.js b/solutions/3541-find-most-frequent-vowel-and-consonant.js
new file mode 100644
index 00000000..69b47b09
--- /dev/null
+++ b/solutions/3541-find-most-frequent-vowel-and-consonant.js
@@ -0,0 +1,42 @@
+/**
+ * 3541. Find Most Frequent Vowel and Consonant
+ * https://leetcode.com/problems/find-most-frequent-vowel-and-consonant/
+ * Difficulty: Easy
+ *
+ * You are given a string s consisting of lowercase English letters ('a' to 'z').
+ *
+ * Your task is to:
+ * - Find the vowel (one of 'a', 'e', 'i', 'o', or 'u') with the maximum frequency.
+ * - Find the consonant (all other letters excluding vowels) with the maximum frequency.
+ *
+ * Return the sum of the two frequencies.
+ *
+ * Note: If multiple vowels or consonants have the same maximum frequency, you may choose
+ * any one of them. If there are no vowels or no consonants in the string, consider their
+ * frequency as 0.
+ *
+ * The frequency of a letter x is the number of times it occurs in the string.
+ */
+
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var maxFreqSum = function(s) {
+ const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
+ const vowelFreq = {};
+ const consonantFreq = {};
+
+ for (const char of s) {
+ if (vowels.has(char)) {
+ vowelFreq[char] = (vowelFreq[char] || 0) + 1;
+ } else {
+ consonantFreq[char] = (consonantFreq[char] || 0) + 1;
+ }
+ }
+
+ const maxVowelFreq = Math.max(0, ...Object.values(vowelFreq));
+ const maxConsonantFreq = Math.max(0, ...Object.values(consonantFreq));
+
+ return maxVowelFreq + maxConsonantFreq;
+};
From 9a721394ae6c21981bde06fa5bc0e6b9e3316046 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 18 Sep 2025 19:00:42 -0500
Subject: [PATCH 977/994] Add solution #3408
---
README.md | 1 +
solutions/3408-design-task-manager.js | 91 +++++++++++++++++++++++++++
2 files changed, 92 insertions(+)
create mode 100644 solutions/3408-design-task-manager.js
diff --git a/README.md b/README.md
index 487ba7de..8ef7856c 100644
--- a/README.md
+++ b/README.md
@@ -2732,6 +2732,7 @@
3403|[Find the Lexicographically Largest String From the Box I](./solutions/3403-find-the-lexicographically-largest-string-from-the-box-i.js)|Medium|
3405|[Count the Number of Arrays with K Matching Adjacent Elements](./solutions/3405-count-the-number-of-arrays-with-k-matching-adjacent-elements.js)|Hard|
3406|[Find the Lexicographically Largest String From the Box II](./solutions/3406-find-the-lexicographically-largest-string-from-the-box-ii.js)|Hard|
+3408|[Design Task Manager](./solutions/3408-design-task-manager.js)|Medium|
3416|[Subsequences with a Unique Middle Mode II](./solutions/3416-subsequences-with-a-unique-middle-mode-ii.js)|Hard|
3422|[Minimum Operations to Make Subarray Elements Equal](./solutions/3422-minimum-operations-to-make-subarray-elements-equal.js)|Medium|
3423|[Maximum Difference Between Adjacent Elements in a Circular Array](./solutions/3423-maximum-difference-between-adjacent-elements-in-a-circular-array.js)|Easy|
diff --git a/solutions/3408-design-task-manager.js b/solutions/3408-design-task-manager.js
new file mode 100644
index 00000000..8d0a56fb
--- /dev/null
+++ b/solutions/3408-design-task-manager.js
@@ -0,0 +1,91 @@
+/**
+ * 3408. Design Task Manager
+ * https://leetcode.com/problems/design-task-manager/
+ * Difficulty: Medium
+ *
+ * There is a task management system that allows users to manage their tasks, each associated
+ * with a priority. The system should efficiently handle adding, modifying, executing, and
+ * removing tasks.
+ *
+ * Implement the TaskManager class:
+ * - TaskManager(vector>& tasks) initializes the task manager with a list of
+ * user-task-priority triples. Each element in the input list is of the form [userId,
+ * taskId, priority], which adds a task to the specified user with the given priority.
+ * - void add(int userId, int taskId, int priority) adds a task with the specified taskId
+ * and priority to the user with userId. It is guaranteed that taskId does not exist in
+ * the system.
+ * - void edit(int taskId, int newPriority) updates the priority of the existing taskId to
+ * newPriority. It is guaranteed that taskId exists in the system.
+ * - void rmv(int taskId) removes the task identified by taskId from the system. It is
+ * guaranteed that taskId exists in the system.
+ * - int execTop() executes the task with the highest priority across all users. If there
+ * are multiple tasks with the same highest priority, execute the one with the highest
+ * taskId. After executing, the taskId is removed from the system. Return the userId
+ * associated with the executed task. If no tasks are available, return -1.
+ *
+ * Note that a user may be assigned multiple tasks.
+ */
+
+/**
+ * @param {number[][]} tasks
+ */
+var TaskManager = function(tasks) {
+ this.taskRegistry = {};
+ this.priorityHeap = new PriorityQueue((a, b) => {
+ return a.priority !== b.priority ? b.priority - a.priority : b.taskId - a.taskId;
+ });
+
+ for (const [userId, taskId, priority] of tasks) {
+ this.taskRegistry[taskId] = { userId, priority, version: 1 };
+ this.priorityHeap.enqueue({ taskId, priority, version: 1 });
+ }
+};
+
+/**
+ * @param {number} userId
+ * @param {number} taskId
+ * @param {number} priority
+ * @return {void}
+ */
+TaskManager.prototype.add = function(userId, taskId, priority) {
+ this.taskRegistry[taskId] = { userId, priority, version: 1 };
+ this.priorityHeap.enqueue({ taskId, priority, version: 1 });
+};
+
+/**
+ * @param {number} taskId
+ * @param {number} newPriority
+ * @return {void}
+ */
+TaskManager.prototype.edit = function(taskId, newPriority) {
+ const currentTask = this.taskRegistry[taskId];
+ currentTask.priority = newPriority;
+ currentTask.version++;
+ this.priorityHeap.enqueue({ taskId, priority: newPriority, version: currentTask.version });
+};
+
+/**
+ * @param {number} taskId
+ * @return {void}
+ */
+TaskManager.prototype.rmv = function(taskId) {
+ delete this.taskRegistry[taskId];
+};
+
+
+/**
+ * @return {number}
+ */
+TaskManager.prototype.execTop = function() {
+ while (!this.priorityHeap.isEmpty()) {
+ const { taskId, priority, version } = this.priorityHeap.dequeue();
+ const activeTask = this.taskRegistry[taskId];
+
+ if (activeTask && activeTask.priority === priority && activeTask.version === version) {
+ const executedUserId = activeTask.userId;
+ delete this.taskRegistry[taskId];
+ return executedUserId;
+ }
+ }
+ return -1;
+};
From 01e63c9a12030557f614e83a2795caef9c61d150 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 19 Sep 2025 18:24:09 -0500
Subject: [PATCH 978/994] Add solution #3484
---
README.md | 1 +
solutions/3484-design-spreadsheet.js | 71 ++++++++++++++++++++++++++++
2 files changed, 72 insertions(+)
create mode 100644 solutions/3484-design-spreadsheet.js
diff --git a/README.md b/README.md
index 8ef7856c..951d27a5 100644
--- a/README.md
+++ b/README.md
@@ -2757,6 +2757,7 @@
3479|[Fruits Into Baskets III](./solutions/3479-fruits-into-baskets-iii.js)|Medium|
3480|[Maximize Subarrays After Removing One Conflicting Pair](./solutions/3480-maximize-subarrays-after-removing-one-conflicting-pair.js)|Hard|
3481|[Apply Substitutions](./solutions/3481-apply-substitutions.js)|Medium|
+3484|[Design Spreadsheet](./solutions/3484-design-spreadsheet.js)|Medium|
3487|[Maximum Unique Subarray Sum After Deletion](./solutions/3487-maximum-unique-subarray-sum-after-deletion.js)|Easy|
3491|[Phone Number Prefix](./solutions/3491-phone-number-prefix.js)|Easy|
3495|[Minimum Operations to Make Array Elements Zero](./solutions/3495-minimum-operations-to-make-array-elements-zero.js)|Hard|
diff --git a/solutions/3484-design-spreadsheet.js b/solutions/3484-design-spreadsheet.js
new file mode 100644
index 00000000..ff042fa3
--- /dev/null
+++ b/solutions/3484-design-spreadsheet.js
@@ -0,0 +1,71 @@
+/**
+ * 3484. Design Spreadsheet
+ * https://leetcode.com/problems/design-spreadsheet/
+ * Difficulty: Medium
+ *
+ * A spreadsheet is a grid with 26 columns (labeled from 'A' to 'Z') and a given number
+ * of rows. Each cell in the spreadsheet can hold an integer value between 0 and 105.
+ *
+ * Implement the Spreadsheet class:
+ * - Spreadsheet(int rows) Initializes a spreadsheet with 26 columns (labeled 'A' to 'Z')
+ * and the specified number of rows. All cells are initially set to 0.
+ * - void setCell(String cell, int value) Sets the value of the specified cell. The cell
+ * reference is provided in the format "AX" (e.g., "A1", "B10"), where the letter represents
+ * the column (from 'A' to 'Z') and the number represents a 1-indexed row.
+ * - void resetCell(String cell) Resets the specified cell to 0.
+ * - int getValue(String formula) Evaluates a formula of the form "=X+Y", where X and Y are
+ * either cell references or non-negative integers, and returns the computed sum.
+ *
+ * Note: If getValue references a cell that has not been explicitly set using setCell, its
+ * value is considered 0.
+ */
+
+/**
+ * @param {number} rows
+ */
+var Spreadsheet = function(rows) {
+ this.cellValues = new Map();
+ this.totalRows = rows;
+};
+
+/**
+ * @param {string} cell
+ * @param {number} value
+ * @return {void}
+ */
+Spreadsheet.prototype.setCell = function(cell, value) {
+ this.cellValues.set(cell, value);
+};
+
+/**
+ * @param {string} cell
+ * @return {void}
+ */
+Spreadsheet.prototype.resetCell = function(cell) {
+ this.cellValues.delete(cell);
+};
+
+/**
+ * @param {string} formula
+ * @return {number}
+ */
+Spreadsheet.prototype.getValue = function(formula) {
+ const expression = formula.slice(1);
+ const operands = expression.split('+');
+
+ const leftValue = this.parseOperand(operands[0]);
+ const rightValue = this.parseOperand(operands[1]);
+
+ return leftValue + rightValue;
+};
+
+/**
+ * @param {string} operand
+ * @return {number}
+ */
+Spreadsheet.prototype.parseOperand = function(operand) {
+ if (/^\d+$/.test(operand)) {
+ return parseInt(operand);
+ }
+ return this.cellValues.get(operand) || 0;
+};
From f529f972a7471db7fa852fa112f0101c2d3753ea Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 20 Sep 2025 18:48:49 -0500
Subject: [PATCH 979/994] Add solution #3508
---
README.md | 1 +
solutions/3508-implement-router.js | 166 +++++++++++++++++++++++++++++
2 files changed, 167 insertions(+)
create mode 100644 solutions/3508-implement-router.js
diff --git a/README.md b/README.md
index 951d27a5..6947142b 100644
--- a/README.md
+++ b/README.md
@@ -2763,6 +2763,7 @@
3495|[Minimum Operations to Make Array Elements Zero](./solutions/3495-minimum-operations-to-make-array-elements-zero.js)|Hard|
3496|[Maximize Score After Pair Deletions](./solutions/3496-maximize-score-after-pair-deletions.js)|Medium|
3506|[Find Time Required to Eliminate Bacterial Strains](./solutions/3506-find-time-required-to-eliminate-bacterial-strains.js)|Hard|
+3508|[Implement Router](./solutions/3508-implement-router.js)|Medium|
3511|[Make a Positive Array](./solutions/3511-make-a-positive-array.js)|Medium|
3516|[Find Closest Person](./solutions/3516-find-closest-person.js)|Easy|
3520|[Minimum Threshold for Inversion Pairs Count](./solutions/3520-minimum-threshold-for-inversion-pairs-count.js)|Medium|
diff --git a/solutions/3508-implement-router.js b/solutions/3508-implement-router.js
new file mode 100644
index 00000000..47b86cfb
--- /dev/null
+++ b/solutions/3508-implement-router.js
@@ -0,0 +1,166 @@
+/**
+ * 3508. Implement Router
+ * https://leetcode.com/problems/implement-router/
+ * Difficulty: Medium
+ *
+ * Design a data structure that can efficiently manage data packets in a network router.
+ * Each data packet consists of the following attributes:
+ * - source: A unique identifier for the machine that generated the packet.
+ * - destination: A unique identifier for the target machine.
+ * - timestamp: The time at which the packet arrived at the router.
+ *
+ * Implement the Router class:
+ * Router(int memoryLimit): Initializes the Router object with a fixed memory limit.
+ * - memoryLimit is the maximum number of packets the router can store at any given time.
+ * - If adding a new packet would exceed this limit, the oldest packet must be removed to
+ * free up space.
+ * bool addPacket(int source, int destination, int timestamp): Adds a packet with the
+ * given attributes to the router.
+ * - A packet is considered a duplicate if another packet with the same source, destination,
+ * and timestamp already exists in the router.
+ * - Return true if the packet is successfully added (i.e., it is not a duplicate); otherwise
+ * return false.
+ * int[] forwardPacket(): Forwards the next packet in FIFO (First In First Out) order.
+ * - Remove the packet from storage.
+ * - Return the packet as an array [source, destination, timestamp].
+ * - If there are no packets to forward, return an empty array.
+ * int getCount(int destination, int startTime, int endTime):
+ * - Returns the number of packets currently stored in the router (i.e., not yet forwarded) that
+ * have the specified destination and have timestamps in the inclusive range [startTime, endTime].
+ *
+ * Note that queries for addPacket will be made in increasing order of timestamp.
+ */
+
+/**
+ * @param {number} memoryLimit
+ */
+var Router = function(memoryLimit) {
+ this.memoryCapacity = memoryLimit;
+ this.packetQueue = [];
+ this.packetSet = new Set();
+ this.destinationTimestamps = new Map();
+ this.removedPacketIndex = new Map();
+};
+
+/**
+ * @param {number} source
+ * @param {number} destination
+ * @param {number} timestamp
+ * @return {boolean}
+ */
+Router.prototype.addPacket = function(source, destination, timestamp) {
+ const packetKey = `${source}-${destination}-${timestamp}`;
+
+ if (this.packetSet.has(packetKey)) {
+ return false;
+ }
+
+ if (this.packetQueue.length === this.memoryCapacity) {
+ const [oldSource, oldDestination, oldTimestamp] = this.packetQueue.shift();
+ const oldPacketKey = `${oldSource}-${oldDestination}-${oldTimestamp}`;
+ this.packetSet.delete(oldPacketKey);
+ this.removedPacketIndex.set(
+ oldDestination,
+ (this.removedPacketIndex.get(oldDestination) || 0) + 1,
+ );
+ }
+
+ this.packetQueue.push([source, destination, timestamp]);
+ this.packetSet.add(packetKey);
+
+ if (!this.destinationTimestamps.has(destination)) {
+ this.destinationTimestamps.set(destination, []);
+ }
+ this.destinationTimestamps.get(destination).push(timestamp);
+
+ return true;
+};
+
+/**
+ * @return {number[]}
+ */
+Router.prototype.forwardPacket = function() {
+ if (this.packetQueue.length === 0) {
+ return [];
+ }
+
+ const [source, destination, timestamp] = this.packetQueue.shift();
+ const packetKey = `${source}-${destination}-${timestamp}`;
+ this.packetSet.delete(packetKey);
+ this.removedPacketIndex.set(destination, (this.removedPacketIndex.get(destination) || 0) + 1);
+
+ return [source, destination, timestamp];
+};
+
+/**
+ * @param {number} destination
+ * @param {number} startTime
+ * @param {number} endTime
+ * @return {number}
+ */
+Router.prototype.getCount = function(destination, startTime, endTime) {
+ if (!this.destinationTimestamps.has(destination)) {
+ return 0;
+ }
+
+ const timestampArray = this.destinationTimestamps.get(destination);
+ const removedCount = this.removedPacketIndex.get(destination) || 0;
+ const totalLength = timestampArray.length;
+
+ if (removedCount >= totalLength) {
+ return 0;
+ }
+
+ const leftBound = this.binarySearchLeft(timestampArray, startTime, removedCount);
+ const rightBound = this.binarySearchRight(timestampArray, endTime, removedCount) - 1;
+
+ if (leftBound > rightBound) {
+ return 0;
+ }
+
+ return rightBound - leftBound + 1;
+};
+
+/**
+ * @param {number[]} array
+ * @param {number} target
+ * @param {number} startIndex
+ * @return {number}
+ */
+Router.prototype.binarySearchLeft = function(array, target, startIndex) {
+ let left = startIndex;
+ let right = array.length;
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (array[mid] < target) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+
+ return left;
+};
+
+/**
+ * @param {number[]} array
+ * @param {number} target
+ * @param {number} startIndex
+ * @return {number}
+ */
+Router.prototype.binarySearchRight = function(array, target, startIndex) {
+ let left = startIndex;
+ let right = array.length;
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (array[mid] <= target) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+
+ return left;
+};
From 6936555bfc6860c67e4130af2bde442ac20622ba Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 9 Oct 2025 08:20:25 -0500
Subject: [PATCH 980/994] Add solution #3494
---
README.md | 1 +
...-minimum-amount-of-time-to-brew-potions.js | 37 +++++++++++++++++++
2 files changed, 38 insertions(+)
create mode 100644 solutions/3494-find-the-minimum-amount-of-time-to-brew-potions.js
diff --git a/README.md b/README.md
index 6947142b..ee885835 100644
--- a/README.md
+++ b/README.md
@@ -2760,6 +2760,7 @@
3484|[Design Spreadsheet](./solutions/3484-design-spreadsheet.js)|Medium|
3487|[Maximum Unique Subarray Sum After Deletion](./solutions/3487-maximum-unique-subarray-sum-after-deletion.js)|Easy|
3491|[Phone Number Prefix](./solutions/3491-phone-number-prefix.js)|Easy|
+3494|[Find the Minimum Amount of Time to Brew Potions](./solutions/3494-find-the-minimum-amount-of-time-to-brew-potions.js)|Medium|
3495|[Minimum Operations to Make Array Elements Zero](./solutions/3495-minimum-operations-to-make-array-elements-zero.js)|Hard|
3496|[Maximize Score After Pair Deletions](./solutions/3496-maximize-score-after-pair-deletions.js)|Medium|
3506|[Find Time Required to Eliminate Bacterial Strains](./solutions/3506-find-time-required-to-eliminate-bacterial-strains.js)|Hard|
diff --git a/solutions/3494-find-the-minimum-amount-of-time-to-brew-potions.js b/solutions/3494-find-the-minimum-amount-of-time-to-brew-potions.js
new file mode 100644
index 00000000..1ddd6793
--- /dev/null
+++ b/solutions/3494-find-the-minimum-amount-of-time-to-brew-potions.js
@@ -0,0 +1,37 @@
+/**
+ * 3494. Find the Minimum Amount of Time to Brew Potions
+ * https://leetcode.com/problems/find-the-minimum-amount-of-time-to-brew-potions/
+ * Difficulty: Medium
+ *
+ * You are given two integer arrays, skill and mana, of length n and m, respectively.
+ *
+ * In a laboratory, n wizards must brew m potions in order. Each potion has a mana capacity
+ * mana[j] and must pass through all the wizards sequentially to be brewed properly. The
+ * time taken by the ith wizard on the jth potion is timeij = skill[i] * mana[j].
+ *
+ * Since the brewing process is delicate, a potion must be passed to the next wizard
+ * immediately after the current wizard completes their work. This means the timing must
+ * be synchronized so that each wizard begins working on a potion exactly when it arrives.
+ *
+ * Return the minimum amount of time required for the potions to be brewed properly.
+ */
+
+/**
+ * @param {number[]} skill
+ * @param {number[]} mana
+ * @return {number}
+ */
+var minTime = function(skill, mana) {
+ const result = new Array(skill.length + 1).fill(0);
+
+ for (let j = 0; j < mana.length; j++) {
+ for (let i = 0; i < skill.length; i++) {
+ result[i + 1] = Math.max(result[i + 1], result[i]) + mana[j] * skill[i];
+ }
+ for (let i = skill.length - 1; i > 0; i--) {
+ result[i] = result[i + 1] - mana[j] * skill[i];
+ }
+ }
+
+ return result[skill.length];
+};
From c41ac67d68f16eea9784ff51b81a1a86d7bd70a9 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 10 Oct 2025 15:09:43 -0500
Subject: [PATCH 981/994] Add solution #3147
---
README.md | 1 +
...-maximum-energy-from-the-mystic-dungeon.js | 39 +++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 solutions/3147-taking-maximum-energy-from-the-mystic-dungeon.js
diff --git a/README.md b/README.md
index ee885835..f2eb9a83 100644
--- a/README.md
+++ b/README.md
@@ -2660,6 +2660,7 @@
3135|[Equalize Strings by Adding or Removing Characters at Ends](./solutions/3135-equalize-strings-by-adding-or-removing-characters-at-ends.js)|Medium|
3136|[Valid Word](./solutions/3136-valid-word.js)|Easy|
3141|[Maximum Hamming Distances](./solutions/3141-maximum-hamming-distances.js)|Hard|
+3147|[Taking Maximum Energy From the Mystic Dungeon](./solutions/3147-taking-maximum-energy-from-the-mystic-dungeon.js)|Medium|
3151|[Special Array I](./solutions/3151-special-array-i.js)|Easy|
3155|[Maximum Number of Upgradable Servers](./solutions/3155-maximum-number-of-upgradable-servers.js)|Medium|
3157|[Find the Level of Tree with Minimum Sum](./solutions/3157-find-the-level-of-tree-with-minimum-sum.js)|Medium|
diff --git a/solutions/3147-taking-maximum-energy-from-the-mystic-dungeon.js b/solutions/3147-taking-maximum-energy-from-the-mystic-dungeon.js
new file mode 100644
index 00000000..e977aecd
--- /dev/null
+++ b/solutions/3147-taking-maximum-energy-from-the-mystic-dungeon.js
@@ -0,0 +1,39 @@
+/**
+ * 3147. Taking Maximum Energy From the Mystic Dungeon
+ * https://leetcode.com/problems/taking-maximum-energy-from-the-mystic-dungeon/
+ * Difficulty: Medium
+ *
+ * In a mystic dungeon, n magicians are standing in a line. Each magician has an attribute
+ * that gives you energy. Some magicians can give you negative energy, which means taking
+ * energy from you.
+ *
+ * You have been cursed in such a way that after absorbing energy from magician i, you will
+ * be instantly transported to magician (i + k). This process will be repeated until you
+ * reach the magician where (i + k) does not exist.
+ *
+ * In other words, you will choose a starting point and then teleport with k jumps until you
+ * reach the end of the magicians' sequence, absorbing all the energy during the journey.
+ *
+ * You are given an array energy and an integer k. Return the maximum possible energy you can gain.
+ *
+ * Note that when you are reach a magician, you must take energy from them, whether it is negative
+ * or positive energy.
+ */
+
+/**
+ * @param {number[]} energy
+ * @param {number} k
+ * @return {number}
+ */
+var maximumEnergy = function(energy, k) {
+ const n = energy.length;
+ const dp = new Array(n).fill(0);
+ let result = -Infinity;
+
+ for (let i = n - 1; i >= 0; i--) {
+ dp[i] = energy[i] + (i + k < n ? dp[i + k] : 0);
+ result = Math.max(result, dp[i]);
+ }
+
+ return result;
+};
From 37d131454bf01ad73dd0d41aa978b7053370f316 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Sat, 11 Oct 2025 15:50:47 -0500
Subject: [PATCH 982/994] Add solution #3186
---
README.md | 1 +
...maximum-total-damage-with-spell-casting.js | 55 +++++++++++++++++++
2 files changed, 56 insertions(+)
create mode 100644 solutions/3186-maximum-total-damage-with-spell-casting.js
diff --git a/README.md b/README.md
index f2eb9a83..269ce1cc 100644
--- a/README.md
+++ b/README.md
@@ -2672,6 +2672,7 @@
3174|[Clear Digits](./solutions/3174-clear-digits.js)|Easy|
3178|[Find the Child Who Has the Ball After K Seconds](./solutions/3178-find-the-child-who-has-the-ball-after-k-seconds.js)|Easy|
3183|[The Number of Ways to Make the Sum](./solutions/3183-the-number-of-ways-to-make-the-sum.js)|Medium|
+3186|[Maximum Total Damage With Spell Casting](./solutions/3186-maximum-total-damage-with-spell-casting.js)|Medium|
3189|[Minimum Moves to Get a Peaceful Board](./solutions/3189-minimum-moves-to-get-a-peaceful-board.js)|Medium|
3191|[Minimum Operations to Make Binary Array Elements Equal to One I](./solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js)|Medium|
3195|[Find the Minimum Area to Cover All Ones I](./solutions/3195-find-the-minimum-area-to-cover-all-ones-i.js)|Medium|
diff --git a/solutions/3186-maximum-total-damage-with-spell-casting.js b/solutions/3186-maximum-total-damage-with-spell-casting.js
new file mode 100644
index 00000000..c392c9ec
--- /dev/null
+++ b/solutions/3186-maximum-total-damage-with-spell-casting.js
@@ -0,0 +1,55 @@
+/**
+ * 3186. Maximum Total Damage With Spell Casting
+ * https://leetcode.com/problems/maximum-total-damage-with-spell-casting/
+ * Difficulty: Medium
+ *
+ * A magician has various spells.
+ *
+ * You are given an array power, where each element represents the damage of a spell. Multiple
+ * spells can have the same damage value.
+ *
+ * It is a known fact that if a magician decides to cast a spell with a damage of power[i],
+ * they cannot cast any spell with a damage of power[i] - 2, power[i] - 1, power[i] + 1, or
+ * power[i] + 2.
+ *
+ * Each spell can be cast only once.
+ *
+ * Return the maximum possible total damage that a magician can cast.
+ */
+
+/**
+ * @param {number[]} power
+ * @return {number}
+ */
+var maximumTotalDamage = function(power) {
+ const frequency = new Map();
+ for (const p of power) {
+ frequency.set(p, (frequency.get(p) || 0) + 1);
+ }
+
+ const uniquePowers = Array.from(frequency.keys()).sort((a, b) => a - b);
+ const n = uniquePowers.length;
+
+ if (n === 0) return 0;
+ if (n === 1) return uniquePowers[0] * frequency.get(uniquePowers[0]);
+
+ const dp = new Array(n).fill(0);
+ dp[0] = uniquePowers[0] * frequency.get(uniquePowers[0]);
+
+ for (let i = 1; i < n; i++) {
+ const currentPower = uniquePowers[i];
+ const currentDamage = currentPower * frequency.get(currentPower);
+
+ let j = i - 1;
+ while (j >= 0 && uniquePowers[j] >= currentPower - 2) {
+ j--;
+ }
+
+ const withCurrent = currentDamage + (j >= 0 ? dp[j] : 0);
+ const withoutCurrent = dp[i - 1];
+
+ dp[i] = Math.max(withCurrent, withoutCurrent);
+ }
+
+ return dp[n - 1];
+};
From 466db0525d63b418cdb3da27196248467f9ae4e4 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 14 Oct 2025 18:26:58 -0500
Subject: [PATCH 983/994] Add solution #3349
---
README.md | 1 +
...jacent-increasing-subarrays-detection-i.js | 36 +++++++++++++++++++
2 files changed, 37 insertions(+)
create mode 100644 solutions/3349-adjacent-increasing-subarrays-detection-i.js
diff --git a/README.md b/README.md
index 269ce1cc..66912aeb 100644
--- a/README.md
+++ b/README.md
@@ -2712,6 +2712,7 @@
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|
3344|[Maximum Sized Array](./solutions/3344-maximum-sized-array.js)|Medium|
+3349|[Adjacent Increasing Subarrays Detection I](./solutions/3349-adjacent-increasing-subarrays-detection-i.js)|Easy|
3353|[Minimum Total Operations](./solutions/3353-minimum-total-operations.js)|Easy|
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|
diff --git a/solutions/3349-adjacent-increasing-subarrays-detection-i.js b/solutions/3349-adjacent-increasing-subarrays-detection-i.js
new file mode 100644
index 00000000..e2af9ede
--- /dev/null
+++ b/solutions/3349-adjacent-increasing-subarrays-detection-i.js
@@ -0,0 +1,36 @@
+/**
+ * 3349. Adjacent Increasing Subarrays Detection I
+ * https://leetcode.com/problems/adjacent-increasing-subarrays-detection-i/
+ * Difficulty: Easy
+ *
+ * Given an array nums of n integers and an integer k, determine whether there exist two
+ * adjacent subarrays of length k such that both subarrays are strictly increasing.
+ * Specifically, check if there are two subarrays starting at indices a and b (a < b),
+ * where:
+ * - Both subarrays nums[a..a + k - 1] and nums[b..b + k - 1] are strictly increasing.
+ * - The subarrays must be adjacent, meaning b = a + k.
+ *
+ * Return true if it is possible to find two such subarrays, and false otherwise.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {boolean}
+ */
+var hasIncreasingSubarrays = function(nums, k) {
+ for (let i = 0; i <= nums.length - 2 * k; i++) {
+ if (helper(i, k) && helper(i + k, k)) {
+ return true;
+ }
+ }
+
+ return false;
+
+ function helper(start, length) {
+ for (let i = start; i < start + length - 1; i++) {
+ if (nums[i] >= nums[i + 1]) return false;
+ }
+ return true;
+ }
+};
From 6a5e0660f7b4a4f6a7ce61c0a78e0123a5292c35 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 15 Oct 2025 18:21:45 -0500
Subject: [PATCH 984/994] Add solution #3539
---
README.md | 1 +
...m-of-array-product-of-magical-sequences.js | 101 ++++++++++++++++++
2 files changed, 102 insertions(+)
create mode 100644 solutions/3539-find-sum-of-array-product-of-magical-sequences.js
diff --git a/README.md b/README.md
index 66912aeb..9bd6d005 100644
--- a/README.md
+++ b/README.md
@@ -2772,6 +2772,7 @@
3516|[Find Closest Person](./solutions/3516-find-closest-person.js)|Easy|
3520|[Minimum Threshold for Inversion Pairs Count](./solutions/3520-minimum-threshold-for-inversion-pairs-count.js)|Medium|
3535|[Unit Conversion II](./solutions/3535-unit-conversion-ii.js)|Medium|
+3539|[Find Sum of Array Product of Magical Sequences](./solutions/3539-find-sum-of-array-product-of-magical-sequences.js)|Hard|
3541|[Find Most Frequent Vowel and Consonant](./solutions/3541-find-most-frequent-vowel-and-consonant.js)|Easy|
## License
diff --git a/solutions/3539-find-sum-of-array-product-of-magical-sequences.js b/solutions/3539-find-sum-of-array-product-of-magical-sequences.js
new file mode 100644
index 00000000..5e7fd749
--- /dev/null
+++ b/solutions/3539-find-sum-of-array-product-of-magical-sequences.js
@@ -0,0 +1,101 @@
+/**
+ * 3539. Find Sum of Array Product of Magical Sequences
+ * https://leetcode.com/problems/find-sum-of-array-product-of-magical-sequences/
+ * Difficulty: Hard
+ *
+ * You are given two integers, m and k, and an integer array nums.
+ *
+ * A sequence of integers seq is called magical if:
+ * - seq has a size of m.
+ * - 0 <= seq[i] < nums.length
+ * - The binary representation of 2seq[0] + 2seq[1] + ... + 2seq[m - 1] has k set bits.
+ *
+ * The array product of this sequence is defined as prod(seq) = (nums[seq[0]]
+ * * nums[seq[1]] * ... * nums[seq[m - 1]]).
+ *
+ * Return the sum of the array products for all valid magical sequences.
+ *
+ * Since the answer may be large, return it modulo 109 + 7.
+ *
+ * A set bit refers to a bit in the binary representation of a number that has a value of 1.
+ */
+
+/**
+ * @param {number} m
+ * @param {number} k
+ * @param {number[]} nums
+ * @return {number}
+ */
+var magicalSum = function(m, k, nums) {
+ const MOD = 1000000007n;
+ const map = new Map();
+ const n = nums.length;
+
+ function bitCount(num) {
+ let count = 0;
+ while (num > 0) {
+ count += num & 1;
+ num >>= 1;
+ }
+ return count;
+ }
+
+ function modPow(base, exp) {
+ let result = 1n;
+ base = BigInt(base) % MOD;
+ let e = BigInt(exp);
+ while (e > 0n) {
+ if (e & 1n) result = (result * base) % MOD;
+ base = (base * base) % MOD;
+ e >>= 1n;
+ }
+ return result;
+ }
+
+ const factorialCache = [1n];
+ function factorial(n) {
+ while (factorialCache.length <= n) {
+ factorialCache.push(
+ factorialCache[factorialCache.length - 1] * BigInt(factorialCache.length)
+ );
+ }
+ return factorialCache[n];
+ }
+
+ function comb(n, r) {
+ if (r > n || r < 0) return 0n;
+ if (r === 0 || r === n) return 1n;
+ return factorial(n) / (factorial(r) * factorial(n - r));
+ }
+
+ function dfs(remaining, oddNeeded, index, carry) {
+ if (remaining < 0 || oddNeeded < 0 || remaining + bitCount(carry) < oddNeeded) {
+ return 0n;
+ }
+ if (remaining === 0) {
+ return bitCount(carry) === oddNeeded ? 1n : 0n;
+ }
+ if (index >= n) {
+ return 0n;
+ }
+
+ const key = `${remaining},${oddNeeded},${index},${carry}`;
+ if (map.has(key)) return map.get(key);
+
+ let result = 0n;
+ for (let take = 0; take <= remaining; take++) {
+ const ways = (comb(remaining, take) * modPow(nums[index], take)) % MOD;
+ const newCarry = carry + take;
+ const contribution = dfs(
+ remaining - take, oddNeeded - (newCarry % 2),
+ index + 1, Math.floor(newCarry / 2),
+ );
+ result = (result + ways * contribution) % MOD;
+ }
+
+ map.set(key, result);
+ return result;
+ }
+
+ return Number(dfs(m, k, 0, 0));
+};
From fdca9a447d55db6f2f07a203a291dc71ce2f65dd Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 15 Oct 2025 18:38:37 -0500
Subject: [PATCH 985/994] Add solution #3350
---
README.md | 1 +
...acent-increasing-subarrays-detection-ii.js | 45 +++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 solutions/3350-adjacent-increasing-subarrays-detection-ii.js
diff --git a/README.md b/README.md
index 9bd6d005..181c8a20 100644
--- a/README.md
+++ b/README.md
@@ -2713,6 +2713,7 @@
3343|[Count Number of Balanced Permutations](./solutions/3343-count-number-of-balanced-permutations.js)|Hard|
3344|[Maximum Sized Array](./solutions/3344-maximum-sized-array.js)|Medium|
3349|[Adjacent Increasing Subarrays Detection I](./solutions/3349-adjacent-increasing-subarrays-detection-i.js)|Easy|
+3350|[Adjacent Increasing Subarrays Detection II](./solutions/3350-adjacent-increasing-subarrays-detection-ii.js)|Medium|
3353|[Minimum Total Operations](./solutions/3353-minimum-total-operations.js)|Easy|
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|
diff --git a/solutions/3350-adjacent-increasing-subarrays-detection-ii.js b/solutions/3350-adjacent-increasing-subarrays-detection-ii.js
new file mode 100644
index 00000000..7f103b4a
--- /dev/null
+++ b/solutions/3350-adjacent-increasing-subarrays-detection-ii.js
@@ -0,0 +1,45 @@
+/**
+ * 3350. Adjacent Increasing Subarrays Detection II
+ * https://leetcode.com/problems/adjacent-increasing-subarrays-detection-ii/
+ * Difficulty: Medium
+ *
+ * Given an array nums of n integers, your task is to find the maximum value of k for which
+ * there exist two adjacent subarrays of length k each, such that both subarrays are strictly
+ * increasing. Specifically, check if there are two subarrays of length k starting at indices
+ * a and b (a < b), where:
+ * - Both subarrays nums[a..a + k - 1] and nums[b..b + k - 1] are strictly increasing.
+ * - The subarrays must be adjacent, meaning b = a + k.
+ *
+ * Return the maximum possible value of k.
+ *
+ * A subarray is a contiguous non-empty sequence of elements within an array.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var maxIncreasingSubarrays = function(nums) {
+ const n = nums.length;
+ const lengths = new Array(n).fill(1);
+
+ for (let i = n - 2; i >= 0; i--) {
+ if (nums[i] < nums[i + 1]) {
+ lengths[i] = lengths[i + 1] + 1;
+ }
+ }
+
+ let result = 0;
+ for (let i = 0; i < n; i++) {
+ const currentLength = lengths[i];
+ result = Math.max(result, Math.floor(currentLength / 2));
+
+ const nextIndex = i + currentLength;
+ if (nextIndex < n) {
+ const minLength = Math.min(currentLength, lengths[nextIndex]);
+ result = Math.max(result, minLength);
+ }
+ }
+
+ return result;
+};
From 1990d22143a97cca24f7e0e02c070583e0574da2 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 22 Oct 2025 18:46:14 -0500
Subject: [PATCH 986/994] Add solution #3347
---
README.md | 1 +
...-element-after-performing-operations-ii.js | 62 +++++++++++++++++++
2 files changed, 63 insertions(+)
create mode 100644 solutions/3347-maximum-frequency-of-an-element-after-performing-operations-ii.js
diff --git a/README.md b/README.md
index 181c8a20..1e992959 100644
--- a/README.md
+++ b/README.md
@@ -2712,6 +2712,7 @@
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|
3344|[Maximum Sized Array](./solutions/3344-maximum-sized-array.js)|Medium|
+3347|[Maximum Frequency of an Element After Performing Operations II](./solutions/3347-maximum-frequency-of-an-element-after-performing-operations-ii.js)|Hard|
3349|[Adjacent Increasing Subarrays Detection I](./solutions/3349-adjacent-increasing-subarrays-detection-i.js)|Easy|
3350|[Adjacent Increasing Subarrays Detection II](./solutions/3350-adjacent-increasing-subarrays-detection-ii.js)|Medium|
3353|[Minimum Total Operations](./solutions/3353-minimum-total-operations.js)|Easy|
diff --git a/solutions/3347-maximum-frequency-of-an-element-after-performing-operations-ii.js b/solutions/3347-maximum-frequency-of-an-element-after-performing-operations-ii.js
new file mode 100644
index 00000000..fdbe1898
--- /dev/null
+++ b/solutions/3347-maximum-frequency-of-an-element-after-performing-operations-ii.js
@@ -0,0 +1,62 @@
+/**
+ * 3347. Maximum Frequency of an Element After Performing Operations II
+ * https://leetcode.com/problems/maximum-frequency-of-an-element-after-performing-operations-ii
+ * Difficulty: Hard
+ *
+ * You are given an integer array nums and two integers k and numOperations.
+ *
+ * You must perform an operation numOperations times on nums, where in each operation you:
+ * - Select an index i that was not selected in any previous operations.
+ * - Add an integer in the range [-k, k] to nums[i].
+ *
+ * Return the maximum possible frequency of any element in nums after performing the operations.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @param {number} numOperations
+ * @return {number}
+ */
+var maxFrequency = function(nums, k, numOperations) {
+ const n = nums.length;
+ nums.sort((a, b) => a - b);
+
+ const count = new Map();
+ for (const num of nums) {
+ count.set(num, (count.get(num) || 0) + 1);
+ }
+
+ let result = 0;
+ let left = 0;
+ let right = 0;
+ for (let mid = 0; mid < n; mid++) {
+ while (nums[mid] - nums[left] > k) {
+ left++;
+ }
+
+ while (right < n - 1 && nums[right + 1] - nums[mid] <= k) {
+ right++;
+ }
+
+ const total = right - left + 1;
+ result = Math.max(
+ result,
+ Math.min(total - count.get(nums[mid]), numOperations) + count.get(nums[mid])
+ );
+ }
+
+ left = 0;
+ for (right = 0; right < n; right++) {
+ let mid = Math.floor((nums[left] + nums[right]) / 2);
+
+ while (mid - nums[left] > k || nums[right] - mid > k) {
+ left++;
+ mid = Math.floor((nums[left] + nums[right]) / 2);
+ }
+
+ result = Math.max(result, Math.min(right - left + 1, numOperations));
+ }
+
+ return result;
+};
From 637f5210d0098476886267ed83f098f5d0ad05f7 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Wed, 22 Oct 2025 18:47:06 -0500
Subject: [PATCH 987/994] Add solution #3346
---
README.md | 1 +
...n-element-after-performing-operations-i.js | 62 +++++++++++++++++++
2 files changed, 63 insertions(+)
create mode 100644 solutions/3346-maximum-frequency-of-an-element-after-performing-operations-i.js
diff --git a/README.md b/README.md
index 1e992959..4e20e6ae 100644
--- a/README.md
+++ b/README.md
@@ -2712,6 +2712,7 @@
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|
3344|[Maximum Sized Array](./solutions/3344-maximum-sized-array.js)|Medium|
+3346|[Maximum Frequency of an Element After Performing Operations I](./solutions/3346-maximum-frequency-of-an-element-after-performing-operations-i.js)|Medium|
3347|[Maximum Frequency of an Element After Performing Operations II](./solutions/3347-maximum-frequency-of-an-element-after-performing-operations-ii.js)|Hard|
3349|[Adjacent Increasing Subarrays Detection I](./solutions/3349-adjacent-increasing-subarrays-detection-i.js)|Easy|
3350|[Adjacent Increasing Subarrays Detection II](./solutions/3350-adjacent-increasing-subarrays-detection-ii.js)|Medium|
diff --git a/solutions/3346-maximum-frequency-of-an-element-after-performing-operations-i.js b/solutions/3346-maximum-frequency-of-an-element-after-performing-operations-i.js
new file mode 100644
index 00000000..3bc5e43c
--- /dev/null
+++ b/solutions/3346-maximum-frequency-of-an-element-after-performing-operations-i.js
@@ -0,0 +1,62 @@
+/**
+ * 3346. Maximum Frequency of an Element After Performing Operations I
+ * https://leetcode.com/problems/maximum-frequency-of-an-element-after-performing-operations-i/
+ * Difficulty: Medium
+ *
+ * You are given an integer array nums and two integers k and numOperations.
+ *
+ * You must perform an operation numOperations times on nums, where in each operation you:
+ * - Select an index i that was not selected in any previous operations.
+ * - Add an integer in the range [-k, k] to nums[i].
+ *
+ * Return the maximum possible frequency of any element in nums after performing the operations.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @param {number} numOperations
+ * @return {number}
+ */
+var maxFrequency = function(nums, k, numOperations) {
+ const n = nums.length;
+ nums.sort((a, b) => a - b);
+
+ const count = new Map();
+ for (const num of nums) {
+ count.set(num, (count.get(num) || 0) + 1);
+ }
+
+ let result = 0;
+ let left = 0;
+ let right = 0;
+ for (let mid = 0; mid < n; mid++) {
+ while (nums[mid] - nums[left] > k) {
+ left++;
+ }
+
+ while (right < n - 1 && nums[right + 1] - nums[mid] <= k) {
+ right++;
+ }
+
+ const total = right - left + 1;
+ result = Math.max(
+ result,
+ Math.min(total - count.get(nums[mid]), numOperations) + count.get(nums[mid])
+ );
+ }
+
+ left = 0;
+ for (right = 0; right < n; right++) {
+ let mid = Math.floor((nums[left] + nums[right]) / 2);
+
+ while (mid - nums[left] > k || nums[right] - mid > k) {
+ left++;
+ mid = Math.floor((nums[left] + nums[right]) / 2);
+ }
+
+ result = Math.max(result, Math.min(right - left + 1, numOperations));
+ }
+
+ return result;
+};
From 64ef6176717e0b0928184a15079288ef7c380d22 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 27 Oct 2025 19:41:29 -0500
Subject: [PATCH 988/994] Add solution #3354
---
README.md | 1 +
.../3354-make-array-elements-equal-to-zero.js | 60 +++++++++++++++++++
2 files changed, 61 insertions(+)
create mode 100644 solutions/3354-make-array-elements-equal-to-zero.js
diff --git a/README.md b/README.md
index 4e20e6ae..191f1ab9 100644
--- a/README.md
+++ b/README.md
@@ -2717,6 +2717,7 @@
3349|[Adjacent Increasing Subarrays Detection I](./solutions/3349-adjacent-increasing-subarrays-detection-i.js)|Easy|
3350|[Adjacent Increasing Subarrays Detection II](./solutions/3350-adjacent-increasing-subarrays-detection-ii.js)|Medium|
3353|[Minimum Total Operations](./solutions/3353-minimum-total-operations.js)|Easy|
+3354|[Make Array Elements Equal to Zero](./solutions/3354-make-array-elements-equal-to-zero.js)|Easy|
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|
3359|[Find Sorted Submatrices With Maximum Element at Most K](./solutions/3359-find-sorted-submatrices-with-maximum-element-at-most-k.js)|Hard|
diff --git a/solutions/3354-make-array-elements-equal-to-zero.js b/solutions/3354-make-array-elements-equal-to-zero.js
new file mode 100644
index 00000000..865cff41
--- /dev/null
+++ b/solutions/3354-make-array-elements-equal-to-zero.js
@@ -0,0 +1,60 @@
+/**
+ * 3354. Make Array Elements Equal to Zero
+ * https://leetcode.com/problems/make-array-elements-equal-to-zero/
+ * Difficulty: Easy
+ *
+ * You are given an integer array nums.
+ *
+ * Start by selecting a starting position curr such that nums[curr] == 0, and choose a movement
+ * direction of either left or right.
+ *
+ * After that, you repeat the following process:
+ * - If curr is out of the range [0, n - 1], this process ends.
+ * - If nums[curr] == 0, move in the current direction by incrementing curr if you are moving
+ * right, or decrementing curr if you are moving left.
+ * - Else if nums[curr] > 0:
+ * - Decrement nums[curr] by 1.
+ * - Reverse your movement direction (left becomes right and vice versa).
+ * - Take a step in your new direction.
+ *
+ * A selection of the initial position curr and movement direction is considered valid if
+ * every element in nums becomes 0 by the end of the process.
+ *
+ * Return the number of possible valid selections.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var countValidSelections = function(nums) {
+ const n = nums.length;
+ let result = 0;
+
+ for (let i = 0; i < n; i++) {
+ if (nums[i] === 0) {
+ if (helper(i, -1)) result++;
+ if (helper(i, 1)) result++;
+ }
+ }
+
+ return result;
+
+ function helper(startIndex, direction) {
+ const arr = [...nums];
+ let current = startIndex;
+ let dir = direction;
+
+ while (current >= 0 && current < n) {
+ if (arr[current] === 0) {
+ current += dir;
+ } else {
+ arr[current]--;
+ dir = -dir;
+ current += dir;
+ }
+ }
+
+ return arr.every(val => val === 0);
+ }
+};
From eff5acd07ff80baba24737eeaf6523b0e52cdc5a Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Tue, 28 Oct 2025 22:08:58 -0500
Subject: [PATCH 989/994] Add solution #3370
---
README.md | 1 +
.../3370-smallest-number-with-all-set-bits.js | 20 +++++++++++++++++++
2 files changed, 21 insertions(+)
create mode 100644 solutions/3370-smallest-number-with-all-set-bits.js
diff --git a/README.md b/README.md
index 191f1ab9..7260425c 100644
--- a/README.md
+++ b/README.md
@@ -2724,6 +2724,7 @@
3362|[Zero Array Transformation III](./solutions/3362-zero-array-transformation-iii.js)|Medium|
3363|[Find the Maximum Number of Fruits Collected](./solutions/3363-find-the-maximum-number-of-fruits-collected.js)|Hard|
3369|[Design an Array Statistics Tracker](./solutions/3369-design-an-array-statistics-tracker.js)|Hard|
+3370|[Smallest Number With All Set Bits](./solutions/3370-smallest-number-with-all-set-bits.js)|Easy|
3372|[Maximize the Number of Target Nodes After Connecting Trees I](./solutions/3372-maximize-the-number-of-target-nodes-after-connecting-trees-i.js)|Medium|
3373|[Maximize the Number of Target Nodes After Connecting Trees II](./solutions/3373-maximize-the-number-of-target-nodes-after-connecting-trees-ii.js)|Hard|
3375|[Minimum Operations to Make Array Values Equal to K](./solutions/3375-minimum-operations-to-make-array-values-equal-to-k.js)|Easy|
diff --git a/solutions/3370-smallest-number-with-all-set-bits.js b/solutions/3370-smallest-number-with-all-set-bits.js
new file mode 100644
index 00000000..ea6b33ca
--- /dev/null
+++ b/solutions/3370-smallest-number-with-all-set-bits.js
@@ -0,0 +1,20 @@
+/**
+ * 3370. Smallest Number With All Set Bits
+ * https://leetcode.com/problems/smallest-number-with-all-set-bits/
+ * Difficulty: Easy
+ *
+ * You are given a positive number n.
+ *
+ * Return the smallest number x greater than or equal to n, such that the binary
+ * representation of x contains only set bits
+ */
+
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var smallestNumber = function(n) {
+ const bits = n.toString(2).length;
+ const result = (1 << bits) - 1;
+ return result >= n ? result : (1 << (bits + 1)) - 1;
+};
From fb56d5f16362166c08fb0502376576cedf9edf4e Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Thu, 30 Oct 2025 19:32:03 -0500
Subject: [PATCH 990/994] Add solution #3289
---
README.md | 1 +
...89-the-two-sneaky-numbers-of-digitville.js | 31 +++++++++++++++++++
2 files changed, 32 insertions(+)
create mode 100644 solutions/3289-the-two-sneaky-numbers-of-digitville.js
diff --git a/README.md b/README.md
index 7260425c..e25cb275 100644
--- a/README.md
+++ b/README.md
@@ -2695,6 +2695,7 @@
3272|[Find the Count of Good Integers](./solutions/3272-find-the-count-of-good-integers.js)|Hard|
3279|[Maximum Total Area Occupied by Pistons](./solutions/3279-maximum-total-area-occupied-by-pistons.js)|Hard|
3284|[Sum of Consecutive Subarrays](./solutions/3284-sum-of-consecutive-subarrays.js)|Medium|
+3289|[The Two Sneaky Numbers of Digitville](./solutions/3289-the-two-sneaky-numbers-of-digitville.js)|Easy|
3294|[Convert Doubly Linked List to Array II](./solutions/3294-convert-doubly-linked-list-to-array-ii.js)|Medium|
3299|[Sum of Consecutive Subsequences](./solutions/3299-sum-of-consecutive-subsequences.js)|Hard|
3304|[Find the K-th Character in String Game I](./solutions/3304-find-the-k-th-character-in-string-game-i.js)|Easy|
diff --git a/solutions/3289-the-two-sneaky-numbers-of-digitville.js b/solutions/3289-the-two-sneaky-numbers-of-digitville.js
new file mode 100644
index 00000000..00f41559
--- /dev/null
+++ b/solutions/3289-the-two-sneaky-numbers-of-digitville.js
@@ -0,0 +1,31 @@
+/**
+ * 3289. The Two Sneaky Numbers of Digitville
+ * https://leetcode.com/problems/the-two-sneaky-numbers-of-digitville/
+ * Difficulty: Easy
+ *
+ * In the town of Digitville, there was a list of numbers called nums containing integers
+ * from 0 to n - 1. Each number was supposed to appear exactly once in the list, however,
+ * two mischievous numbers sneaked in an additional time, making the list longer than usual.
+ *
+ * As the town detective, your task is to find these two sneaky numbers. Return an array of
+ * size two containing the two numbers (in any order), so peace can return to Digitville.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number[]}
+ */
+var getSneakyNumbers = function(nums) {
+ const set = new Set();
+ const result = [];
+
+ for (const n of nums) {
+ if (set.has(n)) {
+ result.push(n);
+ } else {
+ set.add(n);
+ }
+ }
+
+ return result;
+};
From e2e7a19bd9344471f4f0bc711bca758a36191132 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 31 Oct 2025 19:37:44 -0500
Subject: [PATCH 991/994] Add solution #3217
---
README.md | 1 +
...nodes-from-linked-list-present-in-array.js | 37 +++++++++++++++++++
2 files changed, 38 insertions(+)
create mode 100644 solutions/3217-delete-nodes-from-linked-list-present-in-array.js
diff --git a/README.md b/README.md
index e25cb275..a795cb17 100644
--- a/README.md
+++ b/README.md
@@ -2683,6 +2683,7 @@
3205|[Maximum Array Hopping Score I](./solutions/3205-maximum-array-hopping-score-i.js)|Medium|
3208|[Alternating Groups II](./solutions/3208-alternating-groups-ii.js)|Medium|
3215|[Count Triplets with Even XOR Set Bits II](./solutions/3215-count-triplets-with-even-xor-set-bits-ii.js)|Medium|
+3217|[Delete Nodes From Linked List Present in Array](./solutions/3217-delete-nodes-from-linked-list-present-in-array.js)|Medium|
3221|[Maximum Array Hopping Score II](./solutions/3221-maximum-array-hopping-score-ii.js)|Medium|
3223|[Minimum Length of String After Operations](./solutions/3223-minimum-length-of-string-after-operations.js)|Medium|
3227|[Vowels Game in a String](./solutions/3227-vowels-game-in-a-string.js)|Medium|
diff --git a/solutions/3217-delete-nodes-from-linked-list-present-in-array.js b/solutions/3217-delete-nodes-from-linked-list-present-in-array.js
new file mode 100644
index 00000000..62329285
--- /dev/null
+++ b/solutions/3217-delete-nodes-from-linked-list-present-in-array.js
@@ -0,0 +1,37 @@
+/**
+ * 3217. Delete Nodes From Linked List Present in Array
+ * https://leetcode.com/problems/delete-nodes-from-linked-list-present-in-array/
+ * Difficulty: Medium
+ *
+ * You are given an array of integers nums and the head of a linked list. Return the head
+ * of the modified linked list after removing all nodes from the linked list that have
+ * a value that exists in nums.
+ */
+
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val, next) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.next = (next===undefined ? null : next)
+ * }
+ */
+/**
+ * @param {number[]} nums
+ * @param {ListNode} head
+ * @return {ListNode}
+ */
+var modifiedList = function(nums, head) {
+ const set = new Set(nums);
+ const temp = new ListNode(0, head);
+ let current = temp;
+
+ while (current.next) {
+ if (set.has(current.next.val)) {
+ current.next = current.next.next;
+ } else {
+ current = current.next;
+ }
+ }
+
+ return temp.next;
+};
From 1c392a98170db7ea158c1596554f7c3338ecbd69 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Mon, 3 Nov 2025 22:48:41 -0600
Subject: [PATCH 992/994] Add solution #3318
---
README.md | 1 +
...18-find-x-sum-of-all-k-long-subarrays-i.js | 60 +++++++++++++++++++
2 files changed, 61 insertions(+)
create mode 100644 solutions/3318-find-x-sum-of-all-k-long-subarrays-i.js
diff --git a/README.md b/README.md
index a795cb17..ca4318ab 100644
--- a/README.md
+++ b/README.md
@@ -2703,6 +2703,7 @@
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|
3307|[Find the K-th Character in String Game II](./solutions/3307-find-the-k-th-character-in-string-game-ii.js)|Hard|
3313|[Find the Last Marked Nodes in Tree](./solutions/3313-find-the-last-marked-nodes-in-tree.js)|Hard|
+3318|[Find X-Sum of All K-Long Subarrays I](./solutions/3318-find-x-sum-of-all-k-long-subarrays-i.js)|Easy|
3323|[Minimize Connected Groups by Inserting Interval](./solutions/3323-minimize-connected-groups-by-inserting-interval.js)|Medium|
3329|[Count Substrings With K-Frequency Characters II](./solutions/3329-count-substrings-with-k-frequency-characters-ii.js)|Hard|
3330|[Find the Original Typed String I](./solutions/3330-find-the-original-typed-string-i.js)|Easy|
diff --git a/solutions/3318-find-x-sum-of-all-k-long-subarrays-i.js b/solutions/3318-find-x-sum-of-all-k-long-subarrays-i.js
new file mode 100644
index 00000000..2a030036
--- /dev/null
+++ b/solutions/3318-find-x-sum-of-all-k-long-subarrays-i.js
@@ -0,0 +1,60 @@
+/**
+ * 3318. Find X-Sum of All K-Long Subarrays I
+ * https://leetcode.com/problems/find-x-sum-of-all-k-long-subarrays-i/
+ * Difficulty: Easy
+ *
+ * You are given an array nums of n integers and two integers k and x.
+ *
+ * The x-sum of an array is calculated by the following procedure:
+ * - Count the occurrences of all elements in the array.
+ * - Keep only the occurrences of the top x most frequent elements. If two elements
+ * have the same number of occurrences, the element with the bigger value is
+ * considered more frequent.
+ * - Calculate the sum of the resulting array.
+ *
+ * Note that if an array has less than x distinct elements, its x-sum is the sum of the array.
+ *
+ Return an integer array answer of length n - k + 1 where answer[i] is the x-sum of the
+ subarray nums[i..i + k - 1].
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @param {number} x
+ * @return {number[]}
+ */
+var findXSum = function(nums, k, x) {
+ const n = nums.length;
+ const result = [];
+
+ for (let i = 0; i <= n - k; i++) {
+ const subarray = nums.slice(i, i + k);
+ result.push(helper(subarray));
+ }
+
+ return result;
+
+ function helper(subarray) {
+ const frequency = new Map();
+
+ for (const num of subarray) {
+ frequency.set(num, (frequency.get(num) || 0) + 1);
+ }
+
+ const elements = Array.from(frequency.entries());
+ elements.sort((a, b) => {
+ if (a[1] !== b[1]) return b[1] - a[1];
+ return b[0] - a[0];
+ });
+
+ const topX = elements.slice(0, x);
+ let sum = 0;
+
+ for (const [value, count] of topX) {
+ sum += value * count;
+ }
+
+ return sum;
+ }
+};
From 4261a9d1b0a0827a2ec3dab68f79b388efa95f10 Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 21 Nov 2025 23:02:32 -0600
Subject: [PATCH 993/994] Add solution #3190
---
README.md | 1 +
...to-make-all-elements-divisible-by-three.js | 21 +++++++++++++++++++
2 files changed, 22 insertions(+)
create mode 100644 solutions/3190-find-minimum-operations-to-make-all-elements-divisible-by-three.js
diff --git a/README.md b/README.md
index ca4318ab..84a04ff2 100644
--- a/README.md
+++ b/README.md
@@ -2674,6 +2674,7 @@
3183|[The Number of Ways to Make the Sum](./solutions/3183-the-number-of-ways-to-make-the-sum.js)|Medium|
3186|[Maximum Total Damage With Spell Casting](./solutions/3186-maximum-total-damage-with-spell-casting.js)|Medium|
3189|[Minimum Moves to Get a Peaceful Board](./solutions/3189-minimum-moves-to-get-a-peaceful-board.js)|Medium|
+3190|[Find Minimum Operations to Make All Elements Divisible by Three](./solutions/3190-find-minimum-operations-to-make-all-elements-divisible-by-three.js)|Easy|
3191|[Minimum Operations to Make Binary Array Elements Equal to One I](./solutions/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-i.js)|Medium|
3195|[Find the Minimum Area to Cover All Ones I](./solutions/3195-find-the-minimum-area-to-cover-all-ones-i.js)|Medium|
3197|[Find the Minimum Area to Cover All Ones II](./solutions/3197-find-the-minimum-area-to-cover-all-ones-ii.js)|Hard|
diff --git a/solutions/3190-find-minimum-operations-to-make-all-elements-divisible-by-three.js b/solutions/3190-find-minimum-operations-to-make-all-elements-divisible-by-three.js
new file mode 100644
index 00000000..24effff2
--- /dev/null
+++ b/solutions/3190-find-minimum-operations-to-make-all-elements-divisible-by-three.js
@@ -0,0 +1,21 @@
+/**
+ * 3190. Find Minimum Operations to Make All Elements Divisible by Three
+ * https://leetcode.com/problems/find-minimum-operations-to-make-all-elements-divisible-by-three/
+ * Difficulty: Easy
+ *
+ * You are given an integer array nums. In one operation, you can add or subtract 1 from any
+ * element of nums.
+ *
+ * Return the minimum number of operations to make all elements of nums divisible by 3.
+ */
+
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var minimumOperations = function(nums) {
+ return nums.reduce((operations, num) => {
+ const remainder = num % 3;
+ return operations + Math.min(remainder, 3 - remainder);
+ }, 0);
+};
From 0fa289360baf48d556f552c98b95eba22eaef14c Mon Sep 17 00:00:00 2001
From: Josh Crozier <5490537+JoshCrozier@users.noreply.github.com>
Date: Fri, 28 Nov 2025 20:08:47 -0600
Subject: [PATCH 994/994] Add solution #3512
---
README.md | 1 +
...ations-to-make-array-sum-divisible-by-k.js | 21 +++++++++++++++++++
2 files changed, 22 insertions(+)
create mode 100644 solutions/3512-minimum-operations-to-make-array-sum-divisible-by-k.js
diff --git a/README.md b/README.md
index 84a04ff2..baec6d02 100644
--- a/README.md
+++ b/README.md
@@ -2778,6 +2778,7 @@
3506|[Find Time Required to Eliminate Bacterial Strains](./solutions/3506-find-time-required-to-eliminate-bacterial-strains.js)|Hard|
3508|[Implement Router](./solutions/3508-implement-router.js)|Medium|
3511|[Make a Positive Array](./solutions/3511-make-a-positive-array.js)|Medium|
+3512|[Minimum Operations to Make Array Sum Divisible by K](./solutions/3512-minimum-operations-to-make-array-sum-divisible-by-k.js)|Easy|
3516|[Find Closest Person](./solutions/3516-find-closest-person.js)|Easy|
3520|[Minimum Threshold for Inversion Pairs Count](./solutions/3520-minimum-threshold-for-inversion-pairs-count.js)|Medium|
3535|[Unit Conversion II](./solutions/3535-unit-conversion-ii.js)|Medium|
diff --git a/solutions/3512-minimum-operations-to-make-array-sum-divisible-by-k.js b/solutions/3512-minimum-operations-to-make-array-sum-divisible-by-k.js
new file mode 100644
index 00000000..772bb4dc
--- /dev/null
+++ b/solutions/3512-minimum-operations-to-make-array-sum-divisible-by-k.js
@@ -0,0 +1,21 @@
+/**
+ * 3512. Minimum Operations to Make Array Sum Divisible by K
+ * https://leetcode.com/problems/minimum-operations-to-make-array-sum-divisible-by-k/
+ * Difficulty: Easy
+ *
+ * You are given an integer array nums and an integer k. You can perform the following
+ * operation any number of times:
+ * - Select an index i and replace nums[i] with nums[i] - 1.
+ *
+ * Return the minimum number of operations required to make the sum of the array
+ * divisible by k.
+ */
+
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number}
+ */
+var minOperations = function(nums, k) {
+ return nums.reduce((sum, n) => sum + n, 0) % k;
+};