Leetcode 150 - Summary Ranges

Here is two solution for problem “Summary Ranges”

1. Input, Output, Contrains

  1. Input
Input: nums = [0, 1, 2, 4, 5, 7]
  1. Output
Output: ["0->2", "4->5", "7"]
  1. Contrains
  • 0 <= len(nums) <= 20,000

  • -2^31 <= nums[i] <= 2^31 - 1

  • nums sorted and unique

2. Dry run

i	nums[i]	start	prev	Action	result
0	0	0		start new range	[]
1	1	0	0	consecutive	[]
2	2	0	1	consecutive	[]
3	4	0	2	not consecutive  push "0->2"	["0->2"], start=4
4	5	4	4	consecutive	["0->2"]
5	7	4	5	not consecutive  push "4->5"	["0->2", "4->5"], start=7
end		7	7	push last range "7"	["0->2", "4->5", "7"]

3. Solution

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

Last Updated On October 14, 2025