Check if reversing a sub array make the array sorted | Python3 program to check whether reversing a sub array make the array sorted or not ; Return True , if reversing the subarray will sort the array , else return False . ; Find first increasing part ; Find reversed part ; Find last increasing part ; To handle cases like 1 , 2 , 3 , 4 , 20 , 9 , 16 , 17 ; Driver Code
import math as mt NEW_LINE def checkReverse ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT i = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i - 1 ] < arr [ i ] : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT j = i NEW_LINE while ( j < n and arr [ j ] < arr [ j - 1 ] ) : NEW_LINE INDENT if ( i > 1 and arr [ j ] < arr [ i - 2 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( j == n ) : NEW_LINE INDENT return True NEW_LINE DEDENT k = j NEW_LINE if ( arr [ k ] < arr [ i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT while ( k > 1 and k < n ) : NEW_LINE INDENT if ( arr [ k ] < arr [ k - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT k += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT arr = [ 1 , 3 , 4 , 10 , 9 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE if checkReverse ( arr , n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT