Summary Ranges
LeetCode 228 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Extend consecutive runs.
నేను Summary Ranges (LeetCode 228) ను ఇలా పరిష్కరించాను — Intervals ప్యాటర్న్లోని ఒక సులభం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Walk the sorted list and extend a run while each next number is exactly one more. When the run breaks, write it as 'a->b' (or just 'a' for a single number).
Approach
- 1
start = nums[i].
- 2
Advance while nums[i+1] == nums[i] + 1.
- 3
Record start->end or start.
నేను ఎలా పరిష్కరించాను
Run extensionPythonO(n) time
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
i=0
res=[]
n = len(nums)
while i<n:
start = nums[i]
while i+1<n and nums[i+1]==nums[i]+1:
i+=1
end = nums[i]
if start!=end:
res.append(f"{start}->{end}")
else:
res.append(f"{start}")
i+=1
return resSummary Ranges — తరచూ అడిగే ప్రశ్నలు
Summary Ranges వెనుక ఉన్న intuition ఏమిటి?
Walk the sorted list and extend a run while each next number is exactly one more. When the run breaks, write it as 'a->b' (or just 'a' for a single number).
Summary Ranges (LeetCode 228) ను ఎలా పరిష్కరించాలి?
1. start = nums[i]. 2. Advance while nums[i+1] == nums[i] + 1. 3. Record start->end or start.
Summary Ranges యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(1) extra. (Accepted approach: Run extension.)
Summary Ranges లో సాధారణ పొరపాట్లు ఏమిటి?
Empty input returns [].