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.