Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 56 · Sorting

Merge Intervals

LeetCode 56 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Sort by start; extend or append.

நடுத்தரம்ArraySortingQuicksort
LeetCode இல் திற ↗

நான் 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. 1

    Sort intervals by start.

  2. 2

    If merged is empty or the start is beyond the last end, append.

  3. 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.