Longest Consecutive Sequence
Given an unsorted array of integers nums
You must write an algorithm that runs in O(n)
Example 1
Output: 4
Explanation: The longest consecutive elements sequence is
[1, 2, 3, 4]Example 2
Output: 9
Solution 1 - Store numbers into HashSet, find the starting of a sequence then find the longest consecutive sequence
In the problem statement, we were asked to find a solution with O(n)HashSetnumnum-1HashSet
import java.util.HashSet;
import java.util.stream.IntStream;
public class LongestConsecutiveSequence {
/**
*
* First store elements into a HashSet, then loop through each element in the array and find if
* previous number (num-1) exists in set, if it exists that means that is not the first number of
* a starting sequence, and if previous number does not exist, then this is the first number of a
* starting sequence.
*
* When you find a starting number of sequence, keep checking if next number exists (num+1)
* and find the longest
*/
static int longestConsecutiveUsingHashSet(int[] nums) {
HashSet<Integer> set = new HashSet<>(nums.length);
IntStream.of(nums).forEach(set::add);
int longest =0;
for(int num: nums) {
if(!set.contains(num-1)) {
// if the previous number is not in the set, that means this is the starting of sequence.
int currentLong = 1;
int currentNum = num;
while(set.contains(currentNum+1)) {
currentLong++;
currentNum++;
}
if(currentLong >longest) {
longest = currentLong;
}
}
}
return longest;
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n) time where nnums
Space complexity: O(n) since we are storing input array into a HashSet
Above implementations source code can be found at