← Questions

Spell a word on a 5-column letter board

0
MicrosoftCoding

A coding interview question asked at Microsoft. It tests grid, simulation and strings.

A text-entry device shows the 26 lowercase letters on a board 5 columns wide, filled row by row. Letter c sits at row (ord(c) - ord('a')) // 5 and column (ord(c) - ord('a')) % 5:

    0 1 2 3 4
0   a b c d e
1   f g h i j
2   k l m n o
3   p q r s t
4   u v w x y
5   z

The last row holds only z. The cells to its right do not exist, and the cursor may never move onto them or off the board.

The cursor starts on a at (0, 0). It accepts five commands:

  • U, D, L, R: move one cell up, down, left or right.
  • !: select the letter under the cursor.

Implement word_path(word: str) -> str. It returns a command string that types word using the fewest possible moves. Any shortest answer is accepted.

Constraints

  • 0 <= len(word) <= 100
  • word contains only lowercase English letters.

Example 1

word_path("bad")  ->  "R!L!RRR!"

Move right to b and select it, move left to a and select it, then move right three cells to d.

Example 2

word_path("oz")  ->  "DDRRRR!LLLLDDD!"

o is at (2, 4). To reach z the cursor must move left to column 0 before it moves down. Moving down first would step onto a missing cell in row 5.

Clarifying questions

  • For a repeated letter, is ! alone (no moves) correct?
  • Is the empty word the empty string?
  • Is any shortest command string accepted, or a fixed order of moves?

What a strong answer covers

  • Computes each letter's row and column from its code, and for each next letter emits the row and column differences as moves, then !.
  • Avoids the missing cells in row 5 with a fixed order: move up and left first, then down and right. Going to z it moves left before down; leaving z it moves up before right.
  • Shows the path is shortest: it uses exactly the Manhattan distance, which is always reachable on this board.
  • Runs in O(len(word) * 10) at most.
  • Tests the examples, z to z, z to e and e to z, a repeated letter, and the empty word, checking each path never leaves the board.

Follow-ups

  • Allow the board to be any width or any letter layout, including holes.
  • The cursor can wrap around edges.
  • Several cursors, or typing with the fewest total moves when the word can be typed in any order.

Where it's asked

What it tests

grid · simulation · strings

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