algoadvance

Leetcode 2937. Make Three Strings Equal

Problem Statement

You are given three binary strings s1, s2, and target, of the same length. The goal is to make the strings s1 and s2 equal to the target string by performing the following operation any number of times (possibly zero times):

Return true if you can make both s1 and s2 equal to target, and false otherwise.

Clarifying Questions

  1. Input Constraints:
    • What are the length constraints of s1, s2, and target?
      • All strings have the same length ( n ) with ( 1 \leq n \leq 10^5 ).
  2. Character Set:
    • Can the strings contain characters other than ‘0’ and ‘1’?
      • No, the strings contain only ‘0’ and ‘1’.
  3. Operations on the strings:
    • Can we pick any character at any position to flip?
      • Yes, you can flip any character at any position in s1 or s2.

Strategy

To solve this problem, follow these steps:

  1. Position Analysis: Compare each character position i of s1, s2, and target.

  2. Condition Check: Determine if it’s possible to make both s1[i] and s2[i] equal to target[i]:
    • If target[i] == '0', then both s1[i] and s2[i] should be convertible to ‘0’. This means s1[i] and s2[i] can be either ‘0’ or ‘1’, but not both being ‘1’ at the same time (because flipping one will make it zero).
    • If target[i] == '1', then at least one of s1[i] or s2[i] should be ‘1’.
  3. Iteration and Verification: Iterate through each character and check if the above conditions hold for each index. If even one condition fails, return false.

Example Walkthrough

Code

#include <iostream>
#include <string>

bool makeStringsEqual(std::string s1, std::string s2, std::string target) {
    int n = s1.size();
    for (int i = 0; i < n; ++i) {
        char t = target[i];
        if (t == '0') {
            if (s1[i] == '1' && s2[i] == '1') {
                return false;
            }
        } else if (t == '1') {
            if (s1[i] == '0' && s2[i] == '0') {
                return false;
            }
        }
    }
    return true;
}

int main() {
    std::string s1 = "1100", s2 = "1010", target = "1010";
    std::cout << std::boolalpha << makeStringsEqual(s1, s2, target) << std::endl; // Output: true

    return 0;
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI