Minimum operation require to make first and last character same | C # 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
using System ; using System . Collections . Generic ; class GFG { static int MAX = Int32 . MaxValue ; static Dictionary < string , int > m = new Dictionary < string , int > ( ) ; static int Min = Int32 . MaxValue ; static int minOperation ( string s , int i , int j , int count ) { if ( ( i >= s . Length && j < 0 ) || ( i == j ) ) { return MAX ; } if ( s [ i ] == s [ j ] || ( count >= Min ) ) { return count ; } string str = i . ToString ( ) + " | " + j . ToString ( ) ; if ( ! m . ContainsKey ( str ) ) { if ( i >= s . Length ) { m [ str ] = minOperation ( s , i , j - 1 , count + 1 ) ; } else if ( j < 0 ) { m [ str ] = minOperation ( s , i + 1 , j , count + 1 ) ; } else { m [ str ] = Math . Min ( minOperation ( s , i , j - 1 , count + 1 ) , minOperation ( s , i + 1 , j , count + 1 ) ) ; } } if ( m [ str ] < Min ) { Min = m [ str ] ; } return m [ str ] ; } static void Main ( ) { string s = " bacdefghipalop " ; int ans = minOperation ( s , 0 , s . Length - 1 , 0 ) ; if ( ans == MAX ) { Console . WriteLine ( - 1 ) ; } else { Console . WriteLine ( ans ) ; } } }