DEV Community

Cover image for Summary of its ranges
chandra penugonda
chandra penugonda

Posted on • Edited on

Summary of its ranges

Given a sorted integer array without duplicates, return the summary of its ranges.

Example
const summaryRanges = nums => {

};

console.log(summaryRanges([0,2,3,4,6,8,9])) 
// ["0","2->4","6","8->9"]
Enter fullscreen mode Exit fullscreen mode

Solution

function summaryRanges(arr) {
  let i = 0;
  const result = [];
  while (i < arr.length) {
    let j = i + 1;
    while (j < arr.length && arr[j] === arr[j - 1] + 1) j++;
    const val = arr[j - 1];
    result.push(i === j-1 ? val.toString() : `${arr[i]}->${val}`);
    i = j;
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode

Explanation

The summaryRanges function iterates through an array using a while loop. It uses a nested while loop to identify contiguous ranges of numbers. For each range, it constructs a string representing that range and pushes it to a result array. After fully iterating the array, it returns the result array containing the summarized ranges.

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay