Summary Ranges

Easy IntervalsArray

Problem

Given a sorted unique integer array, return the smallest list of ranges that cover every integer in the array. Format: "a" or "a->b".

Example 1 Input: [0,1,2,4,5,7] Output: ["0->2","4->5","7"]
Example 2 Input: [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"]

Constraints

Approach — Core Patterns

This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: see the walkthrough below.

Solution code

Python

class Solution:
    def summaryRanges(self, nums):
        res = []
        i = 0
        n = len(nums)
        while i < n:
            j = i
            while j + 1 < n and nums[j+1] == nums[j] + 1:
                j += 1
            res.append(str(nums[i]) if i == j else "%d->%d" % (nums[i], nums[j]))
            i = j + 1
        return res

Java

import java.util.*;
class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> out = new ArrayList<>();
        int i = 0;
        while (i < nums.length) {
            int j = i;
            while (j + 1 < nums.length && nums[j + 1] == nums[j] + 1) j++;
            out.add(i == j ? "" + nums[i] : nums[i] + "->" + nums[j]);
            i = j + 1;
        }
        return out;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Summary Ranges interactively → ← All solutions