Given an unsorted array, return the length of the longest run of consecutive integers. Aim for O(n) time.
Put everything in a set. Only start counting at x when x − 1 is absent (x starts a run), then walk x+1, x+2, … Each number is visited a constant number of times.
1function longestConsecutive(nums: number[]): number {2const set = new Set(nums);3let best = 0;4for (const x of set) {5if (set.has(x - 1)) continue;6let len = 1;7while (set.has(x + len)) len++;8best = Math.max(best, len);9}10return best;11}
Put every number in a set.
Space: play/pause · ←/→: step