#2087

Minimum Cost Homecoming of a Robot in a Grid

Medium
ArrayGreedyGreedyDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the observation that the robot must traverse all rows and columns between its starting position and home position. By calculating the total cost based on the row and column costs directly, we can avoid unnecessary path exploration and achieve a more efficient solution.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the total cost for all rows between startRow and homeRow by summing the rowCosts.
  2. 2Step 2: Calculate the total cost for all columns between startCol and homeCol by summing the colCosts.
  3. 3Step 3: Return the total cost as the minimum cost to reach home.
solution.py7 lines
1def minCost(startPos, homePos, rowCosts, colCosts):
2    total_cost = 0
3    for r in range(min(startPos[0], homePos[0]), max(startPos[0], homePos[0]) + 1):
4        total_cost += rowCosts[r]
5    for c in range(min(startPos[1], homePos[1]), max(startPos[1], homePos[1]) + 1):
6        total_cost += colCosts[c]
7    return total_cost

Complexity note: The time complexity is O(n) because we are only iterating through the rows and columns between the starting and home positions, which is linear in relation to the distance traveled.

  • 1The robot must traverse all rows and columns between start and home positions, making the path choice irrelevant.
  • 2Summing costs directly based on the range of rows and columns is more efficient than exploring all paths.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.