Skip to content

Commit 9e9a355

Browse files
committed
Runtime: 47 ms (Top 78.6%) | Memory: 41.90 MB (Top 55.1%)
1 parent 05a3520 commit 9e9a355

File tree

1 file changed

+27
-16
lines changed

1 file changed

+27
-16
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
1+
// Runtime: 47 ms (Top 78.6%) | Memory: 41.90 MB (Top 55.1%)
12

3+
// Runtime: 46 ms, faster than 86.21% of JavaScript online submissions for Summary Ranges.
4+
// Time Complexity : O(N)
5+
// Space Complexity : O(1)
26
var summaryRanges = function(nums) {
3-
let result = [];
4-
let startIdx = 0;
5-
6-
for(let i = 0; i < nums.length; i++){
7-
let peekRight = nums[i+1];
8-
let peekLeft = nums[i-1];
9-
if (peekRight !== nums[i] + 1 && peekLeft !== nums[i] - 1){
10-
result.push(`${nums[i]}`);
11-
startIdx++;
12-
} else if ( peekRight !== nums[i] + 1){
13-
result.push(`${nums[startIdx]}->${nums[i]}`);
14-
startIdx = i+1;
15-
}
16-
17-
}
18-
return result;
7+
// Create a list of string to store the output result...
8+
const output = [];
9+
// Start traversing the array from idx = 0 till idx < sizeofarray in a while loop.
10+
let idx = 0;
11+
while(idx < nums.length) {
12+
// Initialize beg and last index for identifying the continuous element in the array...
13+
let beg, last;
14+
// Mark the number at current index as beginning element of the range...
15+
beg = nums[idx];
16+
// Traverse the array beggining from current index & find the last element whose difference from previous element is exactly 1, i.e. nums[idx + 1] == nums[idx] + 1...
17+
while(idx+1 < nums.length && nums[idx+1] == nums[idx] + 1)
18+
idx++;
19+
// Set this element as last element of the range...
20+
last = nums[idx];
21+
// If continuous element isn't present...
22+
if(beg == last)
23+
output.push(beg + "");
24+
// If present...
25+
else
26+
output.push( beg + "->" + last );
27+
idx++;
28+
}
29+
return output; // Return the output result list...
1930
};

0 commit comments

Comments
 (0)