Taro Logo

Longest Consecutive Sequence

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+28
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.7K views
Topics:
Arrays

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

You must write an algorithm that runs in O(n) time.

Example 1:

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Example 2:

Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9

Example 3:

Input: nums = [1,0,1,2]
Output: 3

Constraints:

  • 0 <= nums.length <= 105
  • -109 <= nums[i] <= 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the input array be empty, and if so, what should be returned?
  2. How should duplicate values in the array be handled, and do they impact the length of a consecutive sequence?
  3. Can the array contain negative numbers as well as zeros and positive numbers?
  4. Are the numbers in the array guaranteed to fit within standard 32-bit signed integer limits?
  5. If there are multiple consecutive sequences of the same maximum length, does it matter which one's length is returned?

Brute Force Solution

Approach

Imagine you have a messy pile of numbered cards and you want to find the longest chain of numbers that follow right after one another, like two, three, four, and five. The brute force approach works by picking every single number in your pile as a starting point and manually hunting through the rest of the pile to see how far the chain can go.

Here's how the algorithm would work step-by-step:

  1. Pick the first number in your collection to be the starting point of your chain.
  2. Look at that starting number and check if the number that is greater by one is present in your collection.
  3. If you find it, add one to your chain length and then look for the next number that is greater by one, continuing this search over and over.
  4. Keep searching until you cannot find the next consecutive number in your collection.
  5. Write down the total length of the chain you just built.
  6. Reset your count, pick a completely different number from your collection as a new starting point, and repeat the entire search process.
  7. Do this exhausting check for every single number available in your collection.
  8. Compare the lengths of all the chains you discovered and declare the longest one as your final answer.

Code Implementation

def longest_consecutive(numbers):
    # We must track the longest chain found across all possible starting points
    max_chain_length = 0

    for starting_number in numbers:
        current_chain_length = 1
        current_number = starting_number

        # We hunt through the collection repeatedly to extend our current chain
        while (current_number + 1) in numbers:
            current_number += 1
            current_chain_length += 1

        # We update our record whenever a checked chain beats the previous best
        if current_chain_length > max_chain_length:
            max_chain_length = current_chain_length

    return max_chain_length

Big(O) Analysis

Time Complexity
O(n²) – For each of the n numbers in your collection serving as a starting point, the algorithm exhaustively hunts through the collection to check for the existence of the next consecutive number. In the worst-case scenario, this linear search repeats for up to n steps for every single one of the n starting points. This repeated searching across all elements leads to approximately n * n operations. Simplifying this expression by dropping constants results in a final Big O time complexity of O(n²).
Space Complexity
O(1) – The brute force approach described relies entirely on the original collection of numbers without utilizing any auxiliary data structures, hash sets, or temporary storage. The algorithm only maintains a few primitive integer variables for loop counters and tracking chain lengths, which require a constant amount of extra memory. Therefore, as the input size N grows, the auxiliary space remains entirely static regardless of how many numbers are in the pile. This results in a constant space complexity of O(1).

Optimal Solution

Approach

Instead of sorting everything or checking every possible line starting from every single number, the optimal approach uses a quick lookup helper to only build sequences from their actual starting points. By ignoring numbers that are just middle pieces of a sequence, we save a massive amount of time.

Here's how the algorithm would work step-by-step:

  1. Gather all the unique items into a central lookup list so you can instantly check if any specific value exists.
  2. Look at each item and ask yourself a crucial question: is this item the absolute beginning of a chain?
  3. To answer that question, check your lookup list to see if the value right before the current one exists.
  4. If the value right before exists, ignore the current item because it is just a middle piece and not a starting point.
  5. If the value right before does not exist, you have officially found the start of a brand new chain.
  6. From this verified starting point, begin counting upward by checking your lookup list for the next consecutive values one by one.
  7. Keep track of how far you can go before the chain breaks, and remember this length if it beats your previous best record.
  8. Repeat this quick check only for the items that qualify as true starting points, completely skipping all the middle pieces, until you find the longest chain overall.

Code Implementation

def longest_consecutive(integer_list):
    # Using a set provides O(1) lookups, crucial for checking existence efficiently.
    unique_number_set = set(integer_list)
    
    maximum_chain_length = 0

    for current_number in unique_number_set:
        # Skipping non-starting elements ensures we only evaluate valid sequence heads.
        if (current_number - 1) not in unique_number_set:
            active_number = current_number
            current_chain_length = 1

            while (active_number + 1) in unique_number_set:
                active_number += 1
                current_chain_length += 1

            # We track the highest length found to avoid missing the longest sequence.
            if current_chain_length > maximum_chain_length:
                maximum_chain_length = current_chain_length

    return maximum_chain_length

Big(O) Analysis

Time Complexity
O(n) – First, we insert all n unique items from the array into a hash set, which takes O(n) time since individual insertions take constant time on average. Next, we iterate through each of the n items in the array to check if it is the start of a sequence. Even though there is a while loop that counts consecutive numbers upward, each number in a sequence is only ever inspected inside this while loop when evaluating its true starting point. Therefore, every element is looked up in the set a constant number of times overall across the entire execution. This means the total operations scale linearly as n + n, which simplifies to O(n).
Space Complexity
O(n) – To implement the quick lookup helper mentioned in step 1, we must insert all unique items from the input into a central hash set, where N represents the total number of elements in the input array. This auxiliary hash set stores up to N elements, meaning the extra memory required grows in direct proportion to the input size. Additionally, a few primitive variables are used to keep track of the current sequence length and the best record overall, requiring constant extra space. Therefore, combining the hash set and the tracking variables, the total auxiliary space complexity simplifies to Big O of N.

Edge Cases

Empty array or null input
How to Handle:
Check for null or empty input at the start and return zero immediately.
Array with a single element
How to Handle:
The algorithm skips the sequence-starting check and correctly returns a length of one.
Array containing duplicate numbers
How to Handle:
Inserting elements into a set automatically de-duplicates them without affecting the sequence length calculation.
Array containing negative numbers and zero
How to Handle:
The hash set handles negative integers and zero seamlessly because hash-based lookups work across the entire integer range.
Array with all identical elements
How to Handle:
The set reduces all duplicates to a single value, and since no consecutive neighbors exist, the maximum length returned is one.
Extremely large array with no consecutive sequences
How to Handle:
Using a hash set allows $O(N)$ time complexity, ensuring the solution scales efficiently without hitting time limits.
Disconnected sequences of varying lengths
How to Handle:
The algorithm only initiates a count when it finds the true start of a sequence, avoiding redundant inner loops and maintaining $O(N)$ time.
Numbers near integer overflow limits
How to Handle:
Using standard 32-bit or 64-bit integer addition when checking for num plus one requires care to prevent overflow in languages with strict bounds.
0/75 completed