Summary Ranges

You are given a sorted array of unique integers `nums`. Cover every number with the smallest sorted list of ranges, where a range [a,b] holds every integer from a to b. Write a range as "a->b" when a != b and as "a" when a == b.

30:00

Summary Ranges
easy
Free written solution
Topics
Companies

You are given a sorted array of unique integers nums. Cover every number with the smallest sorted list of ranges, where a range [a,b] holds every integer from a to b. Write a range as "a->b" when a != b and as "a" when a == b.

Example 1:
Input: {"nums":[0,1,2,4,5,7]}
Output: ["0->2","4->5","7"]
Constraints:
  • 0≤nums.length≤200 \leq \text{nums.length} \leq 20

  • −231≤nums[i]≤231−1-2^{31} \leq \text{nums}[i] \leq 2^{31} - 1

  • All the values of nums are unique.

  • nums is sorted in ascending order.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[0,1,2,4,5,7]}

Start with an empty res. Each run of consecutive numbers will become one label in it.

sorted nums: neighbours that differ by 1 chain into one run

0

0

1

1

2

2

4

3

5

4

7

5

does the next number extend the run?

no open run

res

[ ]

Variables
VariableValue
i0
startnull
res[]
DepthFunction Call
Stack empty
0/24