Numbers having Unique (or Distinct) digits

16 Jun, 2022
Given a range, print all numbers having unique digits. 
Examples : 
Input : 10 20
Output : 10 12 13 14 15 16 17 18 19 20  (Except 11)

Input : 1 10
Output : 1 2 3 4 5 6 7 8 9 10
Approach:
As the problem is pretty simple, the only thing to be done is :-
1- Find the digits one by one and keep marking visited digits.
2- If all digits occurs one time only then print that number.
3- Else not.
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to find unique digit// numbers in a range#include<bits/stdc++.h>using namespace std; // Function to print unique digit numbers// in range from l to r.void printUnique(int l, int r){    // Start traversing the numbers    for (int i=l ; i<=r ; i++)    {        int num = i;        bool visited[10] = {false};         // Find digits and maintain its hash        while (num)        {            // if a digit occurs more than 1 time            // then break            if (visited[num % 10])                break;             visited[num%10] = true;             num = num/10;        }         // num will be 0 only when above loop        // doesn't get break that means the        // number is unique so print it.        if (num == 0)            cout << i << " ";    }} // Driver codeint main(){    int l = 1, r = 20;    printUnique(l, r);    return 0;}
// Java implementation to find unique digit// numbers in a rangeclass Test{    // Method to print unique digit numbers    // in range from l to r.    static void printUnique(int l, int r)    {        // Start traversing the numbers        for (int i=l ; i<=r ; i++)        {            int num = i;            boolean visited[] = new boolean[10];                  // Find digits and maintain its hash            while (num != 0)            {                // if a digit occurs more than 1 time                // then break                if (visited[num % 10])                    break;                      visited[num%10] = true;                      num = num/10;            }                  // num will be 0 only when above loop            // doesn't get break that means the            // number is unique so print it.            if (num == 0)                System.out.print(i + " ");        }    }         // Driver method    public static void main(String args[])    {        int l = 1, r = 20;        printUnique(l, r);    }}
# Python3 implementation# to find unique digit# numbers in a range # Function to print# unique digit numbers# in range from l to r.def printUnique(l,r):         # Start traversing    # the numbers    for i in range (l, r + 1):        num = i;        visited = [0,0,0,0,0,0,0,0,0,0];                 # Find digits and        # maintain its hash        while (num):                         # if a digit occurs            # more than 1 time            # then break            if visited[num % 10] == 1:                break;            visited[num % 10] = 1;            num = (int)(num / 10);                     # num will be 0 only when        # above loop doesn't get        # break that means the        # number is unique so        # print it.        if num == 0:            print(i, end = " "); # Driver codel = 1;r = 20;printUnique(l, r); # This code is# contributed by mits
// C# implementation to find unique digit// numbers in a rangeusing System;         public class GFG {         // Method to print unique digit numbers    // in range from l to r.    static void printUnique(int l, int r)    {                 // Start traversing the numbers        for (int i = l ; i <= r ; i++)        {            int num = i;            bool []visited = new bool[10];                 // Find digits and maintain            // its hash            while (num != 0)            {                                 // if a digit occurs more                // than 1 time then break                if (visited[num % 10])                    break;                     visited[num % 10] = true;                     num = num / 10;            }                 // num will be 0 only when            // above loop doesn't get            // break that means the number            // is unique so print it.            if (num == 0)                Console.Write(i + " ");        }    }         // Driver method    public static void Main()    {        int l = 1, r = 20;        printUnique(l, r);    }} // This code is contributed by Sam007.
<?php// PHP implementation to find unique// digit numbers in a range // Function to print unique digit// numbers in range from l to r.function printUnique($l, $r){    // Start traversing the numbers    for ($i = $l ; $i <= $r; $i++)    {        $num = $i;        $visited = (false);         // Find digits and        // maintain its hash        while ($num)        {            // if a digit occurs more            // than 1 time then break            if ($visited[$num % 10])                         $visited[$num % 10] = true;             $num = (int)$num / 10;        }         // num will be 0 only when above        // loop doesn't get break that        // means the number is unique        // so print it.        if ($num == 0)            echo $i , " ";    }} // Driver code$l = 1; $r = 20;printUnique($l, $r); // This code is contributed by aj_36?>
<script> // Javascript implementation to find unique digit// numbers in a range // Function to print unique digit numbers// in range from l to r.function printUnique(l, r){    // Start traversing the numbers    for (let i=l ; i<=r ; i++)    {        let num = i;        let visited = new Array(10);         // Find digits and maintain its hash        while (num)        {            // if a digit occurs more than 1 time            // then break            if (visited[num % 10])                break;             visited[num%10] = true;             num = Math.floor(num/10);        }         // num will be 0 only when above loop        // doesn't get break that means the        // number is unique so print it.        if (num == 0)            document.write(i + " ");    }} // Driver code     let l = 1, r = 20;    printUnique(l, r);     // This code is contributed by Mayank Tyagi </script>
Output: 
1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20
Time Complexity : O(nlogn)
Auxiliary Space: O(1)
Another Approach:
Use set STL for C++ and Java Collections for Java in order to check if a number has only unique digits. Then we can compare the size of string s formed from a given number and newly created set. For example, let us consider the number 1987, then we can convert the number into the string,
C++
Java
int n;cin>>n;string s = to_string(n);
//creating scanner class object for taking user inputScanner sc = new Scanner(System.in); int n=sc.nextInt(); //converting the number to string using String.valueof(number);string s = String.valueof(n);
After that, initialize a set with the contents of string s.
C++
Java
set<int> uniDigits(s.begin(), s.end());
HashSet<Integer> uniDigits = new HashSet<Integer>();for(int i:s.tocharArray()){    uniDigits.add(i);}
Then we can compare the size of string s and newly created set uniDigits.
Here is the code for the above approach:
C++
Java
Python3
C#
Javascript
// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to print unique// numbersvoid printUnique(int l, int r){     // Iterate from l to r  for (int i = l; i <= r; i++) {               // Convert the no. to        // string        string s = to_string(i);               // Convert string to set using stl        set<int> uniDigits(s.begin(), s.end());               // Output if condition satisfies        if (s.size() == uniDigits.size()) {            cout << i << " ";        }    }} // Driver Codeint main(){       // Input of the lower and    // higher limits    int l = 1, r = 20;         // Function Call    printUnique(l, r);    return 0;}
// Java code for the above approachimport java.util.*; class GFG{ // Function to print unique// numbersstatic void printUnique(int l, int r){         // Iterate from l to r    for(int i = l; i <= r; i++)    {                 // Convert the no. to        // String        String s = String.valueOf(i);               // Convert String to set using Java Collections        HashSet<Integer> uniDigits = new HashSet<Integer>();        for(int c : s.toCharArray())            uniDigits.add(c);                     // Output if condition satisfies        if (s.length() == uniDigits.size())        {            System.out.print(i+ " ");        }    }} // Driver Codepublic static void main(String[] args){       // Input of the lower and    // higher limits    int l = 1, r = 20;         // Function Call    printUnique(l, r);}} // This code is contributed by Princi Singh
# Python code for the above approach # Function to print unique# numbersdef printUnique(l, r):     # Iterate from l to r    for i in range(l, r+1):                 # Convert the no. to        # string        s = list(str(i))                 # print(s)        # Convert string to set using stl        unitDigits = set()        for j in range(len(s)):            unitDigits.add(s[j])         # Output if condition satisfies        if len(s) == len(unitDigits):            print(i, end = " ") # Driver Code# Input of the lower and# higher limitsl = 1r = 20 # Function CallprintUnique(l, r) # The code is contributed by Nidhi goel
// C# code for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print unique// numbersstatic void printUnique(int l, int r){         // Iterate from l to r    for(int i = l; i <= r; i++)    {                 // Convert the no. to        // String        String s = String.Join("", i);               // Convert String to set using stl        HashSet<int> uniDigits = new HashSet<int>();        foreach(int c in s.ToCharArray())            uniDigits.Add(c);                     // Output if condition satisfies        if (s.Length == uniDigits.Count)        {            Console.Write(i + " ");        }    }} // Driver Codepublic static void Main(String[] args){       // Input of the lower and    // higher limits    int l = 1, r = 20;         // Function Call    printUnique(l, r);}} // This code is contributed by Princi Singh
<script> // JavaScript code for the above approach // Function to print unique// numbersfunction printUnique(l, r) {     // Iterate from l to r    for (let i = l; i <= r; i++) {         // Convert the no. to        // string        let s = String(i);         // Convert string to set using stl        let uniDigits = new Set();        for(let c of s.split(""))            uniDigits.add(c);                     // Output if condition satisfies        if (s.length == uniDigits.size) {            document.write(i + " ");        }    }} // Driver Code // Input of the lower and// higher limitslet l = 1, r = 20; // Function CallprintUnique(l, r); </script>
1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
jit_t
Mithun Kumar
Sahil_Chhabra
svrrrsvr
mayanktyagi1709
princi singh
gfgking
mdayyanfahim
shivamanandrj9
classroompxico
Amazon
number-digits
Hash
Mathematical
Amazon
Hash
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Longest Consecutive Subsequence
Sort string of characters
Counting frequencies of array elements
Hashing | Set 2 (Separate Chaining)
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays