Given an integer n
, return a string with n
characters such that each character in the string occurs an odd number of times.
Example 1:
Input: n = 4
Output: "pppz"
Explanation: "pppz" is a valid string because 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 because the characters 'x' and 'y' occur once. Note that there are many other valid strings as well, such as "ag" and "ur".
Example 3:
Input: n = 7
Output: "holasss"
Before proceeding, let’s clarify the following:
n = 1
?Let’s assume the answers to the clarifying questions are:
n
is odd, we can return a string consisting of n
occurrences of a single character (e.g., "a"*n
).n
is even, we can return a string consisting of one character n-1
times and another character 1
time (e.g., "a"*(n-1)+"b"
). This ensures both characters have odd occurrences.The solution involves constructing a string of length n
, hence the time complexity is O(n)
.
def generateTheString(n: int) -> str:
if n % 2 == 1: # odd
return "a" * n
else: # even
return "a" * (n - 1) + "b"
# Test cases
print(generateTheString(4)) # Output: "aaab"
print(generateTheString(2)) # Output: "ab"
print(generateTheString(7)) # Output: "aaaaaaa"
print(generateTheString(1)) # Output: "a"
print(generateTheString(5)) # Output: "aaaaa"
This code should correctly generate a string where all characters have odd counts, satisfying the problem’s constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?