Skip to content
Merged

upd #118

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
18 changes: 17 additions & 1 deletion data/leetcode-problems.json
Original file line number Diff line number Diff line change
Expand Up @@ -25823,5 +25823,21 @@
"id": 3772,
"link": "https://leetcode.com/problems/maximum-subgraph-score-in-a-tree/",
"title": "Maximum Subgraph Score in a Tree"
}
},
"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": []},
"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": []},
"1079": {"id": 1079, "category": "Backtracking", "title": "Letter Tile Possibilities", "difficulty": "Medium", "link": "https://leetcode.com/problems/letter-tile-possibilities/", "tags": []},
"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": []},
"1630": {"id": 1630, "category": "Array", "title": "Arithmetic Subarrays", "difficulty": "Medium", "link": "https://leetcode.com/problems/arithmetic-subarrays/", "tags": []},
"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": []},
"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": []},
"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": []},
"2785": {"id": 2785, "category": "String", "title": "Sort Vowels in a String", "difficulty": "Medium", "link": "https://leetcode.com/problems/sort-vowels-in-a-string/", "tags": []},
"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": []},
"2326": {"id": 2326, "category": "Matrix", "title": "Spiral Matrix IV", "difficulty": "Medium", "link": "https://leetcode.com/problems/spiral-matrix-iv/", "tags": []},
"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": []},
"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": []},
"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": []},
"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": []},
"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": []}
}
52 changes: 52 additions & 0 deletions explanations/1008/en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
## Explanation

### Strategy

**Restate the problem**
Given preorder traversal of a BST, reconstruct the tree.

**1.1 Constraints & Complexity**
- **Input Size:** up to 100 nodes.
- **Time Complexity:** O(n) using a stack to place nodes.
- **Space Complexity:** O(n) for the stack/tree nodes.
- **Edge Case:** Single-node preorder list.

