Minimize Deviation in Array — LeetCode 1675 Python Solution

HardGreedyArrayOrdered SetHeap (Priority Queue)
Problem
#1675
Reading time
3 min

The problem

You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: If the element is even, divide it by 2.

Example

Input
nums = [1,2,3,4]
Output
1
Explanation
You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.

Python solution

Python
class Solution:
    def minimumDeviation(self, nums: List[int]) -> int:
        h = []
        mi = inf
        for v in nums:
            if v & 1:
                v <<= 1
            h.append(-v)
            mi = min(mi, v)
        heapify(h)
        ans = -h[0] - mi
        while h[0] % 2 == 0:
            x = heappop(h) // 2
            heappush(h, x)
            mi = min(mi, -x)
            ans = min(ans, -h[0] - mi)
        return ans

Complexity

MeasureComplexity
TimeO(n\log n \times \log m)
SpaceO(1) to O(n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1675. Minimize Deviation in Array 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 1675. Minimize Deviation in Array?
LeetCode 1675. Minimize Deviation in Array is rated Hard on LeetCode.
What topics does LeetCode 1675. Minimize Deviation in Array cover?
LeetCode 1675. Minimize Deviation in Array is tagged Greedy, Array, Ordered Set 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