💡 Sorting the array first helps by putting numbers in order, so consecutive sequences become adjacent, making it easier to count.
Intuition
Sort the array, then scan once to count lengths of consecutive runs by comparing adjacent elements.
Algorithm
- Sort the array.
- Initialize max length and current length counters.
- Iterate through the sorted array, increment current length if consecutive, else reset.
- Return the maximum length found.
💡 Sorting simplifies the problem but costs O(n log n) time; the linear scan then efficiently finds sequences.
def longestConsecutive(nums):
if not nums:
return 0
nums.sort()
max_len = 1
current_len = 1
for i in range(1, len(nums)):
if nums[i] == nums[i-1]:
continue # skip duplicates
elif nums[i] == nums[i-1] + 1:
current_len += 1
else:
max_len = max(max_len, current_len)
current_len = 1
max_len = max(max_len, current_len)
return max_len
# Driver code
if __name__ == '__main__':
print(longestConsecutive([100, 4, 200, 1, 3, 2])) # Output: 4
Line Notes
if not nums:Handle empty input edge case
nums.sort()Sort the array to bring consecutive numbers together
if nums[i] == nums[i-1]:Skip duplicates to avoid counting them multiple times
elif nums[i] == nums[i-1] + 1:Check if current number continues the consecutive sequence
import java.util.*;
public class Solution {
public static int longestConsecutive(int[] nums) {
if (nums.length == 0) return 0;
Arrays.sort(nums);
int maxLen = 1, currentLen = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i-1]) continue;
else if (nums[i] == nums[i-1] + 1) currentLen++;
else {
maxLen = Math.max(maxLen, currentLen);
currentLen = 1;
}
}
maxLen = Math.max(maxLen, currentLen);
return maxLen;
}
public static void main(String[] args) {
int[] nums = {100, 4, 200, 1, 3, 2};
System.out.println(longestConsecutive(nums)); // Output: 4
}
}
Line Notes
if (nums.length == 0) return 0;Handle empty input
Arrays.sort(nums);Sort array to group consecutive numbers
if (nums[i] == nums[i-1]) continue;Skip duplicates to avoid false increments
else if (nums[i] == nums[i-1] + 1)Detect consecutive numbers to increment current length
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int longestConsecutive(vector<int>& nums) {
if (nums.empty()) return 0;
sort(nums.begin(), nums.end());
int maxLen = 1, currentLen = 1;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] == nums[i-1]) continue;
else if (nums[i] == nums[i-1] + 1) currentLen++;
else {
maxLen = max(maxLen, currentLen);
currentLen = 1;
}
}
maxLen = max(maxLen, currentLen);
return maxLen;
}
int main() {
vector<int> nums = {100, 4, 200, 1, 3, 2};
cout << longestConsecutive(nums) << endl; // Output: 4
return 0;
}
Line Notes
if (nums.empty()) return 0;Handle empty input case
sort(nums.begin(), nums.end());Sort to bring consecutive numbers together
if (nums[i] == nums[i-1]) continue;Skip duplicates to avoid counting them multiple times
else if (nums[i] == nums[i-1] + 1)Check if current number continues the consecutive sequence
function longestConsecutive(nums) {
if (nums.length === 0) return 0;
nums.sort((a, b) => a - b);
let maxLen = 1, currentLen = 1;
for (let i = 1; i < nums.length; i++) {
if (nums[i] === nums[i-1]) continue;
else if (nums[i] === nums[i-1] + 1) currentLen++;
else {
maxLen = Math.max(maxLen, currentLen);
currentLen = 1;
}
}
return Math.max(maxLen, currentLen);
}
// Test
console.log(longestConsecutive([100, 4, 200, 1, 3, 2])); // Output: 4
Line Notes
if (nums.length === 0) return 0;Handle empty input edge case
nums.sort((a, b) => a - b);Sort array numerically to group consecutive numbers
if (nums[i] === nums[i-1]) continue;Skip duplicates to avoid false increments
else if (nums[i] === nums[i-1] + 1)Detect consecutive numbers to increment current length
TimeO(n log n)
SpaceO(1) or O(n) depending on sorting implementation
Sorting takes O(n log n), then a single pass O(n) to find longest consecutive sequence.
💡 For n=100000, sorting is feasible but slower than linear solutions; still acceptable in many interviews.
Interview Verdict: Accepted
This approach passes but is not optimal; it is a good intermediate step to show improvement over brute force.