text: Check if a String contains any index with more than K active characters | Java program to implement the above approach ; Function to check if any index contains more than K active characters ; Store the last occurrence of each character in the map . ; Stores the active characters ; Insert the character ; If the size of set exceeds K ; Remove the character from set if i is the last index of the current character ; Driver code
code: import java . util . * ; class GFG { static String checkString ( String s , int K ) { int n = s . length ( ) ; Map < Character , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { mp . put ( s . charAt ( i ) , i ) ; } int cnt = 0 , f = 0 ; Set < Character > st = new HashSet < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { st . add ( s . charAt ( i ) ) ; if ( st . size ( ) > K ) { f = 1 ; break ; } if ( mp . get ( s . charAt ( i ) ) == i ) st . remove ( s . charAt ( i ) ) ; } return ( f == 1 ? " Yes " : " No " ) ; } public static void main ( String [ ] args ) { String s = " aabbcdca " ; int k = 2 ; System . out . println ( checkString ( s , k ) ) ; } }