Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 435 · Intervals

Non-overlapping Intervals

LeetCode 435 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Sort by end; count overlaps with the last kept.

మధ్యస్థంArrayDynamic ProgrammingGreedySorting
LeetCode లో తెరవండి ↗

నేను Non-overlapping Intervals (LeetCode 435) ను ఇలా పరిష్కరించాను — Intervals ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

To keep as many intervals as possible, always keep the one that ends earliest — it leaves the most room for the rest. Sort by end; every interval that starts before the last kept end has to be removed.

Approach

  1. 1

    Sort by end time.

  2. 2

    If start ≥ last end, keep it and update the end.

  3. 3

    Otherwise remove it (count++).

నేను ఎలా పరిష్కరించాను

Greedy by end timePythonO(n log n) time
class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        lastend=-inf
        #sort by end time
        intervals.sort(key=lambda x:x[1])
        ans = 0
        for start,end in intervals:
            if start>=lastend:
                lastend=end
            else:
                ans+=1
        return ans
స్టెప్-త్రూ లోడ్ అవుతోంది…

Non-overlapping Intervals — తరచూ అడిగే ప్రశ్నలు

Non-overlapping Intervals వెనుక ఉన్న intuition ఏమిటి?

To keep as many intervals as possible, always keep the one that ends earliest — it leaves the most room for the rest. Sort by end; every interval that starts before the last kept end has to be removed.

Non-overlapping Intervals (LeetCode 435) ను ఎలా పరిష్కరించాలి?

1. Sort by end time. 2. If start ≥ last end, keep it and update the end. 3. Otherwise remove it (count++).

Non-overlapping Intervals యొక్క time, space complexity ఎంత?

Time: O(n log n). Space: O(1). (Accepted approach: Greedy by end time.)

Non-overlapping Intervals లో సాధారణ పొరపాట్లు ఏమిటి?

Sorting by start instead needs extra logic to keep the smaller end.