Tutorialspoint
Problem
Solution
Submissions

Longest Consecutive Sequence

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

Write a C++ program to find the length of the longest consecutive elements sequence in an unsorted array of integers. A consecutive sequence is a sequence of integers where each value is exactly one more than the previous value.

Example 1
  • Input: nums = [100,4,200,1,3,2]
  • Output: 4
  • Explanation:
    • Step 1: Store all numbers in a hash set for O(1) lookups.
    • Step 2: For each number, check if it's the start of a sequence (no number-1 exists in the set).
    • Step 3: If it's a sequence start, count consecutive numbers (number+1, number+2, etc.).
    • Step 4: The longest sequence is [1,2,3,4] with length 4.
Example 2
  • Input: nums = [0,3,7,2,5,8,4,6,0,1]
  • Output: 9
  • Explanation:
    • Step 1: Store all numbers in a hash set for O(1) lookups.
    • Step 2: For each number, check if it's the start of a sequence (no number-1 exists in the set).
    • Step 3: If it's a sequence start, count consecutive numbers (number+1, number+2, etc.).
    • Step 4: The longest sequence is [0,1,2,3,4,5,6,7,8] with length 9.
Constraints
  • 0 ≤ nums.length ≤ 10^5
  • -10^9 ≤ nums[i] ≤ 10^9
  • Your algorithm should run in O(n) time complexity
  • Time Complexity: O(n) where n is the length of the array
  • Space Complexity: O(n)
Hash MapSetTech MahindraArctwist
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 enable O(1) lookups
  • Only start checking sequences from the smallest element of each sequence
  • For each number, check if it's the start of a sequence by looking for num-1
  • If it's the start of a sequence, count how long the sequence is
  • Consider edge cases like empty arrays or arrays with duplicate elements

Steps to solve by this approach:

 Step 1: Insert all array elements into a hash set for O(1) lookups.
 Step 2: Iterate through each number in the hash set.
 Step 3: For each number, check if it's the start of a sequence by confirming num-1 doesn't exist.
 Step 4: If it's the start of a sequence, count consecutive elements by checking for num+1, num+2, etc.
 Step 5: Update the longest streak length whenever a longer sequence is found.
 Step 6: Handle edge cases like empty arrays.
 Step 7: Return the maximum consecutive sequence length found.

Submitted Code :