Remove 9 - Problem

Start from integer 1, remove any integer that contains the digit 9 such as 9, 19, 29, etc. Now, you will have a new integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, ...].

Given an integer n, return the nth (1-indexed) integer in the new sequence.

Note: The sequence is 1-indexed, meaning the first element is at position 1.

Input & Output

Example 1 — Basic Case
$ Input: n = 8
Output: 8
💡 Note: The sequence without 9s is [1,2,3,4,5,6,7,8,10,11,...]. The 8th number is 8.
Example 2 — Small Position
$ Input: n = 5
Output: 6
💡 Note: The sequence is [1,2,3,4,5,6,7,8,10,...]. The 5th number is 6.
Example 3 — After Multiple 9s
$ 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,...]. 18th number is 20 (skip 9,19).

Constraints

  • 1 ≤ n ≤ 8 × 108

Visualization

Tap to expand
Remove 9 - Base 9 Conversion INPUT n = 8 Original Sequence (1-indexed): 1 2 3 4 5 6 7 8 9 10 11 12 ... New Sequence (no 9s): 1 2 3 4 5 6 7 8 8th 10 11 ... Position 8 = value 8 (9 is skipped!) ALGORITHM STEPS 1 Observe Pattern Sequence is like base-9 numbers (0-8 digits) 2 Convert n to Base 9 8 in base 9 = 8 (8 / 9 = 0 rem 8) 3 Read as Base 10 Base-9 result "8" read as decimal = 8 4 Return Result Answer is 8 Base 9 Conversion: n=8: 8/9=0 r8 Base9: "8" As decimal: 8 --> 8 FINAL RESULT The 8th number in the "no-9s" sequence is: 8 Verification: Position 1: 1 Position 2: 2 Position 3: 3 Position 4: 4 Position 5: 5 Position 6: 6 Position 7: 7 Position 8: 8 Output: 8 Key Insight: The sequence of numbers without any 9s is equivalent to counting in base 9! Convert n to base 9, then interpret the result as a base 10 number. Time Complexity: O(log n) | Space Complexity: O(1) TutorialsPoint - Remove 9 | Optimal Solution (Base 9 Conversion)
Asked in
Google 15 Amazon 10 Facebook 8
23.0K Views
Medium Frequency
~15 min Avg. Time
892 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