Longest Consecutive Sequence
MedPrompt
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
[1, 2, 3, 4]Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9Example 3:
Input: nums = [1,0,1,2]
Output: 3
Constraints:
0 <= nums.length <= 105-109 <= nums[i] <= 109
Approaches
3 approaches with complexity analysis and trade-offs.
This approach iterates through each number in the array. For each number, it attempts to build a sequence by repeatedly checking if the next consecutive number exists anywhere else in the array. This check is done via a linear scan.
Algorithm
- Initialize a variable
maxLengthto 0.\n- For each numbernumin the input arraynums:\n - InitializecurrentNum = numandcurrentLength = 1.\n - Start a loop:\n - Check ifcurrentNum + 1exists in thenumsarray by performing a linear scan.\n - If it exists, incrementcurrentLength, updatecurrentNumtocurrentNum + 1, and continue the loop.\n - If it does not exist, break the loop.\n - UpdatemaxLength = max(maxLength, currentLength).\n- After iterating through all numbers, returnmaxLength.
Walkthrough
The brute-force algorithm iterates through every number in the input array nums. For each number num, it assumes it could be the start of a consecutive sequence. It then enters a while loop, checking for the existence of num + 1, num + 2, and so on. The check for existence is performed by another linear scan through the entire array. The length of the current sequence is tracked, and the maximum length found across all possible starting numbers is returned. This method is straightforward to conceptualize but is highly inefficient due to the nested loops and repeated scans.\n\njava\nclass Solution {\n private boolean arrayContains(int[] arr, int num) {\n for (int i = 0; i < arr.length; i++) {\n if (arr[i] == num) {\n return true;\n }\n }\n return false;\n }\n\n public int longestConsecutive(int[] nums) {\n if (nums.length == 0) {\n return 0;\n }\n\n int longestStreak = 0;\n\n for (int num : nums) {\n int currentNum = num;\n int currentStreak = 1;\n\n while (arrayContains(nums, currentNum + 1)) {\n currentNum += 1;\n currentStreak += 1;\n }\n\n longestStreak = Math.max(longestStreak, currentStreak);\n }\n\n return longestStreak;\n }\n}\n
Complexity
Time
O(n^3)
Space
O(1)
Trade-offs
Pros
Simple to understand and implement.
Uses constant extra space, O(1).
Cons
Extremely inefficient with a time complexity of O(n^3), making it impractical for even moderately sized inputs.
Will result in a 'Time Limit Exceeded' error on most coding platforms.
Solutions
Solution
class Solution { public int longestConsecutive ( int [] nums ) { Set < Integer > s = new HashSet <>(); for ( int x : nums ) { s . add ( x ); } int ans = 0 ; for ( int x : nums ) { if (! s . contains ( x - 1 )) { int y = x + 1 ; while ( s . contains ( y )) { ++ y ; } ans = Math . max ( ans , y - x ); } } return ans ; } }Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.