C++ program to check we can make two strings equal by swapping from third string

Suppose we have three strings S, T and U of same length n. For every index i in range 0 to n-1, we must swap U[i] with either S[i] or T[i]. So in total we have performed n swapping operations. We have to check whether after such n operations we can make string S exactly same as T.

So, if the input is like S = "abc"; T = "bca"; U = "bca", then the output will be True, because for all i if we swap U[i] with S[i], it will be "bca", and T is already "bca".


To solve this, we will follow these steps −

for initialize i := 0, when S[i] is non-zero, update (increase i by 1), do:
   if S[i] is not equal to U[i] and T[i] is not equal to U[i], then:
      return false
   return true


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

bool solve(string S, string T, string U) {
   for (int i = 0; S[i]; ++i)
      if (S[i] != U[i] && T[i] != U[i])
         return false;
   return true;
int main() {
   string S = "abc";
   string T = "bca";
   string U = "bca";
   cout << solve(S, T, U) << endl;


"abc", "bca", "bca"