Problem
Given an unsorted integer array, return the length of the longest run of consecutive integers (like 1,2,3,4) whose values appear in the array, in any order. The original asks for O(n) time.
Original: LeetCode 128: Longest Consecutive Sequence.
Examples
Example 1
`nums = [100, 4, 200, 1, 3, 2]``4`Example 2
`nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]``9`Example 3
`nums = []``0`Constraints
0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Hints
Hint 1
"Consecutive" refers to values, not positions. Duplicates don't extend a run.
Hint 2
The O(n) requirement on unsorted data rules out sorting. Constant-time membership points to a hash set.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. For every number, count upward with a linear search for each next value: O(n²) or worse.
Optimal. Use a set of all values. Only start a run at x when x - 1 isn't present, then extend while x + 1 is. Every value is part of exactly one counted run, so the total work is O(n).
Alternatives.
- Sort and scan, skipping duplicates: O(n log n) time.
- Union-find over neighbouring values also works, but it is more code.
Complexity
- Time
- O(n)
O(n) expected time and O(n) space.
- Space
- O(n)
Code
import java.util.HashSet;
public class LongestConsecutive {
static int longestConsecutive(int[] nums) {
var set = new HashSet<Integer>();
for (int x : nums) set.add(x);
int best = 0;
for (int x : set) {
if (set.contains(x - 1)) continue; // not the start of a run
int len = 1;
while (set.contains(x + len)) len++;
best = Math.max(best, len);
}
return best;
}
public static void main(String[] args) {
System.out.println(longestConsecutive(new int[] {100, 4, 200, 1, 3, 2})); // 4
System.out.println(longestConsecutive(new int[] {0, 3, 7, 2, 5, 8, 4, 6, 0, 1})); // 9
System.out.println(longestConsecutive(new int[] {})); // 0
}
}Edge cases
- An empty array returns 0.
- Duplicates.
- Negative numbers.
- Values next to Integer.MAX_VALUE:
x + lencould overflow. Mention it, and use long arithmetic if the inputs can reach the int limits.
Follow-ups
- Return the sequence itself: remember the start and length of the best run.
- Streaming inserts: union-find or a map from run ends to run lengths.
Interview script
"Sorting gives O(n log n), but they want O(n). I load everything into a hash set and only start counting at numbers whose predecessor is missing. Each value is walked once, so the total is linear."
Source: LeetCode 128: Longest Consecutive Sequence Source: Java SE 17 API: HashSet
Sources (2)
- LeetCode 128: Longest Consecutive Sequenceleetcode.com
- Java SE 17 API: HashSetdocs.oracle.com