Find The Least Frequent Digit Problem
#3663
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3663.
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 <= 2^31 - 1
Solution
Approach: Counting
Count each digit of n in an array cnt of size 10. Then scan the digits from 0 to 9, ignoring those that do not appear, and keep the one with the smallest count. Scanning in increasing order and updating only on a strictly smaller count makes ties go to the smallest digit.
Complexity: time O(log n), space O(1).
from math import inf
class Solution:
def getLeastFrequentDigit(self, n: int) -> int:
cnt = [0] * 10
while n:
n, x = divmod(n, 10)
cnt[x] += 1
ans, f = 0, inf
for x, v in enumerate(cnt):
if 0 < v < f:
f = v
ans = x
return ans