← Questions

Spell a word with letter blocks, one block per letter

0
AmazonCoding

A coding interview question asked at Amazon. It tests bipartite matching, graphs and backtracking.

You have a set of letter blocks. Each block is a list of lowercase characters printed on its faces. You also get a target string.

Implement can_form(blocks: list[list[str]], target: str) -> bool. Return True if you can spell target by taking one character from a block for each position of target, where:

  • each block is used for at most one position,
  • the blocks can be used in any order, and
  • a block that shows the same letter twice still counts as one block.

Constraints: 0 <= len(target) <= 1000, 0 <= len(blocks) <= 1000, each block has 1 to 26 characters.

Example 1

blocks = [["m", "q"], ["o", "p"], ["p", "m"]]
target = "mop"
-> True   # m from block 0, o from block 1, p from block 2

Example 2

blocks = [["r", "s"], ["r"], ["t"]]
target = "rrs"
-> False  # only two blocks have 'r', and one of them is also the only block with 's'

A natural follow-up: return which block is used for each position of target.

Clarifying questions

  • Can the target contain letters that no block has, and should that return False right away?
  • Is an empty target always True, even with no blocks?
  • Can there be more target letters than blocks? Then the answer is False at once.
  • Should the answer be found quickly for the worst case (1,000 letters and 1,000 blocks), or is a backtracking search acceptable?

What a strong answer covers

  • Sees that this is a bipartite matching problem: target positions on one side, blocks on the other, with an edge when a block has that letter. The target can be spelled exactly when every position can be matched.
  • Uses augmenting paths (Kuhn's algorithm, O(V * E)) or Hopcroft-Karp (O(E * sqrt(V))), and explains why greedy assignment fails, as in Example 2.
  • Can shrink the problem by grouping positions with the same letter, which makes it a flow from 26 letters to the blocks with capacities.
  • Quick checks first: the target is longer than the number of blocks, or a letter appears on too few blocks.
  • Tests: both examples, an empty target, a block with repeated letters, a letter on no block, and a case that needs an augmenting path to move an earlier choice.

Follow-ups

  • Return which block is used for each position of the target.
  • Find how many of a list of words can be spelled, each with its own set of blocks.
  • Blocks have a cost to use: spell the target at the lowest total cost.
  • Spell as many letters of the target as possible when it can't be spelled fully.

Where it's asked

What it tests

bipartite matching · graphs · backtracking

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding