Skip to content

Commit 0e8f1db

Browse files
Merge pull request #116 from romankurnovskii/problems-3606-2627-2807-1769-239-2161-2181-2044-1038-2433-2125-2657-2265-1828
Add solutions and explanations for problems 3606, 2807, 1769, 239, 2161, 2181, 2044, 1038, 2433, 2125, 2657, 2265, 1828
2 parents 2d22bd3 + f5d4664 commit 0e8f1db

File tree

27 files changed

+962
-143
lines changed

27 files changed

+962
-143
lines changed

explanations/1038/en.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
## Explanation
2+
3+
### Strategy
4+
5+
**Constraints & Edge Cases**
6+
7+
* **Input Size:** The number of nodes is in the range `[1, 100]`, and node values are between 0 and 100.
8+
* **Time Complexity:** O(n) - We traverse each node exactly once in reverse inorder.
9+
* **Space Complexity:** O(h) - The recursion stack uses space proportional to the height of the tree, where h is at most n.
10+
* **Edge Case:** A tree with a single node returns itself with the same value.
11+
12+
**High-level approach**
13+
We perform a reverse inorder traversal (right, root, left) of the BST. This visits nodes in descending order. As we traverse, we accumulate the sum of all values we've seen and update each node's value to be the sum of itself and all greater values.
14+
15+
**Brute force vs. optimized strategy**
16+
17+
* **Brute Force:** Collect all values, sort them, and update nodes - but this requires extra space.
18+
* **Optimized Strategy:** Use reverse inorder traversal to visit nodes in descending order naturally, updating values in-place.
19+
20+
**Decomposition**
21+
22+
1. **Initialize Accumulator:** Create a variable to track the running sum of all values seen.
23+
2. **Reverse Inorder Traversal:** Traverse right subtree first, then process current node, then left subtree.
24+
3. **Update Node Value:** Add current node's value to the accumulator and update the node.
25+
4. **Continue Traversal:** Process all nodes in descending order.
26+
27+
### Steps
28+
29+
1. **Initialization & Example Setup:**
30+
Let's say we have a BST: `[4, 1, 6, 0, 2, 5, 7, null, null, null, 3, null, null, null, 8]`
31+
We initialize `total = 0`.
32+
33+
2. **Start Traversal:**
34+
We begin reverse inorder traversal (right, root, left).
35+
36+
3. **Trace Walkthrough:**
37+
38+
| Node Value | Total Before | Total After | Node Updated To |
39+
|------------|--------------|-------------|-----------------|
40+
| 8 | 0 | 8 | 8 |
41+
| 7 | 8 | 15 | 15 |
42+
| 6 | 15 | 21 | 21 |
43+
| 5 | 21 | 26 | 26 |
44+
| 4 | 26 | 30 | 30 |
45+
| 3 | 30 | 33 | 33 |
46+
| 2 | 33 | 35 | 35 |
47+
| 1 | 35 | 36 | 36 |
48+
| 0 | 36 | 36 | 36 |
49+
50+
4. **Result:**
51+
The tree is updated in-place with new values.
52+
53+
5. **Return Result:**
54+
Return the modified root of the tree.
55+

explanations/1769/en.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
## Explanation
2+
3+
### Strategy
4+
5+
**Constraints & Edge Cases**
6+
7+
* **Input Size:** The length of boxes string `n` is between 1 and 2000.
8+
* **Time Complexity:** O(n²) - For each of n positions, we iterate through all n boxes to calculate operations.
9+
* **Space Complexity:** O(n) - We create a result array of size n.
10+
* **Edge Case:** If all boxes are empty (all '0'), all positions require 0 operations.
11+
12+
**High-level approach**
13+
For each target position, we calculate the total number of operations needed to move all balls from their current positions to that target. Each ball requires `abs(target_position - current_position)` operations to move.
14+
15+
**Brute force vs. optimized strategy**
16+
17+
* **Brute Force:** For each position, iterate through all boxes and sum the distances. This is O(n²) which is acceptable for n ≤ 2000.
18+
* **Optimized Strategy:** We could use prefix sums to optimize, but for the given constraints, the brute force approach is straightforward and efficient enough.
19+
20+
**Decomposition**
21+
22+
1. **Initialize Result Array:** Create an array of zeros with length n.
23+
2. **For Each Target Position:** Calculate operations needed to move all balls to this position.
24+
3. **Sum Distances:** For each ball (box with '1'), add the absolute distance to the target.
25+
4. **Store Result:** Save the total operations for each position.
26+
27+
### Steps
28+
29+
1. **Initialization & Example Setup:**
30+
Let's say `boxes = "110"` (boxes at positions 0 and 1 have balls).
31+
We create `res = [0, 0, 0]` to store operations for each position.
32+
33+
2. **Start Checking:**
34+
For each position `i` from 0 to n-1, we'll calculate the total operations.
35+
36+
3. **Trace Walkthrough:**
37+
38+
| Target Position | Ball at 0 | Ball at 1 | Total Operations |
39+
|----------------|-----------|-----------|------------------|
40+
| 0 | abs(0-0) = 0 | abs(0-1) = 1 | 0 + 1 = 1 |
41+
| 1 | abs(1-0) = 1 | abs(1-1) = 0 | 1 + 0 = 1 |
42+
| 2 | abs(2-0) = 2 | abs(2-1) = 1 | 2 + 1 = 3 |
43+
44+
4. **Result:**
45+
After processing all positions, `res = [1, 1, 3]`
46+
47+
5. **Return Result:**
48+
Return the result array `[1, 1, 3]`.
49+

