Closest Fair Integer Problem
#2417
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2417.
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.
Return the smallest fair integer that is greater than or equal to n.
Example 1:
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).
Example 2:
Input: n = 403
Output: 1001
Explanation: The smallest fair integer that is greater than or equal to 403 is 1001.
1001 is fair because it has an equal number of even and odd digits (two odd digits and two even digits).
Constraints:
1 <= n <= 10^9
Solution
Approach: Case Analysis
Let k be the number of digits of n, with a odd digits and b even digits.
- If
a == b,nis already fair. - If
kis odd, nok-digit number is fair, and the smallest fair number hask + 1digits: a 1, then zeros, thenk / 2ones (like10000111). - If
kis even, tryn + 1,n + 2, ... until a fair number appears. The gap is small, so this is fast.
Complexity: About O(sqrt(n) log n) time in the worst case of the even-length search, and O(1) extra space.
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)