Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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: 4
Explanation: 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: 9
Example 3:
Input: nums = [1,0,1,2] Output: 3
Constraints:
0 <= nums.length <= 105-109 <= nums[i] <= 109Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Union-Find
[100,4,200,1,3,2]
[0,3,7,2,5,8,4,6,0,1]
[1,0,1,2]
binary-tree-longest-consecutive-sequence)find-three-consecutive-integers-that-sum-to-a-given-number)maximum-consecutive-floors-without-special-floors)length-of-the-longest-alphabetical-continuous-substring)find-the-maximum-number-of-elements-in-subset)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #128: Longest Consecutive Sequence
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> s = new HashSet<>();
for (int x : nums) {
s.add(x);
}
int ans = 0;
Map<Integer, Integer> d = new HashMap<>();
for (int x : nums) {
int y = x;
while (s.contains(y)) {
s.remove(y++);
}
d.put(x, d.getOrDefault(y, 0) + y - x);
ans = Math.max(ans, d.get(x));
}
return ans;
}
}
// Accepted solution for LeetCode #128: Longest Consecutive Sequence
func longestConsecutive(nums []int) (ans int) {
s := map[int]bool{}
for _, x := range nums {
s[x] = true
}
d := map[int]int{}
for _, x := range nums {
y := x
for s[y] {
delete(s, y)
y++
}
d[x] = d[y] + y - x
ans = max(ans, d[x])
}
return
}
# Accepted solution for LeetCode #128: Longest Consecutive Sequence
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
s = set(nums)
ans = 0
d = defaultdict(int)
for x in nums:
y = x
while y in s:
s.remove(y)
y += 1
d[x] = d[y] + y - x
ans = max(ans, d[x])
return ans
// Accepted solution for LeetCode #128: Longest Consecutive Sequence
use std::collections::{HashMap, HashSet};
impl Solution {
pub fn longest_consecutive(nums: Vec<i32>) -> i32 {
let mut s: HashSet<i32> = nums.iter().cloned().collect();
let mut ans = 0;
let mut d: HashMap<i32, i32> = HashMap::new();
for &x in &nums {
let mut y = x;
while s.contains(&y) {
s.remove(&y);
y += 1;
}
let length = d.get(&(y)).unwrap_or(&0) + y - x;
d.insert(x, length);
ans = ans.max(length);
}
ans
}
}
// Accepted solution for LeetCode #128: Longest Consecutive Sequence
function longestConsecutive(nums: number[]): number {
const s = new Set(nums);
let ans = 0;
const d = new Map<number, number>();
for (const x of nums) {
let y = x;
while (s.has(y)) {
s.delete(y++);
}
d.set(x, (d.get(y) || 0) + (y - x));
ans = Math.max(ans, d.get(x)!);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Track components with a list or adjacency matrix. Each union operation may need to update all n elements’ component labels, giving O(n) per union. For n union operations total: O(n²). Find is O(1) with direct lookup, but union dominates.
With path compression and union by rank, each find/union operation takes O(α(n)) amortized time, where α is the inverse Ackermann function — effectively constant. Space is O(n) for the parent and rank arrays. For m operations on n elements: O(m × α(n)) total.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.