Find a sorted subsequence of size 3 in linear time | Python3 Program for above approach ; Function to find the triplet ; If number of elements < 3 then no triplets are possible ; Track best sequence length ( not current sequence length ) ; min number in array ; Least max number in best sequence i . e . track arr [ j ] ( e . g . in array { 1 , 5 , 3 } our best sequence would be { 1 , 3 } with arr [ j ] = 3 ) ; Save arr [ i ] ; Iterate from 1 to nums . size ( ) ; This condition is only hit when current sequence size is 2 ; Update best sequence max number to a smaller value ( i . e . we 've found a smaller value for arr[j]) ; Store best sequence start value i . e . arr [ i ] ; Increase best sequence length & save next number in our triplet ; We 've found our arr[k]!  Print the output ; No triplet found ; Driver Code ; Function Call
import sys NEW_LINE def find3Numbers ( nums ) : NEW_LINE INDENT if ( len ( nums ) < 3 ) : NEW_LINE INDENT print ( " No ▁ such ▁ triplet ▁ found " , end = ' ' ) NEW_LINE return NEW_LINE DEDENT seq = 1 NEW_LINE min_num = nums [ 0 ] NEW_LINE max_seq = - sys . maxsize - 1 NEW_LINE store_min = min_num NEW_LINE for i in range ( 1 , len ( nums ) ) : NEW_LINE INDENT if ( nums [ i ] == min_num ) : NEW_LINE continue NEW_LINE elif ( nums [ i ] < min_num ) : NEW_LINE min_num = nums [ i ] NEW_LINE continue NEW_LINE elif ( nums [ i ] < max_seq ) : NEW_LINE max_seq = nums [ i ] NEW_LINE store_min = min_num NEW_LINE elif ( nums [ i ] > max_seq ) : NEW_LINE if seq == 1 : NEW_LINE INDENT store_min = min_num NEW_LINE DEDENT seq += 1 NEW_LINE if ( seq == 3 ) : NEW_LINE INDENT print ( " Triplet : ▁ " + str ( store_min ) + " , ▁ " + str ( max_seq ) + " , ▁ " + str ( nums [ i ] ) ) NEW_LINE return NEW_LINE DEDENT max_seq = nums [ i ] NEW_LINE DEDENT print ( " No ▁ such ▁ triplet ▁ found " , end = ' ' ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT nums = [ 1 , 2 , - 1 , 7 , 5 ] NEW_LINE find3Numbers ( nums ) NEW_LINE DEDENT