<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest consecutive elements sequence.</em></p>

<p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [100,4,200,1,3,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The longest consecutive elements sequence is <code>[1, 2, 3, 4]</code>. Therefore its length is 4.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [0,3,7,2,5,8,4,6,0,1]
<strong>Output:</strong> 9
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
</ul>

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        if len(nums) <= 1:
            return len(nums)

        nums = list(set(nums))

        sequence_starts = dict()
        sequence_ends = dict()
        
        for i in range(len(nums)):
            if nums[i] - 1 in sequence_ends:
                start_of_sequence = sequence_ends[nums[i] - 1]
                sequence_ends[nums[i]] = start_of_sequence
                del sequence_ends[nums[i] - 1]
                sequence_starts[start_of_sequence] = nums[i]
                
                if nums[i] + 1 in sequence_starts:
                    end_of_sequence = sequence_starts[nums[i] + 1]
                    del sequence_starts[nums[i] + 1]
                    del sequence_ends[nums[i]]
                    sequence_starts[start_of_sequence] = end_of_sequence
                    sequence_ends[end_of_sequence] = start_of_sequence

            elif nums[i] + 1 in sequence_starts:
                end_of_sequence = sequence_starts[nums[i] + 1]
                del sequence_starts[nums[i] + 1]
                sequence_starts[nums[i]] = end_of_sequence
                sequence_ends[end_of_sequence] = nums[i]

            else:
                sequence_starts[nums[i]] = nums[i]
                sequence_ends[nums[i]] = nums[i]

        largest_length = max([end - start + 1
                              for start, end
                              in sequence_starts.items()])
        return largest_length

34450