#3663

Find The Least Frequent Digit

Easy
ArrayHash TableMathCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Use a single pass to count digit frequencies, then find the least frequent digit efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Convert the integer n to a string and initialize a frequency array of size 10.
  2. 2Step 2: Count the occurrences of each digit in a single pass.
  3. 3Step 3: Iterate through the frequency array to find the smallest digit with the least frequency.
solution.py5 lines
1def least_frequent_digit(n):
2    count = [0] * 10
3    for digit in str(n): count[int(digit)] += 1
4    return min(i for i in range(10) if count[i] > 0 and count[i] == min(c for c in count if c > 0))
5

Complexity note: Counting digits in a single pass gives O(n) time complexity, while space remains constant for the frequency array.

  • 1Count frequencies efficiently using an array.
  • 2Use the smallest digit for tie-breaking.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.