Summary Ranges - Problem
Summary Ranges - Transform a sorted array into compact range notation!

You're given a sorted unique integer array nums. Your mission is to convert this array into the smallest possible list of ranges that covers all numbers exactly once.

Range Format:
"a->b" if the range spans multiple numbers (a ≠ b)
"a" if the range contains only one number (a = b)

Goal: Return a list where each element from the original array appears in exactly one range, with no gaps or overlaps.

Example: [0,1,2,4,5,7] becomes ["0->2", "4->5", "7"]

Input & Output

example_1.py — Basic consecutive ranges
$ Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
💡 Note: The ranges are: [0,1,2] → "0->2", [4,5] → "4->5", and [7] → "7"
example_2.py — Mixed single elements and ranges
$ Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
💡 Note: The ranges are: [0] → "0", [2,3,4] → "2->4", [6] → "6", and [8,9] → "8->9"
example_3.py — Edge case empty array
$ Input: []
Output: []
💡 Note: Empty input array results in empty output

Constraints

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

Visualization

Tap to expand
Book0Start RangeBook1ContinueBook2End RangeBook4New RangeBook5End RangeBook7Single"0->2""4->5""7"Gap!Gap!📋 Catalog Entries Created:Range: "0->2"Range: "4->5"Single: "7"✅ All books catalogued efficiently - no book appears in multiple entries!📚 Library Catalog CreationGroup consecutive book numbers into compact range entries
Understanding the Visualization
1
Start cataloging
Begin at the first book (number 0) and start a range
2
Find consecutive books
Books 0, 1, 2 are consecutive - they belong in one range entry
3
Detect gap
Book 4 is not consecutive to 2 (gap of 2) - close the current range
4
Create new range
Start a new range beginning with book 4, continue the process
Key Takeaway
🎯 Key Insight: Since the array is already sorted, we can detect range boundaries by simply checking if consecutive elements differ by exactly 1. When they don't, we know a range has ended!
Asked in
Google 28 Amazon 22 Microsoft 15 Meta 12
68.3K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen