1374. Generate a String With Characters That Have Odd Counts LeetCode Solution
In this guide, you will get 1374. Generate a String With Characters That Have Odd Counts LeetCode Solution with the best time and space complexity. The solution to Generate a String With Characters That Have Odd Counts problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Generate a String With Characters That Have Odd Counts solution in C++
- Generate a String With Characters That Have Odd Counts solution in Java
- Generate a String With Characters That Have Odd Counts solution in Python
- Additional Resources
Problem Statement of Generate a String With Characters That Have Odd Counts
Given an integer n, return a string with n 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.
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
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(n)
1374. Generate a String With Characters That Have Odd Counts LeetCode Solution in C++
class Solution {
public:
string generateTheString(int n) {
string s(n, 'a');
if (n % 2 == 0)
s.back() = 'b';
return s;
}
};
/* code provided by PROGIEZ */
1374. Generate a String With Characters That Have Odd Counts LeetCode Solution in Java
class Solution {
public String generateTheString(int n) {
StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; ++i)
sb.append('a');
if (n % 2 == 0)
sb.setCharAt(n - 1, 'b');
return sb.toString();
}
}
// code provided by PROGIEZ
1374. Generate a String With Characters That Have Odd Counts LeetCode Solution in Python
class Solution:
def generateTheString(self, n: int) -> str:
s = 'a' * n
if n % 2 == 0:
s = s[:-1] + 'b'
return s
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.