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.