How to find the length of the longest consecutive sequence of an unsorted list of integers in Java

1 Answer

0 votes
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
import java.util.List;

public class LongestConsecutiveSequence {

    public static int longestConsecutive(List<Integer> nums) {
        Set<Integer> numSet = new HashSet<>(nums);
        int longestStreak = 0;

        for (int num : numSet) {
            // Check if it's the start of a sequence
            if (!numSet.contains(num - 1)) {
                int currentNum = num;
                int currentStreak = 1;

                // Count the length of the sequence
                while (numSet.contains(currentNum + 1)) {
                    currentNum++;
                    currentStreak++;
                }

                longestStreak = Math.max(longestStreak, currentStreak);
            }
        }

        return longestStreak;
    }

    public static void main(String[] args) {
        List<Integer> nums = Arrays.asList(680, 4, 590, 3, 2, 1);
        
        int result = longestConsecutive(nums);
        
        System.out.println("Length of the longest consecutive sequence: " + result);
    }
}



/*
run:

Length of the longest consecutive sequence: 4

*/

 



answered Aug 18, 2025 by avibootz

Related questions

...