Skip to content

3994. Find The Least Frequent Digit


3994. Find The Least Frequent Digit

Easy


Given an integer n, find the digit that occurs least frequently in its decimal representation. If multiple digits have the same frequency, choose the smallest digit.

Return the chosen digit as an integer.

The frequency of a digit x is the number of times it appears in the decimal representation of n.

 

Example 1:

Input: n = 1553322

Output: 1

Explanation:

The least frequent digit in n is 1, which appears only once. All other digits appear twice.

Example 2:

Input: n = 723344511

Output: 2

Explanation:

The least frequent digits in n are 7, 2, and 5; each appears only once.

 

Constraints:

  • 1 <= n <= 231​​​​​​​ - 1

Solution

class Solution {
    private int freq[];
    public int getLeastFrequentDigit(int n) {
        freq = new int[10];
        int temp = n;
        while (temp > 0) {
            freq[temp % 10]++;
            temp /= 10;
        }
        int mini = Integer.MAX_VALUE, ans = -1;
        for (int i = 0; i <= 9; i++) {
            if (freq[i] == 0) continue;         
            if (freq[i] < mini) {
                mini = freq[i];
                ans = i; 
            }
        }
        return ans;
    }
}

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Explanation

[Add detailed explanation here]