1010public class LongestConsecutiveSubsequence {
1111
1212 /**
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.
1615 * <p>
1716 * Examples:
1817 * Input: arr[] = {1, 9, 3, 10, 4, 20, 2};
@@ -24,14 +23,14 @@ public class LongestConsecutiveSubsequence {
2423 * Output: 5
2524 * The subsequence {36, 35, 33, 34, 32} is the longest subsequence
2625 * of consecutive elements.
27- *
26+ * <p>
2827 * NOTE: You can also sort this array and check for consecutive elements. You can take this approach if interviewer
2928 * asks to solve with no additional space but do bear in mind that some sorting algorithms do require extra space.
3029 *
31- * @param arr unsorted array of integers
30+ * @param arr unsorted array of non-repeating integers
3231 * @return the length of the longest consecutive subsequence
3332 */
34- private static int findLongestConsecutiveSubsequence (int [] arr ) {
33+ private static int findLengthOfLongestConsecutiveSubsequence (int [] arr ) {
3534 int longestSubseqCount = 0 ;
3635 int subseqCount ;
3736 int currElem ;
@@ -67,11 +66,15 @@ private static int findLongestConsecutiveSubsequence(int[] arr) {
6766 }
6867
6968 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 }));
7172 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 []{}));
7679 }
7780}
0 commit comments