← Back to Leo Academy Masterclass

Problem #228: Summary Ranges

Easy Intervals

Intuition & Strategy Breakdown

Iterate through sorted array tracking start of current range. Expand range while nums[i] + 1 == nums[i+1], then format output string.

Python Solution

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

Java Solution

class Solution {
            public List summaryRanges(int[] nums) {
                List res = new ArrayList<>();
                for (int i = 0; i < nums.length; i++) {
                    int start = nums[i];
                    while (i + 1 < nums.length && nums[i + 1] == nums[i] + 1) {
                        i++;
                    }
                    if (start != nums[i]) {
                        res.add(start + "->" + nums[i]);
                    } else {
                        res.add(String.valueOf(start));
                    }
                }
                return res;
            }
        }
Watch Interactive Video on Leo Academy Main App