You are given two binary strings. Find all pairs of strings (π‘Ž,𝑏) such that when all 0s are replaced by π‘Ž and all 1s are replaced by 𝑏, the two binary strings are transformed to the same final string.

For instance, if the two binary strings are 011 and 1000, (ab,abab) is a valid pair.

If both binary strings begin with the same symbol, we can simply delete them and consider the remaining suffixes. We consider two cases:

  1. Both strings are now empty. In this case, all pairs of (π‘Ž,𝑏) are valid.
  2. Otherwise, the starting symbols of the two strings are distinct.

In case 2, this means that π‘Ž is either a prefix or suffix of 𝑏. WLOG, assume π‘Ž is a prefix of 𝑏 and let 𝑒≀𝑣 be the lengths of π‘Ž and 𝑏 respectively.

  • If 𝑒=𝑣, then evidently π‘Ž=𝑏.
  • Otherwise, we can express 𝑏 as π‘Ž+𝑏′ for some non-empty string 𝑏′. Substitute all 1s with 01, and our problem reduces from (𝑒,𝑣) to (𝑒,π‘£βˆ’π‘’).

Note that in the second case, (𝑒,𝑣) strictly decreases so we will hit the 𝑒=𝑣 case eventually. Working backwards, this means that both π‘Ž and 𝑏 must be periodic in gcd(𝑒,𝑣).

Intuitively, the β€œinterlocking pattern” created when 𝑒≠𝑣 is very reminiscent of the Euclidean algorithm, which naturally leads to the periodic constraint derived above.