LeetCode #3609 — HARD

Minimum Moves to Reach Target in Grid

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

You are given four integers sx, sy, tx, and ty, representing two points (sx, sy) and (tx, ty) on an infinitely large 2D grid.

You start at (sx, sy).

At any point (x, y), define m = max(x, y). You can either:

  • Move to (x + m, y), or
  • Move to (x, y + m).

Return the minimum number of moves required to reach (tx, ty). If it is impossible to reach the target, return -1.

Example 1:

Input: sx = 1, sy = 2, tx = 5, ty = 4

Output: 2

Explanation:

The optimal path is:

  • Move 1: max(1, 2) = 2. Increase the y-coordinate by 2, moving from (1, 2) to (1, 2 + 2) = (1, 4).
  • Move 2: max(1, 4) = 4. Increase the x-coordinate by 4, moving from (1, 4) to (1 + 4, 4) = (5, 4).

Thus, the minimum number of moves to reach (5, 4) is 2.

Example 2:

Input: sx = 0, sy = 1, tx = 2, ty = 3

Output: 3

Explanation:

The optimal path is:

  • Move 1: max(0, 1) = 1. Increase the x-coordinate by 1, moving from (0, 1) to (0 + 1, 1) = (1, 1).
  • Move 2: max(1, 1) = 1. Increase the x-coordinate by 1, moving from (1, 1) to (1 + 1, 1) = (2, 1).
  • Move 3: max(2, 1) = 2. Increase the y-coordinate by 2, moving from (2, 1) to (2, 1 + 2) = (2, 3).

Thus, the minimum number of moves to reach (2, 3) is 3.

Example 3:

Input: sx = 1, sy = 1, tx = 2, ty = 2

Output: -1

Explanation:

  • It is impossible to reach (2, 2) from (1, 1) using the allowed moves. Thus, the answer is -1.

Constraints:

  • 0 <= sx <= tx <= 109
  • 0 <= sy <= ty <= 109

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given four integers sx, sy, tx, and ty, representing two points (sx, sy) and (tx, ty) on an infinitely large 2D grid. You start at (sx, sy). At any point (x, y), define m = max(x, y). You can either: Move to (x + m, y), or Move to (x, y + m). Return the minimum number of moves required to reach (tx, ty). If it is impossible to reach the target, return -1.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Math

Example 1

1
2
5
4

Example 2

0
1
2
3

Example 3

1
1
2
2
Step 02

Core Insight

What unlocks the optimal approach

  • Work backwards from <code>(tx, ty)</code> to <code>(sx, sy)</code>, undoing one move at each step.
  • If the larger coordinate >= 2 × (the smaller), undo by halving the larger; otherwise undo by subtracting the smaller from the larger.
  • Count these undo-steps until you hit <code>(sx, sy)</code> (return the count), or return -1 if you drop below or get stuck.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3609: Minimum Moves to Reach Target in Grid
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3609: Minimum Moves to Reach Target in Grid
// package main
// 
// // https://space.bilibili.com/206214
// func minMoves(sx, sy, x, y int) (ans int) {
// 	for ; x != sx || y != sy; ans++ {
// 		if x < sx || y < sy {
// 			return -1
// 		}
// 		if x == y {
// 			if sy > 0 {
// 				x = 0
// 			} else {
// 				y = 0
// 			}
// 			continue
// 		}
// 		// 保证 x > y
// 		if x < y {
// 			x, y = y, x
// 			sx, sy = sy, sx
// 		}
// 		if x >= y*2 {
// 			if x%2 > 0 {
// 				return -1
// 			}
// 			x /= 2
// 		} else {
// 			x -= y
// 		}
// 	}
// 	return
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(log n)
Space
O(1)

Approach Breakdown

ITERATIVE
O(n) time
O(1) space

Simulate the process step by step — multiply n times, check each number up to n, or iterate through all possibilities. Each step is O(1), but doing it n times gives O(n). No extra space needed since we just track running state.

MATH INSIGHT
O(log n) time
O(1) space

Math problems often have a closed-form or O(log n) solution hidden behind an O(n) simulation. Modular arithmetic, fast exponentiation (repeated squaring), GCD (Euclidean algorithm), and number theory properties can dramatically reduce complexity.

Shortcut: Look for mathematical properties that eliminate iteration. Repeated squaring → O(log n). Modular arithmetic avoids overflow.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Overflow in intermediate arithmetic

Wrong move: Temporary multiplications exceed integer bounds.

Usually fails on: Large inputs wrap around unexpectedly.

Fix: Use wider types, modular arithmetic, or rearranged operations.