Skip to main content

Squirrel Simulation - Solution & Explanation

MediumPremiumFree on FleetCodeArrayMath10 min readAsked at: Square
Practice this problem

Problem Statement

You are given two integers height and width representing a garden of size height x width. You are also given:

  • an array tree where tree = [treer, treec] is the position of the tree in the garden,
  • an array squirrel where squirrel = [squirrelr, squirrelc] is the position of the squirrel in the garden,
  • and an array nuts where nuts[i] = [nutir, nutic] is the position of the ith nut in the garden.

The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell.

Return the minimal distance for the squirrel to collect all the nuts and put them under the tree one by one.

The distance is the number of moves.

 

Example 1:

Input: height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]]
Output: 12
Explanation: The squirrel should go to the nut at [2, 5] first to achieve a minimal distance.

Example 2:

Input: height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]]
Output: 3

 

Constraints:

  • 1 <= height, width <= 100
  • tree.length == 2
  • squirrel.length == 2
  • 1 <= nuts.length <= 5000
  • nuts[i].length == 2
  • 0 <= treer, squirrelr, nutir <= height
  • 0 <= treec, squirrelc, nutic <= width

Approach Overview

Problem Overview: A squirrel starts at a given position in a grid and must collect several nuts, dropping each one at a tree. The squirrel can only carry one nut at a time. Normally every nut trip starts and ends at the tree, except the very first trip which starts from the squirrel’s initial position. The task is to compute the minimum total Manhattan distance needed to collect all nuts.

Approach 1: Brute Force First-Nut Choice (O(n²) time, O(1) space)

Every nut except the first effectively costs 2 * dist(nut, tree) because the squirrel goes from the tree to the nut and back. The first nut is different since the squirrel starts at its initial position. One brute-force strategy is to try each nut as the first nut collected. For each candidate, compute the total cost by summing dist(squirrel, nut_i) + dist(nut_i, tree) for the first nut and 2 * dist(nut_j, tree) for the rest. This requires recomputing distances for every candidate, leading to O(n²) time with constant space.

Approach 2: Greedy Math Optimization (O(n) time, O(1) space)

The key observation: if the squirrel started at the tree, the total cost would simply be the sum of 2 * dist(nut, tree) for every nut. The only difference in the real scenario is the first nut. Instead of traveling tree → nut → tree, the squirrel travels squirrel → nut → tree. The change in cost is dist(squirrel, nut) - dist(nut, tree). Iterate through all nuts and find the nut that minimizes this extra cost (or equivalently maximizes the saving dist(nut, tree) - dist(squirrel, nut)). Compute the base cost for all nuts, then adjust it using the best candidate. Distances are simple Manhattan calculations on coordinates stored in an array. This turns the problem into a single linear scan using straightforward math and a small greedy decision.

Recommended for interviews: The greedy mathematical approach is what interviewers expect. It shows you can reduce repeated work by reasoning about the baseline cost and adjusting only the first move. Mentioning the brute-force idea first demonstrates understanding of the movement rules, while the optimized O(n) solution shows strong problem decomposition and distance analysis.

Solution

Observing the squirrel's movement path, we can see that the squirrel will first move to the position of a nut, then move to the position of the tree. After that, the total movement path of the squirrel is equal to "the sum of the distances from the remaining nuts to the tree" multiplied by 2.

Therefore, we only need to select a nut as the squirrel's first target, such that the sum of its distance to the tree is minimized, to obtain the shortest path.

The time complexity is O(n), where n is the number of nuts. The space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Rust

C#

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force First-Nut SimulationO(n²)O(1)Useful for reasoning about the problem or verifying correctness with small inputs
Greedy Mathematical OptimizationO(n)O(1)Best choice for interviews and production; computes base distance once and adjusts using the optimal first nut

Video Solution

LC Premium 573. Squirrel Simulation | One Pass | Two Pass | O(n) time • Aryan Mittal • 734 views views

Watch 4 more video solutions →

Frequently Asked Questions

Is Squirrel Simulation easy or hard?
Squirrel Simulation is rated Medium because the challenge is recognizing the mathematical shortcut. The implementation is simple once you realize that every nut normally costs 2 * dist(nut, tree) and only the first trip changes the total distance.
Squirrel Simulation Python/Java solution
Both Python and Java implementations follow the same logic: compute the base distance 2 * dist(nut, tree) for all nuts, track the maximum saving dist(nut, tree) - dist(squirrel, nut), and add that adjustment to the total. The algorithm runs in O(n) time with constant extra space.
How to solve Squirrel Simulation in O(n)?
First compute the base total distance as the sum of 2 * dist(nut, tree) for all nuts. Then iterate through the nuts and calculate the adjustment value dist(nut, tree) - dist(squirrel, nut). The nut with the maximum saving should be collected first. Add this adjustment to the base total to get the minimum distance.
What is the best approach for Squirrel Simulation?
The optimal approach uses a greedy mathematical observation. First compute the baseline cost assuming the squirrel starts at the tree, which is 2 * Manhattan distance from each nut to the tree. Then adjust the total by choosing the nut that maximizes the saving dist(nut, tree) - dist(squirrel, nut). This reduces the problem to a single O(n) scan.
Is Squirrel Simulation asked at Google/Amazon/Meta?
Squirrel Simulation is a medium-level grid and distance optimization problem commonly seen in interview preparation platforms like LeetCode. Variations of Manhattan distance optimization and greedy selection appear in interviews at large tech companies including Google and Amazon.
What data structure is used in Squirrel Simulation?
The problem primarily uses arrays or lists to store nut coordinates. The main computation relies on Manhattan distance math and a linear scan through the array of nuts, so no advanced data structures are required.
What is the time complexity of Squirrel Simulation?
The optimal solution runs in O(n) time where n is the number of nuts. Each nut is processed once to compute its distance to the tree and to the squirrel. Space complexity is O(1) since only a few running variables are needed.

Ready to solve this problem?

Practice Squirrel Simulation with our built-in code editor and test cases.

Practice on FleetCode