Sobes.tech
Middle — Senior

Describe the task of collapsing neighboring numbers into ranges?

sobes.tech AI

Answer from AI

The task of collapsing neighboring numbers into ranges involves forming the minimal number of continuous intervals (ranges) that cover all these numbers without gaps.

For example, given the numbers: [1, 2, 3, 5, 6, 8]

The result of collapsing:

  • [1-3]
  • [5-6]
  • [8]

This is useful for optimizing storage or display of data when consecutive numbers can be compactly represented as a range.

Main steps of the solution:

  1. Sort the array of numbers.
  2. Iterate through the sorted list, forming the current range.
  3. If the next element is adjacent (current + 1), extend the range.
  4. If not — save the current range and start a new one.

The algorithm complexity is — O(n log n) due to sorting, where n is the number of elements.

Example in Python:

def collapse_ranges(nums):
    if not nums:
        return []
    nums = sorted(set(nums))
    ranges = []
    start = prev = nums[0]
    for num in nums[1:]:
        if num == prev + 1:
            prev = num
        else:
            ranges.append((start, prev))
            start = prev = num
    ranges.append((start, prev))
    return ranges

# Example
print(collapse_ranges([1,2,3,5,6,8]))  # [(1,3), (5,6), (8,8)]