Longest Consecutive Sequence in Java: Explanation & Practice

Find length of longest consecutive elements sequence

Problem summary

Given an unsorted array, find the length of the longest consecutive elements sequence. Use HashSet for O(n) solution.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] nums = {100, 4, 200, 1, 3, 2};
        
        // Add all to HashSet
        // Only start counting from sequence start (n-1 not in set)
        // Count consecutive numbers
        // Print: Length: 4
    }
}

Expected output and test cases

  • [100,4,200,1,3,2] → 1,2,3,4
    Length: 4
  • [0,3,7,2,5,8,4,6,0,1] → 0-8
    Length: 9
  • [] → 0
    Length: 0

Hints

  1. Put all numbers in HashSet for O(1) lookup
  2. Only start counting from sequence beginning (num-1 not in set)
  3. This ensures we count each sequence only once
  4. Count consecutive numbers using set.contains(num+1)

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler