Minimum Garden Perimeter to Collect Enough Apples — LeetCode 1954 Python Solution

MediumMathBinary Search
Problem
#1954
Reading time
2 min

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.

Example

Input
neededApples = 1
Output
8
Explanation
A square plot of side length 1 does not contain any apples.

Python solution

Python
class Solution:
    def minimumPerimeter(self, neededApples: int) -> int:
        x = 1
        while 2 * x * (x + 1) * (2 * x + 1) < neededApples:
            x += 1
        return x * 8

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1954. Minimum Garden Perimeter to Collect Enough Apples is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1954. Minimum Garden Perimeter to Collect Enough Apples?
LeetCode 1954. Minimum Garden Perimeter to Collect Enough Apples is rated Medium on LeetCode.
What topics does LeetCode 1954. Minimum Garden Perimeter to Collect Enough Apples cover?
LeetCode 1954. Minimum Garden Perimeter to Collect Enough Apples is tagged Math and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview