Longest Consecutive Subsequence: O(n) Algorithm Optimization

Problem Statement

Given an unsorted array of integers, the task is to return the length of the longest consecutive elements sequence while ensuring an algorithm with O(n) time complexity. The goal is to calculate the longest chain of consecutive numbers present in the array.

Key constraints include:

  • 0 ≤ nums.length ≤ 10^5
  • -10^9 ≤ nums[i] ≤ 10^9

This guide explains various approaches to solving the problem, including naive, sorting, and optimal HashSet-based methods.

Detailed Examples and Explanations

Example 1

Input: nums = [100, 4, 200, 1, 3, 2]
Output: 4

Explanation: The longest consecutive sequence is [1, 2, 3, 4].
Natural question: How do you determine the start of a sequence?
By checking if the preceding number (num – 1) does not exist in the array, we can confirm the beginning of a consecutive chain.

Example 2

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

Explanation: Although duplicates exist, they are ignored. The consecutive sequence is effectively [0, 1, 2, 3, 4, 5, 6, 7, 8].

Example 3

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

Explanation: The consecutive sequence is [0, 1, 2]. Duplicate entries are not counted more than once.

Approaches and Algorithm Optimization

Naive Approach

The intuitive method involves iterating through each element and checking if the next consecutive element exists in the array. Although straightforward, it has a worst-case time complexity of O(n²) due to repeated searches.

Step-by-Step Process:

  • Iterate over each element.
  • For each element, check if the next consecutive number exists.
  • Count consecutive numbers and update the maximum length.

Issue : Inefficient for large inputs due to repeated searching.

Approaches and Algorithm Optimization

Optimization 1: Sorting (O(n log n))

Sorting the array can significantly reduce the number of lookups required.

Approach:

  1. Sort the Array: This operation takes O(n log n).

     

  2. Count Consecutive Sequences: Iterate through the sorted array, count consecutive numbers, and handle duplicates.

Sample C# Code:

				
					public class Solution {
    public int LongestConsecutive(int[] nums) {
        if (nums.Length == 0) return 0;

        Array.Sort(nums); // O(n log n)
        int maxLength = 1, count = 1;

        for (int i = 1; i < nums.Length; i++) {
            if (nums[i] == nums[i - 1])
                continue; // Skip duplicates

            if (nums[i] == nums[i - 1] + 1)
                count++;
            else {
                maxLength = Math.Max(maxLength, count);
                count = 1; // Reset count
            }
        }

        return Math.Max(maxLength, count);
    }
}

				
			

Optimal Approach: Using HashSet (O(n))

To meet O(n) time complexity, a HashSet is used for quick lookups.

Approach:

  1. Build a HashSet: Insert all elements for O(1) lookup.
  2. Identify Sequence Starts: Iterate through each number and start a sequence only if the previous number (num – 1) is not in the HashSet.
  3. Count Consecutive Elements: For each starting number, count the consecutive sequence length by checking subsequent numbers in the HashSet.
Optimal Approach_ Using HashSet (O(n))

Sample C# Code:

				
					public class Solution {
    public int LongestConsecutive(int[] nums) {
        if (nums.Length == 0) return 0;

        HashSet<int> numSet = new HashSet<int>(nums);
        int maxLength = 0;

        foreach (int num in numSet) {
            if (!numSet.Contains(num - 1)) { // Only start counting if num-1 is not present
                int currentNum = num;
                int count = 1;

                while (numSet.Contains(currentNum + 1)) {
                    currentNum++;
                    count++;
                }

                maxLength = Math.Max(maxLength, count);
            }
        }
        return maxLength;
    }
}

				
			

Dry Run of the HashSet Approach

For the input nums = [100, 4, 200, 1, 3, 2]:

  • Step 1: Insert all elements into a HashSet: {100, 4, 200, 1, 3, 2}.

     

  • Step 2: Iterate through each element.

     

  • For element 1, since 0 is not in the set, begin counting and find the sequence [1, 2, 3, 4].

     

  • Elements that are part of an already counted sequence are skipped.

     

Result: The longest consecutive sequence is of length 4.

Sample C# Code:

Code Implementations in Different Languages

C# Implementation

(See above for detailed C# code examples)

JavaScript Implementation

				
					var longestConsecutive = function(nums) {
    if (nums.length === 0) return 0;

    let maxLength = 0;

    for (let num of nums) {
        let currentNum = num;
        let count = 1;

        while (nums.includes(currentNum + 1)) {  // Searching for the next number
            currentNum++;
            count++;
        }

        maxLength = Math.max(maxLength, count);
    }

    return maxLength;
};

				
			

Python Implementation

				
					def longestConsecutive(nums):
    if not nums:
        return 0

    max_length = 0

    for num in nums:
        current_num = num
        count = 1

        while current_num + 1 in nums:  # Searching for the next number
            current_num += 1
            count += 1

        max_length = max(max_length, count)

    return max_length

				
			

Final Thoughts

This problem illustrates the importance of selecting the right data structure to optimize algorithm performance. The transition from a naive O(n²) approach to a more refined O(n) solution using HashSet shows how minor adjustments can lead to significant improvements in efficiency. This knowledge is beneficial for technical interviews and for understanding practical optimization techniques.

This insightful blog post is authored by Ajit Pedha, who brings his expertise and deep understanding of the topic to provide valuable perspectives.

What Should I Focus on for Airbnb DSA Interviews?

When preparing for Airbnb DSA interviews, focus on mastering the fundamentals of data structures and algorithms. This includes arrays, linked lists, trees, graphs, dynamic programming, and sorting techniques. A well-structured study plan that includes hands-on practice with real-world problems will boost your confidence and performance. For a detailed course on DSA fundamentals, check out this course.

Code optimization is crucial during DSA interviews because it reflects your ability to write efficient and scalable solutions. Interviewers are not only interested in getting the correct answer but also in understanding your thought process and how you handle large inputs. Ensuring your solution runs within optimal time and space limits is essential for success. To learn more about optimizing your coding techniques, explore this web development course.

Absolutely, practicing on paper or a whiteboard can significantly improve your interview performance. It helps simulate the real interview environment where you need to articulate your thought process without the aid of an IDE. Regular practice in this format enables you to organize your ideas better and communicate more effectively under pressure. For more insights on preparing for technical interviews, consider checking out this combined DSA and design course.

DSA, High & Low Level System Designs

Buy for 60% OFF
₹25,000.00 ₹9,999.00

Accelerate your Path to a Product based Career

Boost your career or get hired at top product-based companies by joining our expertly crafted courses. Gain practical skills and real-world knowledge to help you succeed.

Reach Out Now

If you have any queries, please fill out this form. We will surely reach out to you.

Contact Email

Reach us at the following email address.

arun@getsdeready.com

Phone Number

You can reach us by phone as well.

+91-97737 28034

Our Location

Rohini, Sector-3, Delhi-110085

WhatsApp Icon

Master Your Interviews with Our Free Roadmap!

Hi Instagram Fam!
Get a FREE Cheat Sheet on System Design.

Hi LinkedIn Fam!
Get a FREE Cheat Sheet on System Design

Loved Our YouTube Videos? Get a FREE Cheat Sheet on System Design.