Leetcode #2417: Closest Fair Integer
In this guide, we solve Leetcode #2417 Closest Fair Integer in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Math, Enumeration
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
Input: n = 2
Output: 10
Explanation: The smallest fair integer that is greater than or equal to 2 is 10.
10 is fair because it has an equal number of even and odd digits (one odd digit and one even digit).
Python Solution
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
The time complexity is . The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.