Keeping question specifics vague for the time being but just had my AWS Onsite and I'm kicking myself about the second coding round. Looks like it's been asked for Amazon before, similar to this one:
I went with a backtracking solution that worked but accidently gave the time complexity as O(M * N) instead of (M^N). As soon as I left the interview it clicked that I could have done a DP style approach with a bitmask for O(m * 2^n). My solution is below if anbody has a better approaches:
def can_spell_word(word: str, blocks: List[Tuple[str,str]],) -> bool:
seed = (1 << len(blocks)) -1
combinations = {seed,}
for letter in word:
new_combinations = set()
for combination in combinations:
for i,block in enumerate(blocks):
if ((combination >> i) & 0x01) and letter in block:
new_combinations.add(combination & ~(0x01 << i))
combinations = new_combinations
return len(combinations) != 0Hoping I'm not docked too much for that one part because we had a good dialogue about my approach through the entire section and I was able to get a working solution. Just annoyed that when they first shared the problem I casually said "well we could do a bitmask but that's going to be like 2^n complexity so lets see if we can do better", forgetting that that's better than backtracking.


