class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
s = set(nums)
longest = 0
for num in s:
if num - 1 not in s:
next_num = num + 1
length = 1
while next_num in s:
length += 1
next_num += 1
longest = max(longest, length)
return longest
# Time Complexity: O(n)
# Space Complexity: O(n)
The “Longest Consecutive Sequence” problem asks us to find the length of the longest sequence of consecutive integers that can be formed from a given array of integers. The numbers in the sequence do not need to appear in order in the array, and duplicates should be ignored.
For example:
Input: [100, 4, 200, 1, 3, 2] → Output: 4 (the sequence is [1, 2, 3, 4])Input: [0, 3, 7, 2, 5, 8, 4, 6, 0, 1] → Output: 9 (the sequence is [0–8])This problem is commonly used to test your ability to optimize brute-force logic and efficiently track patterns using hash-based data structures. It teaches techniques in sequence construction, set-based lookup, and one-pass logic to eliminate redundancy.
The brute-force solution using sorting would require O(n log n) time. However, the optimal solution leverages a set for O(1) lookups, allowing us to solve the problem in O(n) time.
longest to track the length of the longest sequence found.num in the set:
num if num - 1 is not in the set. This ensures we only begin from the beginning of a potential sequence.currentLength = 1 and currentNum = num + 1.currentNum is in the set, increment currentLength and currentNum.longest to the maximum of itself and currentLength.longest.
Input: [100, 4, 200, 1, 3, 2]
{1, 2, 3, 4, 100, 200}4Time Complexity: O(n), where n is the number of elements in the array. Each element is processed at most twice (once in the loop, once in the inner sequence). Space Complexity: O(n), due to storing the elements in a set.
The “Longest Consecutive Sequence” problem is a great example of replacing brute-force logic with a hash set to achieve optimal time complexity. It rewards careful iteration and teaches the power of only initiating work when it is necessary — a valuable lesson in writing efficient algorithms.