Leetcode 228 Summary Ranges
Summary Ranges – LeetCode
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.
This problem can be solved by using 2 pointers. One represents the left boundary of the interval the other for the right boundary.
Then we just need to move the 2 pointers by checking if the next number is consecutive to the number on the right boundary.
- If true, we move the right pointer
- If false, we push the interval into the result array
One thing to note is at the end of the while loop, we should still add the last interval into the result array. We do this by check if the left pointer is at the end of the array.
Solution
/**
* @param {number[]} nums
* @return {string[]}
*/
var summaryRanges = function(nums) {
if(!nums.length) {
return []
}
let left = 0;
let right = 0;
let result = []
while(right < nums.length) {
if(nums[right+1] - nums[right] > 1) {
if(right === left) {
result.push(`${nums[right]}`)
} else {
result.push(`${nums[left]}->${nums[right]}`)
}
right += 1;
left = right;
} else {
right += 1
}
}
if(left === nums.length - 1) {
result.push(`${nums[left]}`)
} else {
result.push(`${nums[left]}->${nums[nums.length - 1]}`)
}
return result
};
This solution has a time complexity of O(n)
and space complexity of O(1)