Skip to content

Commit da8ac93

Browse files
committed
Add solutions and explanations for problems 2390, 2542, 3753, 3759-3762, 3765-3772
1 parent 380cf1f commit da8ac93

File tree

23 files changed

+879
-27
lines changed

23 files changed

+879
-27
lines changed

data/leetcode-problems.json

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26356,5 +26356,61 @@
2635626356
"title": "Most Common Course Pairs",
2635726357
"difficulty": "Hard",
2635826358
"link": "https://leetcode.com/problems/most-common-course-pairs/"
26359+
},
26360+
"3765": {
26361+
"id": 3765,
26362+
"category": "Math & Geometry",
26363+
"title": "Complete Prime Number",
26364+
"difficulty": "Medium",
26365+
"link": "https://leetcode.com/problems/complete-prime-number/"
26366+
},
26367+
"3766": {
26368+
"id": 3766,
26369+
"category": "Array & Hashing",
26370+
"title": "Minimum Operations to Make Binary Palindrome",
26371+
"difficulty": "Medium",
26372+
"link": "https://leetcode.com/problems/minimum-operations-to-make-binary-palindrome/"
26373+
},
26374+
"3767": {
26375+
"id": 3767,
26376+
"category": "Greedy",
26377+
"title": "Maximize Points After Choosing K Tasks",
26378+
"difficulty": "Medium",
26379+
"link": "https://leetcode.com/problems/maximize-points-after-choosing-k-tasks/"
26380+
},
26381+
"3768": {
26382+
"id": 3768,
26383+
"category": "Array & Hashing",
26384+
"title": "Minimum Inversion Count in Subarrays of Fixed Length",
26385+
"difficulty": "Hard",
26386+
"link": "https://leetcode.com/problems/minimum-inversion-count-in-subarrays-of-fixed-length/"
26387+
},
26388+
"3769": {
26389+
"id": 3769,
26390+
"category": "Array & Hashing",
26391+
"title": "Sort Integers by Binary Reflection",
26392+
"difficulty": "Easy",
26393+
"link": "https://leetcode.com/problems/sort-integers-by-binary-reflection/"
26394+
},
26395+
"3770": {
26396+
"id": 3770,
26397+
"category": "Math & Geometry",
26398+
"title": "Largest Prime from Consecutive Prime Sum",
26399+
"difficulty": "Medium",
26400+
"link": "https://leetcode.com/problems/largest-prime-from-consecutive-prime-sum/"
26401+
},
26402+
"3771": {
26403+
"id": 3771,
26404+
"category": "Dynamic Programming",
26405+
"title": "Total Score of Dungeon Runs",
26406+
"difficulty": "Medium",
26407+
"link": "https://leetcode.com/problems/total-score-of-dungeon-runs/"
26408+
},
26409+
"3772": {
26410+
"id": 3772,
26411+
"category": "Tree",
26412+
"title": "Maximum Subgraph Score in a Tree",
26413+
"difficulty": "Hard",
26414+
"link": "https://leetcode.com/problems/maximum-subgraph-score-in-a-tree/"
2635926415
}
2636026416
}