explanations/1828/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+
**Constraints & Edge Cases**
6+
7+
* **Input Size:** Points array has up to 500 points, and queries array has up to 500 queries.
8+
* **Time Complexity:** O(q * p) - For each query, we check all points, where q is the number of queries and p is the number of points.
9+
* **Space Complexity:** O(q) - We create a result array of size q.
10+
* **Edge Case:** If a circle has radius 0, only points exactly at the center are inside.
11+
12+
**High-level approach**
13+
For each query circle, we check all points to see if they're inside the circle. A point is inside if the distance from the point to the circle center is less than or equal to the radius.
14+
15+
**Brute force vs. optimized strategy**
16+
17+
* **Brute Force:** For each query, check all points - this is O(q * p) which is acceptable for the given constraints.
18+
* **Optimized Strategy:** We could use spatial data structures, but for the given constraints, the brute force approach is simple and efficient.
19+
20+
**Decomposition**
21+
22+
1. **Process Each Query:** For each circle query, extract center coordinates and radius.
23+
2. **Check Each Point:** For each point, calculate distance to circle center.
24+
3. **Check Inclusion:** If distance squared <= radius squared, the point is inside.
25+
4. **Count Points:** Count how many points are inside each circle.
26+
27+
### Steps
28+
29+
1. **Initialization & Example Setup:**
30+
Let's say `points = [[1,3], [3,3], [5,3], [2,2]]` and `queries = [[2,3,1], [4,3,1], [1,1,2]]`.
31+
We create `res = []`.
32+
33+
2. **Start Processing:**
34+
We iterate through each query.
35+
36+
3. **Trace Walkthrough:**
37+
38+
| Query | Center | Radius | Point | Distance² | Inside? | Count |
39+
|-------|--------|--------|-------|-----------|---------|-------|
40+
| [2,3,1] | (2,3) | 1 | [1,3] | (1-2)²+(3-3)²=1 | Yes | 1 |
41+
| | | | [3,3] | (3-2)²+(3-3)²=1 | Yes | 2 |
42+
| | | | [5,3] | (5-2)²+(3-3)²=9 | No | 2 |
43+
| | | | [2,2] | (2-2)²+(2-3)²=1 | Yes | 3 |
44+
| [4,3,1] | (4,3) | 1 | ... | ... | ... | 2 |
45+
| [1,1,2] | (1,1) | 2 | ... | ... | ... | 2 |
46+
47+
4. **Result:**
48+
After processing all queries, `res = [3, 2, 2]`
49+
50+
5. **Return Result:**
51+
Return the array `[3, 2, 2]`.
52+

