# Array

## Longest Consecutive Subsequence

Given an array of integers, find the length of the longest sub-sequence such that elements in the subsequence are consecutive integers, the consecutive numbers can be in any order.

![](https://3169941669-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M1EdxtEZWsdM5mrgEPz%2F-M5a7s_UT3l5wPfqXb9m%2F-M5a88fjkrC3pD1TpYbx%2Fimage.png?alt=media\&token=8f5dddd4-b1e1-44a8-b297-3cb75b2293a2)

```cpp
int longestConsecutive(const vector<int>& arr){
    std::unordered_set<int> S;
    int n = arr.size();
    for(int i = 0; i < n; ++i){
        S.insert(arr[i]);
    }
    
    for(int i = 0; i < n; ++i){
        if(S.find(arr[i] - 1) == arr.end()){
            int anchor = arr[i];
            while(S.find(anchor) != S.end()){
                anchor++;
            }
            ans = max(ans, anchor - arr[i]);
        }
    }
    return ans;
}
```
