Find Longest Consecutive Run in an Unsorted List in Python

Find the length of the longest sequence of consecutive integers in an unsorted list using a set and a linear scan.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

25 lines
Python 3.9+
def longest_run(nums):
    if not nums:
        return 0

    num_set = set(nums)
    longest = 0

    for num in num_set:
        # Only start counting from the smallest number in a sequence
        if num - 1 not in num_set:
            current = num
            length = 1
            while current + 1 in num_set:
                current += 1
                length += 1
            longest = max(longest, length)

    return longest


if __name__ == "__main__":
    sample = [100, 4, 200, 1, 3, 2, 5, 6]
    result = longest_run(sample)
    print(result)  # Expected output: 5 (sequence 1,2,3,4,5,6)
    print(longest_run([]))  # Expected output: 0

Output

stdout
6
0

How it works

The solution converts the list to a set for O(1) membership tests. For each number, it checks if it is the start of a sequence (i.e., num - 1 is not in the set). If so, it counts consecutive numbers with a while loop. Since each number is visited at most twice (once as a potential start, once as part of a chain), the total time complexity is O(n).

Common mistakes

  • Not checking for empty input, causing an unhandled exception.
  • Counting sequences by scanning the entire list instead of using a set for fast lookups.
  • Starting the count from every number, not only sequence starts, leading to O(n²) time.

Variations

  1. Use sorted() to sort the list and then scan for consecutive runs, but that gives O(n log n) time.
  2. Modify to return the actual longest sequence instead of just its length.
  3. Use a dictionary to track visited numbers and build sequences via both directions.

Real-world use cases

  • Identifying the longest streak of consecutive login days in user activity logs.
  • Detecting the maximum range of consecutive serial numbers in inventory or barcode data.
  • Finding the largest contiguous block of available IP addresses in a network scanner.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.