You are on page 1of 4

Please use this Google doc during your interview (your interviewer will see

what you write here). To free your hands for typing, we recommend using a
headset or speakerphone.

1. Our goal is to help understand how to implement a ​transform​(a,b) method which transforms
string a into string b by repeatedly replacing ​all instances​ of a character with another if possible
and otherwise returns the original string.

First, we want to implement ​can_transform(a,b), ​where we test whether we can transform


from string a to string b by repeatedly replacing all instances of a character with another.

Example:
can_transform(‘abca’,’dced’)​ => True
can_transform(‘abba’,’dced’)​ => False

1. if unique chars on both sides is different, they cannot be transformed

a d

{‘a’: ‘d’}
{‘b’: ‘c’}
{‘c’: ‘e’}
def ​can_transform(a, b):
if not a and not b:
return True

if not a or not b:
return False

length = len(a)
if length != len(b):
return False

mapping = {}

for i in range(length):
if a[i] in mapping:
if b[i] != mapping[a[i]]:
return False
else:
continue
else:
mapping[a[i]] = b[i]

return True

____________________

‘abca’ ’dced’
abca -> a->d -> dbcd

c->e -> dbed


b->c -> dced

transform(b, char1, char2)

‘ab’ ‘ba’
a->b -> bb b->a ‘aa’
‘ba’
‘a’
{a,b}
{c,d}
a->c = cb
b->d = cd
c->b = bd
d->a = ba

{c}
a->c = cb
b->a = ca
c->b = ba

‘abab’ ‘baba’
a->b = bbbb
c = ‘!a!a’

How many intermediate characters are needed for two strings?


Is there a case where the intermediate character won’t be available?

abc - cba
a->d dba
a->c = dbc

Given two strings where ​can_transform(a,b)​ is true, implement ​needs_intermediate(a,b)

Example:
needs_intermediate(‘ab’,’ba’)​ -> True
needs_intermediate(‘ab’,’bc’)​ -> False

abcac - ceaca

b->e = aecac
c->a =

abc - bca

{a:b, b:c, c:a}


def ​needs_intermediate(mapping):
keys = mapping.keys()
queue = []
visited_keys = ()
for key in mapping.keys():
if key in visited_keys :
continue

queue = [key]
while queue:
element = queue.pop()
visited_keys.add(element)

if mapping[element] not in mapping.keys():


break

else:
if mapping[element] in visited_keys:
return False
queue.add(mapping[element])

return True

visited_keys = [a, b, c]
a
q = [b]
b a = [c]
c

You might also like