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.