← Questions

Squirrel carrying nuts to a tree

0
AmazonCodingLast asked Mar 2026

A coding interview question asked in Amazon's coding round, last asked Mar 2026. It tests math, greedy and grids.

A squirrel, a tree and some nuts are on a grid with no obstacles. The squirrel must bring every nut to the tree, carrying one nut at a time. Each move goes to a cell that shares a side with the current one. Return the fewest moves needed to deliver all the nuts, over every delivery order. Picking up and dropping cost nothing, and counting stops when the last nut reaches the tree.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • min_moves(height: int, width: int, tree: list[int], squirrel: list[int], nuts: list[list[int]]) -> int — cells are [row, col].

Example

min_moves(4, 5, tree=[1, 1], squirrel=[3, 4], nuts=[[0, 4], [3, 1]])         ->  11
# (0, 4) first: 3 moves to it, 4 to the tree; then (3, 1): 2 out, 2 back. The other order costs 13.

min_moves(1, 10, tree=[0, 2], squirrel=[0, 9], nuts=[[0, 0], [0, 4]])        ->  11
# (0, 4) first: 5 + 2; then (0, 0): 2 + 2

min_moves(3, 3, tree=[1, 1], squirrel=[0, 0], nuts=[[0, 0], [2, 2], [0, 2]]) ->  10
# the nut under the squirrel: 0 + 2; each other nut: 2 out, 2 back

Constraints

  • 1 <= height, width <= 100; 1 <= len(nuts) <= 5000.
  • Nuts are on distinct cells, never on the tree. The squirrel may start on the tree or on a nut.

Clarifying questions

  • Are there obstacles? (No, so distance is Manhattan distance.)
  • Does the squirrel have to return anywhere after the last nut?
  • Can it start on a nut or on the tree?

What a strong answer covers

  • After the first nut, every trip is tree → nut → tree, so the total is sum(2 · d(nut, tree)) adjusted by the first trip.
  • The first nut replaces one d(tree, nut) with d(squirrel, nut): choose the nut that minimizes d(squirrel, nut) - d(nut, tree), even when every choice makes it worse.
  • O(number of nuts) time, O(1) space.
  • Tests: squirrel on the tree, squirrel on a nut, one nut.

Follow-ups

  • The grid has obstacles (BFS from the tree and from the squirrel).
  • The squirrel can carry two nuts at a time.
  • There are two trees and each nut can go to either.

Where it's asked

  • Amazon · Coding · Last asked Mar 202655 min · Usually two rounds; one is often an object-oriented design built in steps · No AI

What it tests

math · greedy · grids

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding