Generate a String With Characters That Have Odd Counts - Problem

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.

Input & Output

Example 1 — Odd Length
$ Input: n = 3
Output: aaa
💡 Note: String has 3 characters, character 'a' appears 3 times (odd count). Any single character repeated 3 times works.
Example 2 — Even Length
$ Input: n = 4
Output: aaab
💡 Note: String has 4 characters, 'a' appears 3 times (odd), 'b' appears 1 time (odd). Both characters have odd counts.
Example 3 — Minimum Case
$ Input: n = 1
Output: a
💡 Note: Single character string, 'a' appears 1 time (odd count). This is the smallest valid case.

Constraints

  • 1 ≤ n ≤ 500

Visualization

Tap to expand
Generate String With Odd Character Counts INPUT n = 3 (Integer input) String Length Needed: 1 2 3 3 positions to fill Constraints: - Use lowercase letters only - Each char: odd count ALGORITHM STEPS 1 Check if n is odd 3 is odd (3 % 2 = 1) 2 If odd: repeat 'a' n times Result: "aaa" (count: 3) 3 If even: use pattern 'a'*(n-1) + 'b' (both odd) 4 Return string All chars have odd count Direct Pattern Logic: n=3 (odd) --> "aaa" n=4 (even) --> "aaab" n=5 (odd) --> "aaaaa" FINAL RESULT "aaa" Output String Character Breakdown: a a a Verification: 'a' appears: 3 times 3 is odd number OK - Valid Output! Key Insight: For odd n: Use single character repeated n times (n is already odd, so count is odd). For even n: Use (n-1) of 'a' plus 1 of 'b'. Both (n-1) and 1 are odd numbers. O(n) time, O(n) space. TutorialsPoint - Generate a String With Characters That Have Odd Counts | Optimized - Direct Pattern
Asked in
Google 15 Amazon 12 Microsoft 8
25.8K Views
Medium Frequency
~10 min Avg. Time
890 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