Created
November 18, 2024 08:00
-
-
Save sAVItar02/a4eda9aa1dfbaa4f6cc38fbf82119bf3 to your computer and use it in GitHub Desktop.
Summary Ranges
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} nums | |
* @return {string[]} | |
*/ | |
var summaryRanges = function(nums) { | |
let arr = []; | |
let start = nums[0]; | |
for(let i=0; i<nums.length; i++) { | |
if(nums[i+1] - nums[i] == 1) continue; | |
if(start == nums[i]) { | |
arr.push(`${start}`); | |
start = nums[i+1]; | |
} | |
else { | |
arr.push(`${start}->${nums[i]}`); | |
start = nums[i+1]; | |
} | |
} | |
return arr; | |
}; | |
// Keep a variable which stores the start value | |
// Loop through the array and check if the element ahead of the current one is 1 more than the current element | |
// If yes then move on normally and keep checking | |
// If not, then check whether the current element is the same as the start element | |
// If yes, then simply push the start into the results array | |
// If not, then push "start->current element" into the results array | |
// Update the start position to the element ahead of the current element | |
// Time:O(n) | |
// Space: O(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment