Problem
You are given a sorted unique integer array nums
.
A range [a,b]
is the set of all integers from a
to b
(inclusive).
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"
ifa != b
"a"
ifa == b
Examples
Example 1:
Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The ranges are:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"
Example 2:
Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: The ranges are:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"
Solution
Method 1 - Iteration
- Initialization: Start with an empty list to store the result and traverse through the given
nums
array. - Range Detection: For each number, if it starts a new range or continues an existing range, manage it accordingly.
- Range Conclusion: If a gap or the end of the array is encountered, conclude the current range and add it to the result list.
- Result Formatting: If the start and end of a range are the same, add it as a single number; otherwise, format it as a range
"a->b"
.
Code
Java
class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> ans = new ArrayList<>();
if (nums.length == 0) return ans;
int start = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i - 1] + 1) {
if (start == nums[i - 1]) {
ans.add(String.valueOf(start));
} else {
ans.add(start + "->" + nums[i - 1]);
}
start = nums[i];
}
}
// Add the last range
if (start == nums[nums.length - 1]) {
ans.add(String.valueOf(start));
} else {
ans.add(start + "->" + nums[nums.length - 1]);
}
return ans;
}
}
Python
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
ans: List[str] = []
if not nums:
return ans
start: int = nums[0]
for i in range(1, len(nums)):
if nums[i] != nums[i - 1] + 1:
if start == nums[i - 1]:
ans.append(f"{start}")
else:
ans.append(f"{start}->{nums[i - 1]}")
start = nums[i]
# Add the last range
if start == nums[-1]:
ans.append(f"{start}")
else:
ans.append(f"{start}->{nums[-1]}")
return ans
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of thenums
array, as we only iterate through the array once. - 🧺 Space complexity:
O(1)
for extra space, not considering the output list.