consecutive integers
list processing
duplicate detection
integer sequences
algorithm optimization

Detecting consecutive integers in a list

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

"Detect consecutive integers in a list" can mean two different tasks: checking whether the entire list forms one consecutive run, or finding all consecutive runs inside a larger collection. The best implementation depends on which of those you actually need, and on whether duplicates should be allowed.

Check whether a list is fully consecutive

If you want to know whether all values can be arranged into one uninterrupted sequence, sort the values and compare each adjacent pair.

python
1def is_consecutive(values):
2    if not values:
3        return False
4
5    ordered = sorted(values)
6    return all(b - a == 1 for a, b in zip(ordered, ordered[1:]))
7
8print(is_consecutive([4, 2, 3, 5]))
9print(is_consecutive([1, 2, 4]))

This works well when duplicates are not allowed and order in the original list does not matter.

Handle duplicates deliberately

Duplicates change the definition. For example, [1, 2, 2, 3] is not strictly consecutive because one step has difference 0, not 1.

If duplicates should be ignored, normalize first:

python
1def is_consecutive_ignore_duplicates(values):
2    unique = sorted(set(values))
3    return bool(unique) and all(b - a == 1 for a, b in zip(unique, unique[1:]))
4
5print(is_consecutive_ignore_duplicates([1, 2, 2, 3]))

The correct behavior depends on the problem definition, so do not hide the duplicate rule.

Use a min-max test for a faster whole-range check

When duplicates are disallowed, another useful trick is comparing the size of the set with the numeric span.

python
1def is_consecutive_fast(values):
2    if not values:
3        return False
4
5    unique = set(values)
6    return len(unique) == len(values) and max(values) - min(values) + 1 == len(values)
7
8print(is_consecutive_fast([10, 11, 12, 13]))

This avoids sorting and runs in linear time on average.

Find consecutive runs inside a sorted sequence

If the goal is to extract runs such as [1, 2, 3] and [7, 8], iterate through the ordered values and break when the gap changes.

python
1def find_runs(values):
2    if not values:
3        return []
4
5    ordered = sorted(values)
6    runs = [[ordered[0]]]
7
8    for value in ordered[1:]:
9        if value == runs[-1][-1] + 1:
10            runs[-1].append(value)
11        else:
12            runs.append([value])
13
14    return runs
15
16print(find_runs([8, 2, 3, 10, 1, 7]))

This is often more useful than a yes-or-no check.

Original order versus numeric order matters

Some problems ask whether consecutive values appear next to each other in the original list. That is a different question from numeric consecutiveness after sorting.

python
1def adjacent_run_lengths(values):
2    if not values:
3        return []
4
5    lengths = []
6    current = 1
7    for a, b in zip(values, values[1:]):
8        if b == a + 1:
9            current += 1
10        else:
11            lengths.append(current)
12            current = 1
13    lengths.append(current)
14    return lengths

Always clarify whether order should be preserved.

A set-based scan is useful for longest streak problems

If the real question is "what is the longest consecutive streak," a set-based scan that starts only at sequence boundaries is often the best approach. That is a different algorithm from simply validating one whole list.

Common Pitfalls

  • Solving the sorted-order problem when the real requirement is original-order adjacency.
  • Forgetting to define how duplicates should be handled.
  • Returning True for an empty list without deciding whether that makes sense for the domain.
  • Sorting when a set-based min-max check would be simpler for a full-range test.
  • Using one function for both "is the whole list consecutive" and "find consecutive runs" even though they are different tasks.

Summary

  • First decide whether you need a boolean check or actual consecutive runs.
  • Sorting and adjacent-difference checks are simple and reliable.
  • A set plus min-max check can verify whole-range consecutiveness efficiently.
  • Duplicates and original-order requirements change the correct algorithm.
  • Make the definition explicit before choosing the implementation.

Course illustration
Course illustration

All Rights Reserved.