You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Solved LeetCode 1520 using interval-closure expansion and right-endpoint greedy selection to maximize non-overlapping substrings containing all occurrences of their characters with runtime = 31ms.
d's span [1,6] contains 'a' at indices 0 and 7 -> expand d to [0,7].
49
+
Now every character inside [0,7] (a,d,e,f) is fully contained.
50
+
51
+
3. Sort the closed intervals by right endpoint ascending, and for equal right endpoints by left endpoint DESCENDING (shortest first).
52
+
This ordering is critical for the greedy to work.
53
+
54
+
4. Greedily scan: keep `end` = end of last chosen interval.
55
+
If a segment's left > end, it doesn't overlap anything chosen so far, so take it and update end = its right.
56
+
57
+
Why greedy works:
58
+
Sorting by right endpoint ascending ensures that when we pick a segment, it finishes as early as possible, leaving maximum room for subsequent picks.
59
+
The left-descending tie-break ensures that among segments with the same end, the one that starts later (i.e. shorter, less likely to conflict with previously-chosen segments) is considered first — though in practice the count is the same.
- Output list holds at most 26 substrings (one per distinct character).
169
+
170
+
Key Observation:
171
+
Each character's minimal valid substring is determined by its first and last occurrence, but this span may be forced to grow to contain other characters' full spans , hence the closure/expansion step.
172
+
Once intervals are closed, sorting by right endpoint and greedily picking non-overlapping ones yields the maximum count, because finishing early always leaves more room.
0 commit comments