InterviewHubPRO
Section Overview
Q7

Question 7 of 100

Part 2: Arrays, Strings & Hash Maps (6 - 18)

7%
DSA Patterns (Multi-Lang)•Part 2: Arrays, Strings & Hash Maps (6 - 18)

Longest Consecutive Sequence.

In Simple Words: Put all numbers in a Set. Only start counting a sequence if num - 1 does NOT exist in the set (meaning num is the start of a streak). Then increment num + 1 while present in the set.

  • Time: $O(N)$ | Space: $O(N)$
Multi-Language Solutions
Switch tabs or choose All
def longestConsecutive(nums: list[int]) -> int:
    num_set = set(nums)
    longest = 0
    for n in num_set:
        # Check if n is the start of a streak
        if (n - 1) not in num_set:
            current_num = n
            streak = 1
            while (current_num + 1) in num_set:
                current_num += 1
                streak += 1
            longest = max(longest, streak)
    return longest