Skip to content
Related Articles

Related Articles

Check if given strings can be made same by swapping two characters of same or different strings
  • Last Updated : 21 Dec, 2020
GeeksforGeeks - Summer Carnival Banner

Given an array of equal-length strings, arr[] of size N, the task is to check if all the strings can be made equal by repeatedly swapping any pair of characters of same or different strings from the given array. If found to be true, then print “YES”. Otherwise, print “NO”.

Examples:

Input: arr[] = { “acbdd”, “abcee” } 
Output: YES 
Explanation: 
Swapping arr[0][1] and arr[0][2] modifies arr[] to { “abcdd”, “abcee” } 
Swapping arr[0][3] and arr[1][4] modifies arr[] to { “abced”, “abced” } 
Therefore, the required output is “YES”.

Input: arr[] = { “abb”, “acc”, “abc” } 
Output: YES 
Explanation: 
Swapping arr[0][2] with arr[1][1] modifies arr[] to { “abc”, “abc”, “abc” }. 
Therefore, the required output is “YES”.

Approach: The idea is to count the frequency of each distinct character of all the strings and check if the frequency of each distinct character is divisible by N or not. If found to be true, then print “YES”. Otherwise, print “NO”. Follow the steps below to solve the problem:



  • Initialize an array, say cntFreq[], to store the frequency of each distinct character of all the strings.
  • Traverse the array and for every string encountered, count the frequency of each distinct character of the string.
  • Traverse the array cntFreq[] using variable i. For every ith character, check if cntFreq[i] is divisible by N or not. If found to be false, then print “NO”.
  • Otherwise, print “YES”.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if all strings can be
// made equal by swapping any pair of
// characters from the same or different strings
bool isEqualStrings(string arr[], int N)
{
    // Stores length of string
    int M = arr[0].length();
 
    // Store frequency of each distinct
    // character of the strings
    int cntFreq[256] = { 0 };
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Iterate over the characters
        for (int j = 0; j < M; j++) {
 
            // Update frequency
            // of arr[i][j]
            cntFreq[arr[i][j] - 'a']++;
        }
    }
 
    // Traverse the array cntFreq[]
    for (int i = 0; i < 256; i++) {
 
        // If cntFreq[i] is
        // divisible by N or not
        if (cntFreq[i] % N != 0) {
 
            return false;
        }
    }
 
    return true;
}
 
// Driver Code
int main()
{
    string arr[] = { "aab", "bbc", "cca" };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    if (isEqualStrings(arr, N)) {
 
        cout << "YES";
    }
    else {
 
        cout << "NO";
    }
 
    return 0;
}

Java




// Java program to implement
// the above approach 
class GFG{
    
// Function to check if all strings can be
// made equal by swapping any pair of
// characters from the same or different strings
static boolean isEqualStrings(String[] arr, int N)
{
     
    // Stores length of string
    int M = arr[0].length();
  
    // Store frequency of each distinct
    // character of the strings
    int[] cntFreq = new int[256];
    for(int i = 0; i < N; i++)
    {
        cntFreq[i] = 0;
    }
     
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Iterate over the characters
        for(int j = 0; j < M; j++)
        {
             
            // Update frequency
            // of arr[i].charAt(j)
            cntFreq[arr[i].charAt(j) - 'a'] += 1;
        }
    }
  
    // Traverse the array cntFreq[]
    for(int i = 0; i < 256; i++)
    {
         
        // If cntFreq[i] is
        // divisible by N or not
        if (cntFreq[i] % N != 0)
        {
            return false;
        }
    }
    return true;
}
    
// Driver Code
public static void main(String[] args)
{
    String[] arr = { "aab", "bbc", "cca" };
    int N = arr.length;
     
    // Function Call
    if (isEqualStrings(arr, N))
    {
        System.out.println("YES");
    }
    else
    {
        System.out.println("NO");
    }
}
}
 
// This code is contributed by AnkThon

Python3




# Python3 program to implement
# the above approach
 
# Function to check if all strings can
# be made equal by swapping any pair of
# characters from the same or different
# strings
def isEqualStrings(arr, N):
 
    # Stores length of string
    M = len(arr[0])
 
    # Store frequency of each distinct
    # character of the strings
    cntFreq = [0] * 256
 
    # Traverse the array
    for i in range(N):
 
        # Iterate over the characters
        for j in range(M): 
             
            # Update frequency
            # of arr[i][j]
            cntFreq[ord(arr[i][j]) - ord('a')] += 1
             
    # Traverse the array cntFreq[]
    for i in range(256):
         
        # If cntFreq[i] is
        # divisible by N or not
        if (cntFreq[i] % N != 0):
            return False
         
    return True
 
# Driver Code
if __name__ == "__main__" :
     
    arr = [ "aab", "bbc", "cca" ]
    N = len(arr)
 
    # Function Call
    if isEqualStrings(arr, N):
        print("YES")
    else:
        print("NO")
     
# This code is contributed by jana_sayantan

C#




// C# program to implement
// the above approach 
using System;
    
class GFG{
    
// Function to check if all strings can be
// made equal by swapping any pair of
// characters from the same or different strings
static bool isEqualStrings(string[] arr, int N)
{
     
    // Stores length of string
    int M = arr[0].Length;
  
    // Store frequency of each distinct
    // character of the strings
    int[] cntFreq = new int[256];
    for(int i = 0; i < N; i++)
    {
        cntFreq[i] = 0;
    }
     
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Iterate over the characters
        for(int j = 0; j < M; j++)
        {
             
            // Update frequency
            // of arr[i][j]
            cntFreq[arr[i][j] - 'a'] += 1;
        }
    }
  
    // Traverse the array cntFreq[]
    for(int i = 0; i < 256; i++)
    {
         
        // If cntFreq[i] is
        // divisible by N or not
        if (cntFreq[i] % N != 0)
        {
            return false;
        }
    }
    return true;
}
    
// Driver Code
public static void Main()
{
    string[] arr = { "aab", "bbc", "cca" };
    int N = arr.Length;
  
    // Function Call
    if (isEqualStrings(arr, N))
    {
        Console.WriteLine("YES");
    }
    else
    {
        Console.WriteLine("NO");
    }
}
}
 
// This code is contributed by susmitakundugoaldanga
Output: 
YES

 

Time Complexity: O(N * M + 256), where M is the length of the string 
Auxiliary Space: O(256)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :