Find Longest Consecutive Sequence Length
C++
Hard
7 views
Problem Description
Find length of longest sequence of consecutive numbers that can be formed from array elements. This teaches set-based thinking.
Logic: For each number, check if it's start of sequence, then count length
Official Solution
void question14_longest_consecutive() {
int arr[] = {100, 4, 200, 1, 3, 2};
int size = 6;
int maxLength = 0;
for(int i = 0; i < size; i++) {
int current = arr[i];
int length = 1;
// Check if current is start of sequence
bool isStart = true;
for(int j = 0; j < size; j++) {
if(arr[j] == current - 1) {
isStart = false;
break;
}
}
if(isStart) {
while(true) {
bool found = false;
for(int j = 0; j < size; j++) {
if(arr[j] == current + 1) {
length++;
current++;
found = true;
break;
}
}
if(!found) break;
}
if(length > maxLength) {
maxLength = length;
}
}
}
cout << "Longest consecutive sequence length: " << maxLength << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!