Algorithm


Problem Name: 228. Summary Ranges

You are given a sorted unique integer array nums.

A range [a,b] is the set of all integers from a to b (inclusive).

Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

Each range [a,b] in the list should be output as:

  • "a->b" if a != b
  • "a" if a == b

 

Example 1:

Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The ranges are:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"

Example 2:

Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: The ranges are:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"

 

Constraints:

  • 0 <= nums.length <= 20
  • -231 <= nums[i] <= 231 - 1
  • All the values of nums are unique.
  • nums is sorted in ascending order.

Code Examples

#1 Code Example with C Programming

Code - C Programming


void ranges(int *nums, int numsz, int ***pp, int *sz, int *n) {
    int a, b;
    int i, l;
    char buff[64];
    
    if (numsz == 0) return;
    
    if (*n == *sz) {
        (*sz) *= 2;
        (*pp) = realloc(*pp, (*sz) * sizeof(char *));
        //assert(*pp);
    }
    b = a = nums[0];
    i = 1;
    while (i  <  numsz && (b + 1) == nums[i]) {
        i ++; b ++;
    }
    l = sprintf(buff, "%d", a);
    if (i > 1) {
        l += sprintf(&buff[l], "->%d", b);
    }
    
    (*pp)[*n] = malloc((l + 1) * sizeof(char));
    strcpy((*pp)[*n], buff);
    (*n) ++;
    
    ranges(&nums[i], numsz - i, pp, sz, n);
}
char** summaryRanges(int* nums, int numsSize, int* returnSize) {
    int sz, n;
    char **p;
    
    *returnSize = 0;
    if (numsSize == 0) return NULL;
    
    sz = 100;
    p = malloc(sz * sizeof(char *));
    
    n = 0;
    ranges(nums, numsSize, &p, &sz, &n);
    
    *returnSize = n;
    
    return p;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [0,1,2,4,5,7]

Output

x
+
cmd
["0->2","4->5","7"]

#2 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector < string>res;
        for(int i = 0, j = 1; i  <  nums.size(); i = j, j = i + 1){
            while(j < nums.size() && nums[j] == nums[j - 1] + 1) j++;
            res.push_back((j == i + 1) ? to_string(nums[i]) : to_string(nums[i]) + "->" + to_string(nums[j - 1]));
        }
        return res;
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [0,1,2,4,5,7]

Output

x
+
cmd
["0->2","4->5","7"]

#3 Code Example with Java Programming

Code - Java Programming


class Solution {
  public List summaryRanges(int[] nums) {
    List result = new ArrayList<>();
    int idx = 0;
    int n = nums.length;
    while (idx  <  n) {
      int start = nums[idx];
      int end = start;
      idx++;
      while (idx  <  n && nums[idx] == end + 1) {
        end = nums[idx];
        idx++;
      }
      result.add(start == end ? String.valueOf(start) : (start + "->" + end));
    }
    return result;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [0,2,3,4,6,8,9]

Output

x
+
cmd
["0","2->4","6","8->9"]

#4 Code Example with Javascript Programming

Code - Javascript Programming


const summaryRanges = function(nums) {
  if (nums == null || nums.length === 0) return []
  const res = []
  if (nums.length === 1) return [`${nums[0]}`]
  let start = nums[0]
  let end = nums[0]
  let endVal = end
  for (let i = 1, len = nums.length; i  <  len; i++) {
    let cur = nums[i]
    if (cur - end > 1) {
      endVal = end
      insert(res, start, end)
      start = cur
      end = cur
    } else {
      end = cur
    }
  }
  if (endVal !== end) {
    insert(res, start, end)
  }
  return res
}

function insert(arr, start, end) {
  if (start === end) {
    arr.push(`${start}`)
  } else {
    arr.push(`${start}->${end}`)
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [0,2,3,4,6,8,9]

Output

x
+
cmd
["0","2->4","6","8->9"]

#5 Code Example with Python Programming

Code - Python Programming


class Solution:
    def summaryRanges(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        res, stack = [], [nums[0] if nums else None, None]
        for i, num in enumerate(nums):
            if i > 0 and nums[i - 1] == num - 1: stack[1] = num
            if i > 0 and nums[i-1] != num - 1: res, stack[0], stack[1] = res + ["->".join(str(q) for q in stack if q != None)], num, None
            if i == len(nums) - 1: res.append("->".join(str(q) for q in stack if q != None))
        return res
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [0,1,2,4,5,7]

Output

x
+
cmd
["0->2","4->5","7"]
Advertisements

Demonstration


Previous
#227 Leetcode Basic Calculator II Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#229 Leetcode Majority Element II Solution in C, C++, Java, JavaScript, Python, C# Leetcode