Generate a String With Characters That Have Odd Counts
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given an integer n, return a string withn characters such that each character in such string occurs an odd number of times.
The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.
Examples
Example 1
Input: n = 4
Output: "pppz"
Explanation: "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love".
Example 2
Input: n = 2
Output: "xy"
Explanation: "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur".
Example 3
Input: n = 7
Output: "holasss"
Constraints
1 <= n <= 500
Solution
Method 1 – Constructing Odd Frequency String
Intuition
To ensure every character appears an odd number of times, if n is odd, we can use a single character repeated n times. If n is even, we can use one character n-1 times and another character once, both of which are odd.
Approach
- If
nis odd, return a string ofn'a's. - If
nis even, return a string ofn-1'a's and one 'b'. - This guarantees all character counts are odd and the string is of length
n.
Code
C++
class Solution {
public:
string generateTheString(int n) {
if (n % 2 == 1) return string(n, 'a');
return string(n - 1, 'a') + 'b';
}
};
Go
type Solution struct{}
func (Solution) generateTheString(n int) string {
if n%2 == 1 {
return strings.Repeat("a", n)
}
return strings.Repeat("a", n-1) + "b"
}
Java
class Solution {
public String generateTheString(int n) {
if (n % 2 == 1) return "a".repeat(n);
return "a".repeat(n - 1) + "b";
}
}
Kotlin
class Solution {
fun generateTheString(n: Int): String {
return if (n % 2 == 1) "a".repeat(n) else "a".repeat(n - 1) + "b"
}
}
Python
class Solution:
def generateTheString(self, n: int) -> str:
if n % 2 == 1:
return 'a' * n
return 'a' * (n - 1) + 'b'
Rust
impl Solution {
pub fn generate_the_string(n: i32) -> String {
if n % 2 == 1 {
"a".repeat(n as usize)
} else {
"a".repeat((n - 1) as usize) + "b"
}
}
}
TypeScript
class Solution {
generateTheString(n: number): string {
if (n % 2 === 1) return 'a'.repeat(n);
return 'a'.repeat(n - 1) + 'b';
}
}
Complexity
- ⏰ Time complexity:
O(n), since the string is constructed of lengthn. - 🧺 Space complexity:
O(n), for the output string.