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
Closest Fair Integer - Smart Construction INPUT n = 1 Single digit number Digit Analysis: 1 ODD digit Even digits 0 Odd digits 1 NOT FAIR (0 != 1) Input: n = 1 ALGORITHM STEPS 1 Check digit count 1 has 1 digit (odd count) 2 Need even length Fair needs equal even/odd 3 Find min 2-digit fair Smallest: 1 even + 1 odd 4 Construct answer "10" = 1(odd) + 0(even) Smart Construction: 1 odd + 0 even Result = 10 1 odd + 1 even = FAIR FINAL RESULT 10 Closest Fair Integer Verification: Odd digits 1 (digit: 1) = Even digits 1 (digit: 0) OK - FAIR! Comparison: Input n = 1 Output = 10 (10 >= 1) Key Insight: A "fair" integer must have equal counts of odd and even digits, requiring an EVEN total number of digits. For small numbers like n=1, we construct the smallest 2-digit fair number: "10" (1 odd + 1 even digit). TutorialsPoint - Closest Fair Integer | Smart Construction Approach
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