Talentd
FleetCode
Make and follow sheets.Sign in

Minimum Garden Perimeter to Collect Enough Apples solution and explanation

MediumBinary SearchMath4 min read55.5% acceptanceUpdated 9 Apr 2026
Minimum Garden Perimeter To Collect Enough Apples leetcode weekly contest 252 Leetcode 1954.CodeinDepth · 9:51 · 2K viewsWatch on YouTube
4 more videos on this problem
  1. Minimum Garden Perimeter To Collect Enough Apples leetcode weekly contest 252 Leetcode 1954.CodeinDepth · 9:51 · 2K views
  2. 1954. Minimum Garden Perimeter to Collect Enough Apples (Leetcode Medium)Programming Live with Larry · 46:49 · 818 views
  3. 1954. Minimum Garden Perimeter to Collect Enough Apples - LeetCodeLACODE · 13:25 · 360 views
  4. 1954. Minimum Garden Perimeter to Collect Enough Apples | Maths | 2D Matrix | Arithmetic ProgressionCoding Gist · 21:40 · 296 views
  5. Leetcode 1954. Minimum Garden Perimeter to Collect Enough Apples (math)LetsCode · 16:35 · 103 views

The problem

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`.

def find_perimeter(needed_apples):
    apples, k = 0, 0
    while apples < needed_apples:
        k += 1
        apples += 12 * k * k
    return 8 * k

needed_apples = 1000000000
print(find_perimeter(needed_apples))
public class Garden {
    public static long findPerimeter(long neededApples) {
        long apples = 0, k = 0;
        while (apples < neededApples) {
            k++;
            apples += 12 * k * k;
        }
        return 8 * k;
    }

    public static void main(String[] args) {
        long neededApples = 1000000000;
        System.out.println(findPerimeter(neededApples));
    }
}
#include <iostream>

long long findPerimeter(long long neededApples) {
    long long apples = 0, k = 0;
    while (apples < neededApples) {
        k++;
        apples += 12 * k * k;
    }
    return 8 * k;
}

int main() {
    long long neededApples = 1000000000;
    std::cout << findPerimeter(neededApples) << std::endl;
    return 0;
}
function findPerimeter(neededApples) {
    let apples = 0, k = 0;
    while (apples < neededApples) {
        k += 1;
        apples += 12 * k * k;
    }
    return 8 * k;
}

const neededApples = 1000000000;
console.log(findPerimeter(neededApples));
#include <stdio.h>
#include <math.h>

long long findPerimeter(long long neededApples) {
    long long apples = 0, k = 0;
    while (apples < neededApples) {
        k++;
        apples += 12 * k * k;
    }
    return 8 * k;
}

int main() {
    long long neededApples = 1000000000;
    printf("%lld\n", findPerimeter(neededApples));
    return 0;
}
using System;

public class Garden {
    public static long FindPerimeter(long neededApples) {
        long apples = 0, k = 0;
        while (apples < neededApples) {
            k++;
            apples += 12 * k * k;
        }
        return 8 * k;
    }
    
    public static void Main() {
        long neededApples = 1000000000;
        Console.WriteLine(FindPerimeter(neededApples));
    }
}

The Python solution similarly loops over expanding layers, calculating the apple count until it's equal to or greater than `neededApples`, returning the corresponding perimeter size.

Complexity

Time Complexity: O(sqrt(n)) due to layer-by-layer checking.
Space Complexity: O(1).

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.

from math import ceil, pow

def min_perimeter(needed_apples):
    k = ceil(pow(needed_apples / 3.0, 1/3.0))
    while 12 * k * (k + 1) * (2 * k + 1) // 6 < needed_apples:
        k += 1
    return 8 * k

needed_apples = 1000000000
print(min_perimeter(needed_apples))
public class Garden {
    public static long minPerimeter(long neededApples) {
        long k = (long) Math.ceil(Math.pow(neededApples / 3.0, 1/3.0));
        while (12 * k * (k + 1) * (2 * k + 1) / 6 < neededApples) {
            k++;
        }
        return 8 * k;
    }

    public static void main(String[] args) {
        long neededApples = 1000000000;
        System.out.println(minPerimeter(neededApples));
    }
}
#include <iostream>
#include <cmath>

long long minPerimeter(long long neededApples) {
    long long k = (long long)ceil(pow(neededApples / 3.0, 1/3.0));
    while (12 * k * (k + 1) * (2 * k + 1) / 6 < neededApples) {
        k++;
    }
    return 8 * k;
}

int main() {
    long long neededApples = 1000000000;
    std::cout << minPerimeter(neededApples) << std::endl;
    return 0;
}
function minPerimeter(neededApples) {
    let mathCeil = Math.ceil;
    let k = mathCeil(Math.pow(neededApples / 3.0, 1/3.0));
    while (12 * k * (k + 1) * (2 * k + 1) / 6 < neededApples) {
        k += 1;
    }
    return 8 * k;
}

const neededApples = 1000000000;
console.log(minPerimeter(neededApples));
#include <stdio.h>
#include <math.h>

long long minPerimeter(long long neededApples) {
    long long k = (long long)ceil(pow(neededApples / 3.0, 1/3.0));
    while (12 * k * (k + 1) * (2 * k + 1) / 6 < neededApples) {
        k++;
    }
    return 8 * k;
}

int main() {
    long long neededApples = 1000000000;
    printf("%lld\n", minPerimeter(neededApples));
    return 0;
}
using System;

public class Garden {
    public static long MinPerimeter(long neededApples) {
        long k = (long)Math.Ceiling(Math.Pow(neededApples / 3.0, 1/3.0));
        while (12 * k * (k + 1) * (2 * k + 1) / 6 < neededApples) {
            k++;
        }
        return 8 * k;
    }
    
    public static void Main() {
        long neededApples = 1000000000;
        Console.WriteLine(MinPerimeter(neededApples));
    }
}

The Python implementation approximates k with mathematical expressions and verifies adjustments, yielding a quick solution estimation.

Complexity

Time Complexity: O(1), iterative adjustments are minimal.
Space Complexity: O(1).

Try this approach in the editor

Approach 3: Default Approach

function minimumPerimeter(neededApples: number): number {
    let x = 1;
    while (2 * x * (x + 1) * (2 * x + 1) < neededApples) {
        ++x;
    }
    return 8 * x;
}
func minimumPerimeter(neededApples int64) int64 {
	var x int64 = 1
	for 2*x*(x+1)*(2*x+1) < neededApples {
		x++
	}
	return 8 * x
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Iterative Expansion Approach

Time Complexity: O(sqrt(n)) due to layer-by-layer checking.
Space Complexity: O(1).

Mathematical Calculation Approach

Time Complexity: O(1), iterative adjustments are minimal.
Space Complexity: O(1).

Default Approach–

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

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.

Comments

Now write it yourselfClose this page and solve Minimum Garden Perimeter to Collect Enough Apples in the editor, without looking.
Practise Minimum Garden Perimeter to Collect Enough Apples