357. Count Numbers with Unique Digits LeetCode Solution

In this guide, you will get 357. Count Numbers with Unique Digits LeetCode Solution with the best time and space complexity. The solution to Count Numbers with Unique Digits problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Count Numbers with Unique Digits solution in C++
  4. Count Numbers with Unique Digits solution in Java
  5. Count Numbers with Unique Digits solution in Python
  6. Additional Resources
357. Count Numbers with Unique DigitsLeetCode Solution image

Problem Statement of Count Numbers with Unique Digits

Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n.

Example 1:

Input: n = 2
Output: 91
Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99

Example 2:

Input: n = 0
Output: 1

Constraints:

0 <= n <= 8

Complexity Analysis

  • Time Complexity: O(9)
  • Space Complexity: O(1)

357. Count Numbers with Unique Digits LeetCode Solution in C++

class Solution {
 public:
  int countNumbersWithUniqueDigits(int n) {
    if (n == 0)
      return 1;

    int ans = 10;
    int uniqueDigits = 9;

    for (int availableNum = 9; n > 1 && availableNum > 0; --n, --availableNum) {
      uniqueDigits *= availableNum;
      ans += uniqueDigits;
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

357. Count Numbers with Unique Digits LeetCode Solution in Java

class Solution {
  public int countNumbersWithUniqueDigits(int n) {
    if (n == 0)
      return 1;

    int ans = 10;
    int uniqueDigits = 9;

    for (int availableNum = 9; n > 1 && availableNum > 0; --n, --availableNum) {
      uniqueDigits *= availableNum;
      ans += uniqueDigits;
    }

    return ans;
  }
}
// code provided by PROGIEZ

357. Count Numbers with Unique Digits LeetCode Solution in Python

class Solution:
  def countNumbersWithUniqueDigits(self, n: int) -> int:
    if n == 0:
      return 1

    ans = 10
    uniqueDigits = 9
    availableNum = 9

    while n > 1 and availableNum > 0:
      uniqueDigits *= availableNum
      ans += uniqueDigits
      n -= 1
      availableNum -= 1

    return ans
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.