Minimum operation require to make first and last character same | Javascript program to find minimum operation require to make first and last character same ; Function to find minimum operation require to make first and last character same ; Base conditions ; If answer found ; If string is already visited ; Decrement ending index only ; Increment starting index only ; Increment starting index and decrement index ; Store the minimum value ; Driver code ; Function call
let MAX = Number . MAX_VALUE ; let m = new Map ( ) ; let Min = Number . MAX_VALUE ; function minOperation ( s , i , j , count ) { if ( ( i >= s . length && j < 0 ) || ( i == j ) ) { return MAX ; } if ( s [ i ] == s [ j ] || ( count >= Min ) ) { return count ; } let str = ( i ) . toString ( ) + " " + ( j ) . toString ( ) ; if ( ! m . has ( str ) ) { if ( i >= s . length ) { m . set ( str , minOperation ( s , i , j - 1 , count + 1 ) ) ; } else if ( j < 0 ) { m . set ( str , minOperation ( s , i + 1 , j , count + 1 ) ) ; } else { m . set ( str , Math . min ( minOperation ( s , i , j - 1 , count + 1 ) , minOperation ( s , i + 1 , j , count + 1 ) ) ) ; } } if ( m . get ( str ) < Min ) { Min = m . get ( str ) ; } return m . get ( str ) ; } let s = " " ; let ans = minOperation ( s , 0 , s . length - 1 , 0 ) ; if ( ans == MAX ) { document . write ( - 1 ) ; } else { document . write ( ans ) ; }