Minimum Knight Moves solution explained
Minimum Knight Moves is a breadth-first search from the origin over knight jumps, with one twist: the board has no edges, so you bound the search by symmetry. Replace the target (x, y) with (|x|, |y|), and only explore squares whose coordinates are at least -2. BFS then returns the fewest jumps, and a short memoized recursion gives the same answer with less memory.
By Evin JohnPublished 8 min read
The problem in plain words
A chess knight moves in an L shape: two squares along one axis and one square along the other, which gives eight possible jumps from any square. Here the board has no boundary. The knight starts at (0, 0) and you are given a target square (x, y). Return the smallest number of jumps that lands the knight exactly on the target. Every square can be reached, so there is no -1 case.
| Target | Fewest jumps | Comment |
|---|---|---|
| (0, 0) | 0 | Already there |
| (3, 3) | 2 | (0, 0) to (1, 2) to (3, 3) |
| (1, 1) | 2 | Close, but it needs a detour such as (2, -1) first, which dips below the x axis |
| (1, 0) | 3 | Adjacent squares are surprisingly expensive for a knight |
| (2, 2) | 4 | Another short distance that costs more than far-away squares like (3, 3) |
| (-4, 7) | 5 | Same as (4, 7) by symmetry |
Those rows explain why simple formulas based on distance fail. The squares right next to the origin are some of the hardest to reach, and the optimal path to (1, 1) leaves the first quadrant. Any pruning you add has to allow for that.
Slow approach: unrestricted BFS
Every jump costs the same, so BFS from (0, 0) finds the shortest path: push the origin, then keep popping squares and pushing their eight neighbors that have not been seen. When the target is popped, its depth is the answer. The problem is the shape of the search. BFS grows a roughly circular region in all directions, so most of the work happens in the three quadrants that do not contain the target. In a quick run toward (60, 60), the unrestricted search marked about 22,300 squares as seen before it stopped.
Main approach: fold, then prune
- Fold the targetThe jump set is symmetric under flipping either axis, so the distance to (x, y) equals the distance to (|x|, |y|). Work in the first quadrant only.
- Allow a small marginSome shortest paths step just below or left of the origin, as (1, 1) shows. Allow coordinates down to -2 and reject anything lower.
- Run BFSPush (0, 0, 0). Pop squares, generate the eight jumps, skip pruned or seen squares, and stop when the folded target is popped.
The margin of two is the common choice, and it held for every target checked here, including all targets within 12 squares of the origin compared against the unrestricted search. On the same run toward (60, 60), the folded search marked about 6,100 squares, roughly a quarter of the unrestricted count.
from collections import deque
def knight_moves(x, y):
x, y = abs(x), abs(y)
jumps = ((1, 2), (2, 1), (-1, 2), (-2, 1), (1, -2), (2, -1), (-1, -2), (-2, -1))
seen = {(0, 0)}
queue = deque([(0, 0, 0)])
while queue:
cx, cy, d = queue.popleft()
if (cx, cy) == (x, y):
return d
for dx, dy in jumps:
nx, ny = cx + dx, cy + dy
if nx >= -2 and ny >= -2 and (nx, ny) not in seen:
seen.add((nx, ny))
queue.append((nx, ny, d + 1))function knightMoves(x, y) {
x = Math.abs(x);
y = Math.abs(y);
const jumps = [[1, 2], [2, 1], [-1, 2], [-2, 1], [1, -2], [2, -1], [-1, -2], [-2, -1]];
const seen = new Set(["0,0"]);
const queue = [[0, 0, 0]];
for (let head = 0; head < queue.length; head++) {
const [cx, cy, d] = queue[head];
if (cx === x && cy === y) return d;
for (const [dx, dy] of jumps) {
const nx = cx + dx, ny = cy + dy;
const key = nx + "," + ny;
if (nx >= -2 && ny >= -2 && !seen.has(key)) {
seen.add(key);
queue.push([nx, ny, d + 1]);
}
}
}
}Alternative: memoized recursion toward the origin
Flip the direction of travel. From a folded square (a, b), a good first jump always heads back toward the origin, either by (-1, -2) or by (-2, -1). Fold the result again with absolute values and recurse. Two base cases cover the awkward squares: a + b = 0 means you are at the origin, and a + b = 2 covers (1, 1), (2, 0) and (0, 2), each of which needs exactly two jumps. Memoize on (a, b) so each square is solved once.
from functools import lru_cache
def knight_moves_memo(x, y):
@lru_cache(maxsize=None)
def f(a, b):
if a + b == 0:
return 0
if a + b == 2:
return 2
return 1 + min(f(abs(a - 1), abs(b - 2)), f(abs(a - 2), abs(b - 1)))
return f(abs(x), abs(y))function knightMovesMemo(x, y) {
const memo = new Map();
const f = (a, b) => {
if (a + b === 0) return 0;
if (a + b === 2) return 2;
const key = a + "," + b;
if (!memo.has(key)) {
memo.set(key, 1 + Math.min(f(Math.abs(a - 1), Math.abs(b - 2)), f(Math.abs(a - 2), Math.abs(b - 1))));
}
return memo.get(key);
};
return f(Math.abs(x), Math.abs(y));
}This version only touches squares in or just beside the rectangle between the origin and the target, so it usually stores far fewer squares than BFS. Its weakness is that the base cases feel like magic unless you justify them, so be ready to show by hand why (1, 1) and (2, 0) both take two jumps. Recursion depth also grows with the distance, which is fine for targets a few hundred squares away in most languages.
Complexity
| Approach | Time | Space |
|---|---|---|
| Unrestricted BFS | O(m²) | O(m²), spread over all four quadrants |
| Folded BFS with margin | O(m²) | O(m²), but only about one quadrant |
| Memoized recursion | O(|x| · |y|) at most | O(|x| · |y|) memo plus recursion depth |
| Bidirectional BFS | O(m²) worst case | Usually much smaller frontiers |
There is also a closed-form formula for knight distance, but it has several special cases and is hard to derive under time pressure. Mention that it exists if asked; do not lead with it.
Edge cases to test
- The origin itself, which must return 0 without exploring.
- (1, 1), (1, 0), (2, 0) and (2, 2): the short squares that break naive formulas.
- Negative coordinates in each quadrant, which must match their mirrored positive versions.
- Targets on an axis far away, such as (0, 10), which take 6 jumps.
- A distant diagonal target like (100, 100), to check speed; it takes 68 jumps.
Common mistakes
- Pruning to coordinates of zero or more. The square (1, 1) then becomes unreachable in two jumps and the answer comes out wrong.
- Forgetting to fold negative targets before running the pruned BFS, which makes the target lie outside the allowed region.
- Marking squares seen when popped instead of when pushed, which bloats the queue several times over.
- Using a JavaScript array as a Set key. Two arrays with the same contents are never equal, so nothing is ever marked seen.
- Writing the recursion without the a + b = 2 base case, which recurses forever or returns too few jumps near the origin.
Walking the interviewer through it
Fictional example
- Candidate
- All jumps cost one, so BFS from the origin gives the minimum. The board is infinite, though, so I need a way to stop it spreading everywhere.
- Candidate
- The jumps are symmetric, so I'll take absolute values of the target and stay mostly in the first quadrant. I can't cut off exactly at zero, because (1, 1) needs a jump through y equals -1, so I'll allow down to -2.
- Interviewer
- Can you do better on memory?
- Candidate
- Yes. I can recurse from the target toward the origin, folding with absolute values each time, and memoize. The base cases are the origin and the three squares where a plus b is two.
Related problems in this set
Earlier in this set, Shortest Path to Get All Keys widens the BFS state with a key mask; here the state stays small and the trick is bounding an infinite space. Next, Walls and Gates runs BFS from many starting points at once to fill a whole grid with distances. The algorithm interview questions page covers when BFS is the right tool and when a weighted search is needed.
Practicing with Natively
This problem rewards explaining the margin and the symmetry clearly, which is easier to judge from a recording than from memory. Natively transcribes a practice session on your computer, so you can reread how you justified the pruning, and in practice it can read a problem screenshot and suggest an approach to compare with yours. The AI interview assistant page has the full picture.
Questions people ask
How do you solve Minimum Knight Moves?
Fold the target to (|x|, |y|) because knight moves are symmetric, then BFS from the origin over knight jumps while allowing coordinates down to -2. The depth at which the target is popped is the fewest moves.
Why allow negative coordinates after folding?
Some shortest paths near the origin dip just outside the first quadrant. Reaching (1, 1) in two jumps, for example, needs a square such as (2, -1).
Is there a faster approach than BFS?
A memoized recursion that jumps back toward the origin usually stores fewer squares, with base cases for the origin and for squares where x + y is 2. A closed-form formula also exists but is hard to derive in an interview.
What is the complexity?
Folded BFS is O(m²) time and space for m = max(|x|, |y|), with roughly one quadrant explored instead of four.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
