Rotated Digits — LeetCode 788 Python Solution

MediumMathDynamic Programming
Problem
#788
Reading time
3 min

The problem

An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone.

Example

Input
n = 10
Output
4
Explanation
There are four good numbers in the range [1, 10] : 2, 5, 6, 9.

Python solution

Python
class Solution:
    def rotatedDigits(self, n: int) -> int:
        def check(x):
            y, t = 0, x
            k = 1
            while t:
                v = t % 10
                if d[v] == -1:
                    return False
                y = d[v] * k + y
                k *= 10
                t //= 10
            return x != y

        d = [0, 1, 5, -1, -1, 2, 9, -1, 8, 6]
        return sum(check(i) for i in range(1, n + 1))

Complexity

MeasureComplexity
TimeO(n \times \log n), where n is the given number
SpaceO(1) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 788. Rotated Digits is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 788. Rotated Digits?
LeetCode 788. Rotated Digits is rated Medium on LeetCode.
What is the time complexity of LeetCode 788. Rotated Digits?
The Python solution on this page runs in O(n \times \log n), where n is the given number.
What is the space complexity of LeetCode 788. Rotated Digits?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 788. Rotated Digits cover?
LeetCode 788. Rotated Digits is tagged Math and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview