array processing
integer arrays
data summarization
programming
coding techniques

How do I summarize array of integers as an array of ranges?

Codemia Knowledge Hub ·

Introduction

Summarizing an integer array into ranges means compressing consecutive values into interval notation such as 1-5 while leaving isolated values as singletons. The usual solution is a single left-to-right scan over a sorted sequence, tracking the start and end of the current run.

What Counts as a Range

Given:

text
[1, 2, 3, 5, 6, 9]

the summarized result is:

text
["1-3", "5-6", "9"]

The rule is simple:

  • consecutive integers belong to the same range
  • a lone number becomes its own entry

This assumes the list is sorted by numeric order.

Single-Pass Algorithm

The algorithm keeps two pointers:

  • 'start for the beginning of the current range'
  • 'end for the current last value in that range'

As you scan the array:

  1. if the next value is exactly end + 1, extend the range
  2. otherwise, emit the previous range and start a new one

That gives linear time after sorting.

Python Example

python
1def summarize_ranges(nums):
2    if not nums:
3        return []
4
5    nums = sorted(set(nums))
6    result = []
7    start = end = nums[0]
8
9    for value in nums[1:]:
10        if value == end + 1:
11            end = value
12        else:
13            result.append(f"{start}-{end}" if start != end else str(start))
14            start = end = value
15
16    result.append(f"{start}-{end}" if start != end else str(start))
17    return result
18
19print(summarize_ranges([1, 2, 3, 5, 6, 9]))

This also removes duplicates by converting the list to set first, which is often useful when the input may repeat values.

Why Sorting Matters

If the input is not already sorted, you have two choices:

  • sort it first
  • preserve original order and accept that "range" no longer means numeric interval compression

For the standard problem, sorting is the correct approach because ranges are about numeric adjacency, not input order.

Example:

python
print(summarize_ranges([9, 1, 2, 3, 6, 5]))

After sorting, this still becomes:

text
["1-3", "5-6", "9"]

Returning Structured Ranges Instead of Strings

Sometimes strings are not the best result format. If another part of the program needs the ranges for later processing, return tuples:

python
1def summarize_ranges_structured(nums):
2    if not nums:
3        return []
4
5    nums = sorted(set(nums))
6    result = []
7    start = end = nums[0]
8
9    for value in nums[1:]:
10        if value == end + 1:
11            end = value
12        else:
13            result.append((start, end))
14            start = end = value
15
16    result.append((start, end))
17    return result
18
19print(summarize_ranges_structured([1, 2, 3, 5, 6, 9]))

This is often cleaner when the formatting layer is separate from the data-processing layer.

Complexity

If the input is already sorted and unique, the scan is O(n). If you must sort first, total complexity is O(n log n) because of the sort.

That is already optimal for general unsorted input, since the order of numbers must be determined somehow before consecutive groups can be formed correctly.

Variations

Depending on the problem statement, you may need to adjust the rules:

  • preserve duplicates instead of removing them
  • summarize only sorted input and reject unsorted arrays
  • use a custom string format such as 1..3
  • group by a gap size other than 1

The scanning structure stays the same; only the adjacency test changes.

Common Pitfalls

  • Assuming the input is sorted when it is not, which creates incorrect ranges.
  • Forgetting to flush the final range after the loop ends.
  • Treating duplicates as if they were consecutive values, which can distort the intended range representation.
  • Returning string ranges when later logic really needs structured interval data.
  • Mixing up numeric adjacency with original array order when the real task is interval compression.

Summary

  • Summarizing integers into ranges is a scan over sorted values.
  • Track the start and end of the current consecutive run.
  • Emit a singleton for isolated numbers and an interval for runs.
  • Use sorting and deduplication if the input is not already normalized.
  • Return tuples instead of strings when downstream code needs the ranges as data rather than display text.

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms