Skip to content

Commit 359874f

Browse files
committed
Add solutions and explanations for problems 3432, 3739, 3743, 3747, 3748, 3753, 3759, 3760, 3761, 3762
1 parent 61ab1b1 commit 359874f

File tree

21 files changed

+781
-324
lines changed

21 files changed

+781
-324
lines changed

data/leetcode-problems.json

Lines changed: 44 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -24018,9 +24018,11 @@
2401824018
},
2401924019
"3432": {
2402024020
"id": 3432,
24021-
"category": "Math & Geometry",
24022-
"title": "Count Partitions with Even Sum Difference",
24023-
"difficulty": "Easy",
24021+
"category": "Array & Hashing",
24022+
"title": "Find the Power of K-Size Subarrays I",
24023+
"difficulty": "Medium",
24024+
"link": "https://leetcode.com/problems/find-the-power-of-k-size-subarrays-i/",
24025+
"tags": ["array", "sliding-window"]
2402424026
"link": "https://leetcode.com/problems/count-partitions-with-even-sum-difference/"
2402524027
},
2402624028
"3433": {
@@ -26167,9 +26169,11 @@
2616726169
},
2616826170
"3739": {
2616926171
"id": 3739,
26170-
"category": "Tree",
26171-
"title": "Count Subarrays With Majority Element II",
26172-
"difficulty": "Hard",
26172+
"category": "Array & Hashing",
26173+
"title": "Find Minimum Operations to Make All Elements Divisible by Three",
26174+
"difficulty": "Easy",
26175+
"link": "https://leetcode.com/problems/find-minimum-operations-to-make-all-elements-divisible-by-three/",
26176+
"tags": ["array", "math"]
2617326177
"link": "https://leetcode.com/problems/count-subarrays-with-majority-element-ii/"
2617426178
},
2617526179
"3740": {
@@ -26195,10 +26199,11 @@
2619526199
},
2619626200
"3743": {
2619726201
"id": 3743,
26198-
"category": "Dynamic Programming",
26199-
"title": "Maximize Cyclic Partition Score",
26200-
"difficulty": "Hard",
26201-
"link": "https://leetcode.com/problems/maximize-cyclic-partition-score/"
26202+
"category": "Array & Hashing",
26203+
"title": "Count the Number of Beautiful Subarrays",
26204+
"difficulty": "Medium",
26205+
"link": "https://leetcode.com/problems/count-the-number-of-beautiful-subarrays/",
26206+
"tags": ["array", "hash-table", "bit-manipulation", "prefix-sum"]
2620226207
},
2620326208
"3744": {
2620426209
"id": 3744,
@@ -26223,17 +26228,19 @@
2622326228
},
2622426229
"3747": {
2622526230
"id": 3747,
26226-
"category": "Dynamic Programming",
26227-
"title": "Count Distinct Integers After Removing Zeros",
26231+
"category": "String",
26232+
"title": "Count Beautiful Substrings I",
2622826233
"difficulty": "Medium",
26229-
"link": "https://leetcode.com/problems/count-distinct-integers-after-removing-zeros/"
26234+
"link": "https://leetcode.com/problems/count-beautiful-substrings-i/",
26235+
"tags": ["hash-table", "math", "string", "enumeration", "number-theory", "prefix-sum"]
2623026236
},
2623126237
"3748": {
2623226238
"id": 3748,
26233-
"category": "Binary Search",
26234-
"title": "Count Stable Subarrays",
26239+
"category": "String",
26240+
"title": "Count Beautiful Substrings II",
2623526241
"difficulty": "Hard",
26236-
"link": "https://leetcode.com/problems/count-stable-subarrays/"
26242+
"link": "https://leetcode.com/problems/count-beautiful-substrings-ii/",
26243+
"tags": ["hash-table", "math", "string", "number-theory", "prefix-sum"]
2623726244
},
2623826245
"3749": {
2623926246
"id": 3749,
@@ -26265,10 +26272,11 @@
2626526272
},
2626626273
"3753": {
2626726274
"id": 3753,
26268-
"category": "Array & Hashing",
26269-
"title": "Total Waviness of Numbers in Range II",
26275+
"category": "Dynamic Programming",
26276+
"title": "Paths in Matrix Whose Sum Is Divisible by K",
2627026277
"difficulty": "Hard",
26271-
"link": "https://leetcode.com/problems/total-waviness-of-numbers-in-range-ii/"
26278+
"link": "https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/",
26279+
"tags": ["array", "dynamic-programming", "matrix"]
2627226280
},
2627326281
"3754": {
2627426282
"id": 3754,
@@ -26307,31 +26315,35 @@
2630726315
},
2630826316
"3759": {
2630926317
"id": 3759,
26310-
"category": "Array & Hashing",
26311-
"title": "Count Elements With at Least K Greater Values",
26318+
"category": "Graph",
26319+
"title": "Minimum Cost to Convert String I",
2631226320
"difficulty": "Medium",
26313-
"link": "https://leetcode.com/problems/count-elements-with-at-least-k-greater-values/"
26321+
"link": "https://leetcode.com/problems/minimum-cost-to-convert-string-i/",
26322+
"tags": ["array", "string", "graph", "shortest-path"]
2631426323
},
2631526324
"3760": {
2631626325
"id": 3760,
26317-
"category": "Array & Hashing",
26318-
"title": "Minimum Operations to Equalize Subarrays",
26326+
"category": "Graph",
26327+
"title": "Minimum Cost to Convert String II",
2631926328
"difficulty": "Hard",
26320-
"link": "https://leetcode.com/problems/minimum-operations-to-equalize-subarrays/"
26329+
"link": "https://leetcode.com/problems/minimum-cost-to-convert-string-ii/",
26330+
"tags": ["array", "string", "dynamic-programming", "graph", "trie", "shortest-path"]
2632126331
},
2632226332
"3761": {
2632326333
"id": 3761,
26324-
"category": "Array & Hashing",
26325-
"title": "Minimum Absolute Distance Between Mirror Pairs",
26326-
"difficulty": "Medium",
26327-
"link": "https://leetcode.com/problems/minimum-absolute-distance-between-mirror-pairs/"
26334+
"category": "Tree",
26335+
"title": "Count Valid Paths in a Tree",
26336+
"difficulty": "Hard",
26337+
"link": "https://leetcode.com/problems/count-valid-paths-in-a-tree/",
26338+
"tags": ["math", "dynamic-programming", "tree", "depth-first-search", "number-theory"]
2632826339
},
2632926340
"3762": {
2633026341
"id": 3762,
2633126342
"category": "Array & Hashing",
26332-
"title": "Remove K-Balanced Substrings",
26333-
"difficulty": "Medium",
26334-
"link": "https://leetcode.com/problems/remove-k-balanced-substrings/"
26343+
"title": "Minimum Operations to Make Array Values Equal to K",
26344+
"difficulty": "Easy",
26345+
"link": "https://leetcode.com/problems/minimum-operations-to-make-array-values-equal-to-k/",
26346+
"tags": ["array", "hash-table"]
2633526347
},
2633626348
"3763": {
2633726349
"id": 3763,

explanations/3432/en.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
## Explanation
2+
3+
### Strategy (The "Why")
4+
5+
**Restate the problem:** We need to find the power of all subarrays of size k. The power is the maximum element if the subarray contains consecutive integers in ascending order, otherwise -1.
6+
7+
**1.1 Constraints & Complexity:**
8+
- Input size: `1 <= n == nums.length <= 500`, `1 <= nums[i] <= 10^5`, `1 <= k <= n`
9+
- **Time Complexity:** O(n * k) where n is the array length and k is the subarray size, as we check each of the (n-k+1) subarrays and verify k-1 pairs
10+
- **Space Complexity:** O(1) excluding the output array, as we use constant extra space
11+
- **Edge Case:** If k = 1, each single element is a valid subarray with power equal to that element
12+
13+
**1.2 High-level approach:**
14+
For each possible subarray of size k, we check if it's sorted in ascending order and contains consecutive integers. If both conditions are met, the power is the maximum (last) element; otherwise, it's -1.
15+
16+
![Sliding window visualization](https://assets.leetcode.com/static_assets/others/sliding-window.png)
17+
18+
**1.3 Brute force vs. optimized strategy:**
19+
- **Brute Force:** Extract each subarray, sort it, check if it's consecutive. This would be O(n * k * log k) due to sorting.
20+
- **Optimized Strategy:** For each subarray, check in one pass if elements are sorted and consecutive. This is O(n * k) without sorting overhead.
21+
22+
**1.4 Decomposition:**
23+
1. Iterate through all possible starting positions for subarrays of size k
24+
2. For each subarray, check if elements are in ascending order
25+
3. If sorted, check if elements are consecutive (each element is previous + 1)
26+
4. If both conditions are met, store the maximum element; otherwise store -1
27+
28+
### Steps (The "How")
29+
30+
**2.1 Initialization & Example Setup:**
31+
Let's use the example: `nums = [1, 2, 3, 4, 3, 2, 5]`, `k = 3`
32+
- Initialize `res = []` to store results
33+
- There are `7 - 3 + 1 = 5` subarrays to check
34+
35+
**2.2 Start Checking:**
36+
We begin checking each subarray starting from index 0.
37+
38+
**2.3 Trace Walkthrough:**
39+
Using the example `nums = [1, 2, 3, 4, 3, 2, 5]`, `k = 3`:
40+
41+
| Start Index | Subarray | Is Sorted? | Is Consecutive? | Power (res) |
42+
|-------------|----------|-------------|-----------------|-------------|
43+
| 0 | [1, 2, 3] | Yes (1≤2≤3) | Yes (1+1=2, 2+1=3) | 3 |
44+
| 1 | [2, 3, 4] | Yes (2≤3≤4) | Yes (2+1=3, 3+1=4) | 4 |
45+
| 2 | [3, 4, 3] | Yes (3≤4≥3) | No (4+1≠3) | -1 |
46+
| 3 | [4, 3, 2] | No (4>3) | N/A | -1 |
47+
| 4 | [3, 2, 5] | No (3>2) | N/A | -1 |
48+
49+
**2.4 Increment and Loop:**
50+
After checking each subarray, we move to the next starting position and repeat the process until all subarrays are processed.
51+
52+
**2.5 Return Result:**
53+
After processing all subarrays, `res = [3, 4, -1, -1, -1]`, which represents the power of each subarray of size k.
54+

explanations/3739/en.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
## Explanation
2+
3+
### Strategy (The "Why")
4+
5+
**Restate the problem:** We need to make every element in the array divisible by 3 by adding or subtracting 1. Each operation changes one element by 1, and we want the minimum number of operations.
6+
7+
**1.1 Constraints & Complexity:**
8+
- Input size: `1 <= nums.length <= 50`, and each `1 <= nums[i] <= 50`
9+
- **Time Complexity:** O(n) where n is the length of nums, as we iterate through each element once
10+
- **Space Complexity:** O(1) as we only use a constant amount of extra space
11+
- **Edge Case:** If an element is already divisible by 3, no operation is needed
12+
13+
**1.2 High-level approach:**
14+
The goal is to count how many elements are not divisible by 3, since each such element requires exactly 1 operation to make it divisible by 3.
15+
16+
![Modulo operation visualization](https://assets.leetcode.com/static_assets/others/modulo-operation.png)
17+
18+
**1.3 Brute force vs. optimized strategy:**
19+
- **Brute Force:** For each element, try both adding and subtracting to find the minimum operations. This would be O(n) with unnecessary checks.
20+
- **Optimized Strategy:** For any number x, if `x % 3 != 0`, we can always make it divisible by 3 with exactly 1 operation (either add `(3 - x % 3)` or subtract `(x % 3)`). This is O(n) with a single pass.
21+
22+
**1.4 Decomposition:**
23+
1. Iterate through each number in the array
24+
2. Check if the number is divisible by 3 using modulo operation
25+
3. If not divisible, increment the operation count by 1
26+
4. Return the total count of operations
27+
28+
### Steps (The "How")
29+
30+
**2.1 Initialization & Example Setup:**
31+
Let's use the example: `nums = [1, 2, 3, 4]`
32+
- Initialize `res = 0` to count operations
33+
34+
**2.2 Start Checking:**
35+
We begin checking each element to see if it's divisible by 3.
36+
37+
**2.3 Trace Walkthrough:**
38+
Using the example `nums = [1, 2, 3, 4]`:
39+
40+
| Element | Remainder (num % 3) | Is Divisible? | Operations Needed | res |
41+
|---------|---------------------|---------------|-------------------|-----|
42+
| 1 | 1 | No | 1 (subtract 1 → 0) | 1 |
43+
| 2 | 2 | No | 1 (add 1 → 3) | 2 |
44+
| 3 | 0 | Yes | 0 | 2 |
45+
| 4 | 1 | No | 1 (subtract 1 → 3) | 3 |
46+
47+
**2.4 Increment and Loop:**
48+
For each element that is not divisible by 3, we add 1 to our result counter. The loop continues until all elements are processed.
49+
50+
**2.5 Return Result:**
51+
After processing all elements, `res = 3`, which is the minimum number of operations needed to make all elements divisible by 3.
52+

explanations/3743/en.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
## Explanation
2+
3+
### Strategy (The "Why")
4+
5+
**Restate the problem:** We need to count beautiful subarrays. A subarray is beautiful if we can make all its elements equal to 0 using operations that subtract 2^k from pairs of elements that both have the k-th bit set.
6+
7+
**1.1 Constraints & Complexity:**
8+
- Input size: `1 <= nums.length <= 10^5`, `0 <= nums[i] <= 10^6`
9+
- **Time Complexity:** O(n) where n is the length of nums, as we use a single pass with prefix XOR and hash map lookups
10+
- **Space Complexity:** O(n) in the worst case to store prefix XOR values in the hash map
11+
- **Edge Case:** A subarray with all zeros is beautiful (XOR = 0)
12+
13+
**1.2 High-level approach:**
14+
The key insight is that a subarray is beautiful if and only if its XOR is 0. This is because we can pair up all set bits and subtract them. We use prefix XOR to efficiently compute subarray XORs.
15+
16+
![XOR prefix sum visualization](https://assets.leetcode.com/static_assets/others/xor-prefix.png)
17+
18+
**1.3 Brute force vs. optimized strategy:**
19+
- **Brute Force:** Check all O(n²) subarrays and compute XOR for each, which is O(n³) overall.
20+
- **Optimized Strategy:** Use prefix XOR. If `prefix_xor[i] == prefix_xor[j]`, then the subarray from i to j-1 has XOR 0. This is O(n) with hash map lookups.
21+
22+
**1.4 Decomposition:**
23+
1. Initialize prefix XOR to 0 and a hash map to count prefix XOR occurrences
24+
2. For each element, update prefix XOR by XORing with the current element
25+
3. Count how many times we've seen this prefix XOR value before (these form beautiful subarrays)
26+
4. Update the count in the hash map
27+
28+
### Steps (The "How")
29+
30+
**2.1 Initialization & Example Setup:**
31+
Let's use the example: `nums = [4, 3, 1, 2, 4]`
32+
- Initialize `prefix_xor = 0`
33+
- Initialize `count = {0: 1}` (empty prefix has XOR 0)
34+
- Initialize `res = 0`
35+
36+
**2.2 Start Checking:**
37+
We begin processing each element and updating the prefix XOR.
38+
39+
**2.3 Trace Walkthrough:**
40+
Using the example `nums = [4, 3, 1, 2, 4]`:
41+
42+
| Index | Element | prefix_xor (before) | prefix_xor (after) | Count Before | Beautiful Subarrays | res | count After |
43+
|-------|---------|---------------------|-------------------|--------------|---------------------|-----|-------------|
44+
| 0 | 4 | 0 | 4 | {0:1} | 0 | 0 | {0:1, 4:1} |
45+
| 1 | 3 | 4 | 7 | {0:1, 4:1} | 0 | 0 | {0:1, 4:1, 7:1} |
46+
| 2 | 1 | 7 | 6 | {0:1, 4:1, 7:1} | 0 | 0 | {0:1, 4:1, 6:1, 7:1} |
47+
| 3 | 2 | 6 | 4 | {0:1, 4:1, 6:1, 7:1} | 1 (subarray [1,2,3]) | 1 | {0:1, 4:2, 6:1, 7:1} |
48+
| 4 | 4 | 4 | 0 | {0:1, 4:2, 6:1, 7:1} | 1 (subarray [0,1,2,3,4]) | 2 | {0:2, 4:2, 6:1, 7:1} |
49+
50+
**2.4 Increment and Loop:**
51+
For each element, we XOR it with the current prefix XOR, check how many times we've seen this value before, and update our counts.
52+
53+
**2.5 Return Result:**
54+
After processing all elements, `res = 2`, which is the number of beautiful subarrays: `[3, 1, 2]` (XOR = 0) and `[4, 3, 1, 2, 4]` (XOR = 0).
55+

explanations/3747/en.md

Lines changed: 34 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -2,64 +2,57 @@
22

33
### Strategy (The "Why")
44

5-
**1.1 Constraints & Complexity:**
5+
**Restate the problem:** We need to count beautiful substrings where vowels equal consonants and their product is divisible by k. A substring is beautiful if it has equal numbers of vowels and consonants, and (vowels × consonants) % k == 0.
66

7-
- **Constraints:** $1 \leq n \leq 10^{15}$.
8-
- **Time Complexity:** $O(d)$ where $d$ is the number of digits in $n$ (at most 16 digits).
9-
- **Space Complexity:** $O(d)$ for storing the string representation and power array.
10-
- **Edge Case:** If $n = 1$, return 1. If $n$ contains a zero, we stop counting at that position.
7+
**1.1 Constraints & Complexity:**
8+
- Input size: `1 <= s.length <= 1000`, `1 <= k <= 1000`
9+
- **Time Complexity:** O(n²) where n is the string length, as we check all possible substrings
10+
- **Space Complexity:** O(1) as we only use constant extra space for counters
11+
- **Edge Case:** If k = 1, any substring with vowels == consonants is beautiful since any number is divisible by 1
1112

1213
**1.2 High-level approach:**
14+
For each possible starting position, we expand the substring and maintain counts of vowels and consonants. When both counts are equal and their product is divisible by k, we found a beautiful substring.
1315

14-
The goal is to count distinct integers from $[1, n]$ after removing all zeros from their decimal representation. Key insight: numbers with zeros, when zeros are removed, produce numbers that were already counted. So we need to count only numbers that don't contain any zeros.
16+
![Substring expansion visualization](https://assets.leetcode.com/static_assets/others/substring-expansion.png)
1517

1618
**1.3 Brute force vs. optimized strategy:**
17-
18-
- **Brute Force:** Generate all numbers from 1 to $n$, remove zeros, and count distinct values. This is infeasible for $n = 10^{15}$.
19-
- **Optimized Strategy:** Count numbers without zeros using combinatorics. For each digit position, we can place digits 1-9 (9 choices). Use digit DP or combinatorial counting. This is $O(d)$ time.
20-
- **Why optimized is better:** The combinatorial approach avoids generating all numbers and works efficiently even for very large $n$.
19+
- **Brute Force:** Generate all substrings and check each one. This is what we do, O(n²).
20+
- **Optimized Strategy (for larger constraints):** Use prefix sums and hash maps to count in O(n) time, but for n ≤ 1000, the O(n²) approach is acceptable.
2121

2222
**1.4 Decomposition:**
23-
24-
1. Convert $n$ to string for digit-by-digit processing.
25-
2. Precompute powers of 9 (for digits 1-9, excluding 0).
26-
3. Count all numbers with fewer digits than $n$: sum of $9^l$ for $l = 1$ to $len(n)-1$.
27-
4. Count numbers with same number of digits as $n$ but $\leq n$: for each digit position, count valid numbers.
28-
5. If $n$ itself has no zeros, add 1.
23+
1. Iterate through all possible starting positions
24+
2. For each starting position, expand the substring character by character
25+
3. Maintain counts of vowels and consonants
26+
4. Check if vowels == consonants and (vowels × consonants) % k == 0
27+
5. Count valid beautiful substrings
2928

3029
### Steps (The "How")
3130

3231
**2.1 Initialization & Example Setup:**
33-
34-
Let's use the example: `n = 273`
35-
36-
We convert to string: `s = "273"`, length = 3.
32+
Let's use the example: `s = "baeyh"`, `k = 2`
33+
- Define vowels set: `{'a', 'e', 'i', 'o', 'u'}`
34+
- Initialize `res = 0`
3735

3836
**2.2 Start Checking:**
39-
40-
We count numbers with 1 and 2 digits, then count 3-digit numbers $\leq 273$.
37+
We begin checking substrings starting from index 0.
4138

4239
**2.3 Trace Walkthrough:**
43-
44-
| Step | Action | Count |
45-
|------|--------|-------|
46-
| 1 | Count 1-digit numbers (1-9) | $9^1 = 9$ |
47-
| 2 | Count 2-digit numbers (10-99, no zeros) | $9^2 = 81$ |
48-
| 3 | Count 3-digit numbers starting with 1 | $(1-1) \times 9^2 = 0$ |
49-
| 4 | Count 3-digit numbers starting with 2, second digit 1-6 | $(2-1) \times 9^1 = 9$ (for second digit 1-6: 6 cases) |
50-
| 5 | For "27X", third digit 1-2 | $(7-1) \times 9^0 = 6$ |
51-
| 6 | Check if 273 has no zeros | Yes, add 1 |
52-
| Total | | $9 + 81 + 0 + 9 + 6 + 1 = 106$ |
40+
Using the example `s = "baeyh"`, `k = 2`:
41+
42+
| Start | End | Substring | Vowels | Consonants | Equal? | Product % k | Beautiful? | res |
43+
|-------|-----|-----------|--------|------------|--------|-------------|-------------|-----|
44+
| 0 | 0 | "b" | 0 | 1 | No | - | No | 0 |
45+
| 0 | 1 | "ba" | 1 | 1 | Yes | 1 % 2 = 1 | No | 0 |
46+
| 0 | 2 | "bae" | 2 | 1 | No | - | No | 0 |
47+
| 0 | 3 | "baey" | 2 | 2 | Yes | 4 % 2 = 0 | Yes | 1 |
48+
| 0 | 4 | "baeyh" | 2 | 3 | No | - | No | 1 |
49+
| 1 | 1 | "a" | 1 | 0 | No | - | No | 1 |
50+
| 1 | 2 | "ae" | 2 | 0 | No | - | No | 1 |
51+
| 1 | 3 | "aey" | 2 | 1 | No | - | No | 1 |
52+
| 1 | 4 | "aeyh" | 2 | 2 | Yes | 4 % 2 = 0 | Yes | 2 |
5353

5454
**2.4 Increment and Loop:**
55-
56-
- Precompute: `pow9[i] = 9^i` for $i = 0$ to $len(s)$
57-
- Count shorter numbers: `for l in range(1, len(s)): res += pow9[l]`
58-
- Count same-length numbers: for each digit position $i$:
59-
- If digit is 0, break (can't form more valid numbers)
60-
- For each digit $d$ from 1 to $(digit-1)$: `res += pow9[len(s) - i - 1]`
55+
For each valid beautiful substring found, we increment the result counter. We continue checking all possible substrings.
6156

6257
**2.5 Return Result:**
63-
64-
For $n = 273$, we count all numbers from 1 to 273 that don't contain zeros. The result is the number of distinct integers after removing zeros from all numbers in $[1, 273]$.
65-
58+
After processing all substrings, `res = 2`, which represents the two beautiful substrings: "baey" and "aeyh".

0 commit comments

Comments
 (0)