Minimum Operations to Halve Array Sum — LeetCode 2208 Python Solution

MediumGreedyArrayHeap (Priority Queue)
Problem
#2208
Reading time
3 min

The problem

You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number.

Example

Input
nums = [5,19,8,1]
Output
3
Explanation
The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.

Python solution

Python
class Solution:
    def halveArray(self, nums: List[int]) -> int:
        s = sum(nums) / 2
        pq = []
        for x in nums:
            heappush(pq, -x)
        ans = 0
        while s > 0:
            t = -heappop(pq) / 2
            s -= t
            heappush(pq, -t)
            ans += 1
        return ans

Complexity

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

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2208. Minimum Operations to Halve Array Sum is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2208. Minimum Operations to Halve Array Sum?
LeetCode 2208. Minimum Operations to Halve Array Sum is rated Medium on LeetCode.
What is the time complexity of LeetCode 2208. Minimum Operations to Halve Array Sum?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2208. Minimum Operations to Halve Array Sum?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2208. Minimum Operations to Halve Array Sum cover?
LeetCode 2208. Minimum Operations to Halve Array Sum is tagged Greedy, Array and Heap (Priority Queue) 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