Leetcode 128: Longest Consecutive Sequence

Solving this problem in O(n) time and space relies on using a hash set to store all numbers. You then go through each element in the array and see if a[n]-1 is in the set, and if it isn’t then we know this is the start of the sequence and we look up subsequent numbers to see how long the sequence is. It works out to O(n) time and space, assuming unordered_set is O(1) lookup.

This entry was posted in programming and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.