Taro Logo

Summary Ranges

#5 Most AskedEasy
0 views
Topics:
ArraysStringsTwo Pointers

You are given a sorted unique integer array nums.

A range [a,b] is the set of all integers from a to b (inclusive).

Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

Each range [a,b] in the list should be output as:

  • "a->b" if a != b
  • "a" if a == b

Example 1:

Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The ranges are:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"

Example 2:

Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: The ranges are:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"

Constraints:

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should be returned if the input array `nums` is empty?
  2. Can the array contain negative numbers and zeros, and is the range of values within standard 32-bit signed integer limits?
  3. Are there any duplicate values in the input array, or are all elements strictly unique?
  4. How should ranges containing only a single element be formatted in the output—as just the number itself without any arrow?
  5. Is the input array guaranteed to be already sorted in ascending order?

Brute Force Solution

Approach

Imagine you are given a sorted list of numbers and you need to group consecutive numbers together into ranges. The brute force strategy involves exhaustively examining the numbers one by one to find unbroken sequences from start to finish.

Here's how the algorithm would work step-by-step:

  1. Look at the very first number in the collection to begin a potential sequence.
  2. Move forward step by step to check if the next numbers immediately follow the previous ones without any gaps.
  3. Keep extending your check as long as the numbers keep increasing by exactly one.
  4. Stop extending the sequence the moment you find a gap or reach the end of the collection.
  5. Write down this completed sequence, either as a single standalone number if it never grew, or as a range from the starting point to the stopping point.
  6. Repeat this entire checking process starting from the very next number after the gap.
  7. Continue this process until every single number in the collection has been included in one of the ranges.

Code Implementation

def summary_ranges(numbers):
    summary_results = []
    total_numbers = len(numbers)
    index_pointer = 0

    # We loop until every single number is processed into a range
    while index_pointer < total_numbers:
        start_pointer = index_pointer

        # We extend the range as long as consecutive numbers increase by one
        while index_pointer + 1 < total_numbers and numbers[index_pointer + 1] == numbers[index_pointer] + 1:
            index_pointer += 1

        # We format the range based on whether it is a single number or a sequence
        if start_pointer == index_pointer:
            summary_results.append(str(numbers[start_pointer]))
        else:
            range_string = f"{numbers[start_pointer]}->{numbers[index_pointer]}"
            summary_results.append(range_string)

        index_pointer += 1

    return summary_results

Big(O) Analysis

Time Complexity
O(n) – To group the sorted numbers into consecutive ranges, we iterate through the input array of size n using a single pass with an inner advancement mechanism. The outer tracker initiates a sequence at an element, while the inner scan moves forward step by step to find the end of the unbroken sequence. Because the inner pointer only moves forward and never backtracks, each of the n elements is visited at most a constant number of times. Summing up these operations yields a linear number of steps overall, which simplifies to Big O of n.
Space Complexity
O(N) – The algorithm requires auxiliary space to store the output collection of formatted ranges, where N represents the number of elements in the input list. In the worst-case scenario where no numbers are consecutive, every single number becomes its own range string stored in the result list. Additionally, only a few primitive pointer variables are used to track the start and end of the current sequence, meaning the output list dominates the extra memory. As the input size N increases, the maximum number of stored ranges grows proportionally, leading to linear space complexity.

Optimal Solution

Approach

The optimal strategy groups consecutive numbers together by scanning through the sorted sequence from start to finish. It tracks the beginning and end of each unbroken chain of numbers, packaging them into neat ranges as it goes.

Here's how the algorithm would work step-by-step:

  1. Look at the very first number in the sequence and mark it as the start of your current chain.
  2. Look at the next numbers one by one to see if they continue the unbroken sequence in order.
  3. Keep moving forward as long as the numbers continue the sequence without any gaps.
  4. If you hit a gap or reach the end of the sequence, stop and look at the last number you successfully included.
  5. If the chain contains only a single number, record that single number by itself.
  6. If the chain contains multiple numbers, record the starting number and the ending number joined together with an arrow.
  7. Repeat this process from the next unvisited number until all numbers have been grouped into ranges.

Code Implementation

def summary_ranges(sorted_numbers):
    collected_ranges = []
    array_index = 0
    total_elements = len(sorted_numbers)

    while array_index < total_elements:
        start_of_chain = sorted_numbers[array_index]
        end_of_chain = start_of_chain

        # We scan ahead to find the boundary where the consecutive sequence breaks.
        while array_index + 1 < total_elements and sorted_numbers[array_index + 1] == sorted_numbers[array_index] + 1:
            array_index += 1
            end_of_chain = sorted_numbers[array_index]

        # A single number range is formatted differently than a multi-number range.
        if start_of_chain == end_of_chain:
            collected_ranges.append(str(start_of_chain))
        else:
            collected_ranges.append(f"{start_of_chain}->{end_of_chain}")

        array_index += 1

    return collected_ranges

Big(O) Analysis

Time Complexity
O(n) – The algorithm scans through the sorted input array of size n exactly once using a single pass to identify consecutive chains. Although there is an inner advancement of the pointer to check for gaps, each element in the array is visited at most twice during the entire traversal. This linear progression means the total operations scale directly with the input size n. Therefore, the overall time complexity simplifies to O(n).
Space Complexity
O(N) – Beyond the input array, the algorithm requires a dynamic list of strings to store the resulting ranges, where N is the number of elements in the input sequence. In the worst-case scenario where no numbers are consecutive, this output list will contain N individual string representations. A few primitive pointer variables are also used to track the start and end of the current chain, which require constant extra space. Therefore, the total auxiliary space is dominated by the storage needed for the output ranges. Simplifying this memory requirement yields a final space complexity of O(N).

Edge Cases

Empty array input
How to Handle:
Check for null or empty array at the start and return an empty list immediately.
Array with a single element
How to Handle:
The iteration loop finishes and appends the single element formatted as a string to the result list.
Array containing negative numbers and zero
How to Handle:
Arithmetic checks like nums[j] + 1 == nums[j + 1] work correctly across zero and into negative ranges.
Array with no continuous ranges
How to Handle:
Every element forms its own standalone range and is formatted individually as a single-number string.
Array with all elements forming a single continuous range
How to Handle:
The pointers expand across the entire array until the end, producing a single range string from start to end.
Large scale arrays near memory and time limits
How to Handle:
A single-pass linear scan approach processes the array in O(n) time and O(1) extra space excluding the output.
Integer boundary values like Integer.MIN_VALUE and Integer.MAX_VALUE
How to Handle:
Comparing nums[j] + 1 can cause integer overflow in languages like Java, so use long casting or check equality with nums[j + 1] - 1 instead.
0/12 completed