128. Longest Consecutive Sequence

202402121906
tags: #hash-map

from collections import defaultdict

class Solution:
	def longestConsecutive(self, nums: List[int]) -> int:
		map = defaultdict(int)
		res = 0
		for num in nums:
			if map[num] != 0:
				continue
			prev = map[num - 1]
			next = map[num + 1]
			sum = prev + next + 1
			map[num] = sum
			res = max(res, sum)
			map[num - prev] = sum
			map[num + next] = sum
		return res

Reference

https://leetcode.com/problems/longest-consecutive-sequence/