-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongest Consecutive Sequence
72 lines (59 loc) · 3.11 KB
/
Longest Consecutive Sequence
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
import java.util.*;
import java.util.stream.*;
class Solution {
public int longestConsecutive(int[] nums) {
/*
UNDERSTANDING THE PROBLEM:
Ok, so the problem wants us to find the longest sequence in the array given. What makes a sequence:
- consecuitve numbers
- these numbers could be anywhere in the array
- sample inpout/ output:
Input: integer array [100, 4, 200, 1, 3, 2]
Output: intger 4 (as 1, 2, 3, 4 is the longest sequence)
INITIAL THOUGHTS:
- What if we sort the array and then find the longest consecutive numbers by going over all the elements once
- A few sorting algorithms available to use:
- Merge Sort O(nlogn)
- Selection Sort O(n square)
- Bubble Sort O(n square)
- Heap Sort O(nlogn)
- Quick Sort O(n square)
- Insertion Sort O(n sqaure)
- However, this would take a lot of time as first we would have to sort the array then look through all the elements one by one. So while this approach is not incorrect let's find a much better solution/ creative solution.
NEW APPROACH:
- let's break the problem down further, how many sequences do we have in our sample input/output example?
[100, 4, 200, 1, 3, 2]
sequences:
100, 1234 , 200
1 4 1
now if we have the sequences we simply need to compare their lengths and provide the solution. Easy! But in code how do we identify the sequences? Let's take a closer look
how do we know something is a sequence? There are no more value before or after it
to make things simpler let's just focus on the start of a sequence
to identiffy the start of a seuquence there must be no n-1 value. Which means if our current number is 100 for it to be a start of the sequence there must not be 99 in the array. In order to check if there is a 99 in the array, put the numbers in a set so in order to check if it is there or not the time taken will be O(1). Now once we identify the start of the sequence we can run a loop and find if there is 101 in the array, 102 and so on so forth. While doing this we can also record the length of the sequence we are creating and compare it with the previous existing longest sequence.
Let's code it now!
*/
// firstly create a set of the input numbers
Set<Integer> set = new HashSet<>();
for(int i: nums)
set.add(i);
//now find the start of the sequences
int longest = 0;
for(int i = 0; i < nums.length; i++)
{
int set_length = 1;
if (!set.contains(nums[i]- 1))
{
//this implies that we have found the begining of a set
int j = 1;
//find the length of the entire set
while(set.contains(nums[i] + j))
{
set_length ++;
j ++;
}
}
longest = Math.max(longest, set_length);
}
return longest;
}
}