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
The Forbidden Number 9 SystemOriginal: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20...Removed: _ _ _ _ _ _ _ _ โœ— _ _ _ _ _ _ _ _ _ โœ— _ ...Result: 1 2 3 4 5 6 7 8 10 11 12 13 14 15 16 17 18 20...Base-9 ConnectionPosition (1-indexed): 1 2 3 4 5 6 7 8 9 10 11 12...Base-9 (0-indexed): 0 1 2 3 4 5 6 7 8 10 11 12...Our Result: 1 2 3 4 5 6 7 8 10 11 12 13...Algorithm Steps1Convert n to 0-indexed: n = n - 12Convert to base-9: repeatedly divide by 9, collect remainders3Map each base-9 digit d to d+1 (this skips digit 9)
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!
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
34.2K Views
Medium-High Frequency
~25 min Avg. Time
1.5K 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