explanations/2390/en.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
## Explanation
2+
3+
### Strategy (The "Why")
4+
5+
**Restate the problem:** We need to remove stars from a string. Each star removes the closest non-star character to its left, along with the star itself.
6+
7+
**1.1 Constraints & Complexity:**
8+
- Input size: `1 <= s.length <= 10^5`
9+
- **Time Complexity:** O(n) where n is the length of the string, as we process each character once
10+
- **Space Complexity:** O(n) for the stack to store characters
11+
- **Edge Case:** If the string contains only stars, all characters will be removed, resulting in an empty string
12+
13+
**1.2 High-level approach:**
14+
We use a stack to simulate the removal process. When we encounter a star, we pop the most recent character (the one to the left). When we encounter a non-star, we push it onto the stack.
15+
16+
![Stack visualization](https://assets.leetcode.com/static_assets/others/stack-operation.png)
17+
18+
**1.3 Brute force vs. optimized strategy:**
19+
- **Brute Force:** For each star, find and remove the closest non-star to the left by scanning backwards, which would be O(n²) in worst case
20+
- **Optimized Strategy:** Use a stack to maintain characters, allowing O(1) removal of the most recent character, resulting in O(n) time
21+
- **Emphasize the optimization:** The stack allows us to efficiently track and remove the "closest left" character without scanning
22+
23+
**1.4 Decomposition:**
24+
1. Initialize an empty stack to store characters
25+
2. Iterate through each character in the string
26+
3. If the character is a star, remove the top element from the stack (if it exists)
27+
4. If the character is not a star, add it to the stack
28+
5. Convert the remaining stack elements to a string and return
29+
30+
### Steps (The "How")
31+
32+
**2.1 Initialization & Example Setup:**
33+
Let's use the example: `s = "leet**cod*e"`
34+
- Initialize an empty stack: `stack = []`
35+
36+
**2.2 Start Processing:**
37+
We iterate through each character in the string from left to right.
38+
39+
**2.3 Trace Walkthrough:**
40+
41+
| Character | Stack Before | Action | Stack After |
42+
|-----------|--------------|--------|-------------|
43+
| 'l' | [] | Push 'l' | ['l'] |
44+
| 'e' | ['l'] | Push 'e' | ['l', 'e'] |
45+
| 'e' | ['l', 'e'] | Push 'e' | ['l', 'e', 'e'] |
46+
| 't' | ['l', 'e', 'e'] | Push 't' | ['l', 'e', 'e', 't'] |
47+
| '*' | ['l', 'e', 'e', 't'] | Pop 't' | ['l', 'e', 'e'] |
48+
| '*' | ['l', 'e', 'e'] | Pop 'e' | ['l', 'e'] |
49+
| 'c' | ['l', 'e'] | Push 'c' | ['l', 'e', 'c'] |
50+
| 'o' | ['l', 'e', 'c'] | Push 'o' | ['l', 'e', 'c', 'o'] |
51+
| 'd' | ['l', 'e', 'c', 'o'] | Push 'd' | ['l', 'e', 'c', 'o', 'd'] |
52+
| '*' | ['l', 'e', 'c', 'o', 'd'] | Pop 'd' | ['l', 'e', 'c', 'o'] |
53+
| 'e' | ['l', 'e', 'c', 'o'] | Push 'e' | ['l', 'e', 'c', 'o', 'e'] |
54+
55+
**2.4 Increment and Loop:**
56+
After processing all characters, we continue to the next step.
57+
58+
**2.5 Return Result:**
59+
The final stack contains `['l', 'e', 'c', 'o', 'e']`, which when joined gives `"lecoe"`, which is the result.

explanations/2542/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 choose a subsequence of k indices from nums1, and our score is the sum of selected nums1 values multiplied by the minimum of selected nums2 values. We want to maximize this score.
6+
7+
**1.1 Constraints & Complexity:**
8+
- Input size: `1 <= n <= 10^5`
9+
- **Time Complexity:** O(n log n) for sorting + O(n log k) for heap operations = O(n log n)
10+
- **Space Complexity:** O(k) for the heap
11+
- **Edge Case:** When k = 1, we simply find the maximum of nums1[i] * nums2[i]
12+
13+
**1.2 High-level approach:**
14+
We sort pairs by nums2 in descending order. As we process each pair, we maintain a min-heap of the k largest nums1 values. The current nums2 value becomes the minimum for our current selection, and we calculate the score.
15+
16+
![Greedy selection visualization](https://assets.leetcode.com/static_assets/others/greedy-selection.png)
17+
18+
**1.3 Brute force vs. optimized strategy:**
19+
- **Brute Force:** Try all C(n,k) combinations, which is exponential
20+
- **Optimized Strategy:** Sort by nums2 descending, use heap to maintain top k nums1 values, achieving O(n log n) time
21+
- **Emphasize the optimization:** By sorting by nums2, we ensure that when we process a pair, its nums2 value is the minimum in our current selection
22+
23+
**1.4 Decomposition:**
24+
1. Create pairs of (nums1[i], nums2[i]) and sort by nums2 in descending order
25+
2. Use a min-heap to maintain the k largest nums1 values seen so far
26+
3. For each pair, add nums1 to heap, maintain heap size k, calculate score
27+
4. Track the maximum score encountered
28+
29+
### Steps (The "How")
30+
31+
**2.1 Initialization & Example Setup:**
32+
Let's use the example: `nums1 = [1,3,3,2]`, `nums2 = [2,1,3,4]`, `k = 3`
33+
- Sort pairs by nums2 descending: [(2,4), (3,3), (1,2), (3,1)]
34+
- Initialize heap and sum: `heap = []`, `current_sum = 0`
35+
36+
**2.2 Start Processing:**
37+
We iterate through sorted pairs.
38+
39+
**2.3 Trace Walkthrough:**
40+
41+
| Pair | Heap Before | Action | Heap After | Sum | Score | Max Score |
42+
|------|-------------|--------|------------|-----|-------|-----------|
43+
| (2,4) | [] | Push 2 | [2] | 2 | 2*4=8 | 8 |
44+
| (3,3) | [2] | Push 3 | [2,3] | 5 | 5*3=15 | 15 |
45+
| (1,2) | [2,3] | Push 1, Pop 1 | [2,3] | 5 | 5*2=10 | 15 |
46+
| (3,1) | [2,3] | Push 3, Pop 2 | [3,3] | 6 | 6*1=6 | 15 |
47+
48+
**2.4 Increment and Loop:**
49+
After processing all pairs, we continue tracking the maximum.
50+
51+
**2.5 Return Result:**
52+
The maximum score encountered is 15, which is the result.

explanations/3762/en.md

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,53 +2,51 @@
22

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

5-
**Restate the problem:** We need to find the minimum number of operations to make all array values equal to k. In each operation, we can select a valid integer h and set all values greater than h to h. A valid h means all values strictly greater than h are identical.
5+
**Restate the problem:** We need to make all array values equal to k using operations. In each operation, we can select a valid integer h and set all values greater than h to h. A valid integer h means all values strictly greater than h are identical.
66

77
**1.1 Constraints & Complexity:**
8-
- Input size: `1 <= nums.length <= 100`, `1 <= nums[i] <= 100`, `1 <= k <= 100`
9-
- **Time Complexity:** O(n) where n is the length of nums, as we iterate through the array once to collect distinct values
10-
- **Space Complexity:** O(n) in the worst case to store distinct values greater than k
11-
- **Edge Case:** If any element is less than k, it's impossible to make all elements equal to k, so return -1
8+
- Input size: `1 <= nums.length <= 100`, `1 <= nums[i] <= 100`
9+
- **Time Complexity:** O(n) where n is the length of nums, as we iterate once to find distinct values
10+
- **Space Complexity:** O(n) for the set storing distinct values greater than k
11+
- **Edge Case:** If any element is less than k, it's impossible to make all elements equal to k, so we return -1
1212

1313
**1.2 High-level approach:**
14-
The key insight is that we need one operation for each distinct value greater than k. We can reduce values from highest to lowest, and each distinct value requires one operation.
14+
We count the number of distinct values greater than k. Each distinct value requires one operation to reduce it. The answer is simply the count of distinct values greater than k.
1515

16-
![Greedy reduction visualization](https://assets.leetcode.com/static_assets/others/greedy-algorithm.png)
16+
![Array reduction visualization](https://assets.leetcode.com/static_assets/others/array-reduction.png)
1717

1818
**1.3 Brute force vs. optimized strategy:**
19-
- **Brute Force:** Try all possible sequences of operations, which would be exponential.
20-
- **Optimized Strategy:** Count the number of distinct values greater than k. This is exactly the number of operations needed, as we can reduce them one by one from highest to lowest.
19+
- **Brute Force:** Try all possible sequences of operations, which is exponential
20+
- **Optimized Strategy:** Recognize that we need one operation per distinct value greater than k, giving us O(n) time
21+
- **Emphasize the optimization:** We can directly count distinct values without simulating operations
2122

2223
**1.4 Decomposition:**
2324
1. Check if any element is less than k (impossible case)
2425
2. Collect all distinct values that are greater than k
25-
3. Return the count of distinct values, which equals the number of operations needed
26+
3. Count the number of distinct values
27+
4. Return the count as the minimum number of operations
2628

2729
### Steps (The "How")
2830

2931
**2.1 Initialization & Example Setup:**
30-
Let's use the example: `nums = [5, 2, 5, 4, 5]`, `k = 2`
31-
- Initialize check for values less than k
32-
- Initialize a set to collect distinct values greater than k
32+
Let's use the example: `nums = [5,2,5,4,5]`, `k = 2`
33+
- Initialize an empty set: `distinct_greater = set()`
3334

3435
**2.2 Start Checking:**
35-
We iterate through the array to check for impossible cases and collect distinct values.
36+
We iterate through each number in the array.
3637

3738
**2.3 Trace Walkthrough:**
38-
Using the example `nums = [5, 2, 5, 4, 5]`, `k = 2`:
3939

40-
| Element | Is < k? | Is > k? | Distinct Set | Action |
41-
|---------|---------|---------|--------------|--------|
42-
| 5 | No | Yes | {5} | Add 5 |
43-
| 2 | No | No | {5} | Skip |
44-
| 5 | No | Yes | {5} | Already in set |
45-
| 4 | No | Yes | {5, 4} | Add 4 |
46-
| 5 | No | Yes | {5, 4} | Already in set |
47-
48-
After processing: distinct values > k = {5, 4}, count = 2
40+
| Number | Is > k? | Add to Set? | distinct_greater |
41+
|--------|---------|-------------|------------------|
42+
| 5 | Yes | Yes | {5} |
43+
| 2 | No | No | {5} |
44+
| 5 | Yes | No (already in set) | {5} |
45+
| 4 | Yes | Yes | {5, 4} |
46+
| 5 | Yes | No (already in set) | {5, 4} |
4947

5048
**2.4 Increment and Loop:**
51-
For each element greater than k, we add it to our set of distinct values. The loop continues until all elements are processed.
49+
After processing all numbers, we have `distinct_greater = {5, 4}`.
5250

5351
**2.5 Return Result:**
54-
The result is the number of distinct values greater than k, which is 2. This means we need 2 operations: first reduce 5 to 4, then reduce 4 to 2.
52+
The count of distinct values greater than k is 2, so we need 2 operations. First operation with h=4 reduces 5 to 4, second operation with h=2 reduces 4 to 2. The result is 2.

explanations/3765/en.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
## Explanation
2+
3+
### Strategy (The "Why")
4+
5+
**Restate the problem:** A number is a "Complete Prime Number" if every prefix and every suffix of the number is prime. We need to check if a given number satisfies this condition.
6+
7+
**1.1 Constraints & Complexity:**
8+
- Input size: `1 <= num <= 10^9`
9+
- **Time Complexity:** O(d * sqrt(n)) where d is the number of digits, as we check primality for each prefix and suffix
10+
- **Space Complexity:** O(d) to store the string representation
11+
- **Edge Case:** Single-digit numbers are complete prime only if they are prime themselves
12+
13+
**1.2 High-level approach:**
14+
We convert the number to a string, then check if all prefixes (from left) and all suffixes (from right) are prime numbers.
15+
16+
![Prime checking visualization](https://assets.leetcode.com/static_assets/others/prime-checking.png)
17+
18+
**1.3 Brute force vs. optimized strategy:**
19+
- **Brute Force:** Check all prefixes and suffixes for primality, which is what we do
20+
- **Optimized Strategy:** Use efficient primality testing (trial division up to sqrt(n)), achieving reasonable performance
21+
- **Emphasize the optimization:** We only need to check divisors up to sqrt(n) for primality testing
22+
23+
**1.4 Decomposition:**
24+
1. Convert the number to a string to access individual digits
25+
2. Check all prefixes: from first digit, first two digits, ..., all digits
26+
3. Check all suffixes: from last digit, last two digits, ..., all digits
27+
4. Return true only if all prefixes and suffixes are prime
28+
29+
### Steps (The "How")
30+
31+
**2.1 Initialization & Example Setup:**
32+
Let's use the example: `num = 23`
33+
- Convert to string: `s = "23"`
34+
35+
**2.2 Start Checking:**
36+
We check all prefixes first, then all suffixes.
37+
38+
**2.3 Trace Walkthrough:**
39+
40+
| Type | Substring | Value | Is Prime? |
41+
|------|-----------|-------|-----------|
42+
| Prefix | "2" | 2 | Yes |
43+
| Prefix | "23" | 23 | Yes |
44+
| Suffix | "3" | 3 | Yes |
45+
| Suffix | "23" | 23 | Yes |
46+
47+
**2.4 Increment and Loop:**
48+
After checking all prefixes and suffixes, we verify all are prime.
49+
50+
**2.5 Return Result:**
51+
All prefixes and suffixes are prime, so the result is `true`.

explanations/3766/en.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
## Explanation
2+
3+
### Strategy (The "Why")
4+
5+
**Restate the problem:** For each number in the array, we need to find the minimum number of operations (increment or decrement by 1) to make it a binary palindrome. A binary palindrome is a number whose binary representation reads the same forward and backward.
6+
7+
**1.1 Constraints & Complexity:**
8+
- Input size: `1 <= nums.length <= 5000`, `1 <= nums[i] <= 5000`
9+
- **Time Complexity:** O(p * n) where p is the number of palindromes (about 100) and n is array length
10+
- **Space Complexity:** O(p) to store precomputed palindromes
11+
- **Edge Case:** If a number is already a binary palindrome, it requires 0 operations
12+
13+
**1.2 High-level approach:**
14+
We precompute all binary palindromes up to 5000, then for each number, find the closest palindrome and calculate the minimum operations needed.
15+
16+
![Binary palindrome visualization](https://assets.leetcode.com/static_assets/others/binary-palindrome.png)
17+
18+
**1.3 Brute force vs. optimized strategy:**
19+
- **Brute Force:** For each number, check all nearby numbers for palindromes, which could be inefficient
20+
- **Optimized Strategy:** Precompute all palindromes once, then use binary search or linear scan to find closest, achieving O(p * n) time
21+
- **Emphasize the optimization:** Precomputation allows us to quickly find the closest palindrome for each number
22+
23+
**1.4 Decomposition:**
24+
1. Precompute all binary palindromes up to the maximum possible value (5000)
25+
2. For each number in the input array, find the closest palindrome
26+
3. Calculate the absolute difference as the minimum operations
27+
4. Return the array of minimum operations
28+
29+
### Steps (The "How")
30+
31+
**2.1 Initialization & Example Setup:**
32+
Let's use the example: `nums = [1,2,4]`
33+
- Precompute palindromes: [1, 3, 5, 7, 9, 15, ...] (numbers with palindromic binary)
34+
35+
**2.2 Start Processing:**
36+
We iterate through each number and find its closest palindrome.
37+
38+
**2.3 Trace Walkthrough:**
39+
40+
| Number | Binary | Closest Palindrome | Operations | Result |
41+
|--------|--------|-------------------|------------|--------|
42+
| 1 | 1 | 1 | |0| = 0 | 0 |
43+
| 2 | 10 | 3 (11) | |2-3| = 1 | 1 |
44+
| 4 | 100 | 3 (11) | |4-3| = 1 | 1 |
45+
46+
**2.4 Increment and Loop:**
47+
After processing all numbers, we have the results.
48+
49+
**2.5 Return Result:**
50+
The result array is `[0, 1, 1]`, representing the minimum operations for each number.

0 commit comments

Comments
 (0)