Recognized it pretty fast as a BFS thing, similar to the walls and gates problem.
Use multi-source BFS starting from all letter cells simultaneously, expanding layer by layer to fill dashes with the nearest letter. For the follow-up tie-breaking, process letters in alphabetical order within each BFS layer so that the smallest letter wins ties.
Pro tip: Mention that multi-source BFS is optimal because it processes each cell once, and for the tie-break, explain that sorting letters alphabetically in the initial queue ensures the smallest letter is assigned first when distances are equal.
Confirm the matrix dimensions, character set, and that distance is Manhattan (adjacent cells only). Ask about tie-breaking rules and whether the matrix can be modified in-place.
Collect all letter cells into a queue. For the follow-up, sort these letters alphabetically before enqueuing so that smaller letters are processed first. Mark dashes as unvisited.
While the queue is not empty, pop a cell and explore its four neighbors. If a neighbor is a dash, replace it with the current cell's letter and enqueue it. This ensures each dash gets the nearest letter.
By processing letters in alphabetical order within the same BFS layer, the first letter to reach a dash is the alphabetically smallest among those at the same distance. Alternatively, track distance and letter, updating only if a smaller letter is found at the same distance.
Time complexity is O(m*n) since each cell is processed once. Space is O(m*n) for the queue. Discuss edge cases: no letters, all letters, dashes at borders, and ties.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.