Problem
Section titled “Problem”Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]Output: 4Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]Output: 9Example 3:
Input: nums = [1,0,1,2]Output: 3Constraints:
-
nums.length -
nums[i]
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”Sorting and scanning for runs works, but costs . To reach we need to find runs without sorting.
Put every value in a hash set. A consecutive run x, x+1, ..., x+k-1 has exactly one start: the value x for which x - 1 is not in the set. If we only begin counting at starts and walk upward (x+1, x+2, …) while the next value exists, every value is visited by at most one walk — the walk of the run it belongs to. So all the walks together take steps.
Counting from every value instead (not just starts) would revisit the same run again and again and degrade to on input like [1, 2, ..., n].
Algorithm
Section titled “Algorithm”- Insert all of
numsinto the hash setseen(this also removes duplicates). - For each value
xinseen:- If
x - 1is inseen, skip it —xis not the start of a run. - Otherwise walk
end = x + 1, x + 2, ...whileendis inseen. The run length isend - x; keep the maximum inbest.
- If
- Return
best.
Walkthrough
Section titled “Walkthrough”For nums = [100,4,200,1,3,2], seen = {100, 4, 200, 1, 3, 2}:
100:99is absent, so it is a start;101is absent, length1.4,3,2:3,2,1are present, so they are skipped.200: start, length1.1:0is absent, so it is a start; walk2, 3, 4are present,5is not, length4.
The answer is 4.
Complexity
Section titled “Complexity”- Time: on average — building the set is ; each value is the subject of one start check and is stepped over by at most one walk, so the walks total hash lookups.
- Space: — the hash set.
Edge cases
Section titled “Edge cases”- Empty array: the set is empty, the loop never runs and
beststays0. - Duplicates (Example 3): the set stores each value once, so
[1,0,1,2]gives the run0, 1, 2of length3. - Extreme values:
x - 1andendare computed inlong long, so-10^9 - 1and10^9 + 1cannot overflow.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { public: int longestConsecutive(vector<int>& nums) { unordered_set<long long> seen(nums.begin(), nums.end()); int best = 0; for (long long x : seen) { if (seen.count(x - 1)) continue; // not the start of a run long long end = x + 1; while (seen.count(end)) end++; best = max(best, (int)(end - x)); } return best; }};class Solution { public int longestConsecutive(int[] nums) { Set<Integer> seen = new HashSet<>(); for (int x : nums) seen.add(x); int best = 0; for (int x : seen) { if (seen.contains(x - 1)) continue; // not the start of a run int end = x + 1; // |x| <= 10^9, so x - 1 and x + 1 fit in an int while (seen.contains(end)) end++; best = Math.max(best, end - x); } return best; }}class Solution: def longestConsecutive(self, nums: list[int]) -> int: seen = set(nums) best = 0 for x in seen: if x - 1 in seen: continue # not the start of a run end = x + 1 while end in seen: end += 1 best = max(best, end - x) return bestGive it a try first
Attempt the problem on LeetCode — the code will still be here.