Problem Description
Given an integer n, return a string with n characters such that each character in the string occurs an odd number of times. The string must consist only of lowercase English letters. If there are multiple valid answers, you can return any one of them.
Key Insights
- If n is odd, a string made up of the same character repeated n times will have an odd count.
- If n is even, using one character repeated (n - 1) times (which is odd) combined with a second character (occurring once, also odd) results in a valid string.
- The problem can be solved in constant time per character with a simple string construction.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n)
Solution
The algorithm checks whether n is odd or even. If n is odd, it returns a string consisting of a single repeated character (like 'a') n times. If n is even, it returns a string with (n-1) repetitions of one character (like 'a') and appends another different character (like 'b'). This guarantees that every character has an odd count: (n-1) is odd when n is even and 1 is odd.