Minimum number of removals required such that no subsequence of length 2 occurs more than once | Java program for the above approach ; Function to remove the minimum count of characters from the string such that no subsequence of length 2 repeats ; Initialize the final string ; Stores if any character occurs in the final string or not ; Store the index of the last character added in the string ; Traverse the string ; Add all the unique characters ; Check if S [ 0 ] appears in the range [ pos + 1 , N - 1 ] ; If the characters are the same ; Print the resultant string ; Driver code
import java . io . * ; class GFG { static void RemoveCharacters ( String s ) { String ans = " " ; int [ ] c = new int [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) c [ i ] = 0 ; int pos = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( c [ ( int ) s . charAt ( i ) - 97 ] == 0 ) { c [ ( int ) s . charAt ( i ) - 97 ] = 1 ; pos = i ; ans += s . charAt ( i ) ; } } for ( int i = pos + 1 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == s . charAt ( 0 ) ) { ans += s . charAt ( i ) ; break ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String S = " abcaadbcd " ; RemoveCharacters ( S ) ; } }