Skip to content

Commit 4dfee7b

Browse files
Merge pull request #112 from romankurnovskii/problems-3583-3772-3771-3770-3769-3768-3767-3766-3765-3764-3762-3761-3760
Add solutions and explanations for problems 3583, 3772, 3771, 3770, 3766, 3768, 3767, 3765, 3761, 3760
2 parents fec1102 + cb2768e commit 4dfee7b

File tree

20 files changed

+493
-389
lines changed

20 files changed

+493
-389
lines changed

books/All.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8922,6 +8922,68 @@ class Solution:
89228922
return res
89238923
```
89248924

8925+
## 1431. Kids With the Greatest Number of Candies [Easy]
8926+
https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
8927+
8928+
### Explanation
8929+
8930+
## 1431. Kids With the Greatest Number of Candies [Easy]
8931+
8932+
https://leetcode.com/problems/kids-with-the-greatest-number-of-candies
8933+
8934+
## Description
8935+
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `i`th kid has, and an integer `extraCandies`, denoting the number of extra candies that you have.
8936+
8937+
Return a boolean array `result` of length `n`, where `result[i]` is `true` if, after giving the `i`th kid all the `extraCandies`, they will have the greatest number of candies among all the kids, or false otherwise.
8938+
8939+
Note that multiple kids can have the greatest number of candies.
8940+
8941+
**Examples**
8942+
8943+
```text
8944+
Input: candies = [2,3,5,1,3], extraCandies = 3
8945+
Output: [true,true,true,false,true]
8946+
Explanation: If you give all extraCandies to:
8947+
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
8948+
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
8949+
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
8950+
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
8951+
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
8952+
8953+
Input: candies = [4,2,1,1,2], extraCandies = 1
8954+
Output: [true,false,false,false,false]
8955+
8956+
Input: candies = [12,1,12], extraCandies = 10
8957+
Output: [true,false,true]
8958+
```
8959+
8960+
**Constraints**
8961+
8962+
```text
8963+
- n == candies.length
8964+
- 2 <= n <= 100
8965+
- 1 <= candies[i] <= 100
8966+
- 1 <= extraCandies <= 50
8967+
```
8968+
8969+
## Hint
8970+
For each kid, check if their candies plus `extraCandies` is at least as much as the current maximum.
8971+
8972+
## Explanation
8973+
First, you want to know the highest number of candies any kid currently has. This is important because you need a reference point to see if giving extra candies to a kid will make them "the greatest."
8974+
8975+
For each kid, you add the `extraCandies` to their current amount. You do this because you want to see if, after the bonus, they can reach or beat the current maximum. If they do, you mark them as `True` in our answer list; otherwise, False.
8976+
8977+
You only need to find the maximum once, and then just compare each kid's total to it. Don't need to recalculate the maximum for every kid.
8978+
8979+
### Solution
8980+
8981+
```python
8982+
def kidsWithCandies(candies, extraCandies):
8983+
max_candies = max(candies) # Find the current maximum
8984+
return [(c + extraCandies) >= max_candies for c in candies]
8985+
```
8986+
89258987
## 1448. Count Good Nodes in Binary Tree [Medium]
89268988
https://leetcode.com/problems/count-good-nodes-in-binary-tree/
89278989

books/LeetCode_75.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -517,6 +517,68 @@ def uniqueOccurrences(arr):
517517
return len(set(count.values())) == len(count)
518518
```
519519

