{x}
blog image

Confusing Number II

Solution Explanation

This problem asks to find the number of confusing numbers within a given range [1, n]. A confusing number is defined as a number that, when rotated 180 degrees, becomes a different number and all digits after rotation are valid. Only 0, 1, 6, 8, and 9 are valid after rotation (becoming 0, 1, 9, 8, and 6 respectively).

The solution uses a depth-first search (DFS) approach to efficiently enumerate all possible numbers up to n and check if they are confusing.

Approach

  1. Digit Mapping: A mapping array d is created to store the rotated values of digits. Invalid digits (2, 3, 4, 5, 7) are represented by -1.

  2. DFS Function: The core logic resides in the recursive dfs function.

    • pos: The current digit position being processed.
    • limit: A boolean flag indicating whether the current digit should be less than or equal to the corresponding digit in the input n. This ensures that we don't exceed the given upper bound n.
    • x: The current number being built during the DFS traversal.
  3. Base Case: If pos reaches the end of the number (all digits processed), the check function is called to determine if the generated number x is confusing. If it is, 1 is returned; otherwise, 0.

  4. Recursive Step: The function iterates through possible digits (0 to 9 or up to the limit). If a digit is valid (not -1), it recursively calls dfs to explore the next digit position, updating x and limit appropriately.

  5. check Function: This helper function rotates the given number x and checks if it's different from the original number.

Time Complexity Analysis

The time complexity is determined by the number of possible confusing numbers up to n. In the worst case, the algorithm explores all possible numbers up to n, which is O(log₁₀(n)) digits. However, many numbers are pruned early because of invalid digits. The time complexity is not strictly O(log₁₀(n)), but it's bounded above by O(5log₁₀(n)), where 5 represents the number of valid rotating digits (0, 1, 6, 8, 9). This simplifies to O(nlog₁₀(5)), which is still sub-exponential, significantly better than a brute-force check of all numbers up to n.

Space Complexity Analysis

The space complexity is dominated by the recursion depth of the dfs function, which is proportional to the number of digits in n (O(log₁₀(n))). The space used by the d array is constant. Therefore, the overall space complexity is O(log₁₀(n)).

Code in Different Languages

The code implementations in Python, Java, C++, Go, and TypeScript provided in the original response accurately reflect this approach. Each implementation follows the same core logic but adapts to the syntax and libraries of its respective language. The dfs function and check function are central to all implementations.