Next Greater Numerically Balanced Number - Problem

A numerically balanced number is a fascinating mathematical concept where each digit d appears exactly d times in the number itself. For example:

  • 1 is balanced because digit 1 appears exactly 1 time
  • 122 is balanced because digit 1 appears 1 time and digit 2 appears 2 times
  • 1333 is balanced because digit 1 appears 1 time and digit 3 appears 3 times

Your task is to find the smallest numerically balanced number that is strictly greater than the given integer n. This is like finding the "next" balanced number in sequence!

Goal: Given an integer n, return the smallest numerically balanced number greater than n.

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 1
โ€บ Output: 22
๐Ÿ’ก Note: The next balanced number after 1 is 22. In 22, digit 2 appears exactly 2 times, making it numerically balanced.
example_2.py โ€” Medium Case
$ Input: n = 1000
โ€บ Output: 1333
๐Ÿ’ก Note: After 1000, the next balanced number is 1333. Here, digit 1 appears 1 time and digit 3 appears 3 times.
example_3.py โ€” Already Balanced
$ Input: n = 122
โ€บ Output: 212
๐Ÿ’ก Note: Even though 122 is balanced, we need the next one strictly greater. 212 is the next balanced number where 1 appears once and 2 appears twice.

Constraints

  • 1 โ‰ค n โ‰ค 106
  • The answer is guaranteed to exist within reasonable bounds
  • Note: Numerically balanced numbers become very sparse for larger values

Visualization

Tap to expand
The Balance Challenge123โŒ NotBalanced122โœ“ Balanced1โ†’1, 2โ†’21333โœ“ Balanced1โ†’1, 3โ†’3144444โœ“ Balanced1โ†’1, 4โ†’4Precomputed Treasure Map1, 22, 122, 212, 221, 1333, 3133, 3313, 3331, 12333, ...Only ~83 balanced numbers exist below 10^7!๐ŸŽฏ Binary Search MagicFind next number in O(log 83) โ‰ˆ O(1) time!
Understanding the Visualization
1
Understanding Balance
A number is balanced when digit d appears exactly d times: 1โ†’1 time, 2โ†’2 times, 3โ†’3 times
2
Rarity Discovery
Balanced numbers are incredibly rare - only about 83 exist below 10^7
3
Smart Solution
Instead of checking every number, precompute all balanced numbers and use binary search
4
Lightning Fast
Binary search in precomputed list gives us practically O(1) performance
Key Takeaway
๐ŸŽฏ Key Insight: Since numerically balanced numbers are extremely rare, the most efficient approach is to precompute all of them and use binary search for instant lookup!
Asked in
Google 15 Amazon 8 Meta 6 Apple 4
22.8K Views
Medium Frequency
~25 min Avg. Time
950 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