You are given a sorted unique integer array nums
.
A range [a,b]
is the smallest interval that includes every number between a
and b
(inclusive). In this case, if a
!= b
, “a->b” should be returned instead of “a”.
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
.
Input:
nums = [0,1,2,4,5,7]
Output:
["0->2","4->5","7"]
Input:
nums = [0,2,3,4,6,8,9]
Output:
["0","2->4","6","8->9"]
Q: What should we return if the input list is empty? A: Return an empty list.
Q: Are the numbers in the input list always sorted in ascending order? A: Yes, they are always sorted and unique.
Q: Can elements in nums
be negative or are they always non-negative?
A: Elements can be negative.
ranges
and two pointers, start
and end
, to traverse the list.Here’s the C++ code to solve this problem:
#include <vector>
#include <string>
using namespace std;
vector<string> summaryRanges(vector<int>& nums) {
vector<string> ranges;
if (nums.empty()) return ranges;
int n = nums.size();
int start = 0;
for (int i = 1; i <= n; ++i) {
// Check if it's the end of the range
if (i == n || nums[i] != nums[i - 1] + 1) {
// Add the range to the result
if (start == i - 1) {
ranges.push_back(to_string(nums[start]));
} else {
ranges.push_back(to_string(nums[start]) + "->" + to_string(nums[i - 1]));
}
// Update start for the next range
start = i;
}
}
return ranges;
}
O(n)
where n
is the number of elements in nums
.
O(1)
for the extra space used, not counting the space needed for the output, which is proportional to the number of ranges created.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?