660. Remove 9


Problem Description

You are to create a sequence of integers, but with a twist. When counting up from 1, any number containing a 9 should be skipped. For instance, you would go from 8, to 10, to 11, skipping 9. The sequence will therefore look like: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, ..., 18, 20, ..., etc. You are given an integer n, and your task is to return the n-th number in this sequence.

For example, if you're asked for the 9th number in the sequence, the sequence would look as follows: 1, 2, 3, 4, 5, 6, 7, 8, 10. Hence, you would return 10.

Solution Approach

The solution to this problem lies in number systems. Specifically, this problem mirrors counting in base 9, where there are only digits from 0-8. This is because our problem essentially forms a new sequence excluding 9, so the count is similarly performed in base 9.

To explain this further with an example, let's take n = 10. When counted in base 10 (which is the normal counting system we use), the 10th integer is 10. However, in our problem, we would need to exclude the number 9 (integers containing 9) from the sequence. If we count in base 9, the 10th integer is 11 (because 9 is not counted).

Python Solution

1
2python
3class Solution:
4    def newInteger(self, n: int) -> int:
5        ans = ""
6        while n:
7            ans = str(n % 9) + ans
8            n //= 9
9        return int(ans)

Java Solution

1
2java
3class Solution {
4    public int newInteger(int n) {
5        String ans = "";
6        while (n > 0) {
7            ans = (n % 9) + ans;
8            n /= 9;
9        }
10        return Integer.parseInt(ans);
11    }
12}

Javascript Solution

1
2javascript
3class Solution {
4    newInteger(n) {
5        let ans = "";
6        while (n) {
7            ans = (n % 9).toString() + ans;
8            n = Math.floor(n / 9);
9        }
10        return parseInt(ans);
11    }
12};

C++ Solution

1
2cpp
3class Solution {
4public:
5    int newInteger(int n) {
6        string ans = "";
7        while (n) {
8            ans = to_string(n % 9) + ans;
9            n /= 9;
10        }
11        return stoi(ans);
12    }
13};

C# Solution

1
2csharp
3public class Solution {
4    public int NewInteger(int n) {
5        string ans = "";
6        while (n > 0) {
7            ans = (n % 9).ToString() + ans;
8            n /= 9;
9        }
10        return Int32.Parse(ans);
11    }
12}

In all these solutions, we're effectively transforming the number form base 10 to base 9 by replacing the digit in the tenth place with the remainder of the division by 9, and then updating the number to be the quotient of the division by 9. We keep doing this in a loop until our original number is reduced to 0. The final answer is obtained by converting the string representation back to integer.The implementations of this algorithm are fairly straightforward across different programming languages. The differences are mainly related to specific language syntax and functionalities.

For example, in Python, the "//" operator is used for integer division. In Java and C#, integer division is the default, and the "%" operator is used for getting the remainder of the division. In Javascript, a separate function Math.floor() is used for integer division.

One important aspect to note in these implementations is how we do the conversion from integers to strings and then back to integers. In Java, C#, and Javascript, we can use the built-in functions Integer.parseInt(), Int32.Parse(), and parseInt() respectively for converting the string representation back to an integer.

During implementation, we don't have to consider the number 9 while generating the sequence. This is due to the property of base 9 numbers. Hence this solution saves us from explicitly checking for numbers containing the digit 9. This would make the solution extremely efficient even for large input values of n.

Finally, note that we concatenate the remainder string on the left of the answer string. This is because the least significant digit in the base 9 representation is obtained first in our algorithm, and we need to append the next digits on its left, not its right.

In conclusion, this problem illustrates how a simple change in perspective - from base 10 to base 9 - can lead to an elegant and efficient solution. By harnessing the power of number theory, we effectively solve this problem with minimal computation and without explicitly checking for digits.

Not Sure What to Study? Take the 2-min Quiz to Find Your Missing Piece:

What's the output of running the following function using input [30, 20, 10, 100, 33, 12]?

1def fun(arr: List[int]) -> List[int]:
2    import heapq
3    heapq.heapify(arr)
4    res = []
5    for i in range(3):
6        res.append(heapq.heappop(arr))
7    return res
8
1public static int[] fun(int[] arr) {
2    int[] res = new int[3];
3    PriorityQueue<Integer> heap = new PriorityQueue<>();
4    for (int i = 0; i < arr.length; i++) {
5        heap.add(arr[i]);
6    }
7    for (int i = 0; i < 3; i++) {
8        res[i] = heap.poll();
9    }
10    return res;
11}
12
1class HeapItem {
2    constructor(item, priority = item) {
3        this.item = item;
4        this.priority = priority;
5    }
6}
7
8class MinHeap {
9    constructor() {
10        this.heap = [];
11    }
12
13    push(node) {
14        // insert the new node at the end of the heap array
15        this.heap.push(node);
16        // find the correct position for the new node
17        this.bubble_up();
18    }
19
20    bubble_up() {
21        let index = this.heap.length - 1;
22
23        while (index > 0) {
24            const element = this.heap[index];
25            const parentIndex = Math.floor((index - 1) / 2);
26            const parent = this.heap[parentIndex];
27
28            if (parent.priority <= element.priority) break;
29            // if the parent is bigger than the child then swap the parent and child
30            this.heap[index] = parent;
31            this.heap[parentIndex] = element;
32            index = parentIndex;
33        }
34    }
35
36    pop() {
37        const min = this.heap[0];
38        this.heap[0] = this.heap[this.size() - 1];
39        this.heap.pop();
40        this.bubble_down();
41        return min;
42    }
43
44    bubble_down() {
45        let index = 0;
46        let min = index;
47        const n = this.heap.length;
48
49        while (index < n) {
50            const left = 2 * index + 1;
51            const right = left + 1;
52
53            if (left < n && this.heap[left].priority < this.heap[min].priority) {
54                min = left;
55            }
56            if (right < n && this.heap[right].priority < this.heap[min].priority) {
57                min = right;
58            }
59            if (min === index) break;
60            [this.heap[min], this.heap[index]] = [this.heap[index], this.heap[min]];
61            index = min;
62        }
63    }
64
65    peek() {
66        return this.heap[0];
67    }
68
69    size() {
70        return this.heap.length;
71    }
72}
73
74function fun(arr) {
75    const heap = new MinHeap();
76    for (const x of arr) {
77        heap.push(new HeapItem(x));
78    }
79    const res = [];
80    for (let i = 0; i < 3; i++) {
81        res.push(heap.pop().item);
82    }
83    return res;
84}
85
Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:

What's the relationship between a tree and a graph?

Solution Implementation

Not Sure What to Study? Take the 2-min Quiz:

What is the space complexity of the following code?

1int sum(int n) {
2  if (n <= 0) {
3    return 0;
4  }
5  return n + sum(n - 1);
6}
Fast Track Your Learning with Our Quick Skills Quiz:

Which of the following is a min heap?


Recommended Readings


Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