Minimum operation require to make first and last character same | C # program to find minimum operation require to make first and last character same ; Return the minimum operation requires to make string first and last character same . ; Store indexes of first occurrences of characters . ; Initialize all the elements to - 1 ; Initialize result ; Traverse through all characters ; Find first occurrence ; Update result for subsequent occurrences ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int MAX = 256 ; static int minimumOperation ( String s ) { int n = s . Length ; List < int > first_occ = new List < int > ( ) ; for ( int i = 0 ; i < MAX ; i ++ ) first_occ . Insert ( i , - 1 ) ; int res = int . MaxValue ; for ( int i = 0 ; i < n ; i ++ ) { int x = ( int ) s [ i ] ; if ( first_occ [ x ] == - 1 ) first_occ . Insert ( x , i ) ; else { int last_occ = ( n - i - 1 ) ; res = Math . Min ( res , first_occ [ x ] + last_occ ) ; } } return res ; } public static void Main ( String [ ] args ) { String s = " bacdefghipalop " ; Console . WriteLine ( minimumOperation ( s ) ) ; } }