Leetcode #1675: Minimize Deviation in Array
In this guide, we solve Leetcode #1675 Minimize Deviation in Array in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Greedy, Array, Ordered Set, Heap (Priority Queue)
Intuition
A locally optimal choice leads to a globally optimal result for this structure.
That means we can commit to decisions as we scan without backtracking.
Approach
Sort or preprocess if needed, then repeatedly take the best available local choice.
Maintain the minimal state necessary to validate the greedy decision.
Steps:
- Sort or preprocess as needed.
- Iterate and pick the best local option.
- Track the current solution.
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
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
The time complexity is . The space complexity is O(1) to O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.