Minimize Deviation in Array

Hard

Topics
ArrayGreedyHeap

Given an array nums of positive integers, you may repeatedly apply two operations any number of times: if an element is even you may halve it, and if an element is odd you may double it. The deviation is the difference between the maximum and minimum elements. Return the minimum possible deviation.

Example 1

10213243
Input:  nums = [1,2,3,4]
Output: 1

Example 2

40115220334
Input:  nums = [4,1,5,20,3]
Output: 3

Example 3

2010182
Input:  nums = [2,10,8]
Output: 3

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^9
Editorial — intuition, approach, complexity and pitfalls

Intuition

The two operations are asymmetric in a way that collapses the search space. An odd number can be doubled, and the result is even; an even number can be halved repeatedly until it becomes odd. So every element has a finite, totally ordered ladder of reachable values, and an odd number's ladder is only reachable upward once.

That means the right move is to double every odd number immediately. After that, every element is even and can only go down. The deviation is then minimised by repeatedly halving whichever element is currently largest — because the maximum is the only element whose reduction can shrink the spread — while tracking the running minimum. Stop when the maximum becomes odd, since it can go no lower.

Doubling the odds first is what makes this a one-directional process; without it you would have to consider raising and lowering at the same time.

Approach

  1. Double every odd element, pushing all values into a max-heap and tracking the minimum.
  2. Pop the maximum, record max - min as a candidate answer.
  3. Stop if the maximum is odd — it cannot be reduced further.
  4. Otherwise halve it, update the minimum, push it back, and repeat.

Dry Run

nums = [4,1,5,20,3]

double the odds: 1 -> 2, 5 -> 10, 3 -> 6      values now [4, 2, 10, 20, 6]
minimum so far 2

  max   deviation   action
  20    20 - 2 = 18 even, halve to 10
  10    10 - 2 = 8  even, halve to 5
  10    10 - 2 = 8  even, halve to 5
  6     6 - 2 = 4   even, halve to 3
  5     5 - 2 = 3   odd, stop

answer 3

  [1,2,3,4] -> 1    doubling gives [2,2,6,4], halving 6 and 4 reaches [2,2,3,2]

Complexity

  • Time — O(n log n log(maxValue)): each element can be halved O(log maxValue) times, and every halving costs a heap operation of O(log n). At the stated bounds that is roughly 10⁵ × 17 × 30 in the worst case, comfortably fast in practice because most elements stop early.
  • Space — O(n) for the heap.

Common Pitfalls

  • Trying to halve and double simultaneously. Doubling every odd number once, up front, is what makes the rest of the process monotone — and it loses nothing, because an odd number that is never doubled is already at its lowest.
  • Doubling an odd number more than once. After one doubling it is even; doubling again only moves it away from the minimum.
  • Reducing the minimum instead of the maximum. Only the maximum's reduction can shrink the spread; raising the minimum is never available once the odds have been doubled.
  • Recording the deviation after halving rather than before. The candidate answer for the current configuration must be taken while the maximum is still the maximum.
  • Forgetting to update the running minimum as values come down. A halved maximum frequently becomes the new minimum — the 20 → 10 → 5 chain above never does, but [1,2,3,4] does.
  • Using a min-heap and tracking the maximum separately. It is the mirror image and does not work: you need to pop the largest element, which a min-heap cannot do cheaply.

Full Solution — all languages

class Solution:
    def minimumDeviation(self, nums):
        import heapq
        heap = []
        mn = float('inf')
        for x in nums:
            if x % 2 == 1:
                x *= 2
            heap.append(-x)
            mn = min(mn, x)
        heapq.heapify(heap)
        res = float('inf')
        while True:
            mx = -heapq.heappop(heap)
            res = min(res, mx - mn)
            if mx % 2 == 1:
                break
            mx //= 2
            mn = min(mn, mx)
            heapq.heappush(heap, -mx)
        return res
Asked at Samsung
SensAI
Beta
Tap the mic to stop voice mode