Check if two arrays of strings are equal by performing swapping operations


The arrays of strings are a 2-dimensional array that stores characters in it. In C++ language we have an inbuilt function, with syntax −

Syntax

swap (first_datatype, second_datatype)

which is used to perform swap operations on two elements, that is, exchange the values they carry. In the following, we are also supposed to do some exchange in positions of the elements of the string to get the expected output. However, we can get our output in a much easier way.

Problem Statement

Now, in this problem, we are provided with two arrays of strings (meaning arrays or arrays of characters instead of numbers). We have to check if we can make the arrays of strings equal by using swap operations frequently on the strings of anyone 2-dimensional array. Let us see how we should proceed to solve this problem.

Sample Examples

Let’s try to understand this problem with the help of some examples.

input

s1 = {"aachg", "klsm", "abcd",  }
s2 = { "aghca", "dbca", "mlks"}

Output

true

Explanation − First string array1 could be swapped back to “aghca” if we swap the second ‘a’ and ‘g’, and then ‘c’ and ‘h’

The second string of array1 can be converted to “mlks” if we swap ‘m’ and ‘s’, then swap ‘s’ and ‘k’

The third string of array1 can be converted to “dbca” if we swap ‘d’ and ‘a’

Thus, if we do all these swap operations we will get the array elements of set 1 the same as all the array elements in set 2. Though the order or the position of strings may vary in both arrays it would be considered to have equal string elements needed.

input

s1 = { "bbs", "aaa", “jsk” }
s2 = { "aaa", "dbs", “kjs” }

Output

false

Explanation − It is impossible to make given two strings equal with any number of string swap operation

Problem Explanation

Let’s try to understand the problem and find its solution. If we want to see if some swap operations can make a string equal to another string and there is no constraint on the number of swap operations we are allowed to perform, we can get to our answer by using a much easier way. We can first sort each string of each array, then if we sort the two arrays as well, we can compare the corresponding string of the two arrays if every string is equal to every other corresponding string then we can say that we can make the two arrays of string are equal by performing swapping operations.

Solution

Algorithm to Define the Above Solution

  • Check the size of both strings if they are not of equal size, there is no way to make the strings both arrays have equal.

  • Sort strings of array 1 and array 2 simultaneously.

  • Sort both arrays as well.

  • Now, if the two arrays can have their strings equal, they would lie in corresponding positions to each other.

  • Check if each string in the sorted array 1 is the same as the string at the corresponding position of array 2 if yes return true else return false.

Example

Now, let us implement the above approach in different programming languages: C++, Java, and Python −

#include <bits/stdc++.h>
using namespace std;
// Helper function to check if we can make the two arrays equal by performing swap operations on any of the two arrays
bool Helper(vector<string> s1, vector<string> s2){
   // If the size of both array sets is not the same we would return false right away as there is no way that we can make all the strings equal
	if(s1.size() != s2.size()){
      return false;
	}
	// Store the length of the string
	int n = s1.size();
	// start a loop to sort each string of both arrays
	for(int i=0; i < n; i++){
	   // sort string present at index i of the array of set 1
	   sort(s1[i].begin(),s1[i].end());
	   // sort string present at index i of the array of set 2
	   sort(s2[i].begin(), s2[i].end());
	}
	// Sort both arrays now so that we can compare the strings directly to ease our process
	sort(s1.begin(), s1.end());
	sort(s2.begin(), s2.end());
   // Start a loop to compare each string present in the two arrays
	for (int i = 0; i < n; i++){
	   // check if any string in set 1 is not equal to the corresponding string of set 2 after sorting, then there is no possible way to make both arrays equal
		if (s1[i] != s2[i]){
		   return false;
		}
	}
	// Return true if every single string of set 1 is equal to every corresponding string of set 2
	return true;
}
// Main function
int main(){
	vector<string> s1 = {"aachg", "klsm", "abcd"};
	vector<string> s2 = { "aghca", "dbca", "mlks"};
   // Call the Helper function to get a binary answer true (1) or false (0) based on which we would deliver our final output
	bool output = Helper(s1, s2);
	if(output==0){
	   cout<< "False: Not every single string of set 1 is equal to every other string of set 2" << endl;
	} else {
	   cout<< "True: Every single string of set 1 is equal to every other string of set 2" << endl;
	}
	return 0;
}	  

