An interactive visualization of how a hash set finds the longest run of consecutive numbers in O(n) time. Watch the algorithm identify sequence starts and extend them.
Hash Map LeetCode 128 โ Mediumnums, return the length of the longest consecutive elements sequence.[1, 2, 3, 4] is a consecutive sequence of length 4.
fun longestConsecutive(nums: IntArray): Int { val numSet = nums.toHashSet() var best = 0 for (n in numSet) { if (n - 1 !in numSet) { // start of seq var length = 1 while (n + length in numSet) { length++ } best = maxOf(best, length) } } return best}
The trick is to only start counting from the beginning of each sequence. A number n is
the start of a consecutive sequence if and only if n - 1 is not in the set.
By skipping numbers that are in the middle of a sequence, we ensure each number is visited at most twice
(once in the outer loop, once when extending), giving us O(n) total time.
n - 1 exists. If it does, n is not the start of a sequence โ skip it.n + 1, n + 2, ... until we find a gap. Track the length.
Although there is a nested while inside the for loop, each number is the start of at
most one sequence. Every number is extended through at most once across all iterations, so the total work is O(n).
The hash set uses O(n) extra space.