Program to check if a given number is Lucky (all digits are different)


A number is lucky if all digits of the number are different. How to check if a given number is lucky or not.


Input: n = 983
Output: true
All digits are different

Input: n = 9838
Output: false
8 appears twice

We strongly recommend you to minimize your browser and try this yourself first.

The idea is to traverse through every digit of given number and mark the traversed digit as visited. Since total number of digits is 10, we need a boolean array of size only 10 to mark visited digits.

Below is C++ implementation of above idea.

// C++ program to check if a given number is lucky
using namespace std;

// This function returns true if n is lucky
bool isLucky(int n)
    // Create an array of size 10 and initialize all
    // elements as false. This array is used to check
    // if a digit is already seen or not.
    bool arr[10];
    for (int i=0; i<10; i++)
        arr[i] = false;

    // Traverse through all digits of given number
    while (n > 0)
        // Find the last digit
        int digit = n%10;

        // If digit is already seen, return false
        if (arr[digit])
           return false;

        // Mark this digit as seen
        arr[digit] = true;

        // REmove the last digit from number
        n = n/10;
    return true;

// Driver program to test above function.
int main()
    int arr[] = {1291, 897, 4566, 1232, 80, 700};
    int n = sizeof(arr)/sizeof(arr[0]);

    for (int i=0; i<n; i++)
        isLucky(arr[i])? cout << arr[i] << " is Lucky \n":
                         cout << arr[i] << " is not Lucky \n";
    return 0;


1291 is not Lucky
897 is Lucky
4566 is not Lucky
1232 is not Lucky
80 is Lucky
700 is not Lucky

Time Complexity: O(d) where d is number of digits in input number.
Auxiliary Space: O(1)

This article is contributed by Himanshu. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:

1 Average Difficulty : 1/5.0
Based on 1 vote(s)

Writing code in comment? Please use, generate link and share the link here.