Problem 1675

Abstract / Summary

Make all numbers even by repeatedly halving odd numbers or doubling the smallest even number to minimize the difference between the largest and smallest values.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1675.py

class Solution:
    def minimumDeviation(self, nums: List[int]) -> int:
        result = inf

        # step 1: maximize elements (second operation, can only be applied once)
        for i in range(len(nums)):
            if (nums[i] & 1) == 1:
                nums[i] *= 2
        # all elements are now even

        low = min(nums)

        # step 2: minimize elements, beginning with the largest => max-heap
        maxheap = [ -n for n in nums ] # max-heap means negated sign
        heapify(maxheap)
        while (maxheap[0] & 1) == 0: # second operation, can be applied multiple times
            smaller = -maxheap[0] // 2
            heappushpop(maxheap, -smaller)

            low    = min(low, smaller)
            high   = -maxheap[0]
            result = min(result, high - low)

        return result
24 lines | 840 bytes | submitted November 17, 2023 | GitHub   31% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Heap (Priority Queue)
  • Ordered Set
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the “minimum deviation” problem for an integer array. The algorithm first normalizes every element to an even value, then repeatedly reduces the current maximum while tracking the smallest value seen. By maintaining a max-heap of the transformed numbers, the method efficiently explores the space of possible deviations and returns the smallest difference between the largest and smallest elements that can be achieved through the allowed operations.

Key Steps

The solution can be divided into three logical phases.

The first phase converts all odd numbers into even numbers by doubling them. This guarantees that every element can later be halved without violating the problem constraints.

for i in range(len(nums)):
    if (nums[i] & 1) == 1:
        nums[i] *= 2

After this transformation the variable low is initialized to the minimum value among the now-even elements.

low = min(nums)

The second phase builds a max-heap from the normalized array. Because Python’s heapq implements a min-heap, each value is stored as its negative counterpart.

maxheap = [-n for n in nums]
heapify(maxheap)

The core loop repeatedly extracts the current maximum (the most negative entry) while it remains even. Inside the loop the maximum is halved, re-inserted into the heap, and both the global low and high bounds are updated. The deviation for the current configuration is computed and the best result is retained.

while (maxheap[0] & 1) == 0:
    smaller = -maxheap[0] // 2
    heappushpop(maxheap, -smaller)

    low    = min(low, smaller)
    high   = -maxheap[0]
    result = min(result, high - low)

When the loop terminates, no further halving of the maximum is possible because it has become odd. At that point the smallest deviation discovered is returned.

return result

Edge Cases Handled

The algorithm gracefully handles arrays that contain only odd numbers. The initial doubling step converts every entry to an even value, ensuring that the subsequent heap-based reduction can proceed without special casing.

If the input consists of a single element, the initial low equals that element, the heap contains one entry, and the while-condition fails immediately because the sole element is even but halving it would not change the deviation (the difference between max and min remains zero). The function therefore returns zero, which is the correct minimal deviation.

Arrays that already contain only even numbers bypass the first loop entirely, preserving their original values. The subsequent heap processing still works because the while-condition checks the parity of the current maximum, allowing reductions only when the maximum is even.

When the maximum element becomes odd after a series of halvings, the loop stops. This prevents an attempt to halve an odd number, which would be illegal under the problem’s operation set. The code therefore respects the constraint that the second operation may be applied only to even numbers.

Performance Optimizations

The use of a max-heap (implemented via negated values) provides logarithmic time updates for each reduction step. By always operating on the current largest element, the algorithm minimizes the number of heap operations required to explore the search space.

Storing the global minimum low separately avoids scanning the entire heap after each modification. The min function is invoked only when a new candidate (smaller) is generated, which reduces overhead compared to recomputing the minimum from the heap each iteration.

The initial conversion of odd numbers to even values is performed in-place, eliminating the need for an auxiliary array and reducing memory pressure.

Finally, the loop condition checks the parity of the heap’s top element directly using a bitwise AND, which is faster than a modulo operation. This small micro-optimization contributes to the overall efficiency of the iterative reduction process.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a group of toy cars that all have different numbers on their roofs. Some numbers are odd and some are even. The goal is to make all the numbers even so they can be ready to race.

First, look for every odd number in the garage. If you find one, double its size to make it even. Now that every car has an even number, find the smallest one and keep it in mind.

Next, put all those numbers into a magic pile that always keeps the biggest number right on top. While that biggest number is still even, you can cut it in half to make it smaller. After you cut it, put it back into the pile. Keep track of the new smallest number you see and find the difference between the biggest one in the pile and the smallest one you have found so far. Keep doing this until that biggest number on top of the pile can no longer be cut in half because it turned into an odd number.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.19 | σ = 2.18

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
27 links | 17 authors | 7 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

6 solutions   November 17, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality