3663. Find The Least Frequent Digit
Description
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
Solutions
Solution 1: Counting
We use an array \(\textit{cnt}\) to count the frequency of each digit. We iterate through each digit of the number \(n\) and update the \(\textit{cnt}\) array.
Then, we use a variable \(f\) to record the current lowest frequency among the digits, and a variable \(\textit{ans}\) to record the corresponding digit.
Next, we iterate through the \(\textit{cnt}\) array. If \(0 < \textit{cnt}[x] < f\), it means we have found a digit with a lower frequency, so we update \(f = \textit{cnt}[x]\) and \(\textit{ans} = x\).
After the iteration, we return \(\textit{ans}\) as the answer.
The time complexity is \(O(\log n)\), and the space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|