Magicsheet logo

Minimum Cost Homecoming of a Robot in a Grid

Medium
47.2%
Updated 6/1/2025

Asked by 3 Companies

Minimum Cost Homecoming of a Robot in a Grid

What is this problem about?

The Minimum Cost Homecoming of a Robot in a Grid problem places a robot at startPos and a home at homePos in a 2D grid. Every time the robot moves into a new row or column, there is a cost associated with that specific row or column. You are given two arrays, rowCosts and colCosts. You need to find the minimum total cost for the robot to reach home.

Why is this asked in interviews?

This is a "trick" Minimum Cost Homecoming interview question seen at Goldman Sachs and Oracle. It looks like a shortest-path problem (like Dijkstra or BFS), but it's actually a Greedy problem. It tests if a candidate can realize that the total cost is independent of the order of moves, as long as you don't move in the wrong direction.

Algorithmic pattern used

The Greedy interview pattern is the intended solution.

  1. No matter which path you take, if you move from row r1 to r2, you must enter every row in between exactly once (if you move optimally).
  2. The total cost is simply the sum of rowCosts for all rows between startPos[0] and homePos[0] (excluding the start row) plus the sum of colCosts for all columns between startPos[1] and homePos[1].
  3. You never need to "deviate" from the direct path because that would just add unnecessary costs.

Example explanation

Start: (1, 0), Home: (2, 3). Row costs: [10, 20, 30]. Col costs: [1, 2, 3, 4].

  1. Move from row 1 to row 2: Enter row 2 (cost 30).
  2. Move from col 0 to col 3: Enter col 1 (2), col 2 (3), col 3 (4).
  3. Total cost = 30 + 2 + 3 + 4 = 39. Any zigzag path will still visit these same rows and columns.

Common mistakes candidates make

  • Using Dijkstra's Algorithm: Implementing a full graph search (O(VlogV)O(V \log V)). While it gives the right answer, it's far too complex and slow for a large grid.
  • Including the start position cost: The problem usually states you pay the cost when you enter a row/column. You are already in the start row, so you don't pay its cost.
  • Handling directions: Not correctly identifying the range of rows/columns if homePos is "above" or "to the left" of startPos.

Interview preparation tip

Don't assume every grid problem requires BFS or DP. Read the cost structure carefully. If the cost depends only on the destination row/column and not the transition, it's likely a Greedy or Mathematical coding problem.

Similar Questions