**1.2 High-level approach**
Iterate preorder; use a stack of ancestors. Each value smaller than stack top goes left; otherwise pop until finding parent, then attach right.
![BST reconstruction from preorder](https://assets.leetcode.com/static_assets/public/images/LeetCode_logo.png)

**1.3 Brute force vs. optimized strategy**
- **Brute Force:** Insert each value via BST insert — still O(n²) worst case (sorted input).
- **Optimized:** Monotonic stack to place nodes in O(n).

**1.4 Decomposition**
1. Create root from first value; push to stack.
2. For each next value:
- If value < stack top, set as left child of top.
- Else pop until stack empty or top > value; last popped is parent; attach as right child.
3. Push new node to stack.
4. Return root.

### Steps

**2.1 Initialization & Example Setup**
Example: `[8,5,1,7,10,12]`; root = 8, stack = [8].

**2.2 Start Checking**
Process each value, updating stack and children.

**2.3 Trace Walkthrough**
| val | Stack before | Action | Child |
|-----|--------------|---------------------------------|--------|
| 5 | [8] | 5 < 8 → left of 8 | left |
| 1 | [8,5] | 1 < 5 → left of 5 | left |
| 7 | [8,5,1] | pop 1,5 (last popped=5) → right | right |
| 10 | [8,7] | pop 7,8 (last popped=8) → right | right |
| 12 | [10] | pop none → right of 10 | right |

**2.4 Increment and Loop**
Continue until all preorder values are attached.

**2.5 Return Result**
Root of the constructed BST.

50 changes: 50 additions & 0 deletions explanations/1079/en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
## Explanation

### Strategy

**Restate the problem**
Count all non-empty sequences that can be formed from the multiset of tiles (letters), respecting available counts.

**1.1 Constraints & Complexity**
- **Input Size:** `1 <= len(tiles) <= 7`.
- **Time Complexity:** O(n! * n) in worst case (backtracking over permutations), acceptable for n <= 7.
- **Space Complexity:** O(n) recursion depth + O(1) counts.
- **Edge Case:** Single tile → exactly 1 sequence.

**1.2 High-level approach**
Use backtracking with frequency counts; at each step, pick a letter with remaining count, decrement, recurse, then restore.
![Backtracking over letter counts](https://assets.leetcode.com/static_assets/public/images/LeetCode_logo.png)

**1.3 Brute force vs. optimized strategy**
- **Brute Force:** Generate all permutations with duplicates and then deduplicate — costly.
- **Optimized:** Use counts to avoid generating identical branches; count as we go.

**1.4 Decomposition**
1. Build frequency map of letters.
2. DFS: for each letter with count > 0, use it (res++), decrement, recurse, restore.
3. Sum all counts encountered.
4. Return `res`.

### Steps

**2.1 Initialization & Example Setup**
Example: `tiles = "AAB"`; counts: A:2, B:1, `res=0`.

**2.2 Start Checking**
Try each available letter, recurse with updated counts.

**2.3 Trace Walkthrough**
| Path | Counts after pick | res increment | Notes |
|---------|-------------------|---------------|--------------|
| A | A:1,B:1 | +1 | recurse more |
| AA | A:0,B:1 | +1 | recurse |
| AAB | A:0,B:0 | +1 | dead end |
| AB | A:1,B:0 | +1 | recurse |
| ... | ... | ... | ... |

**2.4 Increment and Loop**
Each pick adds 1 to `res` (for the new sequence) before deeper recursion.

**2.5 Return Result**
Final `res = 8` for the example.

48 changes: 48 additions & 0 deletions explanations/1261/en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
## Explanation

### Strategy

**Restate the problem**
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.

**1.1 Constraints & Complexity**
- **Input Size:** Up to `1e4` nodes, height <= 20.
- **Time Complexity:** O(n) to recover; O(1) average for `find` via set lookup.
- **Space Complexity:** O(n) to store recovered values.
- **Edge Case:** Single-node tree.

**1.2 High-level approach**
DFS from root, assign values by the given formulas, store all in a hash set for O(1) membership.
![Tree recovery with value formulas](https://assets.leetcode.com/static_assets/public/images/LeetCode_logo.png)

**1.3 Brute force vs. optimized strategy**
- **Brute Force:** Recover on every `find`, re-walking the tree — repeated O(n).
- **Optimized:** Recover once, store in a set — O(n) build, O(1) queries.

**1.4 Decomposition**
1. DFS from root with value parameter.
2. Assign `val`, insert into set.
3. Recurse to children with `2*val+1` and `2*val+2`.
4. `find` checks membership in the set.

### Steps

**2.1 Initialization & Example Setup**
Start at root with value 0, empty set.

**2.2 Start Processing**
DFS visits each node, computing and storing values.

**2.3 Trace Walkthrough**
| Node | Assigned val | Action |
|------|--------------|---------------|
| root | 0 | add to set |
| left | 1 | add to set |
| right| 2 | add to set |

**2.4 Increment and Loop**
Continue recursively; each node’s children follow the formula.

**2.5 Return Result**
`find(target)` returns `target in set`.

53 changes: 53 additions & 0 deletions explanations/1347/en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
## Explanation

### Strategy

**Restate the problem**
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`.

**1.1 Constraints & Complexity**
- **Input Size:** up to 5×10^4 characters.
- **Time Complexity:** O(n) to count frequencies.
- **Space Complexity:** O(1) since alphabet size is fixed (26).
- **Edge Case:** Already anagrams → 0 steps.

**1.2 High-level approach**
Count letters in both strings; for each character, if `s` needs more than `t` has, that deficit contributes to the answer.
![Frequency gap guiding replacements](https://assets.leetcode.com/static_assets/public/images/LeetCode_logo.png)

**1.3 Brute force vs. optimized strategy**
- **Brute Force:** Try all replacement combinations — exponential.
- **Optimized:** Frequency difference — O(n), straightforward.

**1.4 Decomposition**
1. Count frequencies of `s` and `t`.
2. For each letter, compute `max(0, count_s - count_t)` and sum.
3. That sum is the number of replacements needed in `t`.
4. Return the sum.

### Steps

**2.1 Initialization & Example Setup**
Example: `s="leetcode"`, `t="practice"`.

**2.2 Start Checking**
Build `count_s`, `count_t`.

**2.3 Trace Walkthrough**
| Char | count_s | count_t | deficit (if s needs more) |
|------|---------|---------|----------------------------|
| e | 3 | 1 | +2 |
| l | 1 | 0 | +1 |
| t | 1 | 1 | 0 |
| c | 1 | 2 | 0 |
| o | 1 | 0 | +1 |
| d | 1 | 0 | +1 |
| ... | ... | ... | ... |
Total = 5.

**2.4 Increment and Loop**
Sum deficits over all 26 letters.

**2.5 Return Result**
Return the total replacements (5 in the example).

46 changes: 46 additions & 0 deletions explanations/1551/en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
## Explanation

### Strategy

**Restate the problem**
Array is `[1,3,5,...,2n-1]`; in one operation, decrement one element and increment another. Find min operations to make all elements equal.

**1.1 Constraints & Complexity**
- **Input Size:** `1 <= n <= 1e4`.
- **Time Complexity:** O(n) to sum needed moves.
- **Space Complexity:** O(1).
- **Edge Case:** n=1 → 0 operations.

**1.2 High-level approach**
Target value is `n` (the average). Pair symmetric elements; each pair needs `(target - current_lower)` moves. Sum over first half.
![Balancing around the center value](https://assets.leetcode.com/static_assets/public/images/LeetCode_logo.png)

**1.3 Brute force vs. optimized strategy**
- **Brute Force:** Simulate operations — inefficient.
- **Optimized:** Direct formula using symmetry — O(n).

**1.4 Decomposition**
1. Target = n.
2. For i in [0 .. n/2 - 1], current = 2*i+1.
3. Add `target - current` to result.
4. Return result.

### Steps

**2.1 Initialization & Example Setup**
Example: n=3; array [1,3,5], target=3.

**2.2 Start Checking**
Only i=0 in first half: current=1 → need 2 moves.

**2.3 Trace Walkthrough**
| i | current | target | add to res |
|---|---------|--------|------------|
| 0 | 1 | 3 | 2 |

**2.4 Increment and Loop**
Loop over first half (integer division).

**2.5 Return Result**
Return accumulated moves (2 for n=3).

51 changes: 51 additions & 0 deletions explanations/1605/en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
## Explanation

### Strategy

**Restate the problem**
Construct a non-negative matrix that matches given row sums and column sums.

**1.1 Constraints & Complexity**
- **Input Size:** up to 500 rows/cols.
- **Time Complexity:** O(m*n) greedy fill.
- **Space Complexity:** O(m*n) for the output matrix.
- **Edge Case:** Trivial 1x1 matrix equals the shared sum.

**1.2 High-level approach**
Greedy: at cell (i,j), place `min(rowSum[i], colSum[j])`, then decrement both sums; proceed row by row.
![Greedy fill consuming row/col budgets](https://assets.leetcode.com/static_assets/public/images/LeetCode_logo.png)

**1.3 Brute force vs. optimized strategy**
- **Brute Force:** Search all matrices satisfying sums — exponential.
- **Optimized:** Greedy works because any feasible solution can allocate the minimal remaining budget without violating totals.

**1.4 Decomposition**
1. Initialize `res` with zeros.
2. For each cell `(i,j)`:
- `val = min(rowSum[i], colSum[j])`
- Set `res[i][j] = val`, update rowSum/colSum.
3. Continue until all cells processed.
4. Return `res`.

### Steps

**2.1 Initialization & Example Setup**
Example: `rowSum=[3,8]`, `colSum=[4,7]`, res all zeros.

**2.2 Start Checking**
At (0,0): min(3,4)=3 → res[0][0]=3; rowSum=[0,8], colSum=[1,7].

**2.3 Trace Walkthrough**
| Cell | rowSum before | colSum before | placed | rowSum after | colSum after |
|------|---------------|---------------|--------|--------------|--------------|
| (0,0)| 3 | 4 | 3 | 0 | 1 |
| (0,1)| 0 | 7 | 0 | 0 | 7 |
| (1,0)| 8 | 1 | 1 | 7 | 0 |
| (1,1)| 7 | 7 | 7 | 0 | 0 |

**2.4 Increment and Loop**
Proceed left-to-right, top-to-bottom.

**2.5 Return Result**
Matrix satisfies all row/column sums.

47 changes: 47 additions & 0 deletions explanations/1630/en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
## Explanation

### Strategy

**Restate the problem**
For each query `[l_i, r_i]`, decide if the subarray can be rearranged into an arithmetic progression.

**1.1 Constraints & Complexity**
- **Input Size:** `n, m <= 500`.
- **Time Complexity:** O(m * k log k), where k is subarray length (sort each subarray).
- **Space Complexity:** O(k) per query for the sorted copy.
- **Edge Case:** Subarray of length 2 is always arithmetic.

**1.2 High-level approach**
Extract subarray, sort it, ensure consecutive differences are equal.
![Sorted subarray check](https://assets.leetcode.com/static_assets/public/images/LeetCode_logo.png)

**1.3 Brute force vs. optimized strategy**
- **Brute Force:** Try all permutations — factorial blowup.
- **Optimized:** Sorting then one pass diff check — O(k log k).

**1.4 Decomposition**
1. For each query, copy subarray `nums[l:r+1]`.
2. Sort it.
3. Compute common diff = `sorted[1]-sorted[0]`.
4. Verify all consecutive diffs match; if any differ, mark false; else true.

### Steps

**2.1 Initialization & Example Setup**
Example: `nums=[4,6,5,9,3,7]`, query `[0,2]` → subarray `[4,6,5]`.

**2.2 Start Checking**
Sort → `[4,5,6]`, diff = 1.

**2.3 Trace Walkthrough**
| Subarray (sorted) | Step | Diff check | OK? |
|-------------------|------|----------------------|-----|
| [4,5,6] | 4→5 | 1 == diff | ✓ |
| | 5→6 | 1 == diff | ✓ |

**2.4 Increment and Loop**
Repeat for each query independently.

**2.5 Return Result**
Append boolean for each query into `res`.

Loading