Summary Ranges
Problem
You are given a sorted unique 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.
nums = [0,1,2,4,5,7]["0->2","4->5","7"]def summary_ranges(nums):
out = []
i = 0
while i < len(nums):
j = i
while j + 1 < len(nums) and nums[j + 1] == nums[j] + 1:
j += 1
out.append(str(nums[i]) if i == j else f"{nums[i]}->{nums[j]}")
i = j + 1
return out
function summaryRanges(nums) {
const out = [];
let i = 0;
while (i < nums.length) {
let j = i;
while (j + 1 < nums.length && nums[j + 1] === nums[j] + 1) j++;
out.push(i === j ? String(nums[i]) : nums[i] + "->" + nums[j]);
i = j + 1;
}
return out;
}
class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> out = new ArrayList<>();
int i = 0;
while (i < nums.length) {
int j = i;
while (j + 1 < nums.length && nums[j + 1] == nums[j] + 1) j++;
out.add(i == j ? String.valueOf(nums[i]) : nums[i] + "->" + nums[j]);
i = j + 1;
}
return out;
}
}
vector<string> summaryRanges(vector<int>& nums) {
vector<string> out;
int i = 0;
while (i < (int)nums.size()) {
int j = i;
while (j + 1 < (int)nums.size() && nums[j + 1] == nums[j] + 1) ++j;
if (i == j) out.push_back(to_string(nums[i]));
else out.push_back(to_string(nums[i]) + "->" + to_string(nums[j]));
i = j + 1;
}
return out;
}
Explanation
The array is already sorted with unique values, so consecutive runs like 0,1,2 should collapse into one range. The idea is a single pass that groups each consecutive run and prints it.
We use two pointers. Pointer i marks the start of the current run. Pointer j walks forward as long as the next number is exactly one more than the current — that is, while nums[j+1] == nums[j] + 1 — so j stops at the last number of the run.
Once the run ends, we format it: if i == j the run is a single number, so we output just nums[i]; otherwise we output "a->b" using the run's first and last values. Then we jump i to j + 1 to begin the next run.
Example: nums = [0,1,2,4,5,7]. The first run is 0,1,2 giving "0->2". Then 4,5 gives "4->5". Then 7 stands alone, giving "7". Result: ["0->2","4->5","7"].
Each number is visited once, so this runs in O(n) time with only the output list as extra space.