Tutorialspoint
Problem
Solution
Submissions

Longest Consecutive Sequence

Certification: Advanced Level Accuracy: 100% Submissions: 1 Points: 15

Write a Java 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 in which each element is exactly one more than the previous element.

Example 1
  • Input: nums = [100, 4, 200, 1, 3, 2]
  • Output: 4
  • Explanation: The consecutive sequences in the array are [1, 2, 3, 4] and [100], [200]. The longest consecutive sequence is [1, 2, 3, 4] with a length of 4. Therefore, the output is 4.
Example 2
  • Input: nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
  • Output: 9
  • Explanation: The consecutive sequences in the array are [0, 1, 2, 3, 4, 5, 6, 7, 8] and [0]. The longest consecutive sequence is [0, 1, 2, 3, 4, 5, 6, 7, 8] with a length of 9. Therefore, the output is 9.
Constraints
  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • Time Complexity: O(n)
  • Space Complexity: O(n)
ArraysHashSetDeloitteAirbnb
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 HashSet to store all the numbers for O(1) lookup
  • For each number in the array, check if it's the start of a sequence (i.e., num-1 is not in the set)
  • If it's a start, count consecutive numbers (num+1, num+2, etc.) that exist in the set
  • Keep track of the maximum length of consecutive sequences found
  • Since each number is checked at most twice, the time complexity remains O(n)

Steps to solve by this approach:

 Step 1: Handle the edge case of an empty array by returning 0.

 Step 2: Create a HashSet and add all numbers from the array to enable O(1) lookups.
 Step 3: Iterate through each unique number in the HashSet.
 Step 4: For each number, check if it's the start of a sequence by verifying that num-1 does not exist in the set.
 Step 5: If it's a sequence start, count the length of the consecutive sequence by checking if num+1, num+2, etc. exist in the set.
 Step 6: Track the maximum length of consecutive sequences found so far.
 Step 7: Return the longest consecutive sequence length after processing all numbers.

Submitted Code :