# Longest Consecutive Sequence

## Aggregating consecutive numbers

Before

```
[100, 4, 200, 1, 3, 2]
```

After

```
[(100), (4, 1, 3, 2), (200)]
```

### One way to achieve

Two collections one is for input, the other is for aggregated nums

- take a number away from input
- create a tuple to contain the aggregated nums
- search all possiable nums and take them away from input
- loop until the input array is empty

```
nums : [100, 4, 200, 1, 3, 2]
aggr : []
```

move `100`

into `aggr`

```
nums : [4, 200, 1, 3, 2]
aggr : [(100)]
```

`99`

and `101`

is not in the `nums`

, so go to next

move `4`

into `aggr`

```
nums : [200, 1, 3, 2]
aggr : [(100), (4)]
```

`5`

is not in the `nums`

`3`

is in the `nums`

, so move `3`

into `aggr`

```
nums : [200, 1, 2]
aggr : [(100), (4, 3)]
```

`2`

is in the `nums`

, so move `2`

into `aggr`

```
nums : [200, 1]
aggr : [(100), (4, 3, 2)]
```

`1`

is in the `nums`

, so move `1`

into `aggr`

```
nums : [200]
aggr : [(100), (4, 3, 2, 1)]
```

`0`

is not in the `nums`

, so go to next

move `200`

into `aggr`

```
nums : []
aggr : [(100), (4, 3, 2, 1), (200)]
```

In this problem, the sequence is no need to be stored, update the longest length is enough.

so, code may be like

```
while nums is not emtpy
len = 1
n = nums.poll()
// search forward
for i in n .. INFINITE
if i in nums
remove i from nums
len = len + 1
// search backward
for i in n .. -INFINITE
if i in nums
remove i from nums
len = len + 1
longest = MAX(longest, len)
```

### Source code *Read on Github*

```
1 public class Solution {
2 public int longestConsecutive(int[] num) {
3
4 HashSet<Integer> nums = new HashSet<Integer>();
5
6 for(int n : num){
7 nums.add(n);
8 }
9
10 int longest = 0;
11
12 for(final int n : num){
13
14 int l = 1;
15
16 int nn = n;
17
18 nums.remove(n);
19
20 while(nums.contains(++nn)){
21 l++;
22 nums.remove(nn);
23 }
24
25 nn = n;
26
27 while(nums.contains(--nn)){
28 l++;
29 nums.remove(nn);
30 }
31
32 longest = Math.max(longest, l);
33 }
34
35 return longest;
36
37 }
38 }
```