To summarize ranges in a sorted array, we can identify segments of consecutive numbers. Whenever a gap occurs between two numbers, it marks the end of the current range
https://leetcode.com/problems/summary-ranges/description/
We iterate through the array while keeping track of the start of the current range using a variable s.By appending float('inf') to the list, we ensure the final range is processed without requiring additional checks after the loop
At each step, we check if nums[i] - nums[i-1] > 1, which means the consecutive sequence has ended
We then:
nums[i-1]from nums[i]If the start and end of the range are the same, we store it as a single number. Otherwise, we use the "start->end" format
— We go through the list once
— for storing the resulting list of summary strings
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
nums.append(float('inf'))
a=[]
s=nums[0]
for i in range(1,len(nums)):
if nums[i]-nums[i-1]>1:
e=nums[i-1]
if s==e: itv=str(s)
else: itv=str(s)+"->"+str(e)
a.append(itv)
s=nums[i]
return a