For example, given [100, 4, 200, 1, 3, 2]
, the longest consecutive element sequence is [1, 2, 3, 4]
. Return its length: 4
.
Algorithm should run in O(n)
complexity.
JAVA
import java.util.HashSet;
public class LongestConsecutiveSequence {
public int longestConsecutive(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int longestStreak = 0;
for (int num : set) {
if (!set.contains(num - 1)) {
int currentNum = num;
int currentStreak = 1;
while (set.contains(currentNum + 1)) {
currentNum++;
currentStreak++;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
public static void main(String[] args) {
int[] nums = {100, 4, 200, 1, 3, 2};
LongestConsecutiveSequence solution = new LongestConsecutiveSequence();
System.out.println(solution.longestConsecutive(nums)); // Output: 4
}
}
JAVASCRIPT
function longestConsecutive(nums) {
const set = new Set(nums);
let longestStreak = 0;
for (const num of set) {
if (!set.has(num - 1)) {
let currentNum = num;
let currentStreak = 1;
while (set.has(currentNum + 1)) {
currentNum++;
currentStreak++;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
const nums = [100, 4, 200, 1, 3, 2];
console.log(longestConsecutive(nums)); // Output: 4
PYTHON
def longest_consecutive(nums):
num_set = set(nums)
longest_streak = 0
for num in num_set:
if num - 1 not in num_set:
current_num = num
current_streak = 1
while current_num + 1 in num_set:
current_num += 1
current_streak += 1
longest_streak = max(longest_streak, current_streak)
return longest_streak
nums = [100, 4, 200, 1, 3, 2]
print(longest_consecutive(nums)) # Output: 4