Remove 9 - Problem
Imagine a world where the number 9 is considered unlucky and must be completely avoided! Starting from 1, we need to create a new sequence by removing any integer that contains the digit 9.
For example, numbers like 9, 19, 29, 90, 91, 99, 190, 291 would all be banned from our sequence.
This gives us a new sequence: [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, ...]
Goal: Given a positive integer n, return the nth number (1-indexed) in this "9-free" sequence.
Key insight: This is essentially working with a base-9 numbering system using digits 0-8, but we need to map it to digits 1-8, 10 (skipping 9)!
Input & Output
example_1.py โ Basic Case
$
Input:
n = 8
โบ
Output:
10
๐ก Note:
The sequence without 9s is [1,2,3,4,5,6,7,8,10,11,...]. The 8th number is 10 because we skip 9.
example_2.py โ Early Number
$
Input:
n = 5
โบ
Output:
6
๐ก Note:
The first 5 numbers without 9 are [1,2,3,4,5]. The 5th number is 6.
example_3.py โ Larger Number
$
Input:
n = 18
โบ
Output:
20
๐ก Note:
Sequence: [1,2,3,4,5,6,7,8,10,11,12,13,14,15,16,17,18,20,...]. We skip 9,19 so the 18th valid number is 20.
Constraints
- 1 โค n โค 8 ร 108
- n is guaranteed to be a positive integer
- The answer will fit in a 32-bit signed integer
Visualization
Tap to expand
Understanding the Visualization
1
Forbidden Numbers
Any number containing digit 9 is removed: 9, 19, 29, 90-99, etc.
2
Remaining Sequence
Valid numbers: 1,2,3,4,5,6,7,8,10,11,12,13,14,15,16,17,18,20...
3
Pattern Recognition
This is exactly like base-9, but using digits 1-8,10 instead of 0-8
4
Direct Conversion
Convert (n-1) to base-9, then add 1 to each digit
Key Takeaway
๐ฏ Key Insight: Numbers without digit 9 form a bijection with base-9 numbers, enabling O(log n) conversion instead of O(n) counting!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code