Removing Minimum Number of Magic Beans — LeetCode 2171 Python Solution

MediumGreedyArrayEnumerationPrefix SumSorting
Problem
#2171
Pattern
Prefix Sum
Reading time
2 min

The problem

You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag. Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal.

Example

Input
beans = [4,1,6,5]
Output
4
Explanation
- We remove 1 bean from the bag with only 1 bean.

Python solution

Python
class Solution:
    def minimumRemoval(self, beans: List[int]) -> int:
        beans.sort()
        s, n = sum(beans), len(beans)
        return min(s - x * (n - i) for i, x in enumerate(beans))

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2171. Removing Minimum Number of Magic Beans is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2171. Removing Minimum Number of Magic Beans?
LeetCode 2171. Removing Minimum Number of Magic Beans is rated Medium on LeetCode.
What is the time complexity of LeetCode 2171. Removing Minimum Number of Magic Beans?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2171. Removing Minimum Number of Magic Beans?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 2171. Removing Minimum Number of Magic Beans cover?
LeetCode 2171. Removing Minimum Number of Magic Beans is tagged Greedy, Array, Enumeration, Prefix Sum and Sorting 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