10
10
public class LongestConsecutiveSubsequence {
11
11
12
12
/**
13
- * Given an array of integers, find the length of the longest sub-sequence such that
14
- * elements in the subsequence are consecutive integers, the consecutive numbers can
15
- * be in any order.
13
+ * Given an array of distinct integers, find the length of the longest sub-sequence such that
14
+ * elements in the subsequence are consecutive integers, the consecutive numbers can be in any order.
16
15
* <p>
17
16
* Examples:
18
17
* Input: arr[] = {1, 9, 3, 10, 4, 20, 2};
@@ -24,14 +23,14 @@ public class LongestConsecutiveSubsequence {
24
23
* Output: 5
25
24
* The subsequence {36, 35, 33, 34, 32} is the longest subsequence
26
25
* of consecutive elements.
27
- *
26
+ * <p>
28
27
* NOTE: You can also sort this array and check for consecutive elements. You can take this approach if interviewer
29
28
* asks to solve with no additional space but do bear in mind that some sorting algorithms do require extra space.
30
29
*
31
- * @param arr unsorted array of integers
30
+ * @param arr unsorted array of non-repeating integers
32
31
* @return the length of the longest consecutive subsequence
33
32
*/
34
- private static int findLongestConsecutiveSubsequence (int [] arr ) {
33
+ private static int findLengthOfLongestConsecutiveSubsequence (int [] arr ) {
35
34
int longestSubseqCount = 0 ;
36
35
int subseqCount ;
37
36
int currElem ;
@@ -67,11 +66,15 @@ private static int findLongestConsecutiveSubsequence(int[] arr) {
67
66
}
68
67
69
68
public static void main (String [] args ) {
70
- System .out .println ("{1, 9, 3, 10, 4, 20, 2}: " + findLongestConsecutiveSubsequence (new int []{1 , 9 , 3 , 10 , 4 , 20 , 2 }));
69
+
70
+ System .out .println ("{1, 9, 3, 10, 4, 20, 2}: " +
71
+ findLengthOfLongestConsecutiveSubsequence (new int []{1 , 9 , 3 , 10 , 4 , 20 , 2 }));
71
72
System .out .println ("{36, 41, 56, 35, 44, 33, 34, 92, 43, 32, 42}: " +
72
- findLongestConsecutiveSubsequence (new int []{36 , 41 , 56 , 35 , 44 , 33 , 34 , 92 , 43 , 32 , 42 }));
73
- System .out .println ("{1}: " + findLongestConsecutiveSubsequence (new int []{1 }));
74
- System .out .println ("{}: " + findLongestConsecutiveSubsequence (new int []{}));
75
- System .out .println ("{1,5,8,3}: " + findLongestConsecutiveSubsequence (new int []{1 , 5 , 8 , 3 }));
73
+ findLengthOfLongestConsecutiveSubsequence (new int []{36 , 41 , 56 , 35 , 44 , 33 , 34 , 92 , 43 , 32 , 42 }));
74
+ System .out .println ("{1,5,8,3}: " + findLengthOfLongestConsecutiveSubsequence (new int []{1 , 5 , 8 , 3 }));
75
+
76
+ // corner cases
77
+ System .out .println ("{1}: " + findLengthOfLongestConsecutiveSubsequence (new int []{1 }));
78
+ System .out .println ("{}: " + findLengthOfLongestConsecutiveSubsequence (new int []{}));
76
79
}
77
80
}
0 commit comments