Skip to content

Commit 0349164

Browse files
Merge pull request #118 from romankurnovskii/problems-2482-1261-1008-1630-1079-2785-797-237-3271-2637-1605-1551-1347-2326-1823-2221-2120
upd
2 parents c80678c + 3a99b0c commit 0349164

File tree

36 files changed

+1410
-1
lines changed

36 files changed

+1410
-1
lines changed

data/leetcode-problems.json

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25823,5 +25823,21 @@
2582325823
"id": 3772,
2582425824
"link": "https://leetcode.com/problems/maximum-subgraph-score-in-a-tree/",
2582525825
"title": "Maximum Subgraph Score in a Tree"
25826-
}
25826+
},
25827+
"797": {"id": 797, "category": "Graph", "title": "All Paths From Source to Target", "difficulty": "Medium", "link": "https://leetcode.com/problems/all-paths-from-source-to-target/", "tags": []},
25828+
"1008": {"id": 1008, "category": "Tree", "title": "Construct Binary Search Tree from Preorder Traversal", "difficulty": "Medium", "link": "https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/", "tags": []},
25829+
"1079": {"id": 1079, "category": "Backtracking", "title": "Letter Tile Possibilities", "difficulty": "Medium", "link": "https://leetcode.com/problems/letter-tile-possibilities/", "tags": []},
25830+
"1261": {"id": 1261, "category": "Tree", "title": "Find Elements in a Contaminated Binary Tree", "difficulty": "Medium", "link": "https://leetcode.com/problems/find-elements-in-a-contaminated-binary-tree/", "tags": []},
25831+
"1630": {"id": 1630, "category": "Array", "title": "Arithmetic Subarrays", "difficulty": "Medium", "link": "https://leetcode.com/problems/arithmetic-subarrays/", "tags": []},
25832+
"2110": {"id": 2110, "category": "Array", "title": "Number of Smooth Descent Periods of a Stock", "difficulty": "Medium", "link": "https://leetcode.com/problems/number-of-smooth-descent-periods-of-a-stock/", "tags": []},
25833+
"237": {"id": 237, "category": "Linked List", "title": "Delete Node in a Linked List", "difficulty": "Medium", "link": "https://leetcode.com/problems/delete-node-in-a-linked-list/", "tags": []},
25834+
"2482": {"id": 2482, "category": "Matrix", "title": "Difference Between Ones and Zeros in Row and Column", "difficulty": "Medium", "link": "https://leetcode.com/problems/difference-between-ones-and-zeros-in-row-and-column/", "tags": []},
25835+
"2785": {"id": 2785, "category": "String", "title": "Sort Vowels in a String", "difficulty": "Medium", "link": "https://leetcode.com/problems/sort-vowels-in-a-string/", "tags": []},
25836+
"1347": {"id": 1347, "category": "String", "title": "Minimum Number of Steps to Make Two Strings Anagram", "difficulty": "Medium", "link": "https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/", "tags": []},
25837+
"2326": {"id": 2326, "category": "Matrix", "title": "Spiral Matrix IV", "difficulty": "Medium", "link": "https://leetcode.com/problems/spiral-matrix-iv/", "tags": []},
25838+
"1823": {"id": 1823, "category": "Math", "title": "Find the Winner of the Circular Game", "difficulty": "Medium", "link": "https://leetcode.com/problems/find-the-winner-of-the-circular-game/", "tags": []},
25839+
"2120": {"id": 2120, "category": "Simulation", "title": "Execution of All Suffix Instructions Staying in a Grid", "difficulty": "Medium", "link": "https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/", "tags": []},
25840+
"2221": {"id": 2221, "category": "Array", "title": "Find Triangular Sum of an Array", "difficulty": "Medium", "link": "https://leetcode.com/problems/find-triangular-sum-of-an-array/", "tags": []},
25841+
"1605": {"id": 1605, "category": "Matrix", "title": "Find Valid Matrix Given Row and Column Sums", "difficulty": "Medium", "link": "https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/", "tags": []},
25842+
"1551": {"id": 1551, "category": "Math", "title": "Minimum Operations to Make Array Equal", "difficulty": "Medium", "link": "https://leetcode.com/problems/minimum-operations-to-make-array-equal/", "tags": []}
2582725843
}

