Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions data/leetcode-problems.json
Original file line number Diff line number Diff line change
Expand Up @@ -26356,5 +26356,61 @@
"title": "Most Common Course Pairs",
"difficulty": "Hard",
"link": "https://leetcode.com/problems/most-common-course-pairs/"
},
"3765": {
"id": 3765,
"category": "Math & Geometry",
"title": "Complete Prime Number",
"difficulty": "Medium",
"link": "https://leetcode.com/problems/complete-prime-number/"
},
"3766": {
"id": 3766,
"category": "Array & Hashing",
"title": "Minimum Operations to Make Binary Palindrome",
"difficulty": "Medium",
"link": "https://leetcode.com/problems/minimum-operations-to-make-binary-palindrome/"
},
"3767": {
"id": 3767,
"category": "Greedy",
"title": "Maximize Points After Choosing K Tasks",
"difficulty": "Medium",
"link": "https://leetcode.com/problems/maximize-points-after-choosing-k-tasks/"
},
"3768": {
"id": 3768,
"category": "Array & Hashing",
"title": "Minimum Inversion Count in Subarrays of Fixed Length",
"difficulty": "Hard",
"link": "https://leetcode.com/problems/minimum-inversion-count-in-subarrays-of-fixed-length/"
},
"3769": {
"id": 3769,
"category": "Array & Hashing",
"title": "Sort Integers by Binary Reflection",
"difficulty": "Easy",
"link": "https://leetcode.com/problems/sort-integers-by-binary-reflection/"
},
"3770": {
"id": 3770,
"category": "Math & Geometry",
"title": "Largest Prime from Consecutive Prime Sum",
"difficulty": "Medium",
"link": "https://leetcode.com/problems/largest-prime-from-consecutive-prime-sum/"
},
"3771": {
"id": 3771,
"category": "Dynamic Programming",
"title": "Total Score of Dungeon Runs",
"difficulty": "Medium",
"link": "https://leetcode.com/problems/total-score-of-dungeon-runs/"
},
"3772": {
"id": 3772,
"category": "Tree",
"title": "Maximum Subgraph Score in a Tree",
"difficulty": "Hard",
"link": "https://leetcode.com/problems/maximum-subgraph-score-in-a-tree/"
}
}
59 changes: 59 additions & 0 deletions explanations/2390/en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
## Explanation

### Strategy (The "Why")

**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.

**1.1 Constraints & Complexity:**
- Input size: `1 <= s.length <= 10^5`
- **Time Complexity:** O(n) where n is the length of the string, as we process each character once
- **Space Complexity:** O(n) for the stack to store characters
- **Edge Case:** If the string contains only stars, all characters will be removed, resulting in an empty string

**1.2 High-level approach:**
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.

