Problem Description
Given a sorted unique integer array nums, return the smallest sorted list of ranges that exactly covers all the numbers in the array. A range [a,b] is represented as "a->b" if a != b, and "a" if a == b.
Key Insights
- Since the array is sorted and unique, we can simply iterate through it.
- Track the start of a new range, and expand the range as long as the next number is consecutive.
- When a break in consecutiveness is noticed, format the current range accordingly and start a new range.
- Finalize the last range after exiting the loop.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the nums array. Space Complexity: O(1) additional space (excluding the space for the output list).
Solution
We iterate through the array while maintaining a start pointer for the current range. For each element, check if the next element is exactly one greater. If not, the current range ends here. Format the range as "start->end" if there is more than one element in the range, otherwise just as "start". This algorithm leverages the sorted property of the array to accomplish the task in one pass using constant extra space.