Check if a permutation of S2 can be obtained by adding or removing characters from S1 | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool 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 <= sqrt ( n ) ; i += 2 ) { if ( n % i == 0 ) return false ; } return true ; } void checkPermutation ( string s1 , string s2 ) { int freq [ 26 ] = { 0 } ; for ( char ch : s1 ) { freq [ ch - ' a ' ] -- ; } for ( char ch : s2 ) { freq [ ch - ' a ' ] ++ ; } bool isAllChangesPrime = true ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] == 0 ) { continue ; } else if ( ! isPrime ( abs ( freq [ i ] ) ) ) { isAllChangesPrime = false ; break ; } } if ( isAllChangesPrime ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { string S1 = " gekforgk " ; string S2 = " geeksforgeeks " ; checkPermutation ( S1 , S2 ) ; }