longest Consecutive Seq Algorithm
The Longest Consecutive Sequence Algorithm is an efficient method used to determine the longest consecutive sequence of elements within an unsorted array or a set of integers. This algorithm can be very useful in various real-life applications, such as identifying patterns and trends in data analysis, or for solving problems in competitive programming contests. The primary objective of this algorithm is to find the length of the longest consecutive subsequence present in the given array, where each element in the subsequence differs by exactly one from its neighboring elements. The longest consecutive sequence does not have to be a contiguous subarray; it can be a sequence of elements whose consecutive integers are present in the array without any particular ordering.
The algorithm begins by initializing a data structure, such as a hash set, to store the unique elements of the input array. This data structure helps in efficiently determining if an element exists in the array or not. Next, the algorithm iterates through each element in the array and checks if the current element is the starting point of a sequence. This is done by checking if the element minus one is present in the hash set. If not, it means that the current element could be the starting point of a sequence. The algorithm then iterates through the consecutive integers starting from the current element until an integer is not found in the hash set. During this iteration, the length of the sequence is tracked and updated as necessary. After iterating through all the elements, the algorithm returns the length of the longest consecutive sequence found. The time complexity of this algorithm is O(n), where n is the number of elements in the input array, making it highly efficient for solving problems dealing with large datasets.
/**
* Leet code problem:
* Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
* For example,
* Given [100, 4, 200, 1, 3, 2],
* The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
*/
#include <iostream>
#include <vector>
#include <unordered_map>
int longestConsecutive(std::vector<int>& nums) {
std::unordered_map<int,int> hashMap;
for ( auto n : nums ) {
hashMap.insert({n, -1});
}
int max_so_far = 0;
for ( size_t i = 0; i < nums.size(); ++i ) {
int j = 0;
int k = nums[i];
while( hashMap.find(k + j) != hashMap.end() ) {
if (hashMap[k+j] != -1 ) {
j += hashMap[k+j];
break;
}
++j;
}
hashMap[k] = j;
if ( j > max_so_far ) {
max_so_far = j;
}
}
return max_so_far;
}
void printVec(std::vector<int> & vec) {
for ( auto & v : vec ) {
std::cout << v << " ";
}
std::cout << std::endl;
}
int main() {
std::cout << "Vector:";
std::vector<int> vec{ 100, 4, 200, 1, 3, 2 };
printVec(vec);
std::cout << "Longest consecutive sequence length:" << longestConsecutive(vec) << std::endl;
return 0;
}