Check if a permutation of S2 can be obtained by adding or removing characters from S1 | Java program for the above approach ; Function to check if the given number is prime or not ; If the number is less than 2 ; If the number is 2 ; If N is a multiple of 2 ; Otherwise , check for the odds values ; Function to check if S1 can be a permutation of S2 by adding or removing characters from S1 ; Initialize a frequency array ; Decrement the frequency for occurrence in s1 ; Increment the frequency for occurence in s2 ; If frequency of current char is same in s1 and s2 ; Check the frequency for the current char is not prime ; Print the result ; Driver Code
public class GFG { private static boolean isPrime ( int n ) { if ( n <= 1 ) return false ; else if ( n == 2 ) return true ; else if ( n % 2 == 0 ) return false ; for ( int i = 3 ; i <= Math . sqrt ( n ) ; i += 2 ) { if ( n % i == 0 ) return false ; } return true ; } private static void checkPermutation ( String s1 , String s2 ) { int freq [ ] = new int [ 26 ] ; for ( char ch : s1 . toCharArray ( ) ) { freq [ ch - ' a ' ] -- ; } for ( char ch : s2 . toCharArray ( ) ) { freq [ ch - ' a ' ] ++ ; } boolean isAllChangesPrime = true ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] == 0 ) { continue ; } else if ( ! isPrime ( Math . abs ( freq [ i ] ) ) ) { isAllChangesPrime = false ; break ; } } if ( isAllChangesPrime ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } public static void main ( String [ ] args ) { String S1 = " gekforgk " ; String S2 = " geeksforgeeks " ; checkPermutation ( S1 , S2 ) ; } }