Facebook Pixel

1374. Generate a String With Characters That Have Odd Counts

EasyString
Leetcode Link

Problem Description

Given an integer n, you need to create a string that has exactly n characters where each character appears an odd number of times. The string can only contain lowercase English letters.

The problem allows flexibility - if there are multiple valid strings that satisfy the condition, you can return any one of them.

For example:

  • If n = 4, you could return "aaab" (where 'a' appears 3 times and 'b' appears 1 time - both odd)
  • If n = 5, you could return "aaaaa" (where 'a' appears 5 times - odd)

The solution uses a clever approach based on whether n is odd or even:

  • When n is odd, the entire string can be filled with the same character (like n 'a's), since an odd number is already odd
  • When n is even, we use n-1 of one character and 1 of another character (like n-1 'a's and 1 'b'), ensuring both counts are odd

The code checks if n is odd using the bitwise operation n & 1 (which returns 1 if odd, 0 if even), then constructs the appropriate string accordingly.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The key insight is recognizing that we need to ensure every character appears an odd number of times. Let's think about the simplest possible constructions:

If we use just one character repeated n times, this works perfectly when n is odd - the character appears an odd number of times. But what happens when n is even? A single character repeated an even number of times violates our requirement.

When n is even, we need to get creative. We can't use a single character, so let's try using two different characters. How should we split them?

Consider that the sum of two odd numbers is always even. So if n is even and we want to split it into two parts where each part is odd, we could use:

  • 1 occurrence of one character (odd)
  • n-1 occurrences of another character (odd, since n is even means n-1 is odd)

This gives us 1 + (n-1) = n total characters, and both characters appear an odd number of times!

This leads to our elegant solution:

  • Odd n: Use all the same character ('a' * n)
  • Even n: Use one character n-1 times and another character once ('a' * (n-1) + 'b')

The beauty of this approach is its simplicity - we only need to handle two cases based on the parity of n, and we can construct valid strings using at most two distinct characters.

Solution Approach

The implementation follows a straightforward construction pattern based on the parity of n.

First, we check if n is odd or even. The solution uses the bitwise AND operation n & 1 to determine this:

  • If n & 1 equals 1, then n is odd
  • If n & 1 equals 0, then n is even

Based on this check, we construct the string:

Case 1: When n is odd

  • Simply return a string with n copies of the character 'a'
  • Expression: 'a' * n
  • Example: If n = 5, return "aaaaa"

Case 2: When n is even

  • Return a string with n-1 copies of 'a' and 1 copy of 'b'
  • Expression: 'a' * (n - 1) + 'b'
  • Example: If n = 4, return "aaab"

The entire solution is implemented in a single line using a ternary expression:

return 'a' * n if n & 1 else 'a' * (n - 1) + 'b'

This construction guarantees that:

  • In the odd case: character 'a' appears n times (odd)
  • In the even case: character 'a' appears n-1 times (odd) and character 'b' appears 1 time (odd)

The time complexity is O(n) for string construction, and the space complexity is O(n) for storing the result string.

Ready to land your dream job?

Unlock your dream job with a 3-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with two examples to see how it handles both odd and even cases.

Example 1: n = 7 (odd number)

  1. Check if n is odd: 7 & 1 = 1 (binary: 111 & 001 = 001), so n is odd
  2. Since n is odd, we can use a single character repeated n times
  3. Construct the string: 'a' * 7 = "aaaaaaa"
  4. Verify: Character 'a' appears 7 times, which is odd ✓
  5. Return: "aaaaaaa"

Example 2: n = 6 (even number)

  1. Check if n is odd: 6 & 1 = 0 (binary: 110 & 001 = 000), so n is even
  2. Since n is even, we need to use two characters with odd counts
  3. Split n into two odd parts: (n-1) + 1 = 5 + 1 = 6
  4. Construct the string: 'a' * (6-1) + 'b' = 'a' * 5 + 'b' = "aaaaab"
  5. Verify:
    • Character 'a' appears 5 times (odd) ✓
    • Character 'b' appears 1 time (odd) ✓
    • Total length is 5 + 1 = 6 ✓
  6. Return: "aaaaab"

The key insight is that when n is even, we can't make all characters the same (that would give an even count). By using n-1 of one character and 1 of another, we guarantee both counts are odd since an even number minus 1 is odd, and 1 is already odd.

Solution Implementation

