Closest Fair Integer — LeetCode 2417 Python Solution

MediumLeetCode PremiumMathEnumeration
Problem
#2417
Reading time
3 min

The problem

You are given a positive integer n. We call an integer k fair if the number of even digits in k is equal to the number of odd digits in it.

Example

Input
n = 2
Output
10
Explanation
The smallest fair integer that is greater than or equal to 2 is 10.

Python solution

Python
class Solution:
    def closestFair(self, n: int) -> int:
        a = b = k = 0
        t = n
        while t:
            if (t % 10) & 1:
                a += 1
            else:
                b += 1
            t //= 10
            k += 1
        if k & 1:
            x = 10**k
            y = int('1' * (k >> 1) or '0')
            return x + y
        if a == b:
            return n
        return self.closestFair(n + 1)

Complexity

MeasureComplexity
TimeO(\sqrt{n} \times \log_{10} n)
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2417. Closest Fair Integer is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2417. Closest Fair Integer?
LeetCode 2417. Closest Fair Integer is rated Medium on LeetCode.
What is the time complexity of LeetCode 2417. Closest Fair Integer?
The Python solution on this page runs in O(\sqrt{n} \times \log_{10} n).
What is the space complexity of LeetCode 2417. Closest Fair Integer?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2417. Closest Fair Integer cover?
LeetCode 2417. Closest Fair Integer is tagged Math and Enumeration on LeetCode.
Is LeetCode 2417. Closest Fair Integer a premium problem?
Yes. LeetCode 2417. Closest Fair Integer is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview