Tutorialspoint
Problem
Solution
Submissions

Longest Consecutive Sequence

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

Write a C# program to implement the LongestConsecutive(int[] nums) function, which finds the length of the longest consecutive elements sequence in an unsorted array of integers. Your function should run in O(n) time complexity.

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
  • Explanation:
    • The longest consecutive elements sequence is [0, 1, 2, 3, 4, 5, 6, 7, 8]. Therefore its length is 9.
Constraints
  • 0 ≤ nums.length ≤ 10^5
  • -10^9 ≤ nums[i] ≤ 10^9
  • Time Complexity: O(n)
  • Space Complexity: O(n)
ArraysHash MapZomatoArctwist
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 efficiently check if elements exist in the array
  • For each number, check if it's the start of a sequence by verifying if its predecessor exists
  • If it's a start, count the consecutive sequence length
  • Keep track of the maximum sequence length encountered
  • A single pass through the array is sufficient for O(n) time complexity

Steps to solve by this approach:

 Step 1: Create a HashSet to store all numbers from the input array for O(1) lookups.
 Step 2: Initialize a variable to track the maximum length of consecutive sequence.
 Step 3: Iterate through each number in the array.
 Step 4: For each number, check if it's the start of a sequence by verifying its predecessor doesn't exist.
 Step 5: If it's a start of a sequence, count how long the sequence extends by checking for consecutive numbers.
 Step 6: Update the maximum length if the current sequence is longer.
 Step 7: Return the maximum length found after checking all possible sequences.

Submitted Code :