520+
## 1431. Kids With the Greatest Number of Candies [Easy]
521+
https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
522+
523+
### Explanation
524+
525+
## 1431. Kids With the Greatest Number of Candies [Easy]
526+
527+
https://leetcode.com/problems/kids-with-the-greatest-number-of-candies
528+
529+
## Description
530+
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `i`th kid has, and an integer `extraCandies`, denoting the number of extra candies that you have.
531+
532+
Return a boolean array `result` of length `n`, where `result[i]` is `true` if, after giving the `i`th kid all the `extraCandies`, they will have the greatest number of candies among all the kids, or false otherwise.
533+
534+
Note that multiple kids can have the greatest number of candies.
535+
536+
**Examples**
537+
538+
```text
539+
Input: candies = [2,3,5,1,3], extraCandies = 3
540+
Output: [true,true,true,false,true]
541+
Explanation: If you give all extraCandies to:
542+
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
543+
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
544+
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
545+
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
546+
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
547+
548+
Input: candies = [4,2,1,1,2], extraCandies = 1
549+
Output: [true,false,false,false,false]
550+
551+
Input: candies = [12,1,12], extraCandies = 10
552+
Output: [true,false,true]
553+
```
554+
555+
**Constraints**
556+
557+
```text
558+
- n == candies.length
559+
- 2 <= n <= 100
560+
- 1 <= candies[i] <= 100
561+
- 1 <= extraCandies <= 50
562+
```
563+
564+
## Hint
565+
For each kid, check if their candies plus `extraCandies` is at least as much as the current maximum.
566+
567+
## Explanation
568+
First, you want to know the highest number of candies any kid currently has. This is important because you need a reference point to see if giving extra candies to a kid will make them "the greatest."
569+
570+
For each kid, you add the `extraCandies` to their current amount. You do this because you want to see if, after the bonus, they can reach or beat the current maximum. If they do, you mark them as `True` in our answer list; otherwise, False.
571+
572+
You only need to find the maximum once, and then just compare each kid's total to it. Don't need to recalculate the maximum for every kid.
573+
574+
### Solution
575+
576+
```python
577+
def kidsWithCandies(candies, extraCandies):
578+
max_candies = max(candies) # Find the current maximum
579+
return [(c + extraCandies) >= max_candies for c in candies]
580+
```
581+
520582
## 2215. Find the Difference of Two Arrays [Easy]
521583
https://leetcode.com/problems/find-the-difference-of-two-arrays/
522584

