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