1class Solution:
2    def generateTheString(self, n: int) -> str:
3        """
4        Generate a string of length n where each character appears an odd number of times.
5      
6        Args:
7            n: The length of the string to generate
8          
9        Returns:
10            A string of length n with characters appearing odd number of times
11        """
12        # Check if n is odd using bitwise AND operation
13        if n & 1:  # n is odd
14            # If n is odd, return n 'a's (odd count)
15            return 'a' * n
16        else:  # n is even
17            # If n is even, return (n-1) 'a's and 1 'b'
18            # This ensures 'a' appears odd times (n-1) and 'b' appears odd times (1)
19            return 'a' * (n - 1) + 'b'
20
1class Solution {
2    /**
3     * Generates a string of length n where all characters have odd frequencies.
4     * 
5     * @param n the desired length of the string
6     * @return a string of length n with all characters having odd frequencies
7     */
8    public String generateTheString(int n) {
9        // If n is odd, return a string with n identical characters (odd frequency)
10        if (n % 2 == 1) {
11            return "a".repeat(n);
12        }
13        // If n is even, return a string with (n-1) 'a's and 1 'b'
14        // This ensures both characters have odd frequencies: (n-1) is odd, and 1 is odd
15        else {
16            return "a".repeat(n - 1) + "b";
17        }
18    }
19}
20
1class Solution {
2public:
3    string generateTheString(int n) {
4        // Initialize a string of length n with all 'a' characters
5        string result(n, 'a');
6      
7        // If n is even, we need to make one character different
8        // to ensure odd count for each unique character
9        if (n % 2 == 0) {
10            // Change the first character to 'b'
11            // This gives us (n-1) 'a's and 1 'b', both odd counts
12            result[0] = 'b';
13        }
14        // If n is odd, all n characters can be 'a' (odd count)
15      
16        return result;
17    }
18};
19
1/**
2 * Generates a string of length n where each character appears an odd number of times
3 * @param n - The length of the string to generate
4 * @returns A string of length n with characters appearing odd number of times
5 */
6function generateTheString(n: number): string {
7    // Create an array of size n filled with 'a'
8    const resultArray: string[] = Array(n).fill('a');
9  
10    // If n is even, change the first character to 'b'
11    // This ensures 'a' appears (n-1) times (odd) and 'b' appears 1 time (odd)
12    if (n % 2 === 0) {
13        resultArray[0] = 'b';
14    }
15    // If n is odd, all characters remain 'a', appearing n times (odd)
16  
17    // Join the array elements into a single string
18    return resultArray.join('');
19}
20

Time and Space Complexity

The time complexity is O(n), where n is the input parameter representing the length of the string to be generated. This is because the string multiplication operation 'a' * n or 'a' * (n - 1) requires creating a string of length proportional to n, which takes linear time. The string concatenation operation + 'b' when n is even adds constant time, but the overall complexity remains O(n).

The space complexity is O(n), where n is the length of the string. This is because the function creates and returns a new string of length n. Whether the string consists entirely of 'a' characters (when n is odd) or n-1 'a' characters plus one 'b' character (when n is even), the total space required to store the output string is proportional to n.

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

Common Pitfalls

1. Misunderstanding the Problem Requirements

Pitfall: A common mistake is thinking that ALL characters in the string must appear an odd number of times, leading to overcomplicated solutions that try to distribute characters evenly.

Why it happens: The problem statement "each character appears an odd number of times" can be misinterpreted as requiring multiple different characters, each with odd counts.

Correct Understanding: The requirement is that every character that appears in the string must have an odd count. Using just one character (when n is odd) or two characters (when n is even) is perfectly valid.

2. Overcomplicating the Even Case

Pitfall: When n is even, developers might try complex distributions like:

# Incorrect approach - unnecessarily complex
if n % 2 == 0:
    return 'a' * (n//2 - 1) + 'b' * (n//2 + 1)  # Wrong if n//2 is even

Issue: This fails because when n=4, it would give "abbb" where 'a' appears 1 time (odd ✓) but 'b' appears 3 times (odd ✓). While this works for n=4, it fails for n=6 where it would give "aabbbb" with 'a' appearing 2 times (even ✗).

Solution: Stick to the simple pattern: (n-1) of one character and 1 of another. This always guarantees both counts are odd.

3. Using Modulo Instead of Bitwise Operation

Pitfall: While using n % 2 works correctly, some might write it incorrectly:

# Common error
if n % 2 == 1:
    return 'a' * n
return 'a' * (n - 1) + 'b'  # This line might not be reached in some IDEs

Better Practice: Use bitwise n & 1 or ensure proper else clause:

# Clear and efficient
return 'a' * n if n & 1 else 'a' * (n - 1) + 'b'

4. Edge Case Handling

Pitfall: Not considering n=1 or n=2 as special cases and adding unnecessary complexity:

# Unnecessary special case handling
if n == 1:
    return 'a'
elif n == 2:
    return 'ab'
else:
    # ... complex logic

Reality: The simple formula 'a' * n if n & 1 else 'a' * (n - 1) + 'b' handles all cases including n=1 and n=2 correctly without special treatment.

5. String Concatenation Performance

Pitfall: Building strings character by character in a loop:

# Inefficient approach
result = ""
for i in range(n - 1):
    result += 'a'  # String concatenation in loop is inefficient
result += 'b'
return result

Solution: Use string multiplication which is optimized in Python:

# Efficient
return 'a' * (n - 1) + 'b'
Discover Your Strengths and Weaknesses: Take Our 3-Minute Quiz to Tailor Your Study Plan:

Depth first search is equivalent to which of the tree traversal order?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More