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" if a != b
"a" if a == b
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"
Constraints:
- 0 <= nums.length <= 20
- -231 <= nums[i] <= 231 - 1
- All the values of nums are unique.
- nums is sorted in ascending order.
My Solution
To solve this problem we can keep track of two pointers, start and end. Start and end both point to the start of the array in the beginning. As we iterate through the array, if the current element of the array and end differ by only 1, we just update end and continue. If they don’t, then we need to create a range and add it to our output list. We can do this with StringBuilder to create the string in place. Finally, once we have iterated through the entire array, we add the last range. We also need to keep track of the corner case where nums is an empty array.
Time complexity would be O(n) since we do one pass through the array. Space complexity would be O(n) to maintain the ranges list.
class Solution {
public List<String> summaryRanges(int[] nums) {
int n = nums.length;
List<String> ranges = new ArrayList<>();
if (n == 0) {
return ranges;
}
int start = nums[0];
int end = nums[0];
for (int i = 1; i < n; i++) {
if (nums[i] - 1 == end) {
end = nums[i];
}
else {
StringBuilder s = new StringBuilder();
if (start < end) {
s.append(start);
s.append("->");
s.append(end);
}
else {
s.append(start);
}
ranges.add(s.toString());
start = nums[i];
end = nums[i];
}
}
StringBuilder s = new StringBuilder();
if (start < end) {
s.append(start);
s.append("->");
s.append(end);
}
else {
s.append(start);
}
ranges.add(s.toString());
return ranges;
}
}