#3609

Minimum Moves to Reach Target in Grid

Hard
MathGreedyBacktracking
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log(max(tx, ty)))
Space
O(1)
O(1)
💡

Intuition

Time O(log(max(tx, ty)))Space O(1)

Instead of moving forward, we work backwards from the target to the start. This allows us to efficiently determine the minimum moves by undoing the operations.

⚙️

Algorithm

3 steps
  1. 1Step 1: While (tx, ty) is greater than (sx, sy), check if tx > ty or ty > tx.
  2. 2Step 2: If the larger coordinate is at least double the smaller, halve the larger coordinate.
  3. 3Step 3: Otherwise, subtract the smaller coordinate from the larger until reaching (sx, sy) or impossible.
solution.py17 lines
1def minMoves(sx, sy, tx, ty):
2    moves = 0
3    while tx >= sx and ty >= sy:
4        if tx == sx and ty == sy:
5            return moves
6        if tx > ty:
7            if ty > sy:
8                tx -= ty // 2
9            else:
10                tx -= ty
11        else:
12            if tx > sx:
13                ty -= tx // 2
14            else:
15                ty -= tx
16        moves += 1
17    return -1

Complexity note: The complexity is logarithmic because we effectively halve the larger coordinate each step, reducing the problem size quickly.

  • 1Working backwards simplifies the problem.
  • 2Halving the larger coordinate reduces the number of moves.

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