---
# System prepended metadata

title: '[Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)'
tags: [Leetcode, Medium, Arrays and Hashing]

---

# [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)
###### tags: `Leetcode`, `Medium`, `Arrays and Hashing`

## Approach
* Add all the elements of the input list to a set
* Initialize `longestSeq`
* For every `num` in the input list
    * Check if `num - 1` does not exist in the set; initialize `length`
    * Then keep checking if `num + 1` exists in the set; if present, increment `length` by 1
    * set `longestSeq` to `max(longestSeq, length)`
* Return longestSeq

## Asymptotic Analysis
### Time Complexity: **O(N)**
### Space Complexity: **O(N)**

## Code
``` python
from typing import List


class LongestConsecutiveSequence:

    @staticmethod
    def longestConsecutive(nums: List[int]) -> int:
        num_set = set(nums)
        longest = 0
        for num in nums:
            if num - 1 not in num_set:
                current_longest = 1
                while num + 1 in num_set:
                    num += 1
                    current_longest += 1
                longest = max(longest, current_longest)
        return longest


nums = [100, 1, 200, 3, 201, 2, 4]
print(LongestConsecutiveSequence.longestConsecutive(nums))
```