#1954
Minimum Garden Perimeter to Collect Enough Apples
MediumMathBinary SearchMathematical FormulasBinary Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log n)Space O(1)
Instead of checking each side length one by one, we can use a mathematical formula to directly calculate the number of apples in a square plot of side length L. This allows us to use binary search to efficiently find the minimum L that meets the requirement.
⚙️
Algorithm
3 steps- 1Step 1: Define a function to calculate the number of apples in a square of side length L.
- 2Step 2: Use binary search to find the smallest L such that the number of apples is at least neededApples.
- 3Step 3: Calculate the perimeter as 4 * L once the correct L is found.
solution.py13 lines
1# Full working Python code
2
3def minGardenPerimeter(neededApples):
4 def apples_in_square(L):
5 return (L // 2) * (L // 2 + 1) * 2
6 left, right = 1, 2 * 10**9
7 while left < right:
8 mid = (left + right) // 2
9 if apples_in_square(mid) < neededApples:
10 left = mid + 1
11 else:
12 right = mid
13 return 4 * leftℹ
Complexity note: The time complexity is logarithmic because we are using binary search to narrow down the possible values of L, which significantly reduces the number of iterations needed compared to the brute force approach.
- 1The number of apples in a square plot can be calculated using a mathematical formula based on the side length.
- 2Using binary search allows us to efficiently find the minimum side length that meets the apple requirement.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.