Mid/Senior

Minimum Knight Moves

You are given an infinite chessboard with coordinates extending from -infinity to +infinity in both directions. A knight starts at coordinate (0, 0).

A knight can move in any of the following 8 ways in one step:

  • (x + 1, y + 2)
  • (x + 1, y - 2)
  • (x - 1, y + 2)
  • (x - 1, y - 2)
  • (x + 2, y + 1)
  • (x + 2, y - 1)
  • (x - 2, y + 1)
  • (x - 2, y - 1)

Given the target coordinate (x, y), return the minimum number of knight moves needed to reach (x, y) from (0, 0).

Example 1
Inputx = 2, y = 1
Output1
A knight can move directly from (0, 0) to (2, 1) in one move.
Example 2
Inputx = 5, y = 5
Output4
The shortest path from (0, 0) to (5, 5) requires 4 knight moves.

Constraints

  • -300 <= x, y <= 300

Asked at 12 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate