The 30 second answer
I put all numbers in a HashSet. Then I only start counting from numbers that begin a run, meaning x minus 1 is not in the set, and walk upward while x plus 1 exists. Each number is visited at most twice, so it is linear time even though there is a nested loop. Sorting would also work, but in n log n.
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.
Understanding the prompt "Consecutive" refers to values, not positions. Duplicates don't extend a run.
Pattern recognition The O(n) requirement on unsorted data rules out sorting. Constant-time membership points to a hash set.
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.
Java solution
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
}
}Complexity O(n) expected time and O(n) space.
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.
Tests [100,4,200,1,3,2] returns 4. [0,3,7,2,5,8,4,6,0,1] returns 9. [] returns 0.
How to say it in the interview "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."
Sources (2)
- LeetCode 128: Longest Consecutive Sequenceleetcode.com
- Java SE 17 API: HashSetdocs.oracle.com