LeetCode 128: Longest Consecutive Sequence Solution
Master LeetCode problem 128 (Longest Consecutive Sequence), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
128. Longest Consecutive Sequence
Problem Explanation
Explanation:
To solve this problem in O(n) time, we can use a HashSet to store all elements in the array. Then, we iterate through the array and for each element, we check if it is the start of a new consecutive sequence. To do this, we check if the element minus 1 is not in the set, which means it is the start of a sequence. We then keep incrementing the element by 1 and check if the incremented element is in the set. If it is, we keep incrementing the sequence length and update the maximum length found so far.
- Time complexity: O(n) where n is the number of elements in the input array.
- Space complexity: O(n) to store the elements in a HashSet.
Solution Code
import java.util.HashSet;
class Solution {
public int longestConsecutive(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int longestStreak = 0;
for (int num : nums) {
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 128 (Longest Consecutive Sequence)?
This page provides optimized solutions for LeetCode problem 128 (Longest Consecutive Sequence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 128 (Longest Consecutive Sequence)?
The time complexity for LeetCode 128 (Longest Consecutive Sequence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 128 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 128 in Java, C++, or Python.