explanations/2044/en.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
## Explanation
2+
3+
### Strategy
4+
5+
**Constraints & Edge Cases**
6+
7+
* **Input Size:** Array length is between 1 and 16, and values are between 1 and 10⁵.
8+
* **Time Complexity:** O(2^n * n) - We generate 2^n subsets, and for each subset we compute the OR in O(n) time.
9+
* **Space Complexity:** O(1) - We only use a constant amount of extra space (excluding the output).
10+
* **Edge Case:** When all elements are the same, all non-empty subsets have the same OR value.
11+
12+
**High-level approach**
13+
The maximum possible bitwise OR is achieved by taking the OR of all elements. We generate all non-empty subsets and count how many have this maximum OR value.
14+
15+
**Brute force vs. optimized strategy**
16+
17+
* **Brute Force:** Generate all subsets using bitmasks and check their OR values - this is what we do, and it's efficient for n ≤ 16.
18+
* **Optimized Strategy:** Same approach - use bitmasking to enumerate all 2^n subsets efficiently.
19+
20+
**Decomposition**
21+
22+
1. **Calculate Maximum OR:** Compute the OR of all elements to find the maximum possible OR.
23+
2. **Generate Subsets:** Use bitmasks from 1 to 2^n - 1 to represent all non-empty subsets.
24+
3. **Compute Subset OR:** For each subset, calculate its bitwise OR.
25+
4. **Count Matches:** Count how many subsets have OR equal to the maximum.
26+
27+
### Steps
28+
29+
1. **Initialization & Example Setup:**
30+
Let's say `nums = [3, 1]`.
31+
We calculate `max_or = 3 | 1 = 3`.
32+
33+
2. **Start Processing:**
34+
We iterate through all bitmasks from 1 to (1 << n) - 1 = 3.
35+
36+
3. **Trace Walkthrough:**
37+
38+
| Mask (binary) | Subset | OR Value | Match? |
39+
|---------------|--------|----------|--------|
40+
| 01 | [3] | 3 | Yes |
41+
| 10 | [1] | 1 | No |
42+
| 11 | [3, 1] | 3 | Yes |
43+
44+
4. **Result:**
45+
We count 2 subsets with OR = 3.
46+
47+
5. **Return Result:**
48+
Return `res = 2`.
49+

explanations/2125/en.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
## Explanation
2+
3+
### Strategy
4+
5+
**Constraints & Edge Cases**
6+
7+
* **Input Size:** The bank has dimensions m x n where `1 <= m, n <= 500`.
8+
* **Time Complexity:** O(m * n) - We iterate through all rows to count devices, then through device counts to calculate beams.
9+
* **Space Complexity:** O(m) - We store device counts for each row (at most m rows).
10+
* **Edge Case:** If there's only one row with devices, there are no beams (need at least two rows).
11+
12+
**High-level approach**
13+
We count security devices in each row, skip empty rows, and calculate beams between adjacent non-empty rows. The number of beams between two rows equals the product of device counts in those rows.
14+
15+
**Brute force vs. optimized strategy**
16+
17+
* **Brute Force:** For each device pair, check if there's a clear path - this is O(m² * n²).
18+
* **Optimized Strategy:** Count devices per row, then multiply counts of adjacent rows. This is O(m * n).
19+
20+
**Decomposition**
21+
22+
1. **Count Devices Per Row:** Count '1' characters in each row.
23+
2. **Filter Non-Empty Rows:** Only keep rows with at least one device.
24+
3. **Calculate Beams:** For each pair of adjacent rows, multiply their device counts.
25+
4. **Sum Total:** Add up all beam counts.
26+
27+
### Steps
28+
29+
1. **Initialization & Example Setup:**
30+
Let's say `bank = ["011001", "000000", "010100", "001000"]`.
31+
We create `device_counts = []`.
32+
33+
2. **Start Counting:**
34+
We iterate through each row and count '1' characters.
35+
36+
3. **Trace Walkthrough:**
37+
38+
| Row | Devices | Count | Action |
39+
|-----|---------|-------|--------|
40+
| "011001" | 3 | 3 | Add to device_counts |
41+
| "000000" | 0 | 0 | Skip (empty row) |
42+
| "010100" | 2 | 2 | Add to device_counts |
43+
| "001000" | 1 | 1 | Add to device_counts |
44+
45+
After counting: `device_counts = [3, 2, 1]`
46+
47+
4. **Calculate Beams:**
48+
- Between rows 0 and 1: 3 * 2 = 6 beams
49+
- Between rows 1 and 2: 2 * 1 = 2 beams
50+
- Total: 6 + 2 = 8 beams
51+
52+
5. **Return Result:**
53+
Return `res = 8`.
54+

