Sorting
Intuition
A straightforward approach is to sort the array first. Once sorted, consecutive numbers will be adjacent. We scan through the sorted array, counting the length of each consecutive run while skipping duplicates. This does not meet the O(n) requirement but is simple to implement and easy to understand.
Algorithm
- If the array is empty, return 0.
- Sort the array.
- Initialize longest to 1 and currentStreak to 1.
- Iterate from index 1 to n-1. If nums[i] == nums[i-1], skip (duplicate). If nums[i] == nums[i-1] + 1, increment currentStreak. Otherwise, reset currentStreak to 1.
- Update longest with the maximum of longest and currentStreak at each step.
- Return longest.
O(n log n)SpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if (nums.empty()) return 0;
sort(nums.begin(), nums.end());
int longest = 1;
int currentStreak = 1;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] == nums[i - 1]) continue;
if (nums[i] == nums[i - 1] + 1) {
currentStreak++;
} else {
currentStreak = 1;
}
longest = max(longest, currentStreak);
}
return longest;
}
};class Solution {
public int longestConsecutive(int[] nums) {
if (nums.length == 0) return 0;
Arrays.sort(nums);
int longest = 1;
int currentStreak = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) continue;
if (nums[i] == nums[i - 1] + 1) {
currentStreak++;
} else {
currentStreak = 1;
}
longest = Math.max(longest, currentStreak);
}
return longest;
}
}def longestConsecutive(nums: list[int]) -> int:
if not nums:
return 0
nums.sort()
longest = 1
current_streak = 1
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
continue
if nums[i] == nums[i - 1] + 1:
current_streak += 1
else:
current_streak = 1
longest = max(longest, current_streak)
return longestimport "sort"
func longestConsecutive(nums []int) int {
if len(nums) == 0 {
return 0
}
sort.Ints(nums)
longest := 1
currentStreak := 1
for i := 1; i < len(nums); i++ {
if nums[i] == nums[i-1] {
continue
}
if nums[i] == nums[i-1]+1 {
currentStreak++
} else {
currentStreak = 1
}
if currentStreak > longest {
longest = currentStreak
}
}
return longest
}