Skip to content

Latest commit

 

History

History
83 lines (60 loc) · 1.81 KB

_128. Longest Consecutive Sequence.md

File metadata and controls

83 lines (60 loc) · 1.81 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 13, 2024

Last updated : July 01, 2024


Related Topics : Array, Hash Table, Union Find

Acceptance Rate : 47.31 %


Solutions

Java

class Solution {
    public int longestConsecutive(int[] nums) {
        HashSet<Integer> vals = new HashSet<>();

        for (int n : nums) {
            vals.add(n);
        }

        int maxCounter = 0;
        for (int n : vals) {
            if (vals.contains(n - 1)) {
                continue;
            }

            int counter = 1;
            while (vals.contains(n + counter)) {
                counter++;
            }

            if (counter > maxCounter) {
                maxCounter = counter;
            }

        }
        return maxCounter;
    }
}

Python

# O(n) solution babyyyy

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        if len(nums) == 0 :
            return 0
        
        vals = set(nums)                # O(n) creation, O(1) lookups

        maxx = 0
        for val in vals:                # O(n) looping
            if val - 1 in vals:         # not start of sequence
                continue
            
            cnter = 1
            while val + cnter in vals :
                cnter += 1

            maxx = max(maxx, cnter)

        return maxx