Skip to content

Commit 2cd9188

Browse files
committed
Missed-problems sweep: 27 more pages — Sqrt, Split Array Largest Sum, Regex Matching, Delete Ops, Remove Dups, Pascal, Robot Bounded, Increasing Triplet, Copy List w/ Random, Swap Pairs, Reverse K Groups, Populate Next Right, Max Area Island, Pacific Atlantic, Merge K Lists, Asteroid Collision, Stock Span, atoi, Text Justification, Design HashMap, Group Shifted Strings, Destroying Asteroids, Find All Anagrams, Divide Two Ints, Articulation Points, BST Iterator
1 parent 9568735 commit 2cd9188

41 files changed

Lines changed: 6197 additions & 0 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CodingInterviewFightClub/src/SUMMARY.md‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@
2828
- [1.15 Search A 2D Matrix](ch01-binary-search/search-a-2d-matrix.md)
2929
- [1.16 Search In Rotated Sorted Array II](ch01-binary-search/search-in-rotated-sorted-array-ii.md)
3030
- [1.17 Search In Rotated Sorted Array](ch01-binary-search/search-in-rotated-sorted-array.md)
31+
- [1.19 Sqrt(x)](ch01-binary-search/sqrt-x.md)
32+
- [1.20 Split Array Largest Sum](ch01-binary-search/split-array-largest-sum.md)
3133
- [1.18 Search Insert Position](ch01-binary-search/search-insert-position.md)
3234
- [1.19 Single Element In A Sorted Array](ch01-binary-search/single-element-in-a-sorted-array.md)
3335
- [1.20 Valley Element](ch01-binary-search/valley-element.md)
@@ -57,6 +59,8 @@
5759
- [2.20 Burst Balloons](ch02-dynamic-programming/burst-balloons.md)
5860
- [2.21 Target Sum](ch02-dynamic-programming/target-sum.md)
5961
- [2.22 Interleaving String](ch02-dynamic-programming/interleaving-string.md)
62+
- [2.23 Regular Expression Matching](ch02-dynamic-programming/regular-expression-matching.md)
63+
- [2.24 Delete Operations For Two Strings](ch02-dynamic-programming/delete-operations-for-two-strings.md)
6064

