Skip to content

Commit 99fa4b3

Browse files
committed
Longest Consecutive Sequence
1 parent dd713b4 commit 99fa4b3

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// we will be implementing the code for the problem Longest Consecutive Sequence
2+
#include<iostream>
3+
#include<vector>
4+
#include<unordered_map>
5+
using namespace std;
6+
int longestconsecutivesequence(vector<int>& nums){
7+
unordered_map<int, bool> mp;
8+
for(int i = 0; i < nums.size(); i++){
9+
mp[nums[i]] = true;
10+
}
11+
for(int i = 0; i < nums.size(); i++){
12+
if(mp.find(nums[i] - 1) != mp.end()){
13+
mp[nums[i]] = false;
14+
}
15+
}
16+
int maxLen = 0;
17+
for(int i = 0; i < nums.size(); i++){
18+
if(mp[nums[i]]){
19+
int j = 0;
20+
int count = 0;
21+
while(mp.count(nums[i] + j) > 0){
22+
count++;
23+
j++;
24+
}
25+
if(count > maxLen){
26+
maxLen = count;
27+
}
28+
}
29+
}
30+
return maxLen;
31+
}
32+
int main(){
33+
int n;
34+
cout << "Enter the number of elements in the array: ";
35+
cin >> n;
36+
vector<int> nums(n);
37+
cout << "Enter the elements of the array: ";
38+
for(int i = 0; i < n; i++){
39+
cin >> nums[i];
40+
}
41+
int result = longestconsecutivesequence(nums);
42+
cout << "The Length of the longest consecutive sequence is: " << result << endl;
43+
return 0;
44+
}

0 commit comments

Comments
 (0)