Summary Ranges - Problem
Summary Ranges - Transform a sorted array into compact range notation!
You're given a
Range Format:
•
•
Goal: Return a list where each element from the original array appears in exactly one range, with no gaps or overlaps.
Example:
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
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!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code