6165
- [3. Arrays, Two Pointers & Matrices](ch03-arrays/index.md)
6266
- [3.0 Pattern Primer: Two Pointers & The Sorted-Array Dance](ch03-arrays/pattern-primer.md)
@@ -77,6 +81,10 @@
7781
- [3.15 Find Pivot Index](ch03-arrays/find-pivot-index.md)
7882
- [3.16 Shuffle An Array](ch03-arrays/shuffle-an-array.md)
7983
- [3.17 Convex Hull (Erect The Fence)](ch03-arrays/convex-hull.md)
84+
- [3.18 Remove Duplicates From Sorted Array](ch03-arrays/remove-duplicates-from-sorted-array.md)
85+
- [3.19 Pascal's Triangle](ch03-arrays/pascals-triangle.md)
86+
- [3.20 Robot Bounded In Circle](ch03-arrays/robot-bounded-in-circle.md)
87+
- [3.21 Increasing Triplet Subsequence](ch03-arrays/increasing-triplet-subsequence.md)
8088
- [2.12 Closest Subsequence Sum](ch02-dynamic-programming/closest-subsequence-sum.md)
8189

8290
- [4. Linked Lists](ch04-linked-lists/index.md)
@@ -90,6 +98,9 @@
9098
- [4.7 Add Two Numbers](ch04-linked-lists/add-two-numbers.md)
9199
- [4.8 Middle Of The Linked List](ch04-linked-lists/middle-of-the-linked-list.md)
92100
- [4.9 Palindrome Linked List](ch04-linked-lists/palindrome-linked-list.md)
101+
- [4.10 Copy List With Random Pointer](ch04-linked-lists/copy-list-with-random-pointer.md)
102+
- [4.11 Swap Nodes In Pairs](ch04-linked-lists/swap-nodes-in-pairs.md)
103+
- [4.12 Reverse Nodes In K Groups](ch04-linked-lists/reverse-nodes-in-k-groups.md)
93104

94105
- [5. Trees](ch05-trees/index.md)
95106
- [5.0 Pattern Primer: The Recursive Data Structure](ch05-trees/pattern-primer.md)
@@ -107,6 +118,7 @@
107118
- [5.12 All Nodes Distance K In Binary Tree](ch05-trees/all-nodes-distance-k.md)
108119
- [5.13 Binary Tree ZigZag Level Order](ch05-trees/zigzag-level-order.md)
109120
- [5.14 Count Good Nodes In Binary Tree](ch05-trees/count-good-nodes.md)
121+
- [5.15 Populating Next Right Pointers In Each Node](ch05-trees/populating-next-right-pointers.md)
110122

111123
- [6. Graphs](ch06-graphs/index.md)
112124
- [6.0 Pattern Primer: The Seven Engines](ch06-graphs/pattern-primer.md)
@@ -126,6 +138,8 @@
126138
- [6.14 Rotting Oranges](ch06-graphs/rotting-oranges.md)
127139
- [6.15 Accounts Merge](ch06-graphs/accounts-merge.md)
128140
- [6.16 Surrounded Regions](ch06-graphs/surrounded-regions.md)
141+
- [6.17 Max Area Of Island](ch06-graphs/max-area-of-island.md)
142+
- [6.18 Pacific Atlantic Water Flow](ch06-graphs/pacific-atlantic-water-flow.md)
129143

130144
- [7. Heaps & Priority Queues](ch07-heaps/index.md)
131145
- [7.0 Pattern Primer: The Lazy Sorted Structure](ch07-heaps/pattern-primer.md)
@@ -139,6 +153,7 @@
139153
- [7.8 The Skyline Problem](ch07-heaps/the-skyline-problem.md)
140154
- [7.9 Design Hit Counter](ch07-heaps/design-hit-counter.md)
141155
- [7.10 Longest Happy String](ch07-heaps/longest-happy-string.md)
156+
- [7.11 Merge K Sorted Lists](ch07-heaps/merge-k-sorted-lists.md)
142157

143158
- [8. Stacks & Queues](ch08-stacks/index.md)
144159
- [8.0 Pattern Primer: LIFO, FIFO, and the Monotonic Stack](ch08-stacks/pattern-primer.md)
@@ -154,6 +169,8 @@
154169
- [8.10 Basic Calculator II](ch08-stacks/basic-calculator-ii.md)
155170
- [8.11 Basic Calculator](ch08-stacks/basic-calculator.md)
156171
- [8.12 Basic Calculator III](ch08-stacks/basic-calculator-iii.md)
172+
- [8.13 Asteroid Collision](ch08-stacks/asteroid-collision.md)
173+
- [8.14 Online Stock Span](ch08-stacks/online-stock-span.md)
157174

158175
- [9. Strings](ch09-strings/index.md)
159176
- [9.0 Pattern Primer: The Three Lenses](ch09-strings/pattern-primer.md)
@@ -170,6 +187,8 @@
170187
- [9.11 Valid Palindrome](ch09-strings/valid-palindrome.md)
171188
- [9.12 Count And Say](ch09-strings/count-and-say.md)
172189
- [9.13 Add Strings](ch09-strings/add-strings.md)
190+
- [9.14 String To Integer (atoi)](ch09-strings/string-to-integer-atoi.md)
191+
- [9.15 Text Justification](ch09-strings/text-justification.md)
173192

174193
- [10. Hash Tables & Sets](ch10-hash-tables/index.md)
175194
- [10.0 Pattern Primer: O(1) Lookup, Three Moves](ch10-hash-tables/pattern-primer.md)
@@ -188,6 +207,8 @@
188207
- [10.13 Unique Number Of Occurrences](ch10-hash-tables/unique-number-of-occurrences.md)
189208
- [10.14 Integer To English Words](ch10-hash-tables/integer-to-english-words.md)
190209
- [10.15 Max Points On A Line](ch10-hash-tables/max-points-on-a-line.md)
210+
- [10.16 Design HashMap](ch10-hash-tables/design-hashmap.md)
211+
- [10.17 Group Shifted Strings](ch10-hash-tables/group-shifted-strings.md)
191212

192213
- [11. Greedy](ch11-greedy/index.md)
193214
- [11.0 Pattern Primer: The Local Choice, Defended](ch11-greedy/pattern-primer.md)
@@ -203,6 +224,7 @@
203224
- [11.10 Reorganize String](ch11-greedy/reorganize-string.md)
204225
- [11.11 Minimum Number Of Arrows To Burst Balloons](ch11-greedy/minimum-number-of-arrows-to-burst-balloons.md)
205226
- [11.12 Can Place Flowers](ch11-greedy/can-place-flowers.md)
227+
- [11.13 Destroying Asteroids](ch11-greedy/destroying-asteroids.md)
206228

207229
- [12. Backtracking](ch12-backtracking/index.md)
208230
- [12.0 Pattern Primer: DFS With an Undo Button](ch12-backtracking/pattern-primer.md)
@@ -255,6 +277,7 @@
255277
- [15.8 Permutation In String](ch15-sliding-window/permutation-in-string.md)
256278
- [15.9 Maximum Erasure Value](ch15-sliding-window/maximum-erasure-value.md)
257279
- [15.10 Longest Subarray Of 1s After Deleting One](ch15-sliding-window/longest-subarray-of-ones-after-deleting-one.md)
280+
- [15.11 Find All Anagrams In A String](ch15-sliding-window/find-all-anagrams.md)
258281

259282
- [16. Bit Manipulation](ch16-bit-manipulation/index.md)
260283
- [16.0 Pattern Primer: The Bit Identities](ch16-bit-manipulation/pattern-primer.md)
@@ -266,6 +289,7 @@
266289
- [16.6 Sum Of All Subset XOR Totals](ch16-bit-manipulation/sum-of-all-subset-xor-totals.md)
267290
- [16.7 Smallest Number With All Set Bits](ch16-bit-manipulation/smallest-number-with-all-set-bits.md)
268291
- [16.8 Pow(x, n)](ch16-bit-manipulation/pow-x-n.md)
292+
- [16.9 Divide Two Integers](ch16-bit-manipulation/divide-two-integers.md)
269293

270294
- [17. Advanced Graphs](ch17-advanced-graphs/index.md)
271295
- [17.0 Pattern Primer: Flow, Matching, MST, and State-Space BFS](ch17-advanced-graphs/pattern-primer.md)
@@ -282,6 +306,7 @@
282306
- [17.11 Walls And Gates](ch17-advanced-graphs/walls-and-gates.md)
283307
- [17.12 Bus Routes](ch17-advanced-graphs/bus-routes.md)
284308
- [17.13 Minimum Genetic Mutations](ch17-advanced-graphs/minimum-genetic-mutations.md)
309+
- [17.14 Find Articulation Points](ch17-advanced-graphs/find-articulation-points.md)
285310

286311
- [18. Design & Caches](ch18-design-caches/index.md)
287312
- [18.0 Pattern Primer: Composing Structures](ch18-design-caches/pattern-primer.md)
@@ -295,6 +320,7 @@
295320
- [18.8 Weighted Reservoir Sampling](ch18-design-caches/weighted-reservoir-sampling.md)
296321
- [18.9 LRU Cache — The Repo's Seven Implementations](ch18-design-caches/lru-cache-variants.md)
297322
- [18.11 My Calendar](ch18-design-caches/my-calendar.md)
323+
- [18.12 BST Iterator](ch18-design-caches/bst-iterator.md)
298324

299325
## Appendix
300326

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
# 1.20 Split Array Largest Sum
2+
3+
> **Source:** [`src/main/kotlin/array/dp/SplitArrayLargestSum.kt`](https://github.com/arpanpathak/AdvancedAlgorithmPatterns/blob/main/src/main/kotlin/array/dp/SplitArrayLargestSum.kt)
4+
> **Pattern:** minimize the max — binary search the answer · **Core page**
5+
6+
## The Problem
7+
8+
Split `nums` into `k` contiguous subarrays minimizing the **largest sum** among them.
9+
10+
- Constraints: $1 \le k \le n \le 1000$.
11+
12+
## Examples
13+
14+
```
15+
Input: nums = [7,2,5,10,8], k = 2 -> Output: 18 ([7,2,5] and [10,8])
16+
Input: nums = [1,2,3,4,5], k = 2 -> Output: 9 ([1,2,3] and [4,5])
17+
```
18+
19+
## Intuition — "minimize the max" is binary-searchable
20+
21+
If a cap `C` can split the array into ≤ k parts each ≤ C, then any larger cap also works — **monotone**. Binary search the smallest feasible cap in `[max(nums), sum(nums)]`:
22+
23+
```
24+
canSplit(C): greedy-pack: walk nums, start a new part whenever the running sum would exceed C.
25+
feasible iff parts ≤ k.
26+
27+
binary search: lo = max(nums), hi = sum(nums)
28+
mid = (lo + hi) / 2
29+
canSplit(mid) ? hi = mid : lo = mid + 1
30+
return lo
31+
```
32+
33+
**Why `max(nums)` as the floor?** No part can hold less than the biggest element — `C < max(nums)` is infeasible by construction. The [1.x](../ch01-binary-search/pattern-primer.md) "answer must lie in [lo, hi]" tightening.
34+
35+
**Why greedy packing for feasibility?** To test a cap, greedily extend the current part as far as possible — any feasible split can be rearranged into the greedy one (exchange argument), so the greedy part count is the *minimum* possible. The repo's memoized DP ([2.x](../ch02-dynamic-programming/pattern-primer.md) `dfs(i, splitsLeft)` over prefix sums) is the exact alternative; the binary search is the canonical LeetCode answer.
36+
37+
## Approach 1 — DP over (index, parts) (the repo's version)
38+
39+
`dfs(i, k)` = min largest sum splitting `nums[i:]` into k parts (prefix-sum lookups, prune when `currentSum > best`): O(n²k).
40+
41+
## Approach 2 — Binary search the answer (optimal)
42+
43+
```kotlin
44+
class SplitArrayLargestSum {
45+
/**
46+
* @param nums input array
47+
* @param k number of subarrays
48+
* @return minimized largest subarray sum
49+
*/
50+
fun splitArray(nums: IntArray, k: Int): Int {
51+
var lo = 0L
52+
var hi = 0L
53+
for (num in nums) { lo = maxOf(lo, num.toLong()); hi += num }
54+
55+
fun canSplit(cap: Long): Boolean {
56+
var parts = 1
57+
var running = 0L
58+
for (num in nums) {
59+
if (running + num > cap) { parts++; running = 0 }
60+
running += num
61+
}
62+
return parts <= k
63+
}
64+
65+
while (lo < hi) {
66+
val mid = lo + (hi - lo) / 2
67+
if (canSplit(mid)) hi = mid
68+
else lo = mid + 1
69+
}
70+
return lo.toInt()
71+
}
72+
}
73+
```
74+
75+
```java
76+
public class SplitArrayLargestSum {
77+
/**
78+
* @param nums input array
79+
* @param k number of subarrays
80+
* @return minimized largest subarray sum
81+
*/
82+
public int splitArray(int[] nums, int k) {
83+
long lo = 0, hi = 0;
84+
for (int num : nums) { lo = Math.max(lo, num); hi += num; }
85+
86+
while (lo < hi) {
87+
long mid = lo + (hi - lo) / 2;
88+
89+
int parts = 1;
90+
long running = 0;
91+
for (int num : nums) {
92+
if (running + num > mid) { parts++; running = 0; }
93+
running += num;
94+
}
95+
96+
if (parts <= k) hi = mid;
97+
else lo = mid + 1;
98+
}
99+
return (int) lo;
100+
}
101+
}
102+
```
103+
104+
```cpp
105+
#include <vector>
106+
#include <algorithm>
107+
108+
class SplitArrayLargestSum {
109+
public:
110+
/**
111+
* @param nums input array
112+
* @param k number of subarrays
113+
* @return minimized largest subarray sum
114+
*/
115+
int splitArray(std::vector<int>& nums, int k) {
116+
long lo = 0, hi = 0;
117+
for (int num : nums) { lo = std::max(lo, (long)num); hi += num; }
118+
119+
while (lo < hi) {
120+
long mid = lo + (hi - lo) / 2;
121+
122+
int parts = 1;
123+
long running = 0;
124+
for (int num : nums) {
125+
if (running + num > mid) { parts++; running = 0; }
126+
running += num;
127+
}
128+
129+
if (parts <= k) hi = mid;
130+
else lo = mid + 1;
131+
}
132+
return (int)lo;
133+
}
134+
};
135+
```
136+
137+
```python
138+
def split_array(nums: list[int], k: int) -> int:
139+
"""
140+
@param nums: input array
141+
@param k: number of subarrays
142+
@return: minimized largest subarray sum
143+
"""
144+
def can_split(cap: int) -> bool:
145+
parts = 1
146+
running = 0
147+
for num in nums:
148+
if running + num > cap:
149+
parts += 1
150+
running = 0
151+
running += num
152+
return parts <= k
153+
154+
lo, hi = max(nums), sum(nums)
155+
while lo < hi:
156+
mid = (lo + hi) // 2
157+
if can_split(mid):
158+
hi = mid
159+
else:
160+
lo = mid + 1
161+
return lo
162+
```
163+
164+
```rust
165+
impl Solution {
166+
/// @param nums input array
167+
/// @param k number of subarrays
168+
/// @return minimized largest subarray sum
169+
pub fn split_array(nums: Vec<i32>, k: i32) -> i32 {
170+
let can_split = |cap: i64| -> bool {
171+
let mut parts = 1i64;
172+
let mut running = 0i64;
173+
for &num in &nums {
174+
if running + num as i64 > cap { parts += 1; running = 0; }
175+
running += num as i64;
176+
}
177+
parts <= k as i64
178+
};
179+
180+
let mut lo = *nums.iter().max().unwrap() as i64;
181+
let mut hi: i64 = nums.iter().map(|&v| v as i64).sum();
182+
183+
while lo < hi {
184+
let mid = lo + (hi - lo) / 2;
185+
if can_split(mid) { hi = mid; } else { lo = mid + 1; }
186+
}
187+
lo as i32
188+
}
189+
}
190+
```
191+
192+
## Dry run
193+
194+
**Input:** `nums = [7,2,5,10,8]`, `k = 2`.
195+
196+
```
197+
lo = max = 10, hi = sum = 32
198+
mid = 21: canSplit(21)? 7+2+5=14, +10=24 > 21 -> new part. [14][10+8=18] = 2 parts ≤ 2 ✓ -> hi=21
199+
mid = 15: 7+2+5=14, +10>15 -> [14][10], 8 -> 3 parts > 2 ✗ -> lo=16
200+
mid = 18: 7+2+5=14, +10>18 -> [14][10], 8: 10+8=18 ≤ 18 -> [14][18] = 2 parts ✓ -> hi=18
201+
mid = 17: 14, +10>17 -> [14][10], 8 -> 3 parts ✗ -> lo=18
202+
lo == hi == 18. Output: 18 ✓
203+
```
204+
205+
The monotone predicate is the crux: cap 18 works (2 parts), cap 17 doesn't (3 parts) — the boundary is exactly the answer. The greedy pack computes the *minimum* part count for each cap, and the search zooms to the smallest feasible cap.
206+
207+
## Complexity
208+
209+
**Time.** O(n) feasibility × O(log Σ) iterations:
210+
211+
$$
212+
T(n) = O(n \log \Sigma)
213+
$$
214+
215+
**Space.** Scalars:
216+
217+
$$
218+
S(n) = O(1)
219+
$$
220+
221+
## Variants & follow-ups
222+
223+
- **Capacity To Ship Packages** ([1.2](capacity-to-ship-packages.md)) — the same "minimize the max with a feasible-cap binary search", with days instead of parts.
224+
- **Koko Eating Bananas** ([1.3](koko-eating-bananas.md)) — the same shape, eating speed instead of cap.
225+
- **Interview follow-up:** "Why is the greedy part count the minimum?" If a cap is feasible with some split, the greedy (extend each part maximally) uses *at most* as many parts — any split's parts can be merged into greedier ones without exceeding the cap. So `greedyParts ≤ any split's parts`; testing `greedyParts ≤ k` decides feasibility exactly.

0 commit comments

Comments
 (0)