Minimize Deviation in Array - 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.
  • If the element is odd, multiply it by 2.

The deviation of the array is the maximum difference between any two elements in the array.

Return the minimum deviation the array can have after performing some number of operations.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4]
Output: 1
💡 Note: Convert 1→2, 3→6. Array becomes [2,2,6,4]. Then reduce 6→3, 4→2. Final: [2,2,3,2]. Deviation = 3-2 = 1.
Example 2 — All Odds
$ Input: nums = [4,1,5,20,3]
Output: 3
💡 Note: Convert odds: 1→2, 5→10, 3→6. Array: [4,2,10,20,6]. After optimal reductions: deviation is 3.
Example 3 — Single Element
$ Input: nums = [2]
Output: 0
💡 Note: Only one element, so deviation is 0.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimize Deviation in Array INPUT nums = [1, 2, 3, 4] 1 odd 2 even 3 odd 4 even Operations: - Even: divide by 2 - Odd: multiply by 2 Max Possible Values 1 --> 2 2 --> 2 3 --> 6 4 --> 4 ALGORITHM (Greedy) 1 Maximize Odds Double all odd numbers [2, 2, 6, 4] 2 Use Max Heap Track max element heap: [6,4,2,2] 3 Reduce Max Divide max by 2 if even 6/2=3 --> [4,3,2,2] 4 Track Min Dev Update min deviation dev = max - min Iterations: [6,4,2,2] dev=4 [4,3,2,2] dev=2 [3,2,2,2] dev=1 (stop:odd) FINAL RESULT Optimal Configuration: 3 2 2 2 Maximum: 3 Minimum: 2 Deviation: 3 - 2 = 1 Output 1 [OK] Minimum Deviation Cannot reduce further (max is odd, can't divide) Key Insight: First maximize all odd numbers (multiply by 2), making everything even. Then use a max-heap to repeatedly divide the maximum element by 2. Track the minimum deviation throughout. Stop when the maximum becomes odd (cannot divide further). Time: O(n log n log M), Space: O(n). TutorialsPoint - Minimize Deviation in Array | Greedy Approach
Asked in
Google 45 Amazon 32 Facebook 28
38.2K Views
Medium Frequency
~25 min Avg. Time
1.6K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen