Generate a String With Characters That Have Odd Counts - Problem

Generate a String With Characters That Have Odd Counts

You're tasked with creating a balanced string puzzle! Given an integer n, you need to construct a string containing exactly n characters where every unique character appears an odd number of times.

The Challenge:

  • Your string must be exactly n characters long
  • Only lowercase English letters (a-z) are allowed
  • Each unique character must appear 1, 3, 5, 7... times (odd occurrences only)
  • Multiple valid solutions exist - return any one of them

Example: For n = 4, you could return "aaab" where 'a' appears 3 times and 'b' appears 1 time (both odd counts).

This problem tests your understanding of mathematical patterns and string construction strategies.

Input & Output

example_1.py โ€” Basic odd case
$ Input: n = 4
โ€บ Output: "aaab"
๐Ÿ’ก Note: n=4 is even, so we use (4-1)=3 copies of 'a' and 1 copy of 'b'. Both 3 and 1 are odd counts.
example_2.py โ€” Basic even case
$ Input: n = 5
โ€บ Output: "aaaaa"
๐Ÿ’ก Note: n=5 is odd, so we can use all 5 characters as the same letter. Count of 'a' is 5 (odd).
example_3.py โ€” Minimal case
$ Input: n = 1
โ€บ Output: "a"
๐Ÿ’ก Note: n=1 is odd, so we use 1 copy of 'a'. Count of 'a' is 1 (odd).

Visualization

Tap to expand
๐ŸŽ‰ Party Invitation StrategyOdd Total (n=5)One group: 5 people (odd โœ“)Result: "aaaaa"Even Total (n=6)Group A: 5 (odd)Group B: 1 (odd)Two groups: 5+1 peopleResult: "aaaaab"๐ŸŽฏ Golden RuleOdd total โ†’ One group with all peopleEven total โ†’ Split into (n-1) + 1Why? Because odd + odd = even, so we split evens into two odds!๐Ÿš€ Time: O(n) | Space: O(n) | Elegant & Efficient!
Understanding the Visualization
1
Check total invitations
If n is odd, put everyone in one group. If n is even, you need at least two groups.
2
Apply the rule
For even n: create one big group with (n-1) people and one small group with 1 person.
3
Verify constraints
Both groups have odd sizes, and total equals n. Perfect!
Key Takeaway
๐ŸŽฏ Key Insight: Every even number can be expressed as the sum of two odd numbers (n-1 and 1), while odd numbers are already perfect as-is. This mathematical property gives us an O(n) solution!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Only need to construct the string once, which takes O(n) time

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Space needed for the output string of length n

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค n โ‰ค 500
  • The returned string must contain only lowercase English letters
  • Each character must appear an odd number of times
  • Multiple valid answers exist - return any one
Asked in
Google 15 Amazon 8 Microsoft 6 Meta 4
23.8K Views
Medium Frequency
~8 min Avg. Time
985 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen