Minimize Deviation in Array - Problem
Problem: You are given an array nums of n positive integers. Your goal is to minimize the deviation of the array through strategic operations.

Available Operations:
• If an element is even, you can divide it by 2
• If an element is odd, you can multiply it by 2

The deviation is defined as the maximum difference between any two elements in the array after performing operations.

Example: Given [1,2,3,4], you could transform it to [2,1,6,1] by: multiply 1→2, divide 2→1, multiply 3→6, divide 4→2→1. The deviation would be 6-1=5.

Goal: Return the minimum possible deviation after performing any number of operations.

Input & Output

example_1.py — Basic Case
$ Input: nums = [1,2,3,4]
Output: 1
💡 Note: Start with [1,2,3,4]. Double odds: [2,2,6,4]. Then systematically reduce: 6→3, 4→2→1. Final possible arrays include [1,1,3,1] with deviation 3-1=2, or [2,1,3,1] with deviation 3-1=2, or [2,2,3,2] with deviation 3-2=1. The minimum deviation is 1.
example_2.py — All Even Numbers
$ Input: nums = [4,1,5,20,3]
Output: 3
💡 Note: Double odds: [4,2,10,20,6]. Systematically reduce maximums: 20→10→5, then 10→5, then 6→3. Through optimal reductions, we can achieve arrays like [4,2,5,5,3] with deviation 5-2=3.
example_3.py — Single Element
$ Input: nums = [2]
Output: 0
💡 Note: With only one element, the deviation is always 0 since max - min = element - element = 0.

Constraints

  • n == nums.length
  • 1 ≤ n ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • All elements are positive integers

Visualization

Tap to expand
🌡️ Smart Building Temperature ControlRoom 121°(odd → 42°)Room 216°(even → keep)Room 323°(odd → 46°)Room 424°(even → keep)After heating odd temperaturesRoom 142°Room 216°Room 346°Room 424°🔥 Hottest: 46°❄️ Coldest: 16°Difference: 30°Cool down hottest room (46° → 23°)Final State:23°16°23°12°✅ Optimal!Min Deviation: 11°(23° - 12° = 11°)
Understanding the Visualization
1
Heat All Odd Rooms
First, heat up all rooms at odd temperatures (multiply by 2) since they can only be heated once
2
Track Temperatures
Keep track of the hottest room (max heap) and the coldest temperature ever seen
3
Cool Down Systematically
Always cool down the hottest room (if even temperature) and update the temperature range
4
Stop When Optimal
Stop when the hottest room is at an odd temperature (can't cool further)
Key Takeaway
🎯 Key Insight: Always maximize odd numbers first (they can only increase once), then systematically reduce the maximum element while tracking the global minimum. This greedy approach guarantees the optimal solution.
Asked in
Google 42 Amazon 38 Meta 29 Microsoft 24
67.2K Views
Medium Frequency
~25 min Avg. Time
1.9K 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