Problem
Closest Bathroom / Desk on a Grid
Learn this problemProblem statement
You are given a two-dimensional office grid. Each cell contains one of three characters:
'B': a bathroom'D': a desk'_': an empty cell
Movement is allowed in the four cardinal directions, and the base version has no obstacles. For every desk cell, compute the shortest step distance to any bathroom.
Return an integer matrix with the same dimensions as grid. For cells containing desks, store the nearest-bathroom distance. For non-desk cells, store -1. If the grid has no bathrooms, every desk distance should be -1.
Function
closestBathroomDistances(grid: String[][]) → int[][]Examples
Example 1
grid = [["B", "_", "D"], ["_", "D", "_"], ["D", "_", "B"]]return = [[-1, -1, 2], [-1, 2, -1], [2, -1, -1]]Each desk is two steps away from the nearest bathroom using 4-directional movement.
Example 2
grid = [["D", "_"], ["_", "D"]]return = [[-1, -1], [-1, -1]]There are no bathrooms in the grid, so no desk has a reachable bathroom.
Constraints
gridis a rectangular matrix.- Each cell is one of
"B","D", or"_". - Movement uses four directions: up, down, left, and right.
More Snowflake problems
- Minimum N-ary Tree Depth DeletionsPHONE SCREEN · Seen Jul 2026
- Simulate a Queued Multi-Rule Rate LimiterPHONE SCREEN · Seen Jul 2026
- Minimum Clicks Between Wiki PagesOA · Seen Jul 2026
- Closest Target CharacterPHONE SCREEN · Seen Jul 2026
- Horizontal Pod AutoscalerOA · Seen Jul 2026
- Minimum HeightOA · Seen Jul 2026
- Vowel SubstringOA · Seen Jun 2026
- String Formation (Also for AI/ML Software Engineer Intern :)OA · Seen Jun 2026