books/Visualization.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,68 @@ def __init__(self, val=0, next=None):
8686
self.next = next
8787
```
8888

89+
## 1431. Kids With the Greatest Number of Candies [Easy]
90+
https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
91+
92+
### Explanation
93+
94+
## 1431. Kids With the Greatest Number of Candies [Easy]
95+
96+
https://leetcode.com/problems/kids-with-the-greatest-number-of-candies
97+
98+
## Description
99+
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `i`th kid has, and an integer `extraCandies`, denoting the number of extra candies that you have.
100+
101+
Return a boolean array `result` of length `n`, where `result[i]` is `true` if, after giving the `i`th kid all the `extraCandies`, they will have the greatest number of candies among all the kids, or false otherwise.
102+
103+
Note that multiple kids can have the greatest number of candies.
104+
105+
**Examples**
106+
107+
```text
108+
Input: candies = [2,3,5,1,3], extraCandies = 3
109+
Output: [true,true,true,false,true]
110+
Explanation: If you give all extraCandies to:
111+
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
112+
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
113+
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
114+
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
115+
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
116+
117+
Input: candies = [4,2,1,1,2], extraCandies = 1
118+
Output: [true,false,false,false,false]
119+
120+
Input: candies = [12,1,12], extraCandies = 10
121+
Output: [true,false,true]
122+
```
123+
124+
**Constraints**
125+
126+
```text
127+
- n == candies.length
128+
- 2 <= n <= 100
129+
- 1 <= candies[i] <= 100
130+
- 1 <= extraCandies <= 50
131+
```
132+
133+
## Hint
134+
For each kid, check if their candies plus `extraCandies` is at least as much as the current maximum.
135+
136+
## Explanation
137+
First, you want to know the highest number of candies any kid currently has. This is important because you need a reference point to see if giving extra candies to a kid will make them "the greatest."
138+
139+
For each kid, you add the `extraCandies` to their current amount. You do this because you want to see if, after the bonus, they can reach or beat the current maximum. If they do, you mark them as `True` in our answer list; otherwise, False.
140+
141+
You only need to find the maximum once, and then just compare each kid's total to it. Don't need to recalculate the maximum for every kid.
142+
143+
### Solution
144+
145+
```python
146+
def kidsWithCandies(candies, extraCandies):
147+
max_candies = max(candies) # Find the current maximum
148+
return [(c + extraCandies) >= max_candies for c in candies]
149+
```
150+
89151
## 1798. Maximum Number of Consecutive Values You Can Make [Medium]
90152
https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make/
91153

data/book-sets.json

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -176,13 +176,13 @@
176176
3475, 3477, 3478, 3479, 3480, 3482, 3483, 3484, 3485, 3486, 3487, 3488, 3489, 3490, 3492, 3493, 3494, 3495, 3497, 3498, 3499, 3500, 3501, 3502,
177177
3503, 3504, 3505, 3507, 3508, 3509, 3510, 3513, 3514, 3515, 3516, 3517, 3518, 3519, 3521, 3523, 3524, 3525, 3527, 3528, 3529, 3530, 3531, 3532,
178178
3533, 3534, 3536, 3537, 3538, 3539, 3541, 3542, 3543, 3544, 3545, 3546, 3547, 3548, 3550, 3551, 3552, 3553, 3554, 3556, 3557, 3558, 3559, 3560,
179-
3561, 3562, 3563, 3564, 3566, 3567, 3568, 3569, 3570, 3572, 3573, 3574, 3575, 3576, 3577, 3578, 3579, 3580, 3582, 3583, 3584, 3585, 3586, 3587,
180-
3588, 3589, 3590, 3591, 3592, 3593, 3594, 3597, 3598, 3599, 3600, 3601, 3604, 3605, 3609, 3611, 3612, 3613, 3614, 3615, 3617, 3618, 3619, 3620,
181-
3621, 3624, 3626, 3627, 3628, 3629, 3630, 3633, 3634, 3635, 3636, 3637, 3638, 3639, 3640, 3642, 3643, 3644, 3645, 3646, 3648, 3649, 3650, 3651,
182-
3652, 3653, 3654, 3655, 3657, 3658, 3659, 3660, 3661, 3664, 3665, 3666, 3669, 3670, 3671, 3673, 3674, 3675, 3676, 3677, 3679, 3680, 3681, 3684,
183-
3685, 3686, 3689, 3690, 3691, 3693, 3694, 3695, 3698, 3699, 3700, 3702, 3703, 3704, 3705, 3706, 3708, 3709, 3710, 3711, 3713, 3714, 3715, 3716,
184-
3717, 3719, 3720, 3721, 3725, 3729, 3730, 3732, 3733, 3734, 3735, 3744, 3746, 3749, 3758, 3763, 3773, 3774, 3775, 3776, 3777, 3778, 3779, 3780,
185-
3781, 3782, 3783, 3784, 3785, 3786, 3787, 3788, 3789, 3790, 3791, 3792, 3793, 3794, 3795, 3796, 3797, 3798, 3799
179+
3561, 3562, 3563, 3564, 3566, 3567, 3568, 3569, 3570, 3572, 3573, 3574, 3575, 3576, 3577, 3578, 3579, 3580, 3582, 3584, 3585, 3586, 3587, 3588,
180+
3589, 3590, 3591, 3592, 3593, 3594, 3597, 3598, 3599, 3600, 3601, 3604, 3605, 3609, 3611, 3612, 3613, 3614, 3615, 3617, 3618, 3619, 3620, 3621,
181+
3624, 3626, 3627, 3628, 3629, 3630, 3633, 3634, 3635, 3636, 3637, 3638, 3639, 3640, 3642, 3643, 3644, 3645, 3646, 3648, 3649, 3650, 3651, 3652,
182+
3653, 3654, 3655, 3657, 3658, 3659, 3660, 3661, 3664, 3665, 3666, 3669, 3670, 3671, 3673, 3674, 3675, 3676, 3677, 3679, 3680, 3681, 3684, 3685,
183+
3686, 3689, 3690, 3691, 3693, 3694, 3695, 3698, 3699, 3700, 3702, 3703, 3704, 3705, 3706, 3708, 3709, 3710, 3711, 3713, 3714, 3715, 3716, 3717,
184+
3719, 3720, 3721, 3725, 3729, 3730, 3732, 3733, 3734, 3735, 3744, 3746, 3749, 3758, 3763, 3773, 3774, 3775, 3776, 3777, 3778, 3779, 3780, 3781,
185+
3782, 3783, 3784, 3785, 3786, 3787, 3788, 3789, 3790, 3791, 3792, 3793, 3794, 3795, 3796, 3797, 3798, 3799
186186
],
187187
"premium": [
188188
27, 156, 157, 158, 159, 161, 163, 170, 186, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 259, 261, 265, 266, 267, 269,

explanations/3583/en.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
## Explanation
2+
3+
### Strategy (The "Why")
4+
5+
**Restate the problem:** We need to count special triplets (i, j, k) where i < j < k, nums[i] == nums[j] * 2, and nums[k] == nums[j] * 2. In other words, for each middle element j, we need to count how many i < j have nums[i] == target and how many k > j have nums[k] == target, where target = nums[j] * 2.
6+
7+
**1.1 Constraints & Complexity:**
8+
- Input size: `3 <= n <= 10^5`, `0 <= nums[i] <= 10^5`
9+
- **Time Complexity:** O(n) - single pass through array with hash map operations
10+
- **Space Complexity:** O(n) for hash maps storing frequencies
11+
- **Edge Case:** If no triplets exist, return 0
12+
13+
**1.2 High-level approach:**
14+
We process each position j as the middle element. We maintain two frequency maps: one for elements before j (freq_before) and one for elements after j (freq_after). For each j, we count how many i < j have nums[i] == target and how many k > j have nums[k] == target, then multiply these counts.
15+
16+
![Frequency counting for triplets visualization](https://assets.leetcode.com/static_assets/others/frequency-counting-triplets.png)
17+
18+
**1.3 Brute force vs. optimized strategy:**
19+
- **Brute Force:** Check all triplets (i, j, k) where i < j < k, which is O(n³)
20+
- **Optimized Strategy:** For each j, use hash maps to count valid i and k positions in O(1), achieving O(n) time
21+
- **Emphasize the optimization:** Hash maps allow us to count frequencies before and after each position efficiently without nested loops
22+
23+
**1.4 Decomposition:**
24+
1. Initialize freq_before (empty) and freq_after (contains all elements initially)
25+
2. Process each position j from left to right
26+
3. Remove nums[j] from freq_after (since j is no longer "after")
27+
4. Calculate target = nums[j] * 2
28+
5. Count valid i positions (freq_before[target]) and valid k positions (freq_after[target])
29+
6. Multiply counts and add to result (modulo 10^9 + 7)
30+
7. Add nums[j] to freq_before for future j positions
31+
32+
### Steps (The "How")
33+
34+
**2.1 Initialization & Example Setup:**
35+
Let's use the example: `nums = [6, 3, 6]`
36+
- Initialize: `freq_before = {}`, `freq_after = {6: 2, 3: 1}`, `res = 0`, `MOD = 10^9 + 7`
37+
38+
**2.2 Start Processing:**
39+
We iterate through each position j from 0 to n-1.
40+
41+
**2.3 Trace Walkthrough:**
42+
43+
| j | nums[j] | Remove from freq_after | target | freq_before[target] | freq_after[target] | Count | res |
44+
|---|---------|------------------------|--------|---------------------|-------------------|-------|-----|
45+
| 0 | 6 | freq_after = {6: 1, 3: 1} | 12 | 0 | 0 | 0 * 0 = 0 | 0 |
46+
| 0 | - | Add to freq_before | - | freq_before = {6: 1} | - | - | 0 |
47+
| 1 | 3 | freq_after = {6: 1} | 6 | 1 (from freq_before) | 1 (from freq_after) | 1 * 1 = 1 | 1 |
48+
| 1 | - | Add to freq_before | - | freq_before = {6: 1, 3: 1} | - | - | 1 |
49+
| 2 | 6 | freq_after = {} | 12 | 0 | 0 | 0 * 0 = 0 | 1 |
50+
51+
**2.4 Increment and Loop:**
52+
For each j, we update frequency maps and count triplets where j is the middle element.
53+
54+
**2.5 Return Result:**
55+
After processing all positions, `res = 1`, which is the number of special triplets. The triplet is (0, 1, 2) where nums[0] = 6 = 3 * 2 and nums[2] = 6 = 3 * 2.
56+

explanations/3760/en.md

Lines changed: 26 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -2,55 +2,50 @@
22

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

5-
**Restate the problem:** We need to convert string `source` to `target` with minimum cost using substring conversions. Operations must be disjoint or identical (can't overlap partially).
5+
**Restate the problem:** We need to find the maximum number of substrings we can split a string into such that each substring starts with a distinct character. No two substrings can start with the same character.
66

77
**1.1 Constraints & Complexity:**
8-
- Input size: `1 <= source.length == target.length <= 1000`, `1 <= original.length <= 100`
9-
- **Time Complexity:** O(m³ + n² * m) where m is number of unique strings and n is string length, due to Floyd-Warshall and DP
10-
- **Space Complexity:** O(m² + n) for distance matrix and DP array
11-
- **Edge Case:** If source == target, return 0
8+
- Input size: `1 <= s.length <= 10^5`
9+
- **Time Complexity:** O(n) - single pass to count distinct characters
10+
- **Space Complexity:** O(1) - using a set of at most 26 characters (lowercase English letters)
11+
- **Edge Case:** If all characters are the same (e.g., "aaaa"), we can only have 1 substring
1212

1313
**1.2 High-level approach:**
14-
We model substring conversions as a graph, use Floyd-Warshall to find shortest paths, then use dynamic programming to find the minimum cost to convert prefixes of the source string.
14+
The key insight is that each substring must start with a distinct character. Since we can only use each starting character once, the maximum number of substrings equals the number of distinct characters in the string.
1515

16-
![DP with substring matching visualization](https://assets.leetcode.com/static_assets/others/dp-substring-matching.png)
16+
![Distinct characters visualization](https://assets.leetcode.com/static_assets/others/distinct-characters.png)
1717

1818
**1.3 Brute force vs. optimized strategy:**
19-
- **Brute Force:** Try all possible sequences of substring conversions, which is exponential.
20-
- **Optimized Strategy:** Precompute shortest paths between all string pairs using Floyd-Warshall, then use DP where dp[i] = minimum cost to convert first i characters.
19+
- **Brute Force:** Try all possible ways to split the string, which is exponential
20+
- **Optimized Strategy:** Simply count distinct characters - each distinct character can start exactly one substring, so the answer is the count of distinct characters
21+
- **Emphasize the optimization:** The constraint that each substring must start with a distinct character directly limits the answer to the number of distinct characters
2122

2223
**1.4 Decomposition:**
23-
1. Assign unique IDs to all unique strings in original and changed arrays
24-
2. Build graph and run Floyd-Warshall to find shortest conversion costs
25-
3. Use DP: dp[i] = min cost to convert source[0:i] to target[0:i]
26-
4. For each position, try all possible substring conversions ending there
27-
5. Return dp[n] or -1 if impossible
24+
1. Count the number of distinct characters in the string
25+
2. Since each substring must start with a distinct character, and we can only use each character once as a start
26+
3. The maximum number of substrings equals the number of distinct characters
27+
4. Return the count
2828

2929
### Steps (The "How")
3030

3131
**2.1 Initialization & Example Setup:**
32-
Let's use the example: `source = "abcd"`, `target = "acbe"`, `original = ["a","b","c","c","e","d"]`, `changed = ["b","c","b","e","b","e"]`, `cost = [2,5,5,1,2,20]`
33-
- Map strings to IDs: a→0, b→1, c→2, e→3, d→4
34-
- Build graph and run Floyd-Warshall
32+
Let's use the example: `s = "abab"`
33+
- Distinct characters: 'a' and 'b' (2 distinct characters)
34+
- We can split into: "a" and "bab" (starts with 'a' and 'b')
3535

36-
**2.2 Start Processing:**
37-
We initialize dp[0] = 0, then process each position.
36+
**2.2 Start Checking:**
37+
We count distinct characters in the string.
3838

3939
**2.3 Trace Walkthrough:**
40-
Processing `source = "abcd"` to `target = "acbe"`:
4140

42-
| i | source[0:i] | target[0:i] | Options | dp[i] |
43-
|---|-------------|-------------|---------|-------|
44-
| 0 | "" | "" | Base case | 0 |
45-
| 1 | "a" | "a" | No change (dp[0] + 0) | 0 |
46-
| 2 | "ab" | "ac" | Try "b"→"c": dp[1] + cost(b→c) = 0 + 5 = 5 | 5 |
47-
| 3 | "abc" | "acb" | Try "c"→"b": dp[2] + cost(c→b) = 5 + 5 = 10<br>Or "bc"→"cb": need to check if exists | 10 |
48-
| 4 | "abcd" | "acbe" | Try "d"→"e": dp[3] + cost(d→e) = 10 + 20 = 30 | 30 |
49-
50-
Actually, we need to check all substring conversions. For position 2, we can convert "b" to "c" at cost 5. For position 3, we convert "c" to "b" at cost 5 (or find better path). For position 4, we convert "d" to "e" at cost 20. Total: 5 + 5 + 20 = 30, but the example says 28, so there must be a better path.
41+
| String | Distinct Characters | Count | Maximum Substrings |
42+
|--------|-------------------|-------|-------------------|
43+
| "abab" | {'a', 'b'} | 2 | 2 |
44+
| "abcd" | {'a', 'b', 'c', 'd'} | 4 | 4 |
45+
| "aaaa" | {'a'} | 1 | 1 |
5146

5247
**2.4 Increment and Loop:**
53-
For each position i, we try all possible substring conversions ending at i and take the minimum cost.
48+
We iterate through the string once to collect all distinct characters in a set.
5449

5550
**2.5 Return Result:**
56-
After processing, `dp[4] = 28` (using optimal conversions), which is the minimum cost to convert "abcd" to "acbe".
51+
For "abab", we have 2 distinct characters, so the maximum number of substrings is 2. We can split as "a" + "bab" where "a" starts with 'a' and "bab" starts with 'b'.

0 commit comments

Comments
 (0)