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.