Tutorialspoint
Problem
Solution
Submissions

Longest Consecutive Sequence

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 20

Write a C program to find the length of the longest consecutive elements sequence in an unsorted array of integers. The algorithm must run in O(n) time complexity. A consecutive sequence is a sequence of integers where each number is exactly one more than the previous number.

Example 1
  • Input: nums = [100, 4, 200, 1, 3, 2]
  • Output: 4
  • Explanation:
    • The array contains [100, 4, 200, 1, 3, 2].
    • The longest consecutive sequence is [1, 2, 3, 4].
    • The length of this sequence is 4.
Example 2
  • Input: nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
  • Output: 9
  • Explanation:
    • The array contains [0, 3, 7, 2, 5, 8, 4, 6, 0, 1].
    • The longest consecutive sequence is [0, 1, 2, 3, 4, 5, 6, 7, 8].
    • The length of this sequence is 9.
Constraints
  • 0 ≤ nums.length ≤ 10^5
  • -10^9 ≤ nums[i] ≤ 10^9
  • Time Complexity: O(n)
  • Space Complexity: O(n)
  • Cannot use sorting algorithms
ArraysAirbnbTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a hash set to store all numbers for O(1) lookup time
  • For each number, check if it's the start of a sequence (no predecessor exists)
  • If it's a sequence start, count consecutive numbers from that point
  • Keep track of the maximum sequence length encountered
  • Skip numbers that are not sequence starts to avoid redundant work

Steps to solve by this approach:

 Step 1: Create a hash set and add all numbers from the array for O(1) lookup operations.

 Step 2: Iterate through each number in the original array to find potential sequence starts.
 Step 3: For each number, check if it's the beginning of a sequence (predecessor doesn't exist).
 Step 4: If it's a sequence start, count consecutive numbers by incrementing and checking existence.
 Step 5: Keep track of the maximum sequence length found during the iteration.
 Step 6: Skip numbers that are not sequence starts to avoid redundant counting.
 Step 7: Return the maximum consecutive sequence length after checking all potential starts.

Submitted Code :