explanations/2161/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+
**Constraints & Edge Cases**
6+
7+
* **Input Size:** Array length can be up to 10⁵, and values can range from -10⁶ to 10⁶.
8+
* **Time Complexity:** O(n) - We make a single pass through the array to partition elements.
9+
* **Space Complexity:** O(n) - We create three lists to store elements (less, equal, greater).
10+
* **Edge Case:** All elements equal to pivot results in returning the original array.
11+
12+
**High-level approach**
13+
We partition the array into three groups: elements less than pivot, elements equal to pivot, and elements greater than pivot. We maintain the relative order within each group, then combine them.
14+
15+
**Brute force vs. optimized strategy**
16+
17+
* **Brute Force:** Sort the array - but this doesn't maintain relative order of elements within groups.
18+
* **Optimized Strategy:** Use three separate lists to collect elements in a single pass, preserving relative order.
19+
20+
**Decomposition**
21+
22+
1. **Create Three Lists:** Initialize lists for elements less than, equal to, and greater than pivot.
23+
2. **Partition Elements:** Iterate through the array and place each element into the appropriate list.
24+
3. **Combine Lists:** Concatenate the three lists in order: less, equal, greater.
25+
26+
### Steps
27+
28+
1. **Initialization & Example Setup:**
29+
Let's say `nums = [9, 12, 5, 10, 14, 3, 10]` and `pivot = 10`.
30+
We create three empty lists: `less = []`, `equal = []`, `greater = []`.
31+
32+
2. **Start Processing:**
33+
We iterate through each element in `nums`.
34+
35+
3. **Trace Walkthrough:**
36+
37+
| Element | Comparison | Action | less | equal | greater |
38+
|---------|-------------|--------|------|-------|---------|
39+
| 9 | 9 < 10 | Add to less | [9] | [] | [] |
40+
| 12 | 12 > 10 | Add to greater | [9] | [] | [12] |
41+
| 5 | 5 < 10 | Add to less | [9, 5] | [] | [12] |
42+
| 10 | 10 == 10 | Add to equal | [9, 5] | [10] | [12] |
43+
| 14 | 14 > 10 | Add to greater | [9, 5] | [10] | [12, 14] |
44+
| 3 | 3 < 10 | Add to less | [9, 5, 3] | [10] | [12, 14] |
45+
| 10 | 10 == 10 | Add to equal | [9, 5, 3] | [10, 10] | [12, 14] |
46+
47+
4. **Combine:**
48+
`res = less + equal + greater = [9, 5, 3] + [10, 10] + [12, 14] = [9, 5, 3, 10, 10, 12, 14]`
49+
50+
5. **Return Result:**
51+
Return the combined array `[9, 5, 3, 10, 10, 12, 14]`.
52+

explanations/2181/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+
**Constraints & Edge Cases**
6+
7+
* **Input Size:** The number of nodes is in the range `[3, 2 * 10⁵]`, and node values are between 0 and 1000.
8+
* **Time Complexity:** O(n) - We traverse the linked list once, visiting each node exactly once.
9+
* **Space Complexity:** O(1) - We only use a constant amount of extra space (excluding the output list).
10+
* **Edge Case:** The list always starts and ends with zero nodes, and there are no two consecutive zeros.
11+
12+
**High-level approach**
13+
We traverse the linked list, summing values between consecutive zero nodes. Each sum becomes a new node in the result list, and we skip the zero nodes.
14+
15+
**Brute force vs. optimized strategy**
16+
17+
* **Brute Force:** Create a new list by collecting values between zeros - this is what we do, and it's optimal.
18+
* **Optimized Strategy:** Same approach - single pass through the list, summing values between zeros.
19+
20+
**Decomposition**
21+
22+
1. **Skip First Zero:** Start from the node after the first zero.
23+
2. **Sum Values:** Accumulate values until we encounter the next zero.
24+
3. **Create Node:** Create a new node with the sum and add it to the result.
25+
4. **Repeat:** Continue until we've processed all nodes.
26+
27+
### Steps
28+
29+
1. **Initialization & Example Setup:**
30+
Let's say we have a linked list: `[0, 3, 1, 0, 4, 5, 2, 0]`
31+
We skip the first zero and start with `current` pointing to node with value 3.
32+
33+
2. **Start Processing:**
34+
We create a dummy node to build the result list: `dummy = ListNode(0)`, `tail = dummy`.
35+
36+
3. **Trace Walkthrough:**
37+
38+
| Current Node | Value | Sum | Action |
39+
|-------------|------|-----|--------|
40+
| 3 | 3 | 3 | Add to sum |
41+
| 1 | 1 | 4 | Add to sum |
42+
| 0 | 0 | - | Create node(4), reset sum |
43+
| 4 | 4 | 4 | Add to sum |
44+
| 5 | 5 | 9 | Add to sum |
45+
| 2 | 2 | 11 | Add to sum |
46+
| 0 | 0 | - | Create node(11), done |
47+
48+
4. **Result:**
49+
After processing, we have a list: `[4, 11]`
50+
51+
5. **Return Result:**
52+
Return `dummy.next` which points to the first merged node.
53+

0 commit comments

Comments
 (0)