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.
Python code
25 linesdef 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
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
- Use sorted() to sort the list and then scan for consecutive runs, but that gives O(n log n) time.
- Modify to return the actual longest sequence instead of just its length.
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.