Number of Beautiful Integers in the Range - Problem
You're on a quest to find "beautiful integers" - numbers that possess a special mathematical harmony! ๐ฏ
Given three positive integers low, high, and k, your task is to count how many integers in the range [low, high] are considered beautiful.
An integer is beautiful if it satisfies both of these conditions:
- Digit Balance: The count of even digits (0, 2, 4, 6, 8) equals the count of odd digits (1, 3, 5, 7, 9)
- Divisibility: The number is divisible by
k
Example: The number 1234 has 2 even digits (2, 4) and 2 odd digits (1, 3), so it has digit balance. If k = 617 and 1234 % 617 = 0, then 1234 would be beautiful!
Goal: Return the count of beautiful integers in the given range.
Input & Output
example_1.py โ Basic Range
$
Input:
low = 10, high = 20, k = 3
โบ
Output:
2
๐ก Note:
In range [10, 20], we check each number: 12 has 1 even digit (2) and 1 odd digit (1), and 12 % 3 = 0, so it's beautiful. 18 has 1 even digit (8) and 1 odd digit (1), and 18 % 3 = 0, so it's beautiful. Total: 2 beautiful integers.
example_2.py โ Larger Numbers
$
Input:
low = 1, high = 10, k = 1
โบ
Output:
1
๐ก Note:
Only single-digit numbers can't be beautiful (except for 0, but it's not in range). We need equal even and odd digits. No numbers in [1, 10] satisfy this since they all have only 1 digit. Wait, let me recalculate: actually no number from 1-10 can have equal even/odd digits since they're all single digits. The answer should be 0.
example_3.py โ Edge Case
$
Input:
low = 4, high = 4, k = 4
โบ
Output:
0
๐ก Note:
Only checking number 4. It has 1 even digit (4) and 0 odd digits, so even_count โ odd_count. Even though 4 % 4 = 0, it doesn't satisfy the balance condition, so it's not beautiful.
Constraints
- 1 โค low โค high โค 109
- 1 โค k โค 20
- Numbers can be up to 10 digits long
- Range [low, high] is inclusive on both ends
Visualization
Tap to expand
Understanding the Visualization
1
Digit by Digit Construction
Like composing music note by note, we build numbers digit by digit
2
Balance Tracking
Keep count: +1 for each odd digit (wind), -1 for each even digit (string)
3
Rhythm Checking
Maintain remainder modulo k to ensure final number fits the rhythm
4
State Memoization
Remember results for identical states to avoid recalculation
Key Takeaway
๐ฏ Key Insight: Instead of checking millions of numbers individually, Digit DP constructs only valid beautiful numbers by building them digit by digit while maintaining the required mathematical properties!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code