Minimum Garden Perimeter to Collect Enough Apples - 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

Input & Output

Example 1 — Small Square
$ Input: neededApples = 1
Output: 8
💡 Note: The smallest square that contains at least 1 apple has radius 1. At radius 1, we have a 3×3 grid with total 12 apples, which is ≥ 1. Perimeter = 8 × 1 = 8.
Example 2 — Medium Square
$ Input: neededApples = 13
Output: 16
💡 Note: At radius 1: 12 apples (not enough). At radius 2: 60 apples (≥ 13). So minimum radius is 2, perimeter = 8 × 2 = 16.
Example 3 — Larger Square
$ Input: neededApples = 1000000000
Output: 5040
💡 Note: For very large needed apples, we use binary search to find the minimum radius efficiently. The answer is perimeter = 8 × 630 = 5040.

Constraints

  • 1 ≤ neededApples ≤ 2 × 1015

Visualization

Tap to expand
Garden Square: Find Minimum Perimeter for 13 ApplesRadius 1 (3×3)012 apples < 13Not enough ✗Radius 2 (5×5)060 apples ≥ 13Sufficient ✓Formula:Radius n apples =2×n×(n+1)×(2n+1)n=1: 2×1×2×3 = 12n=2: 2×2×3×5 = 60Minimum radius = 2, Perimeter = 8×2 = 16
Understanding the Visualization
1
Input
neededApples = 13
2
Process
Find minimum square radius containing ≥13 apples
3
Output
Return perimeter = 8 × radius
Key Takeaway
🎯 Key Insight: Use mathematical formula with binary search to efficiently find minimum square radius
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
23.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen