Skip to main content

Minimum Garden Perimeter to Collect Enough Apples - Solution & Explanation

MediumMathBinary Search10 min readAsked at: Amazon
Practice this problem

Problem Statement

In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it.

You will buy an axis-aligned square plot of land that is centered at (0, 0).

Given an integer neededApples, return the minimum perimeter of a plot such that at least neededApples apples are inside or on the perimeter of that plot.

The value of |x| is defined as:

  • x if x >= 0
  • -x if x < 0

 

Example 1:

Input: neededApples = 1
Output: 8
Explanation: A square plot of side length 1 does not contain any apples.
However, a square plot of side length 2 has 12 apples inside (as depicted in the image above).
The perimeter is 2 * 4 = 8.

Example 2:

Input: neededApples = 13
Output: 16

Example 3:

Input: neededApples = 1000000000
Output: 5040

 

Constraints:

  • 1 <= neededApples <= 1015

Approach Overview

Problem Overview: You are given neededApples. Apples grow on an infinite grid where the number of apples increases as you expand a square garden centered at the origin. The task is to find the minimum perimeter of a square garden that collects at least neededApples.

The garden expands in square layers. If the side length reaches distance k from the center, the garden perimeter becomes 8 * k. The key observation is that apples accumulate in predictable mathematical patterns as layers expand.

Approach 1: Iterative Expansion Approach (O(sqrt(n)) time, O(1) space)

Expand the garden one square layer at a time. Let k represent the current layer distance from the center. Each new layer contributes 12 * k^2 apples to the total. Start from k = 1, add apples layer by layer, and stop when the cumulative count reaches or exceeds neededApples. Once the correct layer is found, compute the perimeter as 8 * k. This approach works because the apple pattern follows a deterministic formula, so you only simulate layer growth instead of scanning grid cells. Time complexity is O(sqrt(n)) since the required layer grows roughly with the cube root/square-root scale of the target apples, and space usage remains O(1).

Approach 2: Mathematical Calculation with Binary Search (O(log n) time, O(1) space)

The cumulative number of apples within k layers follows the closed-form formula total = 2 * k * (k + 1) * (2 * k + 1). Instead of expanding sequentially, treat the problem as finding the smallest k such that this formula is at least neededApples. Because the function is strictly increasing, you can apply binary search on the value of k. For each midpoint, compute the apple total using the formula and adjust the search bounds accordingly. Once the minimal valid k is found, return 8 * k. This approach leverages mathematical pattern recognition and avoids iterative accumulation, making it significantly faster for very large inputs.

Recommended for interviews: Interviewers usually expect you to first recognize the layer pattern and derive the formula for total apples. A simple iterative expansion demonstrates understanding of the pattern. The stronger solution uses the mathematical formula with binary search to reduce the search space to O(log n), which shows comfort with monotonic functions and optimization techniques.

Approach 1: Iterative Expansion Approach

In this approach, you simulate expanding squares centered at (0, 0) incrementally and calculate the apples contained within each square until the apple count meets or exceeds the `neededApples`.

In the C solution, we iterate through square layers, where each square layer contributes 12 * k * k apples (considering all contributions on each segment). We keep track of the total apples accumulated and stop when it exceeds `neededApples`. The perimeter is simply the side k multiplied by 8.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(sqrt(n)) where `n` is the number of needed apples, since we incrementally check squares.
Space Complexity: O(1) as we use only a fixed number of variables.

Try this approach in the editor →

Approach 2: Mathematical Calculation Approach

This approach formulates a mathematical solution to avoid iterative calculations by directly finding the k such that the sum of apples within the square is equal to or greater than the neededApples.

The C solution calculates an approximation for 'k' directly and adjusts iteratively to the needed apple count precision. This leverages mathematical summation of the series formed by square dimensions.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(1) for initial approximation and O(sqrt(k)) for convergence to precise 'k'.
Space Complexity: O(1).

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Iterative Expansion Approach

Time Complexity: O(sqrt(n)) where `n` is the number of needed apples, since we incrementally check squares.
Space Complexity: O(1) as we use only a fixed number of variables.

Mathematical Calculation Approach

Time Complexity: O(1) for initial approximation and O(sqrt(k)) for convergence to precise 'k'.
Space Complexity: O(1).

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Iterative ExpansionO(sqrt(n))O(1)Good for quickly implementing the idea once the layer pattern is known
Mathematical Formula + Binary SearchO(log n)O(1)Best for very large inputs where iterative expansion may take many steps

Video Solution

Leetcode: Minimum Garden Perimeter • Coding For Dummies • 2,438 views views

Watch 5 more video solutions →

Frequently Asked Questions

Is Minimum Garden Perimeter to Collect Enough Apples easy or hard?
The problem is classified as Medium on LeetCode. The main challenge is identifying the mathematical pattern of apple growth and translating it into a formula. Once the pattern is known, the implementation using iteration or binary search is straightforward.
Minimum Garden Perimeter to Collect Enough Apples Python/Java solution
Most implementations compute the apple total using the formula 2 * k * (k + 1) * (2 * k + 1). Python, Java, and C++ solutions typically apply binary search to find the smallest valid k, then return 8 * k as the perimeter. This keeps the runtime O(log n) and memory usage constant.
How to solve Minimum Garden Perimeter to Collect Enough Apples in O(log n)?
Compute the total apples using the formula total = 2 * k * (k + 1) * (2 * k + 1). Perform binary search on k to find the smallest layer count where total >= neededApples. Because the function grows monotonically, each check narrows the search space. The resulting garden perimeter is 8 * k.
What is the best approach for Minimum Garden Perimeter to Collect Enough Apples?
The most efficient solution uses a mathematical formula with binary search. The total apples after k layers is 2 * k * (k + 1) * (2 * k + 1). Since this value increases monotonically, binary search finds the smallest k where the apple count is at least neededApples. The final perimeter is 8 * k, giving O(log n) time complexity and O(1) space.
Is Minimum Garden Perimeter to Collect Enough Apples asked at Google/Amazon/Meta?
This problem represents the type of mathematical pattern and binary search optimization commonly asked in companies like Google and Amazon. It tests the ability to derive formulas from patterns and apply binary search on a monotonic function rather than searching arrays.
What data structure is used in Minimum Garden Perimeter to Collect Enough Apples?
The solution does not rely on complex data structures. It mainly uses mathematical formulas and optionally binary search over integers. The focus is recognizing the growth pattern of apples in expanding square layers.
What is the time complexity of Minimum Garden Perimeter to Collect Enough Apples?
The optimal solution runs in O(log n) time using binary search on the number of garden layers. Each step evaluates the formula 2 * k * (k + 1) * (2 * k + 1). A simpler iterative approach exists with O(sqrt(n)) time by expanding layers until the apple count reaches the target.

Ready to solve this problem?

Practice Minimum Garden Perimeter to Collect Enough Apples with our built-in code editor and test cases.

Practice on FleetCode