Sponsored
Sponsored
This approach involves detecting the start and end of each range by iterating through the array sequentially. You remember the start of a potential range and adjust the range's end as long as consecutive numbers are found. When a break in consecutiveness occurs, you fix the end of the current range and start a new one.
Time Complexity: O(n)
Space Complexity: O(n)
1
2function summaryRanges(nums) {
3 const result = [];
4 let i = 0;
5 while (i < nums.length) {
6 let start = i;
7 while (i + 1 < nums.length && nums[i] + 1 === nums[i + 1]) {
8 i++;
9 }
10 if (start === i) {
11 result.push(`${nums[start]}`);
12 } else {
13 result.push(`${nums[start]}->${nums[i]}`);
14 }
15 i++;
16 }
17 return result;
18}
19
The JavaScript solution is implemented using a loop to identify ranges. It employs backticks for easy string interpolation when creating the range strings. Result is returned as an array of strings.
This approach utilizes a two-pointer method where one pointer marks the beginning of a new range, and another pointer (or the loop index itself) expands the range as far as possible until the next number isn't consecutive. Once a sequence ends, if numbers are the same, it is a single-element range; otherwise, a range connecting two different numbers is formed.
Time Complexity: O(n)
Space Complexity: O(n)
1
Java's solution also utilizes two pointers, with 'i' marking the start and an additional pointer 'j' expanding as far as consecutiveness permits. Once the range is determined, the results are added to the list as strings.