DEV Community

Debesh P.
Debesh P.

Posted on

128. Longest Consecutive Sequence | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/longest-consecutive-sequence/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/longest-consecutive-sequence/solutions/7500715/most-optimal-solution-in-internet-beats-t0gk3


leetcode 128


Solution

class Solution {
    public int longestConsecutive(int[] nums) {

        int n = nums.length;
        if (n == 0) return 0;
        int longestLength = 1;

        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < n; i++) {
            set.add(nums[i]);
        }

        for (int i : set) {
            if (!set.contains(i - 1)) {
                int count = 1;
                int x = i;
                while (set.contains(x + 1)) {
                    x++;
                    count++;
                }
                longestLength = Math.max(count, longestLength);
            }
        }

        return longestLength;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)