We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Count Numbers With Unique Digits II

Number: 3343

Difficulty: Easy

Paid? Yes

Companies: Amazon


Problem Description

Given two positive integers a and b, count the numbers in the range [a, b] (inclusive) that have unique digits. A number is said to have unique digits if no digit appears more than once in the number.


Key Insights

  • Convert each number to a string to easily examine its digits.
  • Use a set (or similar data structure) to determine if a number's digits are unique.
  • The problem constraints (1 <= a <= b <= 1000) allow a brute-force approach.
  • Checking the uniqueness of digits for each number is efficient enough given the low upper limit.

Space and Time Complexity

Time Complexity: O(n * d) where n is the number of numbers in the range [a, b] and d is the number of digits per number (constant factor due to small input sizes).
Space Complexity: O(1) extra space (ignoring space for converting numbers to strings and using sets, which is minimal).


Solution

The solution iterates through every number in the given range [a, b]. For each number, convert it to its string representation and then use a set (or an array for tracking digits in languages like Java) to determine if all digits are unique. Increase a counter for each number that meets the unique-digit condition. Due to the small input range (up to 1000), this brute-force method is efficient.

Data structures used include strings, sets (or arrays for flags), and loops. The key insight is converting the number to a string and comparing the length of the string with the size of a set constructed from the string’s characters. If both are equal, the number has unique digits.


Code Solutions

def count_unique_digits(a, b):
    # Initialize counter to zero
    unique_count = 0
    # Iterate over every number in the range [a, b] inclusive
    for num in range(a, b + 1):
        # Convert number to string to check its digits
        num_str = str(num)
        # Check if all digits are unique by comparing length of set to string length
        if len(num_str) == len(set(num_str)):
            unique_count += 1
    return unique_count

# Example usage:
if __name__ == "__main__":
    a = 80
    b = 120
    print("Count of unique digit numbers:", count_unique_digits(a, b))
← Back to All Questions