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 require to make string first and last character same . ; Store indexes of first occurrences of characters . ; Initialize result ; Traverse through all characters ; Find first occurrence ; Update result for subsequent occurrences ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX  256 NEW_LINE int minimumOperation ( string s ) { int n = s . length ( ) ; vector < int > first_occ ( MAX , -1 ) ; int res = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { char x = s [ i ] ; if ( first_occ [ x ] == -1 ) first_occ [ x ] = i ; else { int last_occ = ( n - i - 1 ) ; res = min ( res , first_occ [ x ] + last_occ ) ; } } return res ; } int main ( ) { string s = " bacdefghipalop " ; cout << minimumOperation ( s ) << endl ; return 0 ; }