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 01/19] 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 3fb04db..3ee503c 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 0000000..ee45ca4 --- /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 02/19] 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 3ee503c..6f30346 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 0000000..39c28f7 --- /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 03/19] 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 6f30346..115378b 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 0000000..21b9bc1 --- /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 04/19] 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 115378b..dc05171 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 0000000..5f67f5c --- /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 05/19] 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 dc05171..f20841a 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 0000000..3ecf506 --- /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 06/19] 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 f20841a..88dcffe 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 0000000..4b0b6cd --- /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 07/19] 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 88dcffe..67d1a52 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 0000000..bde90e2 --- /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 08/19] 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 67d1a52..09bbbbc 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 0000000..1fa9805 --- /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 09/19] 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 09bbbbc..25a0901 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 0000000..f239c80 --- /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 10/19] 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 25a0901..81c5cb7 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 0000000..d6f4d85 --- /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 11/19] 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 81c5cb7..576739b 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 0000000..789a5ff --- /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 12/19] 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 576739b..6ea9664 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 0000000..64f29a9 --- /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 13/19] 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 6ea9664..33118ca 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 0000000..2cdcce2 --- /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 14/19] 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 33118ca..92d4f64 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 0000000..586dcda --- /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 15/19] 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 92d4f64..39ad8d0 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 0000000..7e26720 --- /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 16/19] 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 39ad8d0..a2027bd 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 0000000..8dc163e --- /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 17/19] 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 a2027bd..68703de 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 0000000..0af443f --- /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 18/19] 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 68703de..e38866e 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 0000000..ff401c3 --- /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 19/19] 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 e38866e..6c3c231 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 0000000..4645204 --- /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(' '); +};