Intuition
Because the array is sorted, consecutive numbers form a run. Walk once: extend the current run while each next number is exactly one more than the last, then emit the run as either 'start' or 'start->end'.
Explanation
Idea
The array is sorted and has no duplicates, so a maximal range is just a run of consecutive integers. We scan once, and whenever nums[i+1] == nums[i] + 1 we're still inside the same run; otherwise the run ends and we record it.
Algorithm
- Start at index
i = 0. - Mark
start = nums[i]. Advanceiwhilenums[i+1] == nums[i] + 1(extend the run). - Now
nums[i]is the run's end. Emitstr(start)ifstart == nums[i], elsestr(start) + "->" + str(nums[i]). - Move past this run (
i += 1) and repeat until the array is consumed.
Worked example: [0,1,2,4,5,7]
start = 0; 1 = 0+1 ✓, 2 = 1+1 ✓, then 4 ≠ 2+1 → run is 0..2 →"0->2".start = 4; 5 = 4+1 ✓, then 7 ≠ 5+1 → run is 4..5 →"4->5".start = 7; no next → single →"7".
Result: ["0->2", "4->5", "7"].
Complexity
- Time: O(n) — one pass.
- Space: O(1) extra (ignoring the output list).
Implementation
import java.util.ArrayList;
import java.util.List;
class Solution {
public String[] summaryRanges(int[] nums) {
List<String> result = new ArrayList<>();
int i = 0, n = nums.length;
while (i < n) {
int start = nums[i];
while (i + 1 < n && nums[i + 1] == nums[i] + 1) {
i++;
}
if (start == nums[i]) {
result.add(String.valueOf(start));
} else {
result.add(start + "->" + nums[i]);
}
i++;
}
return result.toArray(new String[0]);
}
}