Databricks questions

Fastest Commute Mode

DatabricksOnsiteMedium

A city map is a list of equal-length strings, one per row. It holds exactly one S (the start) and one D (the destination). Every other cell is X (blocked) or a digit from 1 to 4, a road for the travel mode with that number.

A trip moves one step at a time to an edge-adjacent cell (up, down, left or right; no diagonals). A trip in mode m may only step on cells marked m, plus S and D.

Part 1: Fastest mode

Implement fastest_commute_mode(grid, time, cost). time[m - 1] and cost[m - 1] are the time and the price of one step in mode m.

For each mode, take the trip from S to D with the fewest steps that stays on that mode's cells. A trip of s steps in mode m takes s * time[m - 1] time and costs s * cost[m - 1].

Return the mode (1 to 4) with the smallest total time. If several modes tie on time, the one with the smaller total cost wins; if cost ties as well, the smallest mode number wins. Return -1 if no mode can reach D.

  1. Example 1
    cost
    [1,3,1,1]
    grid
    ["S11X","2X1X","2X1D","2222"]
    time
    [4,2,1,1]
    Output
    2

    Why: Mode 1 takes 5 steps along the top row and down the 1 column: time 5 4 = 20, cost 5. Mode 2 takes 7 steps down the left side and along the bottom row: time 7 2 = 14, cost 21. Modes 3 and 4 have no cells and cannot reach D. Time decides first, so the answer is 2.

Constraints

  • 1 <= len(grid) <= 500
  • 1 <= len(grid[0]) <= 500
  • every row of grid has the same length
  • grid contains exactly one 'S' and one 'D'
  • every other cell of grid is 'X' or a digit '1' to '4'
  • len(time) == 4 and 1 <= time[i] <= 10^4
  • len(cost) == 4 and 1 <= cost[i] <= 10^4
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Fastest Commute Mode: Databricks interview question | LoopCoach