-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0228-summary-ranges.js
More file actions
41 lines (33 loc) · 1.33 KB
/
0228-summary-ranges.js
File metadata and controls
41 lines (33 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Summary Ranges
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var summaryRanges = function (nums) {
const collectedRanges = [];
const totalElementsCount = nums.length;
if (totalElementsCount === 0) {
return collectedRanges;
}
let currentRangeStartIndex = 0;
for (let currentIterationIndex = 0; currentIterationIndex < totalElementsCount; currentIterationIndex++) {
const valueAtCurrentIndex = nums[currentIterationIndex];
const valueAfterCurrent = nums[currentIterationIndex + 1];
const expectedNextConsecutive = valueAtCurrent + 1;
const isLastElement = (currentIterationIndex === totalElementsCount - 1);
const isNotConsecutive = (expectedNextConsecutive !== valueAfterCurrent);
if (isLastElement || isNotConsecutive) {
const rangeStartNumber = nums[currentRangeStartIndex];
const rangeEndNumber = valueAtCurrent;
let rangeOutputString;
if (rangeStartNumber === rangeEndNumber) {
rangeOutputString = `${rangeStartNumber}`;
} else {
rangeOutputString = `${rangeStartNumber}->${rangeEndNumber}`;
}
collectedRanges.push(rangeOutputString);
currentRangeStartIndex = currentIterationIndex + 1;
}
}
return collectedRanges;
};