Non-overlapping Intervals
LeetCode 435 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Sort by end; count overlaps with the last kept.
मैंने Non-overlapping Intervals (LeetCode 435) ऐसे हल किया — Intervals पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
To keep as many intervals as possible, always keep the one that ends earliest — it leaves the most room for the rest. Sort by end; every interval that starts before the last kept end has to be removed.
Approach
- 1
Sort by end time.
- 2
If start ≥ last end, keep it and update the end.
- 3
Otherwise remove it (count++).
मैंने कैसे हल किया
Greedy by end timePythonO(n log n) time
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
lastend=-inf
#sort by end time
intervals.sort(key=lambda x:x[1])
ans = 0
for start,end in intervals:
if start>=lastend:
lastend=end
else:
ans+=1
return ansNon-overlapping Intervals — अक्सर पूछे जाने वाले प्रश्न
Non-overlapping Intervals के पीछे intuition क्या है?
To keep as many intervals as possible, always keep the one that ends earliest — it leaves the most room for the rest. Sort by end; every interval that starts before the last kept end has to be removed.
Non-overlapping Intervals (LeetCode 435) कैसे हल करें?
1. Sort by end time. 2. If start ≥ last end, keep it and update the end. 3. Otherwise remove it (count++).
Non-overlapping Intervals की time और space complexity क्या है?
Time: O(n log n)। Space: O(1)। (Accepted approach: Greedy by end time।)
Non-overlapping Intervals में आम गलतियाँ क्या हैं?
Sorting by start instead needs extra logic to keep the smaller end.