-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongestConsecutiveSequence.java
102 lines (60 loc) · 1.64 KB
/
LongestConsecutiveSequence.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package practice;
import java.util.HashSet;
import java.util.Set;
public class LongestConsecutiveSequence {
public static int[] input = { 100, 4, 200, 1, 3, 2 };
/**
*
* trick is to use hash set and put all the numbers in a hash set
*
* Now iterate through each number and keep incrementing count if number -1 is
* present in hash set
*
* similarly also check if number +1 is present in hash set and increment count.
*
* finally update the max count find so far
*
* @param input
*
* @return
*
*/
public static int longestConsecutiveSequence(int[] input) {
Set<Integer> deduper = new HashSet<>();
// putting all the unique numbers in hashSet
for (int num : input) {
deduper.add(num);
}
int max = 1;
// iterate through numbers
for (int num : input) {
int left = num - 1;
int right = num + 1;
int count = 1;
// check if number -1 ... number -n is present in hashSet
while (deduper.contains(left)) {
// increment the counter
count++;
// remove the number so that it will not be counted again for any other number
deduper.remove(left);
// go even more more level left
left--;
}
// check if number +1 is present
while (deduper.contains(right)) {
// increment the count
count++;
// remove it from the set so that it will not be counted twice
deduper.remove(right);
// go to one more level right
right++;
}
// update the max with maximum of count found so far
max = Math.max(max, count);
}
return max;
}
public static void main(String[] args) {
System.out.println(longestConsecutiveSequence(input));
}
}