228. Summary Ranges ๐
Difficulty: Easy
- Tags: Array
Problem Statement ๐
You are given a sorted unique integer array nums
.
A range [a,b]
is the set of all integers from a
to b
(inclusive).
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
.
Each range [a,b]
in the list should be output as:
"a->b"
ifa != b
"a"
ifa == b
Examples ๐
๐น Example 1:
Input:
Output:
Explanation:
[0,2]
-->"0->2"
[4,5]
-->"4->5"
[7,7]
-->"7"
๐น Example 2:
Input:
Output:
Explanation:
[0,0]
-->"0"
[2,4]
-->"2->4"
[6,6]
-->"6"
[8,9]
-->"8->9"
Constraints โ๏ธ
0 <= nums.length <= 20
-2^31 <= nums[i] <= 2^31 - 1
All the values of
nums
are unique.nums
is sorted in ascending order.
Solution ๐ก
The goal is to identify consecutive ranges in the sorted array and format them as described.
Java Solution
Explanation of the Solution
Initialize Start Point:
Use a
start
variable to track the beginning of the current range.
Iterate Over the Array:
Compare the current number with the previous one to detect the end of a range.
When a range ends or the array ends:
If the
start
is equal to the last number, it's a single element range.Otherwise, format it as
"start->end"
.
Update for the Next Range:
Reset
start
to the next number in the array.
Time Complexity โณ
O(n): Each element is processed once.
Space Complexity ๐พ
O(1): No additional space is used other than the result list.
You can find the full solution here.
Last updated