explanations/1008/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
4+
5+
**Restate the problem**
6+
Given preorder traversal of a BST, reconstruct the tree.
7+
8+
**1.1 Constraints & Complexity**
9+
- **Input Size:** up to 100 nodes.
10+
- **Time Complexity:** O(n) using a stack to place nodes.
11+
- **Space Complexity:** O(n) for the stack/tree nodes.
12+
- **Edge Case:** Single-node preorder list.
13+
14+
**1.2 High-level approach**
15+
Iterate preorder; use a stack of ancestors. Each value smaller than stack top goes left; otherwise pop until finding parent, then attach right.
16+
![BST reconstruction from preorder](https://assets.leetcode.com/static_assets/public/images/LeetCode_logo.png)
17+
18+
**1.3 Brute force vs. optimized strategy**
19+
- **Brute Force:** Insert each value via BST insert — still O(n²) worst case (sorted input).
20+
- **Optimized:** Monotonic stack to place nodes in O(n).
21+
22+
**1.4 Decomposition**
23+
1. Create root from first value; push to stack.
24+
2. For each next value:
25+
- If value < stack top, set as left child of top.
26+
- Else pop until stack empty or top > value; last popped is parent; attach as right child.
27+
3. Push new node to stack.
28+
4. Return root.
29+
30+
### Steps
31+
32+
**2.1 Initialization & Example Setup**
33+
Example: `[8,5,1,7,10,12]`; root = 8, stack = [8].
34+
35+
**2.2 Start Checking**
36+
Process each value, updating stack and children.
37+
38+
**2.3 Trace Walkthrough**
39+
| val | Stack before | Action | Child |
40+
|-----|--------------|---------------------------------|--------|
41+
| 5 | [8] | 5 < 8 → left of 8 | left |
42+
| 1 | [8,5] | 1 < 5 → left of 5 | left |
43+
| 7 | [8,5,1] | pop 1,5 (last popped=5) → right | right |
44+
| 10 | [8,7] | pop 7,8 (last popped=8) → right | right |
45+
| 12 | [10] | pop none → right of 10 | right |
46+
47+
**2.4 Increment and Loop**
48+
Continue until all preorder values are attached.
49+
50+
**2.5 Return Result**
51+
Root of the constructed BST.
52+

explanations/1079/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
4+
5+
**Restate the problem**
6+
Count all non-empty sequences that can be formed from the multiset of tiles (letters), respecting available counts.
7+
8+
**1.1 Constraints & Complexity**
9+
- **Input Size:** `1 <= len(tiles) <= 7`.
10+
- **Time Complexity:** O(n! * n) in worst case (backtracking over permutations), acceptable for n <= 7.
11+
- **Space Complexity:** O(n) recursion depth + O(1) counts.
12+
- **Edge Case:** Single tile → exactly 1 sequence.
13+
14+
**1.2 High-level approach**
15+
Use backtracking with frequency counts; at each step, pick a letter with remaining count, decrement, recurse, then restore.
16+
![Backtracking over letter counts](https://assets.leetcode.com/static_assets/public/images/LeetCode_logo.png)
17+
18+
**1.3 Brute force vs. optimized strategy**
19+
- **Brute Force:** Generate all permutations with duplicates and then deduplicate — costly.
20+
- **Optimized:** Use counts to avoid generating identical branches; count as we go.
21+
22+
**1.4 Decomposition**
23+
1. Build frequency map of letters.
24+
2. DFS: for each letter with count > 0, use it (res++), decrement, recurse, restore.
25+
3. Sum all counts encountered.
26+
4. Return `res`.
27+
28+
### Steps
29+
30+
**2.1 Initialization & Example Setup**
31+
Example: `tiles = "AAB"`; counts: A:2, B:1, `res=0`.
32+
33+
**2.2 Start Checking**
34+
Try each available letter, recurse with updated counts.
35+
36+
**2.3 Trace Walkthrough**
37+
| Path | Counts after pick | res increment | Notes |
38+
|---------|-------------------|---------------|--------------|
39+
| A | A:1,B:1 | +1 | recurse more |
40+
| AA | A:0,B:1 | +1 | recurse |
41+
| AAB | A:0,B:0 | +1 | dead end |
42+
| AB | A:1,B:0 | +1 | recurse |
43+
| ... | ... | ... | ... |
44+
45+
**2.4 Increment and Loop**
46+
Each pick adds 1 to `res` (for the new sequence) before deeper recursion.
47+
48+
**2.5 Return Result**
49+
Final `res = 8` for the example.
50+

explanations/1261/en.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
## Explanation
2+
3+
### Strategy
4+
5+
**Restate the problem**
6+
Recover a contaminated binary tree where original root was 0 and children follow `left = 2*x+1`, `right = 2*x+2`. Support queries to check if a target value exists.
7+
8+
**1.1 Constraints & Complexity**
9+
- **Input Size:** Up to `1e4` nodes, height <= 20.
10+
- **Time Complexity:** O(n) to recover; O(1) average for `find` via set lookup.
11+
- **Space Complexity:** O(n) to store recovered values.
12+
- **Edge Case:** Single-node tree.
13+
14+
**1.2 High-level approach**
15+
DFS from root, assign values by the given formulas, store all in a hash set for O(1) membership.
16+
![Tree recovery with value formulas](https://assets.leetcode.com/static_assets/public/images/LeetCode_logo.png)
17+
18+
**1.3 Brute force vs. optimized strategy**
19+
- **Brute Force:** Recover on every `find`, re-walking the tree — repeated O(n).
20+
- **Optimized:** Recover once, store in a set — O(n) build, O(1) queries.
21+
22+
**1.4 Decomposition**
23+
1. DFS from root with value parameter.
24+
2. Assign `val`, insert into set.
25+
3. Recurse to children with `2*val+1` and `2*val+2`.
26+
4. `find` checks membership in the set.
27+
28+
### Steps
29+
30+
**2.1 Initialization & Example Setup**
31+
Start at root with value 0, empty set.
32+
33+
**2.2 Start Processing**
34+
DFS visits each node, computing and storing values.
35+
36+
**2.3 Trace Walkthrough**
37+
| Node | Assigned val | Action |
38+
|------|--------------|---------------|
39+
| root | 0 | add to set |
40+
| left | 1 | add to set |
41+
| right| 2 | add to set |
42+
43+
**2.4 Increment and Loop**
44+
Continue recursively; each node’s children follow the formula.
45+
46+
**2.5 Return Result**
47+
`find(target)` returns `target in set`.
48+

explanations/1347/en.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
## Explanation
2+
3+
### Strategy
4+
5+
**Restate the problem**
6+
Given two equal-length lowercase strings `s` and `t`, find the minimum number of character replacements in `t` to make it an anagram of `s`.
7+
8+
**1.1 Constraints & Complexity**
9+
- **Input Size:** up to 5×10^4 characters.
10+
- **Time Complexity:** O(n) to count frequencies.
11+
- **Space Complexity:** O(1) since alphabet size is fixed (26).
12+
- **Edge Case:** Already anagrams → 0 steps.
13+
14+
**1.2 High-level approach**
15+
Count letters in both strings; for each character, if `s` needs more than `t` has, that deficit contributes to the answer.
16+
![Frequency gap guiding replacements](https://assets.leetcode.com/static_assets/public/images/LeetCode_logo.png)
17+
18+
**1.3 Brute force vs. optimized strategy**
19+
- **Brute Force:** Try all replacement combinations — exponential.
20+
- **Optimized:** Frequency difference — O(n), straightforward.
21+
22+
**1.4 Decomposition**
23+
1. Count frequencies of `s` and `t`.
24+
2. For each letter, compute `max(0, count_s - count_t)` and sum.
25+
3. That sum is the number of replacements needed in `t`.
26+
4. Return the sum.
27+
28+
### Steps
29+
30+
**2.1 Initialization & Example Setup**
31+
Example: `s="leetcode"`, `t="practice"`.
32+
33+
**2.2 Start Checking**
34+
Build `count_s`, `count_t`.
35+
36+
**2.3 Trace Walkthrough**
37+
| Char | count_s | count_t | deficit (if s needs more) |
38+
|------|---------|---------|----------------------------|
39+
| e | 3 | 1 | +2 |
40+
| l | 1 | 0 | +1 |
41+
| t | 1 | 1 | 0 |
42+
| c | 1 | 2 | 0 |
43+
| o | 1 | 0 | +1 |
44+
| d | 1 | 0 | +1 |
45+
| ... | ... | ... | ... |
46+
Total = 5.
47+
48+
**2.4 Increment and Loop**
49+
Sum deficits over all 26 letters.
50+
51+
**2.5 Return Result**
52+
Return the total replacements (5 in the example).
53+

explanations/1551/en.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
## Explanation
2+
3+
### Strategy
4+
5+
**Restate the problem**
6+
Array is `[1,3,5,...,2n-1]`; in one operation, decrement one element and increment another. Find min operations to make all elements equal.
7+
8+
**1.1 Constraints & Complexity**
9+
- **Input Size:** `1 <= n <= 1e4`.
10+
- **Time Complexity:** O(n) to sum needed moves.
11+
- **Space Complexity:** O(1).
12+
- **Edge Case:** n=1 → 0 operations.
13+
14+
**1.2 High-level approach**
15+
Target value is `n` (the average). Pair symmetric elements; each pair needs `(target - current_lower)` moves. Sum over first half.
16+
![Balancing around the center value](https://assets.leetcode.com/static_assets/public/images/LeetCode_logo.png)
17+
18+
**1.3 Brute force vs. optimized strategy**
19+
- **Brute Force:** Simulate operations — inefficient.
20+
- **Optimized:** Direct formula using symmetry — O(n).
21+
22+
**1.4 Decomposition**
23+
1. Target = n.
24+
2. For i in [0 .. n/2 - 1], current = 2*i+1.
25+
3. Add `target - current` to result.
26+
4. Return result.
27+
28+
### Steps
29+
30+
**2.1 Initialization & Example Setup**
31+
Example: n=3; array [1,3,5], target=3.
32+
33+
**2.2 Start Checking**
34+
Only i=0 in first half: current=1 → need 2 moves.
35+
36+
**2.3 Trace Walkthrough**
37+
| i | current | target | add to res |
38+
|---|---------|--------|------------|
39+
| 0 | 1 | 3 | 2 |
40+
41+
**2.4 Increment and Loop**
42+
Loop over first half (integer division).
43+
44+
**2.5 Return Result**
45+
Return accumulated moves (2 for n=3).
46+

explanations/1605/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
4+
5+
**Restate the problem**
6+
Construct a non-negative matrix that matches given row sums and column sums.
7+
8+
**1.1 Constraints & Complexity**
9+
- **Input Size:** up to 500 rows/cols.
10+
- **Time Complexity:** O(m*n) greedy fill.
11+
- **Space Complexity:** O(m*n) for the output matrix.
12+
- **Edge Case:** Trivial 1x1 matrix equals the shared sum.
13+
14+
**1.2 High-level approach**
15+
Greedy: at cell (i,j), place `min(rowSum[i], colSum[j])`, then decrement both sums; proceed row by row.
16+
![Greedy fill consuming row/col budgets](https://assets.leetcode.com/static_assets/public/images/LeetCode_logo.png)
17+
18+
**1.3 Brute force vs. optimized strategy**
19+
- **Brute Force:** Search all matrices satisfying sums — exponential.
20+
- **Optimized:** Greedy works because any feasible solution can allocate the minimal remaining budget without violating totals.
21+
22+
**1.4 Decomposition**
23+
1. Initialize `res` with zeros.
24+
2. For each cell `(i,j)`:
25+
- `val = min(rowSum[i], colSum[j])`
26+
- Set `res[i][j] = val`, update rowSum/colSum.
27+
3. Continue until all cells processed.
28+
4. Return `res`.
29+
30+
### Steps
31+
32+
**2.1 Initialization & Example Setup**
33+
Example: `rowSum=[3,8]`, `colSum=[4,7]`, res all zeros.
34+
35+
**2.2 Start Checking**
36+
At (0,0): min(3,4)=3 → res[0][0]=3; rowSum=[0,8], colSum=[1,7].
37+
38+
**2.3 Trace Walkthrough**
39+
| Cell | rowSum before | colSum before | placed | rowSum after | colSum after |
40+
|------|---------------|---------------|--------|--------------|--------------|
41+
| (0,0)| 3 | 4 | 3 | 0 | 1 |
42+
| (0,1)| 0 | 7 | 0 | 0 | 7 |
43+
| (1,0)| 8 | 1 | 1 | 7 | 0 |
44+
| (1,1)| 7 | 7 | 7 | 0 | 0 |
45+
46+
**2.4 Increment and Loop**
47+
Proceed left-to-right, top-to-bottom.
48+
49+
**2.5 Return Result**
50+
Matrix satisfies all row/column sums.
51+

explanations/1630/en.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
## Explanation
2+
3+
### Strategy
4+
5+
**Restate the problem**
6+
For each query `[l_i, r_i]`, decide if the subarray can be rearranged into an arithmetic progression.
7+
8+
**1.1 Constraints & Complexity**
9+
- **Input Size:** `n, m <= 500`.
10+
- **Time Complexity:** O(m * k log k), where k is subarray length (sort each subarray).
11+
- **Space Complexity:** O(k) per query for the sorted copy.
12+
- **Edge Case:** Subarray of length 2 is always arithmetic.
13+
14+
**1.2 High-level approach**
15+
Extract subarray, sort it, ensure consecutive differences are equal.
16+
![Sorted subarray check](https://assets.leetcode.com/static_assets/public/images/LeetCode_logo.png)
17+
18+
**1.3 Brute force vs. optimized strategy**
19+
- **Brute Force:** Try all permutations — factorial blowup.
20+
- **Optimized:** Sorting then one pass diff check — O(k log k).
21+
22+
**1.4 Decomposition**
23+
1. For each query, copy subarray `nums[l:r+1]`.
24+
2. Sort it.
25+
3. Compute common diff = `sorted[1]-sorted[0]`.
26+
4. Verify all consecutive diffs match; if any differ, mark false; else true.
27+
28+
### Steps
29+
30+
**2.1 Initialization & Example Setup**
31+
Example: `nums=[4,6,5,9,3,7]`, query `[0,2]` → subarray `[4,6,5]`.
32+
33+
**2.2 Start Checking**
34+
Sort → `[4,5,6]`, diff = 1.
35+
36+
**2.3 Trace Walkthrough**
37+
| Subarray (sorted) | Step | Diff check | OK? |
38+
|-------------------|------|----------------------|-----|
39+
| [4,5,6] | 4→5 | 1 == diff ||
40+
| | 5→6 | 1 == diff ||
41+
42+
**2.4 Increment and Loop**
43+
Repeat for each query independently.
44+
45+
**2.5 Return Result**
46+
Append boolean for each query into `res`.
47+

0 commit comments

Comments
 (0)