labels: Arrays, Hashing, Medium
Time Completed: N/A
Link to problem: 128. Longest Consecutive Sequence
- Create hashset from nums
- Iterate through nums
- Check if num is the start of a sequence by confirming num - 1 isnt in the set
- if num is start of sequence, check num + 1 until it doesnt exist in the set. increment length
- set longest length to max()
- done
- Sometimes the solution calls for a simple hashmap but devising an algorithm that efficiently uses the properties of a hashmap. For example, in this problem we use a hashmap just to store the nums for O(1) lookup and devise an algorithm to check for sequences. Although we use a hashmap, the hard part was devising the algorithm
def longestConsecutive(self, nums):
hashmap = set(nums)
longest = 0
for num in nums:
# check if its the start of a sequence
if (num - 1) not in hashmap:
length = 0
while (num + length) in hashmap:
length += 1
longest = max(length, longest)
return longest