Closest Fair Integer - Problem
You are given a positive integer n. Your task is to find the closest fair integer that is greater than or equal to n.
An integer is considered fair if it has an equal number of even digits and odd digits. For example:
1234is fair (even digits: 2,4 | odd digits: 1,3)567is not fair (even digits: 6 | odd digits: 5,7)1122is fair (even digits: 2,2 | odd digits: 1,1)
Goal: Return the smallest fair integer that is greater than or equal to n.
Input & Output
example_1.py โ Basic Fair Number
$
Input:
n = 13
โบ
Output:
14
๐ก Note:
13 has 0 even digits and 2 odd digits (not fair). 14 has 1 even digit (4) and 1 odd digit (1), so it's fair.
example_2.py โ Already Fair
$
Input:
n = 1234
โบ
Output:
1234
๐ก Note:
1234 has 2 even digits (2,4) and 2 odd digits (1,3), so it's already fair. Return it as is.
example_3.py โ Single Digit Edge Case
$
Input:
n = 5
โบ
Output:
10
๐ก Note:
Single digits cannot be fair (1 odd, 0 even OR 0 odd, 1 even). The smallest fair number is 10 (1 odd, 1 even).
Visualization
Tap to expand
Understanding the Visualization
1
Check Current Balance
See if the given number already has equal even and odd digits
2
Search Nearby
Look at numbers close to the input to find the nearest balanced one
3
Smart Construction
If needed, construct fair numbers using known patterns like 10, 1010, 101010...
4
Return Solution
Return the smallest fair number that meets our criteria
Key Takeaway
๐ฏ Key Insight: Fair integers require equal counts of even and odd digits, which means they must have an even total number of digits. The most efficient approach combines checking nearby numbers with pattern-based construction for optimal performance.
Time & Space Complexity
Time Complexity
O(d * k)
d is number of digits, k is small constant for construction attempts
โ Linear Growth
Space Complexity
O(d)
Space to store digit representations
โ Linear Space
Constraints
- 1 โค n โค 106
- The answer will always exist and fit in a 32-bit integer
- Note: Fair numbers must have equal counts of even and odd digits
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code