Magicsheet logo

Find Minimum Time to Reach Last Room II

Medium
12.5%
Updated 8/1/2025

Find Minimum Time to Reach Last Room II

What is this problem about?

The Find Minimum Time to Reach Last Room II interview question is an evolution of the grid-waiting problem. In this version, the time it takes to move between rooms is no longer always 1 second. Instead, it alternates: your first move takes 1 second, your second move takes 2 seconds, your third takes 1 second, and so on. The "waiting for room to open" logic remains the same.

Why is this asked in interviews?

Google and Uber ask this variation to see if you can incorporate "Path History" or "Move Count" into your shortest path calculation. It evaluates your ability to define a Multi-dimensional State in Dijkstra's algorithm. It checks if you understand that the "cost" to reach a node now depends on how many steps you've taken to get there.

Algorithmic pattern used

This follows the Dijkstra's Algorithm pattern with an Expanded State.

  1. State: The priority queue should store (time, row, col, moveType), where moveType is 0 or 1 (representing 1-second or 2-second moves).
  2. Transition:
    • If current moveType is 0, the next move takes 1 second. The neighbor will have moveType 1.
    • If current moveType is 1, the next move takes 2 seconds. The neighbor will have moveType 0.
  3. Logic: newTime = max(currentTime, grid[nr][nc]) + (1 if moveType == 0 else 2).

Example explanation

Grid: [[0, 1], [1, 1]]. Start (0,0) at t=0t=0, move parity 0.

  1. Move to (0,1): t=max(0,1)+1=2t = max(0, 1) + 1 = 2. Next move parity: 1.
  2. Move to (1,1): t=max(2,1)+2=4t = max(2, 1) + 2 = 4. Result: 4. (If moves were always 1 second, the result would have been 3).

Common mistakes candidates make

  • Ignoring Parity: Trying to solve it with standard Dijkstra without tracking if the next move is a "1-sec" or "2-sec" move.
  • Incorrect Visited logic: Only tracking minTime[r][c]. Since the time to reach a cell depends on the move parity, you might need minTime[r][c][parity]. (Wait, actually, in this specific problem, reaching a cell with fewer steps is always better regardless of parity, but be careful with this assumption).
  • Parity Calculation: Using (row + col) % 2 to determine move cost. This only works if you don't revisit cells; tracking it in the state is safer.

Interview preparation tip

When a rule changes based on "how many times" an action has been performed, always add that count (or its parity) to your BFS/Dijkstra state. This is a foundational technique for "Hard" Graph interview patterns.

Similar Questions