Given a sorted integer array nums
, return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums
is covered by exactly one of the ranges, and there is no integer x
such that x
is in one of the ranges but not in nums
.
Each range [a,b]
in the list should be output as:
a
!= b
a
== b
def summaryRanges(nums):
ranges = []
if not nums:
return ranges
start = nums[0]
for i in range(1, len(nums)):
# Check if the current number is not consecutive
if nums[i] != nums[i-1] + 1:
# If the start number is the same as the previous number
if start == nums[i-1]:
ranges.append(f"{start}")
else:
ranges.append(f"{start}->{nums[i-1]}")
# Update the start to the current number
start = nums[i]
# Handle the last range
if start == nums[-1]:
ranges.append(f"{start}")
else:
ranges.append(f"{start}->{nums[-1]}")
return ranges
# Example usage:
nums = [0,1,2,4,5,7]
print(summaryRanges(nums)) # Output: ["0->2", "4->5", "7"]
nums = [0,2,3,4,6,8,9]
print(summaryRanges(nums)) # Output: ["0", "2->4", "6", "8->9"]
ranges
to store the result.nums
is empty, return the empty list.start
and the previous number.ranges
list.start
to the current number.ranges
list.The time complexity of this solution is (O(n)), where (n) is the number of elements in the input array nums
. This is because we are iterating through the list once, performing constant-time operations within the loop.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?