Merge Intervals
LeetCode 56 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Sort by start; extend or append.
నేను Merge Intervals (LeetCode 56) ను ఇలా పరిష్కరించాను — Sorting ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Sort by start time. Then each interval either starts after the last merged one ends (start a new block) or overlaps it (extend the end). One pass does the job.
Approach
- 1
Sort intervals by start.
- 2
If merged is empty or the start is beyond the last end, append.
- 3
Otherwise extend the last end to max(end, last end).
నేను ఎలా పరిష్కరించాను
Sort + sweepPythonO(n log n) time
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
merged=[]
intervals.sort(key=lambda x:x[0])
for start,end in intervals:
if len(merged)==0 or start>merged[-1][1]:
merged.append([start,end])
else:
merged[-1][1]=max(merged[-1][1],end)
return merged
Merge Intervals — తరచూ అడిగే ప్రశ్నలు
Merge Intervals వెనుక ఉన్న intuition ఏమిటి?
Sort by start time. Then each interval either starts after the last merged one ends (start a new block) or overlaps it (extend the end). One pass does the job.
Merge Intervals (LeetCode 56) ను ఎలా పరిష్కరించాలి?
1. Sort intervals by start. 2. If merged is empty or the start is beyond the last end, append. 3. Otherwise extend the last end to max(end, last end).
Merge Intervals యొక్క time, space complexity ఎంత?
Time: O(n log n). Space: O(n). (Accepted approach: Sort + sweep.)
Merge Intervals లో సాధారణ పొరపాట్లు ఏమిటి?
Touching intervals like [1,4] and [4,5] count as overlapping.