Python coding

Two strings woven into a third

Given three strings a, b and c, return True if c can be woven from a and b: it uses every character of both exactly once, the characters taken from a keep a's order, and those taken from b keep b's order. The two may alternate in any pattern, in runs of any length. Otherwise return False.

Each string has 0 to 100 characters, and the comparison is case-sensitive. Aim for O(len(a) · len(b)) time.

Besides the tests, one large input (two 13-letter strings) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • can_weave("dog", "cat", "dcoagt") → true
  • can_weave("abc", "xyz", "axbzcy") → false
  • can_weave("aab", "aac", "aacaab") → true
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Taking from a whenever its next character matches fails: with a = "aab", b = "aac" and c = "aacaab", b must go first. Keep both choices open: dynamic programming over prefixes.

Hint 2

Let ok[i][j] mean the first i + j characters of c can be woven from a[:i] and b[:j]. The last of them came from a or from b.

Hint 3

ok[i][j] holds if ok[i-1][j] and a[i-1] == c[i+j-1], or ok[i][j-1] and b[j-1] == c[i+j-1]. Check the lengths first: they must add up.

Solution and why it works
pythonO(m·n), m = len(a), n = len(b) · O(n)
def can_weave(a: str, b: str, c: str) -> bool:
    if len(a) + len(b) != len(c):
        return False                     # every character is used exactly once
    ok = [False] * (len(b) + 1)          # ok[j]: c[:i + j] can be woven from a[:i] and b[:j]
    for i in range(len(a) + 1):
        for j in range(len(b) + 1):
            if i == 0 and j == 0:
                ok[j] = True             # nothing woven from nothing
            else:                        # the last character of c[:i + j] came from a or from b
                from_a = i > 0 and ok[j] and a[i - 1] == c[i + j - 1]       # ok[j] is still row i - 1
                from_b = j > 0 and ok[j - 1] and b[j - 1] == c[i + j - 1]
                ok[j] = from_a or from_b
    return ok[-1]

The last character of c[:i + j] came from a or from b, and either way a smaller prefix pair remains, so (m + 1) × (n + 1) cells at O(1) each settle it; plain recursion over both choices revisits the same pairs along every path, exponentially. Greedy fails when both strings offer the same next character: "aab" and "aac" weave into "aacaab" only if b goes first. Check the lengths before the table: it only reads c[:m + n], so extra characters would go unnoticed.

Related lab: Big-O growth