Blind 75

Longest Consecutive Sequence

Problem
LC 128
Category
Graph
File
blind75_LC128LongestConsecutiveSequence.java
Path
pkg5leetcode/blind75/blind75_LC128LongestConsecutiveSequence.java
Package
pkg5leetcode.blind75
Command
java pkg5leetcode/blind75/blind75_LC128LongestConsecutiveSequence.java
Approach
HashSet; start streak only from sequence minimum.
Complexity
Time O(n), Space O(n)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/blind75/blind75_LC128LongestConsecutiveSequence.java
1package pkg5leetcode.blind75;2 3/*4 * Longest Consecutive Sequence | LC 1285 * APPROACH: HashSet; start streak only from sequence minimum.6 * COMPLEXITY: Time O(n), Space O(n)7 */8import java.util.*;9 10public class blind75_LC128LongestConsecutiveSequence {11    static int longestConsecutive(int[] nums) {12        Set<Integer> set = new HashSet<>();13        for (int x : nums) set.add(x);14        int best = 0;15        for (int x : set) {16            if (set.contains(x - 1)) continue;17            int len = 1;18            while (set.contains(x + len)) len++;19            best = Math.max(best, len);20        }21        return best;22    }23 24    public static void main(String[] args) {25        check(longestConsecutive(new int[]{100, 4, 200, 1, 3, 2}) == 4, "case1");26        check(longestConsecutive(new int[]{0, 3, 7, 2, 5, 8, 4, 6, 0, 1}) == 9, "case2");27        System.out.println("all tests passed");28    }29 30    static void check(boolean cond, String name) {31        if (!cond) throw new AssertionError("FAILED: " + name);32        System.out.println("  PASS " + name);33    }34}