Closest Fair Integer - 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.

Return the smallest fair integer that is greater than or equal to n.

Example:

  • For n = 1, return 10 (1 even digit: 0, 1 odd digit: 1)
  • For n = 123, return 1230 (2 even digits: 2,0, 2 odd digits: 1,3)

Input & Output

Example 1 — Single Digit
$ Input: n = 1
Output: 10
💡 Note: 1 has 1 odd digit (1) and 0 even digits, so it's not fair. The smallest fair number ≥ 1 is 10: 1 odd digit (1) and 1 even digit (0).
Example 2 — Already Fair
$ Input: n = 32
Output: 32
💡 Note: 32 has 1 odd digit (3) and 1 even digit (2), so equal counts. It's already fair, return 32.
Example 3 — Need More Digits
$ Input: n = 123
Output: 1023
💡 Note: 123 has 2 odd digits (1,3) and 1 even digit (2). Need equal counts. The next fair number is 1023: 2 odd digits (1,3) and 2 even digits (0,2).

Constraints

  • 1 ≤ n ≤ 109
  • n is a positive integer

Visualization

Tap to expand
Find Closest Fair Integer: Equal Even/Odd Digit CountsInput: 123Not Fair123OddEvenOddOdd: 2, Even: 1 → Not FairOutput: 1023Fair!1023OddEvenEvenOddOdd: 2, Even: 2 → Fair!Find smallest number ≥ n with equal even and odd digit counts
Understanding the Visualization
1
Input
Given positive integer n = 123
2
Analyze
Count digits: 1(odd), 2(even), 3(odd) → 2 odd, 1 even
3
Find Fair
Next fair number: 1023 has 2 odd, 2 even digits
Key Takeaway
🎯 Key Insight: Fair numbers need equal counts of even and odd digits - build them systematically rather than checking every number
Asked in
Google 15 Microsoft 12 Amazon 8
12.4K Views
Medium Frequency
~25 min Avg. Time
234 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