Python coding

Strings with the same shape

Two strings s and t of the same length have the same shape when you can turn s into t by renaming its characters: every copy of a character becomes the same new character, and two different characters never become the same one. A character may keep its own name. Return True if s and t have the same shape, otherwise False.

Any character counts, spaces and digits included. Aim for one pass.

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

  • same_shape("egg", "add") → true
  • same_shape("foo", "bar") → false
  • same_shape("ab", "cc") → false
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Walk both strings together: each pair (s[i], t[i]) says what a character becomes. The shape breaks when a character is told to become two different things.

Hint 2

One map from s to t accepts "ab" → "cc", where both letters become c. Keep a second map from t back to s, and check both on every pair.

Solution and why it works
pythonO(n) · O(k), k = distinct characters
def same_shape(s: str, t: str) -> bool:
    forward, backward = {}, {}          # s-char -> t-char, t-char -> s-char
    for a, b in zip(s, t):
        if forward.setdefault(a, b) != b or backward.setdefault(b, a) != a:
            return False
    return True

Renaming must be one-to-one, so it takes two maps: s → t catches a character that would become two different ones, and t → s catches two characters that would become the same one. With only the first map, "ab" and "cc" pass. setdefault stores a pair the first time and returns the stored partner after that, so each step costs O(1) on average. Comparing every pair of positions also works, in O(n²).

Related lab: Loops in motion