Python coding

Longest streak of consecutive numbers

Given an unsorted list of integers nums, return the length of the longest streak of consecutive values x, x + 1, x + 2, … that can be formed with values from the list. The values can sit anywhere in the list, and repeats count once.

nums may be empty (the answer is then 0) and may contain negatives. Aim for O(n): no sorting.

Besides the tests, one large input (5,000 numbers) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • longest_streak([8,3,20,1,4,2]) → 4
  • longest_streak([5,5,5]) → 1
  • longest_streak([0,-1,7,1,-2]) → 4
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Sorting gives O(n log n). For O(n) you need to answer "is x + 1 in the list?" in constant time: a set.

Hint 2

Start counting only at a value x whose predecessor x − 1 is missing: that is where a streak begins. Then walk x + 1, x + 2, … while they are present.

Hint 3

Without that check every value re-walks its streak and the pass is O(n²). Iterate over the set, not the list, so repeats cost nothing.

Solution and why it works
pythonO(n) · O(n)
def longest_streak(nums: list[int]) -> int:
    values = set(nums)
    best = 0
    for x in values:
        if x - 1 in values:            # x is inside a streak, not its start
            continue
        end = x
        while end + 1 in values:
            end += 1
        best = max(best, end - x + 1)
    return best

A set answers "is x + 1 present?" in O(1). Counting upward only from values whose predecessor is absent means each streak is walked once, from its start: the inner loop takes O(n) steps in total, not per element. Skip that check and a list like 1…n costs O(n²). The set also removes repeats, which break sort-and-scan solutions that reset or double-count on equal neighbors.

Related lab: Loops in motion