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

1
2
3
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

1
2
3
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

1
2
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

  1. If n is odd, return a string of n ‘a’s.
  2. If n is even, return a string of n-1 ‘a’s and one ‘b’.
  3. This guarantees all character counts are odd and the string is of length n.

Code

1
2
3
4
5
6
7
class Solution {
public:
    string generateTheString(int n) {
        if (n % 2 == 1) return string(n, 'a');
        return string(n - 1, 'a') + 'b';
    }
};
1
2
3
4
5
6
7
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"
}
1
2
3
4
5
6
class Solution {
    public String generateTheString(int n) {
        if (n % 2 == 1) return "a".repeat(n);
        return "a".repeat(n - 1) + "b";
    }
}
1
2
3
4
5
class Solution {
    fun generateTheString(n: Int): String {
        return if (n % 2 == 1) "a".repeat(n) else "a".repeat(n - 1) + "b"
    }
}
1
2
3
4
5
class Solution:
    def generateTheString(self, n: int) -> str:
        if n % 2 == 1:
            return 'a' * n
        return 'a' * (n - 1) + 'b'
1
2
3
4
5
6
7
8
9
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"
        }
    }
}
1
2
3
4
5
6
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 length n.
  • 🧺 Space complexity: O(n), for the output string.