Insert Interval
LeetCode 57 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Three phases: before, overlap-merge, after.
நான் Insert Interval (LeetCode 57) ஐ இப்படித் தீர்த்தேன் — Intervals பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
The intervals are sorted and disjoint. Copy everything that ends before the new interval starts, merge everything that overlaps it into one, then copy the rest.
Approach
- 1
Append intervals ending before newInterval starts.
- 2
While intervals start before newInterval ends, widen newInterval.
- 3
Append the merged interval, then the remainder.
நான் எப்படித் தீர்த்தேன்
Three-phase sweepPythonO(n) time
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
#1,3 ->new interval 4,5 -> insert - 3<4
#1,3 ->new interval 2,5 -> merge 1<=5 - > start<=new_interval_end
res=[]
i=0
n = len(intervals)
merged = []
#no overlaps before merging
while i<n and intervals[i][1]<newInterval[0]:
merged.append(intervals[i])
i+=1
#intervals after mering
while i<n and intervals[i][0]<=newInterval[1]:
newInterval[0]=min(intervals[i][0],newInterval[0])
newInterval[1]=max(intervals[i][1],newInterval[1])
i+=1
merged.append(newInterval)
#no overlapping intervals after merging
while i<n:
merged.append(intervals[i])
i+=1
return mergedInsert Interval — அடிக்கடி கேட்கப்படும் கேள்விகள்
Insert Interval பின்னாலுள்ள intuition என்ன?
The intervals are sorted and disjoint. Copy everything that ends before the new interval starts, merge everything that overlaps it into one, then copy the rest.
Insert Interval (LeetCode 57) ஐ எப்படித் தீர்ப்பது?
1. Append intervals ending before newInterval starts. 2. While intervals start before newInterval ends, widen newInterval. 3. Append the merged interval, then the remainder.
Insert Interval இன் time மற்றும் space complexity என்ன?
Time: O(n). Space: O(n). (Accepted approach: Three-phase sweep.)
Insert Interval இல் பொதுவான தவறுகள் என்ன?
Touching intervals ([1,2] and [2,3]) overlap.