![Stack visualization](https://assets.leetcode.com/static_assets/others/stack-operation.png)

**1.3 Brute force vs. optimized strategy:**
- **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
- **Optimized Strategy:** Use a stack to maintain characters, allowing O(1) removal of the most recent character, resulting in O(n) time
- **Emphasize the optimization:** The stack allows us to efficiently track and remove the "closest left" character without scanning

**1.4 Decomposition:**
1. Initialize an empty stack to store characters
2. Iterate through each character in the string
3. If the character is a star, remove the top element from the stack (if it exists)
4. If the character is not a star, add it to the stack
5. Convert the remaining stack elements to a string and return

### Steps (The "How")

**2.1 Initialization & Example Setup:**
Let's use the example: `s = "leet**cod*e"`
- Initialize an empty stack: `stack = []`

**2.2 Start Processing:**
We iterate through each character in the string from left to right.

**2.3 Trace Walkthrough:**

| Character | Stack Before | Action | Stack After |
|-----------|--------------|--------|-------------|
| 'l' | [] | Push 'l' | ['l'] |
| 'e' | ['l'] | Push 'e' | ['l', 'e'] |
| 'e' | ['l', 'e'] | Push 'e' | ['l', 'e', 'e'] |
| 't' | ['l', 'e', 'e'] | Push 't' | ['l', 'e', 'e', 't'] |
| '*' | ['l', 'e', 'e', 't'] | Pop 't' | ['l', 'e', 'e'] |
| '*' | ['l', 'e', 'e'] | Pop 'e' | ['l', 'e'] |
| 'c' | ['l', 'e'] | Push 'c' | ['l', 'e', 'c'] |
| 'o' | ['l', 'e', 'c'] | Push 'o' | ['l', 'e', 'c', 'o'] |
| 'd' | ['l', 'e', 'c', 'o'] | Push 'd' | ['l', 'e', 'c', 'o', 'd'] |
| '*' | ['l', 'e', 'c', 'o', 'd'] | Pop 'd' | ['l', 'e', 'c', 'o'] |
| 'e' | ['l', 'e', 'c', 'o'] | Push 'e' | ['l', 'e', 'c', 'o', 'e'] |

**2.4 Increment and Loop:**
After processing all characters, we continue to the next step.

**2.5 Return Result:**
The final stack contains `['l', 'e', 'c', 'o', 'e']`, which when joined gives `"lecoe"`, which is the result.
52 changes: 52 additions & 0 deletions explanations/2542/en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
## Explanation

### Strategy (The "Why")

**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.

**1.1 Constraints & Complexity:**
- Input size: `1 <= n <= 10^5`
- **Time Complexity:** O(n log n) for sorting + O(n log k) for heap operations = O(n log n)
- **Space Complexity:** O(k) for the heap
- **Edge Case:** When k = 1, we simply find the maximum of nums1[i] * nums2[i]

**1.2 High-level approach:**
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.

![Greedy selection visualization](https://assets.leetcode.com/static_assets/others/greedy-selection.png)

**1.3 Brute force vs. optimized strategy:**
- **Brute Force:** Try all C(n,k) combinations, which is exponential
- **Optimized Strategy:** Sort by nums2 descending, use heap to maintain top k nums1 values, achieving O(n log n) time
- **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

**1.4 Decomposition:**
1. Create pairs of (nums1[i], nums2[i]) and sort by nums2 in descending order
2. Use a min-heap to maintain the k largest nums1 values seen so far
3. For each pair, add nums1 to heap, maintain heap size k, calculate score
4. Track the maximum score encountered

### Steps (The "How")

**2.1 Initialization & Example Setup:**
Let's use the example: `nums1 = [1,3,3,2]`, `nums2 = [2,1,3,4]`, `k = 3`
- Sort pairs by nums2 descending: [(2,4), (3,3), (1,2), (3,1)]
- Initialize heap and sum: `heap = []`, `current_sum = 0`

**2.2 Start Processing:**
We iterate through sorted pairs.

**2.3 Trace Walkthrough:**

| Pair | Heap Before | Action | Heap After | Sum | Score | Max Score |
|------|-------------|--------|------------|-----|-------|-----------|
| (2,4) | [] | Push 2 | [2] | 2 | 2*4=8 | 8 |
| (3,3) | [2] | Push 3 | [2,3] | 5 | 5*3=15 | 15 |
| (1,2) | [2,3] | Push 1, Pop 1 | [2,3] | 5 | 5*2=10 | 15 |
| (3,1) | [2,3] | Push 3, Pop 2 | [3,3] | 6 | 6*1=6 | 15 |

**2.4 Increment and Loop:**
After processing all pairs, we continue tracking the maximum.

**2.5 Return Result:**
The maximum score encountered is 15, which is the result.
50 changes: 24 additions & 26 deletions explanations/3762/en.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,53 +2,51 @@

### Strategy (The "Why")

**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.
**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.

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

**1.2 High-level approach:**
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.
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.

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

**1.3 Brute force vs. optimized strategy:**
- **Brute Force:** Try all possible sequences of operations, which would be exponential.
- **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.
- **Brute Force:** Try all possible sequences of operations, which is exponential
- **Optimized Strategy:** Recognize that we need one operation per distinct value greater than k, giving us O(n) time
- **Emphasize the optimization:** We can directly count distinct values without simulating operations

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

### Steps (The "How")

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

**2.2 Start Checking:**
We iterate through the array to check for impossible cases and collect distinct values.
We iterate through each number in the array.

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

| Element | Is < k? | Is > k? | Distinct Set | Action |
|---------|---------|---------|--------------|--------|
| 5 | No | Yes | {5} | Add 5 |
| 2 | No | No | {5} | Skip |
| 5 | No | Yes | {5} | Already in set |
| 4 | No | Yes | {5, 4} | Add 4 |
| 5 | No | Yes | {5, 4} | Already in set |

After processing: distinct values > k = {5, 4}, count = 2
| Number | Is > k? | Add to Set? | distinct_greater |
|--------|---------|-------------|------------------|
| 5 | Yes | Yes | {5} |
| 2 | No | No | {5} |
| 5 | Yes | No (already in set) | {5} |
| 4 | Yes | Yes | {5, 4} |
| 5 | Yes | No (already in set) | {5, 4} |

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

**2.5 Return Result:**
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.
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.
51 changes: 51 additions & 0 deletions explanations/3765/en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
## Explanation

### Strategy (The "Why")

**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.

**1.1 Constraints & Complexity:**
- Input size: `1 <= num <= 10^9`
- **Time Complexity:** O(d * sqrt(n)) where d is the number of digits, as we check primality for each prefix and suffix
- **Space Complexity:** O(d) to store the string representation
- **Edge Case:** Single-digit numbers are complete prime only if they are prime themselves

**1.2 High-level approach:**
We convert the number to a string, then check if all prefixes (from left) and all suffixes (from right) are prime numbers.

![Prime checking visualization](https://assets.leetcode.com/static_assets/others/prime-checking.png)

**1.3 Brute force vs. optimized strategy:**
- **Brute Force:** Check all prefixes and suffixes for primality, which is what we do
- **Optimized Strategy:** Use efficient primality testing (trial division up to sqrt(n)), achieving reasonable performance
- **Emphasize the optimization:** We only need to check divisors up to sqrt(n) for primality testing

**1.4 Decomposition:**
1. Convert the number to a string to access individual digits
2. Check all prefixes: from first digit, first two digits, ..., all digits
3. Check all suffixes: from last digit, last two digits, ..., all digits
4. Return true only if all prefixes and suffixes are prime

### Steps (The "How")

**2.1 Initialization & Example Setup:**
Let's use the example: `num = 23`
- Convert to string: `s = "23"`

**2.2 Start Checking:**
We check all prefixes first, then all suffixes.

**2.3 Trace Walkthrough:**

| Type | Substring | Value | Is Prime? |
|------|-----------|-------|-----------|
| Prefix | "2" | 2 | Yes |
| Prefix | "23" | 23 | Yes |
| Suffix | "3" | 3 | Yes |
| Suffix | "23" | 23 | Yes |

**2.4 Increment and Loop:**
After checking all prefixes and suffixes, we verify all are prime.

**2.5 Return Result:**
All prefixes and suffixes are prime, so the result is `true`.
50 changes: 50 additions & 0 deletions explanations/3766/en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
## Explanation

### Strategy (The "Why")

**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.

**1.1 Constraints & Complexity:**
- Input size: `1 <= nums.length <= 5000`, `1 <= nums[i] <= 5000`
- **Time Complexity:** O(p * n) where p is the number of palindromes (about 100) and n is array length
- **Space Complexity:** O(p) to store precomputed palindromes
- **Edge Case:** If a number is already a binary palindrome, it requires 0 operations

**1.2 High-level approach:**
We precompute all binary palindromes up to 5000, then for each number, find the closest palindrome and calculate the minimum operations needed.

![Binary palindrome visualization](https://assets.leetcode.com/static_assets/others/binary-palindrome.png)

**1.3 Brute force vs. optimized strategy:**
- **Brute Force:** For each number, check all nearby numbers for palindromes, which could be inefficient
- **Optimized Strategy:** Precompute all palindromes once, then use binary search or linear scan to find closest, achieving O(p * n) time
- **Emphasize the optimization:** Precomputation allows us to quickly find the closest palindrome for each number

**1.4 Decomposition:**
1. Precompute all binary palindromes up to the maximum possible value (5000)
2. For each number in the input array, find the closest palindrome
3. Calculate the absolute difference as the minimum operations
4. Return the array of minimum operations

### Steps (The "How")

**2.1 Initialization & Example Setup:**
Let's use the example: `nums = [1,2,4]`
- Precompute palindromes: [1, 3, 5, 7, 9, 15, ...] (numbers with palindromic binary)

**2.2 Start Processing:**
We iterate through each number and find its closest palindrome.

**2.3 Trace Walkthrough:**

| Number | Binary | Closest Palindrome | Operations | Result |
|--------|--------|-------------------|------------|--------|
| 1 | 1 | 1 | |0| = 0 | 0 |
| 2 | 10 | 3 (11) | |2-3| = 1 | 1 |
| 4 | 100 | 3 (11) | |4-3| = 1 | 1 |

Comment on lines +40 to +45
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Fix table formatting and clarify operations expressions

The absolute-value notation in the Operations column introduces extra | characters, breaking the table (and triggering MD056), and the first row’s formula is a bit unclear.

You can avoid both issues by rewriting the Operations cells without | characters:

-| 1 | 1 | 1 | |0| = 0 | 0 |
-| 2 | 10 | 3 (11) | |2-3| = 1 | 1 |
-| 4 | 100 | 3 (11) | |4-3| = 1 | 1 |
+| 1 | 1 | 1 | abs(1-1) = 0 | 0 |
+| 2 | 10 | 3 (11) | abs(2-3) = 1 | 1 |
+| 4 | 100 | 3 (11) | abs(4-3) = 1 | 1 |

This keeps the table well-formed and makes the math explicit.

🧰 Tools
🪛 markdownlint-cli2 (0.18.1)

42-42: Table column count
Expected: 5; Actual: 7; Too many cells, extra data will be missing

(MD056, table-column-count)


43-43: Table column count
Expected: 5; Actual: 7; Too many cells, extra data will be missing

(MD056, table-column-count)


44-44: Table column count
Expected: 5; Actual: 7; Too many cells, extra data will be missing

(MD056, table-column-count)

🤖 Prompt for AI Agents
In explanations/3766/en.md around lines 40–45, the Operations column uses
literal '|' characters for absolute-value notation which breaks the Markdown
table; replace those with a plain, pipe-free expression (e.g., use abs(1-1) = 0,
abs(2-3) = 1, abs(4-3) = 1) and update the first row to explicitly show abs(1-1)
= 0 so the table cells contain no '|' characters and render correctly.

**2.4 Increment and Loop:**
After processing all numbers, we have the results.

**2.5 Return Result:**
The result array is `[0, 1, 1]`, representing the minimum operations for each number.
Loading
Loading