Output

True: Every single string of set 1 is equal to every other string of set 2
import java.util.Arrays;
public class Main {
   // Helper function to check if we can make the two arrays equal by performing swap operations on any of the two arrays
   public static boolean helper(String[] s1, String[] s2) {
      // If the sizes of both arrays are not the same, return false immediately as there's no way to make them equal
      if (s1.length != s2.length) {
         return false;
      }

      int n = s1.length; // Store the length of the arrays

      // Sort each string in both arrays
      for (int i = 0; i < n; i++) {
         char[] s1Chars = s1[i].toCharArray();
         char[] s2Chars = s2[i].toCharArray();
         Arrays.sort(s1Chars);
         Arrays.sort(s2Chars);
         s1[i] = new String(s1Chars);
         s2[i] = new String(s2Chars);
      }

      // Sort both arrays to compare the strings directly
      Arrays.sort(s1);
      Arrays.sort(s2);

      // Compare each string in the two arrays
      for (int i = 0; i < n; i++) {
         // If any string in s1 is not equal to the corresponding string in s2 after sorting, there's no way to make both arrays equal
         if (!s1[i].equals(s2[i])) {
            return false;
         }
      }
      // Return true if every string in s1 is equal to the corresponding string in s2
      return true;
   }
   // Main function
   public static void main(String[] args) {
      String[] s1 = {"aachg", "klsm", "abcd"};
      String[] s2 = {"aghca", "dbca", "mlks"};

      // Call the helper function to get a binary answer: true or false
      boolean output = helper(s1, s2);
      if (!output) {
         System.out.println("False: Not every single string of set 1 is equal to every other string of set 2");
      } else {
         System.out.println("True: Every single string of set 1 is equal to every other string of set 2");
      }
   }
}

Output

True: Every single string of set 1 is equal to every other string of set 2
def helper(s1, s2):
   # If the sizes of both lists are not the same, return False immediately as there's no way to make them equal
   if len(s1) != len(s2):
      return False
    
   n = len(s1)  # Store the length of the lists
   # Sort each string in both lists
   for i in range(n):
      s1[i] = ''.join(sorted(s1[i]))
      s2[i] = ''.join(sorted(s2[i]))
    
   # Sort both lists to compare the strings directly
   s1.sort()
   s2.sort()
    
   # Compare each string in the two lists
   for i in range(n):
      # If any string in s1 is not equal to the corresponding string in s2 after sorting, there's no way to make both lists equal
      if s1[i] != s2[i]:
         return False
    
   # Return True if every string in s1 is equal to the corresponding string in s2
   return True

# Main function
def main():
   s1 = ["aachg", "klsm", "abcd"]
   s2 = ["aghca", "dbca", "mlks"]
    
   # Call the helper function to get a binary answer: True (1) or False (0)
   output = helper(s1, s2)
    
   if output == 0:
      print("False: Not every single string of set 1 is equal to every other string of set 2")
   else:
      print("True: Every single string of set 1 is equal to every other string of set 2")

if __name__ == "__main__":
   main()

Output

True: Every single string of set 1 is equal to every other string of set 2

Complexities for the Above Code

  • Time complexity − O(n*log(n)); where n is the size of the array and as we used sorting here and we know the time complexity of the inbuilt function ‘sort’ is ‘n*log(n)’

  • Space complexity − O(1); We have not stored any variable in some data structure in the above code.

Conclusion

In this article, to check if the two arrays of strings are equal by performing swapping operations. We will first observe that we do not have any constraints on the number of swaps we have to make to reach our goal. We will use this fact to make our problem a little bit easier if we take the two string arrays that can be made equal by performing swapping operations after we have sorted the individual strings in each array. If we have sorted the two arrays as well, we can compare the corresponding strings in the two arrays and conclude that we can do so.

Updated on: 22-Jan-2024

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements