Count Odd Letters from Number Problem
#3581
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 3581.
You are given an integer n perform the following steps:
- Convert each digit of
ninto its lowercase English word (e.g., 4 → "four", 1 → "one"). - Concatenate those words in the original digit order to form a string
s.
Return the number of distinct characters in s that appear an odd number of times.
Example 1:
Input: n = 41
Output: 5
Explanation:
41 → "fourone"
Characters with odd frequencies: 'f', 'u', 'r', 'n', 'e'. Thus, the answer is 5.
Example 2:
Input: n = 20
Output: 5
Explanation:
20 → "twozero"
Characters with odd frequencies: 't', 'w', 'z', 'e', 'r'. Thus, the answer is 5.
Constraints:
1 <= n <= 10^9
Solution
Approach: Parity Bitmask
Write each digit of n as its English word and toggle one bit per letter in a 26-bit mask. A bit ends up as 1 exactly when the letter appears an odd number of times, so the answer is the number of set bits in the mask.
Complexity: O(log n) time and O(1) space.
d = {
0: "zero",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
}
class Solution:
def countOddLetters(self, n: int) -> int:
mask = 0
while n:
x = n % 10
n //= 10
for c in d[x]:
mask ^= 1 << (ord(c) - ord("a"))
return bin(mask).count("1")