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.