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:

  • 1234 is fair (even digits: 2,4 | odd digits: 1,3)
  • 567 is not fair (even digits: 6 | odd digits: 5,7)
  • 1122 is 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
Finding the Closest Fair IntegerInputn = 135E:0, O:3Analysis Process135: Even=0, Odd=3 โŒ136: Even=1, Odd=2 โŒ137: Even=0, Odd=3 โŒ...1200: Even=2, Odd=2 โœ“Result1200Fair! โœ“Fair Number Patterns2 digits10, 12, 14, 16, 1821, 23, 25, 27, 294 digits1010, 1012, 10141030, 1032, 10346 digits101010, 1010123 even, 3 odd๐Ÿ’ก Key Insight: Fair numbers must have even length (so even and odd counts can be equal)Construction strategy: Use patterns like alternating digits or groups of even/odd digits
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

n
2n
โœ“ Linear Growth
Space Complexity
O(d)

Space to store digit representations

n
2n
โœ“ 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
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
38.9K Views
Medium Frequency
~18 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen