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.
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:
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.
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.
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.
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
Truefor 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.

