Longest Consecutive Subsequence | Python program to find longest contiguous subsequence ; Hash all the array elements ; check each possible sequence from the start then update optimal length ; if current element is the starting element of a sequence ; Then check for next elements in the sequence ; update optimal length if this length is more ; Driver code
from sets import Set NEW_LINE def findLongestConseqSubseq ( arr , n ) : NEW_LINE INDENT s = Set ( ) NEW_LINE ans = 0 NEW_LINE for ele in arr : NEW_LINE INDENT s . add ( ele ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] - 1 ) not in s : NEW_LINE INDENT j = arr [ i ] NEW_LINE while ( j in s ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT ans = max ( ans , j - arr [ i ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 7 NEW_LINE arr = [ 1 , 9 , 3 , 10 , 4 , 20 , 2 ] NEW_LINE print " Length ▁ of ▁ the ▁ Longest ▁ contiguous ▁ subsequence ▁ is ▁ " , NEW_LINE print findLongestConseqSubseq ( arr , n ) NEW_LINE DEDENT