Problem Category:: Array, Set Neetcode Category:: Arrays and Hashing

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

Given an unsorted array of integers nums, return _the length of the longest consecutive elements sequence.

  • You must write an algorithm that runs in  time.

Thoughts

  • so sorting is unlikely, probably have to use a dict based method with either Dictionary ADT or Set ADT
  • If we can’t avoid a nested loop, then we must find a way

Optimal

Sets and avoiding repetition when sequence building

Alter the brute force algorithm to use the Dictionary based Set ADT for constant lookup, and then thus avoid repetition when building sequences

Python full solution

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        max_streak = 0
        # Use set which is implemented by a dict
        num_set = set(nums)
        
        # O(n)
        for num in num_set:
            current_num = num
            current_streak = 1
            # Ensure the preceding number is not already in the set to avoid repetition - if not then it will be a unique sequence
            if (num - 1) not in num_set: #O(1) lookup
                while current_num + 1 in num_set:
                    current_streak += 1
                    current_num += 1
                max_streak = max(max_streak, current_streak)
        
        return max_streak

Time complexity:

  • The inner while loop only runs time throughout the entire algorithm as it only passes once through each unique “increasing sequence”
  • Conversion to set Space complexity: to store the set

Failed solutions

Brute force

  • Loop through the list, try to build a streak by searching for the next number each time
  • time complexity, space complexity

Sorting