1374. Generate a String With Characters That Have Odd Counts

Leetcode Link

Problem Description

The task in this problem is to construct a string that consists of exactly n characters where n is an integer input provided to the function. Importantly, each character within the resulting string must appear an odd number of times. For instance, if the string is composed of 3 ‘a’ characters and 1 ‘b’ character, both 'a' and 'b' occur an odd number of times, which is valid. The string can only be formed using lowercase English letters. There may be several valid strings that satisfy these conditions, and any one of them is considered an acceptable solution.


To solve this problem, we first recognize a fundamental property of integers: every integer is either odd or even. We can leverage this property by building a string where all but potentially one character has an even count, and the remaining character (if necessary) has an odd count. This design ensures all characters collectively appear an odd number of times.

The solution's intuition is quite straightforward:

  • If n is odd, we can simply create a string consisting of n instances of the same character (e.g., 'a'). Since n is odd, our condition is immediately satisfied with just one character.
  • If n is even, we cannot use a single character an even number of times because it would not meet the odd occurrence requirement. In this case, we construct a string with n - 1 instances of one character (e.g., 'a') and 1 instance of another character (e.g., 'b'). The 'a's appear n - 1 times, which is odd since n is even, and the occurrence of 'b' is odd as well since it’s only there once.

By using this simple conditional operation, we guarantee our string meets the problem criteria regardless of whether n is odd or even.

Solution Approach

The implementation of the solution uses a simple conditional check to determine whether n is odd or even and then constructs the string accordingly.

Here's a breakdown of the solution algorithm:

  1. Use the bitwise AND operator & to check if n is odd or even. For any integer n, n & 1 will be 1 if n is odd and 0 if n is even.
    • n & 1 essentially checks the least significant bit of n. If it is 1, n is odd; if it is 0, n is even.
  2. If n is odd (n & 1 == 1), return a string of n 'a' characters.
    • This satisfies the condition since there is only one character, and it occurs n times, which is an odd number.
  3. If n is even (n & 1 == 0), return a string of n - 1 'a' characters concatenated with 'b'.
    • Here, 'a' occurs an odd number of times (n - 1), and 'b' occurs exactly once, which is also odd.

This approach does not require any complex data structures or algorithms. It simply uses two string concatenation operations and a bitwise operator for the conditional check. The time complexity is O(1) since the string construction involves a constant number of operations that do not depend on the size of n. The space complexity is also O(n), where n is the length of the result string, because we need to store the result string.

The code in context looks like this:

1class Solution:
2    def generateTheString(self, n: int) -> str:
3        # Check if n is odd using bitwise AND with 1
4        if n & 1:
5            # Return n 'a' chars if n is odd
6            return 'a' * n
7        else:
8            # Return n-1 'a' chars plus 'b' if n is even
9            return 'a' * (n - 1) + 'b'

Each part of the code correlates directly with the steps laid out in the algorithm above.

Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:

In a binary min heap, the maximum element can be found in:

Example Walkthrough

Let's go through the solution approach with a small example where n = 5 which is an odd number, and n = 6 which is an even number.

  • For n = 5:

    1. We check if n is odd or even. Here, 5 & 1 equals 1 indicating that n is odd.
    2. Since n is odd, we return a string that consists of 5 instances of the 'a' character. Therefore, the resulting string is 'aaaaa'.
    3. The string 'aaaaa' contains the character 'a' exactly 5 times, which is odd, satisfying the condition.
  • For n = 6:

    1. We check if n is odd or even. Here, 6 & 1 equals 0 indicating that n is even.
    2. Since n is even, we need to construct a string of 6 - 1 instances of 'a' and add 1 instance of 'b' at the end. Therefore, the resulting string is 'aaaaab'.
    3. In the string 'aaaaab', the character 'a' appears 5 times which is an odd number, and the character 'b' appears 1 time, which is also an odd number. This fulfills the requirement.

Using the methodology provided in the solution, we can quickly determine the correct form of the string for any given n by simply checking if it's odd or even and constructing the string accordingly. The simplicity of this approach ensures it is easy to understand and efficient to execute.

Solution Implementation

1class Solution:
2    def generate_the_string(self, n: int) -> str:
3        # If n is even, we generate a string with (n-1) 'a' characters and 1 'b' to make the length odd
4        # If n is odd, we generate a string with all 'a' characters, as odd-length palindrome is already non-equal
5        return 'a' * (n - 1) + 'b' if n % 2 == 0 else 'a' * n
1class Solution {
2    // Method to generate a string based on the input integer n
3    public String generateTheString(int n) {
4        StringBuilder stringBuilder = new StringBuilder(); // Initialize a StringBuilder to construct the string
6        if (n % 2 == 1) { // Check if n is odd
7            // If n is odd, append 'a' n times to the StringBuilder
8            for (int i = 0; i < n; i++) {
9                stringBuilder.append("a");
10            }
11        } else { // If n is even
12            // Append 'a' (n-1) times to make the length (n-1), ensuring the final string will have an odd count of 'a'
13            for (int i = 0; i < n - 1; i++) {
14                stringBuilder.append("a");
15            }
16            // Append 'b' once to make the total length of the string equal to n
17            stringBuilder.append("b");
18        }
20        // Convert StringBuilder to String and return the result
21        return stringBuilder.toString();
22    }
1class Solution {
3    // This function generates a string with 'n' characters
4    // such that it has an odd count of at least one unique character
5    string generateTheString(int n) {
6        // Create a string 'result' with 'n' characters initialized to 'a'
7        string result(n, 'a');
9        // If 'n' is even, change the first character to 'b'
10        // to satisfy the condition of having odd count of unique characters
11        if (n % 2 == 0) {
12            result[0] = 'b';
13        }
15        // Return the resultant string
16        return result;
17    }
1// Function to generate a string with a given length 'n' where each character is 'a'
2// but if 'n' is even, the first character will be 'b' to ensure that all characters 
3// are not the same.
4function generateTheString(n: number): string {
5    // Initialize an array of 'n' elements, all set to 'a'
6    const resultArray = Array(n).fill('a');
8    // If 'n' is even, set the first element to 'b' to meet the condition
9    if (n % 2 === 0) {
10        resultArray[0] = 'b';
11    }
13    // Join the array into a string and return
14    return resultArray.join('');

Time and Space Complexity

The time complexity of the function generateTheString is O(n) where n is the input to the function. This is because the function involves concatenating n or n-1 characters which takes linear time in the size of the number of characters to concatenate.

The space complexity of the function is also O(n) because it generates a string which requires space proportional to the number of characters in the string, which in this case is n or n-1.

Learn more about how to find time and space complexity quickly using problem constraints.

Fast Track Your Learning with Our Quick Skills Quiz:

Which of the following uses divide and conquer strategy?

Recommended Readings

Got a question? Ask the Monster Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.