Summary Ranges
XXX. Summary Ranges
Problem Statement:
Given a sorted unique integer array nums
, return the smallest sorted list of ranges
that cover all the numbers in the array exactly. A range [a,b]
is represented as:
"a->b"
if a != b
, and "a"
if a == b
.
Example:
Approach:
- Initialize two pointers,
i
andj
, to iterate over the array. - Move
j
forward as long as the next number is consecutive (nums[j] + 1 == nums[j+1]
). - Once a non-consecutive element is found, add the range
"nums[i]->nums[j]"
or single element"nums[j]"
to the result. - Repeat until the end of the array is reached.
Algorithm Intuition:
The algorithm works by identifying contiguous segments of numbers in the array using two pointers. It groups numbers into ranges whenever they are consecutive and adds these ranges to the result. Single numbers are treated as ranges with the same start and end.
Complexity:
Time Complexity: O(n), where n
is the length of the array. The algorithm performs a single pass through the array.
Space Complexity: O(1), ignoring the space required for the output list.
Java Implementation:
// Two-pointer approach to summarize ranges in a sorted array
public List summaryRanges(int[] nums) {
int i = 0, j = 0;
List intervals = new ArrayList<>();
// Iterate through the array
while (j < nums.length) {
// Move the end pointer (j) if the next number is consecutive
while (j != nums.length - 1 && nums[j] + 1 == nums[j + 1])
j++;
// Add the range or single element to the intervals
addInterval(nums[i], nums[j], intervals, i != j);
// Move the start pointer (i) to the next position
i = ++j;
}
return intervals;
}
// Helper method to format and add the range to the result
public void addInterval(Integer start, Integer end, List intervals, boolean range) {
// If it's a range, format as "start->end"; otherwise, just the single number
String s = range ? start.toString() + "->" + end.toString() : end.toString();
intervals.add(s);
}