Algo-Sim › Arrays & Hashing
Longest Consecutive Sequence
Medium · Arrays & Hashing · step through it in Java, Python and C++ on your own input
Find the length of the longest run of consecutive integers in an unsorted array, in O(n), with a hash set.
Problem
Given an unsorted integer array nums, return the length of the longest run of values x, x + 1, x + 2, … that are all present in the array. The values need not be adjacent in nums, and duplicates count once.
Constraints
- 0 ≤ nums.length ≤ 10⁵
- -10⁹ ≤ nums[i] ≤ 10⁹
- Must run in O(n), so sorting is not allowed
Edge cases to test
- Empty array:
0 - Duplicates:
[1, 2, 2, 3]is a run of 3 - Negative values and a run that crosses
0
Follow-up questions
- Why is it O(n) when there is a loop inside the loop?
- A run is only walked from its smallest value (the one with no
x − 1in the set), so each value is visited a constant number of times overall. - What if you can sort?
- Sort and count runs, skipping equal neighbours: O(n log n) time, O(1) extra space.
- What if numbers keep arriving?
- Union-find over value neighbours (or a map from run ends to lengths): near O(1) amortized per insert.
Solution
Java
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int x : nums) set.add(x);
int best = 0;
for (int x : set) {
if (set.contains(x - 1)) continue;
int length = 1;
while (set.contains(x + length)) length++;
best = Math.max(best, length);
}
return best;
}Python
def longest_consecutive(nums):
num_set = set(nums)
best = 0
for x in num_set:
if x - 1 in num_set:
continue
length = 1
while x + length in num_set:
length += 1
best = max(best, length)
return bestC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int longestConsecutive(vector<int> &nums) {
unordered_set<int> set = {};
for (int x : nums)
set.insert(x);
int best = 0;
for (int x : set) {
if (set.count(x - 1))
continue;
int length = 1;
while (set.count(x + length))
length++;
best = std::max(best, length);
}
return best;
}
};
More Arrays & Hashing problems
- Contains Duplicate (Easy)
- Valid Anagram (Easy)
- Two Sum (Easy)
- Group Anagrams (Medium)
- Top K Frequent Elements (Medium)
- Encode and Decode Strings (Medium)
- Product of Array Except Self (Medium)
- Majority Element (Easy)
- Find All Numbers Disappeared in an Array (Easy)
- First Missing Positive (Hard)
- Range Sum Query - Immutable (Easy)
- Subarray Sum Equals K (Medium)
- Design HashMap (Easy)