Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Arrays and hashing

Can one word be renamed into another?

Easy · Target 15 minutes · Arrays and hashing· Type asked at

You're given two strings s and t of the same length. I'd like you to say whether t can be made from s by renaming letters, where every copy of a letter is renamed to the same new letter and no two different letters are allowed to end up with the same name. A letter may also keep its own name.

Examples

InputOutputWhy
s = "egg", t = "add"trueIf you rename e to a and g to d you get add, and nothing gets renamed twice.
s = "foo", t = "bar"falseThe two copies of o would have to turn into a and into r at the same time.
s = "badc", t = "baba"falseGoing from s to t looks fine, but b and d would both have to be renamed to b and that isn't allowed.

Constraints

  • 1 ≤ n ≤ 5 × 10⁴
  • s.length = t.length
  • s and t hold printable ASCII characters

Hints

Hint 1

I'd walk along both strings together and write down what each letter of s has been renamed to so far, because the first time you see a letter you're free to choose and every time after that you aren't.

Hint 2

That one map catches foo and bar, but try it on badc and baba and you'll see it says yes when the answer is no, so ask yourself what it isn't checking.

Hint 3

Keep a second map from the letters of t back to the letters of s, and only say yes if both of them stay consistent all the way along the strings.

Where people lose marks

  • Keeping only the map from s to t. It passes the examples that people usually try first and then says yes on badc and baba, so I'd always test a case where two letters of s collide on one letter of t.
  • Checking whether t[i] already appears somewhere among the values of the first map. That gets the right answer but it's a scan over the map at every step, and the second map does the same job with one lookup.
  • Forgetting that the strings can hold any printable character at all, spaces and digits included, so a fixed array of 26 slots will break on a space or a digit and you'd want 128 slots or a hash map.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.