Skip to content

Simple Number Problems: Set 2

  • Summary Ranges (LeetCode 228)

Summary Ranges (LeetCode 228)

You are given a sorted unique integer array nums. 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

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

python
class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        out = []
        n = len(nums)
        i = 0
        
        while i < n:
            start = nums[i]
            
            while i + 1 < n and nums[i + 1] == nums[i] + 1:
                i += 1
            
            end = nums[i]
            
            if start == end:
                out.append(str(start))
            else:
                out.append(f"{start}->{end}")
            
            i += 1
        
        return out

Java version

java
import java.util.*;

class Solution {
    public List<String> summaryRanges(int[] nums) {
        
        List<String> out = new ArrayList<>();
        int n = nums.length;
        int i = 0;

        while (i < n) {
            int start = nums[i];
            
            while (i+1 < n && nums[i+1] == nums[i]+1) {
                i++;
            }
            
            int end = nums[i];
            
            if (start == end) {
                //out.add(String.valueOf(start));
                out.add( "" + start );
            } else {
	            //out.add(String.format("%d->%d", start, end));
				out.add(start + "->" + end);
            }
            i++;
        }
        return out;
    }
}