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 [].