Subarray permutation that satisfies the given condition | Function that returns true if the required subarray exists in the given array ; Map to store the positions of each integer in the original permutation ; To store the address of each entry in arr [ n ] but with 1 - based indexing ; To track minimum position sumcur for sum of all positions till this position ; Summing up addresses ; Tracking minimum address encountered till now ; The sum of the addresses if it forms the required subarray ; If current sum of address is equal to val ; Driver code
function subArray ( arr , n , m ) { var i ; var mp = new Map ( ) ; for ( i = 0 ; i < n ; i ++ ) { mp . set ( arr [ i ] , i + 1 ) ; } var sumcur = 0 ; var p = 1000000000 ; var ans = [ ] ; for ( i = 1 ; i <= m ; i ++ ) { sumcur += mp . get ( i ) ; p = Math . min ( p , mp . get ( i ) ) ; var val = p * i - i + parseInt ( ( i * ( i + 1 ) ) / 2 ) ; if ( i == m ) { if ( val == sumcur ) { return true ; } else return false ; } } } var arr = [ 4 , 5 , 1 , 3 , 2 , 6 ] ; var n = arr . length ; var m = 3 ; if ( subArray ( arr , n , m ) ) document . write ( " " ) ; else document . write ( " " ) ;