Rotated Digits (LeetCode 788): Solution and Explanation

Medium
Math
Dynamic Programming

A number is good if turning every digit upside down gives a valid, different number. Count the good numbers from 1 to n. Up to 10 there are four: 2, 5, 6 and 9.

Intuition

Each digit falls into one of three kinds. 3, 4 and 7 cannot be turned over at all. 0, 1 and 8 turn into themselves. 2, 5, 6 and 9 turn into a different digit.

So a number is good exactly when it has no digit of the first kind and at least one digit of the third kind. You could check each number digit by digit, but there is a neater way to reuse work.

Write x as its prefix x // 10 followed by its last digit x % 10. The prefix is smaller than x, so its class is already known. The class of x is invalid if either part is invalid, otherwise it changes if either part changes, otherwise it stays the same.

Encoding the classes as 0, 1, 2 turns that rule into one line: 0 if a == 0 or b == 0 else max(a, b). Laying the numbers out in rows of ten shows it well: every cell looks up its row's number and its column's digit.

Approach: Prefix DP over the numbers

  1. Set kind = [1, 1, 2, 0, 0, 2, 2, 0, 1, 2] (0 invalid, 1 same, 2 changes) for the digits 0 to 9.
  2. Make dp of size n + 1 with dp[0] = 1, so a single digit takes its own kind.
  3. For x from 1 to n, let a = dp[x // 10] and b = kind[x % 10], and set dp[x] = 0 if either is 0, else max(a, b).
  4. Count the x with dp[x] == 2 and return the count.

Step-by-step example

n = 10
  1. For 1 to 9 the prefix is 0 with dp[0] = 1, so each number takes its digit's kind: 2, 5, 6 and 9 change, 1 and 8 stay the same, 3, 4 and 7 are invalid.
  2. After x = 9 the count is 4.
  3. x = 10: the prefix 1 has class 1 and the last digit 0 has kind 1, so 10 turns into itself and is not good.
  4. The answer is 4.

Code: Python, Java, C++

1class Solution:
2    def rotatedDigits(self, n: int) -> int:
3        kind = [1, 1, 2, 0, 0, 2, 2, 0, 1, 2]
4        dp = [0] * (n + 1)
5        dp[0] = 1
6        count = 0
7        for x in range(1, n + 1):
8            a, b = dp[x // 10], kind[x % 10]
9            dp[x] = 0 if a == 0 or b == 0 else max(a, b)
10            if dp[x] == 2:
11                count += 1
12        return count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Digit DP on n O(log n)
Prefix DP over the numbers O(n)
Check each number's digits O(n log n)
Time

O(n)

Each number is classified with one table lookup, one digit lookup and a comparison.

Space

O(n)

The dp array stores a class for every number up to n.

Other approaches

Check each number's digits (time O(n log n), space O(1))

For every x, scan its digits, reject on 3, 4 or 7, and remember whether any digit was 2, 5, 6 or 9. Uses no extra memory and is easy to write.

Digit DP on n (time O(log n), space O(1))

Walk the digits of n from the left, counting numbers that are smaller with only valid digits, then subtract those made only of 0, 1 and 8. Handles huge n.

Common mistakes

  • Counting numbers that turn into themselves, such as 1, 8, 10 or 818. They are valid but not different, so they are not good.
  • Forgetting that one bad digit ruins the whole number. 23 contains a 3, so it is invalid even though 2 changes.
  • Starting dp[0] at 0. That would mark every 1-digit number invalid; the empty prefix must be the neutral class 1.
  • Confusing this with strobogrammatic numbers. Here digits are rotated in place, not reversed in order.

Frequently asked questions

Why does max(a, b) give the right class?

When neither part is invalid, the classes are 1 (same) or 2 (changes). The whole number changes if any part changes, which is exactly the larger of the two.

Why use x // 10 instead of looking at the first digit?

x // 10 is a smaller number whose class is already in the table, so one lookup covers all but the last digit. It is the standard way to build a DP over numbers.

Is the O(n) table fast enough?

Yes. n is at most 10^4, so the loop runs at most ten thousand times. The digit DP is only needed if n could be very large.