Leetcode 1374. Generate a String With Characters That Have Odd Counts
1374. Generate a String With Characters That Have Odd Counts
Given an integer n
, return a string with n
characters such that each character in the string occurs an odd number of times.
The returned string must contain only lowercase English letters. If there are multiple valid strings, return any of them.
n = 4
"pppz"
"pppz"
is a valid string since the occurrences of 'p'
is 3 and 'z'
is 1, both of which are odd. Note that there are many other valid strings such as "ohhh"
and "love"
.n = 2
"xy"
"xy"
is a valid string since the occurrences of 'x'
and 'y'
are 1, both of which are odd. Note that there are many other valid strings such as "qz"
and "he"
.n = 7
"holasss"
1 <= n <= 500
To solve this problem, the main idea is to ensure that each character in the resultant string has an odd count. To achieve this:
n
is odd:
n
times, since n
is odd.n
is even:
n-1
times and another different character 1 time. This way, both characters will have an odd count.This approach ensures that we cover all cases with minimal effort and guarantees the resultant string’s characters meet the criteria for having odd counts.
#include <string>
class Solution {
public:
std::string generateTheString(int n) {
// If n is odd, use 'a' n times
if (n % 2 == 1) {
return std::string(n, 'a');
}
// If n is even, use 'a' (n-1) times and 'b' 1 time
else {
return std::string(n - 1, 'a') + 'b';
}
}
};
The time complexity of this solution is O(n) because we are constructing a string of length n
using simple operations which involve initializing and appending characters to the string.
n
directly involves writing n
characters, resulting in O(n)
time complexity.This solution is efficient and straightforward as it directly addresses both cases (when n
is odd and when n
is even) with minimal logic branching.
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?