150NeetCode 150

9.Longest Consecutive Sequence

MediumBlind 75Arrays & Hashing Ā· 9/9

Problem

Given an unsorted array of integers nums, return the length of the longest run of consecutive values (like 1, 2, 3, 4) that can be formed from its elements. The values do not need to be adjacent in the array — only their values matter.

You must write an algorithm that runs in O(n) time.

Examples

Input:  nums = [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive run is [1, 2, 3, 4].
Input:  nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
Output: 9
Explanation: 0 through 8 are all present (the duplicate 0 does not extend the run).
Input:  nums = []
Output: 0

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

šŸ’” Key Insight

Put all values in a HashSet for O(1) membership tests. A value x is the start of a run only if x - 1 is not in the set. Only from those starts do we count upward (x + 1, x + 2, …). Each value is then counted as part of exactly one upward walk, so the total work is O(n) even though there is a nested loop.

Brute Force

TimeO(n³)SpaceO(1)

Intuition

Treat every element as a potential start, and repeatedly search the array for the next value (x + 1, x + 2, …) with a linear scan until it is missing.

Algorithm

  1. best = 0.
  2. For each num:
    • cur = num, length = 1.
    • While contains(nums, cur + 1) (a linear scan): cur++, length++.
    • best = max(best, length).
  3. Return best.

Visualization

nums = [100, 4, 200, 1, 3, 2]

start 100: 101? no              → 1
start 4:   5? no                → 1
start 1:   2 āœ“ 3 āœ“ 4 āœ“ 5? no    → 4
start 3:   4 āœ“ 5? no            → 2
best = 4

Code

java
class Solution {
    public int longestConsecutive(int[] nums) {
        int best = 0;
        for (int num : nums) {
            int cur = num;
            int length = 1;
            while (contains(nums, cur + 1)) { // O(n) scan for every step
                cur++;
                length++;
            }
            best = Math.max(best, length);
        }
        return best;
    }

    private boolean contains(int[] nums, int target) {
        for (int x : nums) {
            if (x == target) {
                return true;
            }
        }
        return false;
    }
}

Complexity

  • Time: O(n³) — for each start, up to n steps, each with an O(n) scan.
  • Space: O(1) — no extra structures.

Complexity Comparison

Approach Time Space
Brute Force O(n³) O(1)
Sorting O(n log n) O(1)–O(log n)
Hash Set with Run Starts O(n) O(n)

Common Pitfalls

  • Skipping the x - 1 check — the solution is still correct but degrades to O(n²) on a long run like [1..10^5].
  • Iterating over nums instead of the set: an array with many copies of a run start re-walks the run each time (e.g. [1,1,1,...,2,3,...]), which can blow up to O(n²).
  • In the sorting approach, resetting cur on a duplicate — [0, 0, 1, 2] must give 3, not 2.
  • Forgetting the empty array, which must return 0.