CF BUDDY
← Problems·

1504B · Flip the Bits

1200 · constructive algorithms, greedy, implementation

Problem: There is a binary string aa of length nn. In one operation, you can select any prefix of aa with an equal number of 00 and 11 symbols. Then all symbols in the prefix are inverted: each 00 becomes 11 and each 11 becomes 00.

For example, suppose a=0111010000a=0111010000.

  • In the first operation, we can select the prefix of length 88 since it has four 00's and four 11's: [01110100]00[10001011]00[01110100]00\to [10001011]00.
  • In the second operation, we can select the prefix of length 22 since it has one 00 and one 11: [10]00101100[01]00101100[10]00101100\to [01]00101100.
  • It is illegal to select the prefix of length 44 for the third operation, because it has three 00's and one 11.

Can you transform the string aa into the string bb using some finite number of operations (possibly, none)?

Input Format: The first line contains a single integer tt (1t1041\le t\le 10^4) — the number of test cases.

The first line of each test case contains a single integer nn (1n31051\le n\le 3\cdot 10^5) — the length of the strings aa and bb.

The following two lines contain strings aa and bb of length nn, consisting of symbols 00 and 11.

The sum of nn across all test cases does not exceed 31053\cdot 10^5.

Output Format: For each test case, output "YES" if it is possible to transform aa into bb, or "NO" if it is impossible. You can print each letter in any case (upper or lower).

Note: The first test case is shown in the statement.

In the second test case, we transform aa into bb by using zero operations.

In the third test case, there is no legal operation, so it is impossible to transform aa into bb.

In the fourth test case, here is one such transformation:

  • Select the length 22 prefix to get 100101010101100101010101.
  • Select the length 1212 prefix to get 011010101010011010101010.
  • Select the length 88 prefix to get 100101011010100101011010.
  • Select the length 44 prefix to get 011001011010011001011010.
  • Select the length 66 prefix to get 100110011010100110011010.

In the fifth test case, the only legal operation is to transform aa into 111000111000. From there, the only legal operation is to return to the string we started with, so we cannot transform aa into bb.

Sample Cases

Case 1

Input

5
10
0111010000
0100101100
4
0000
0000
3
001
000
12
010101010101
100110011010
6
000111
110100

Output

YES
YES
NO
YES
NO

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback