#1374
Generate a String With Characters That Have Odd Counts
EasyStringString ManipulationArray Construction
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
For an optimal solution, we can directly construct the string based on whether n is odd or even. If n is odd, we can fill the string entirely with 'a's. If n is even, we can fill it with 'a's and replace the last character with 'b'. This guarantees odd counts efficiently.
⚙️
Algorithm
2 steps- 1Step 1: If n is odd, return a string of 'a' repeated n times.
- 2Step 2: If n is even, return 'a' repeated (n-1) times followed by 'b'.
solution.py3 lines
1n = 4
2result = 'a' * n if n % 2 != 0 else 'a' * (n - 1) + 'b'
3print(result)ℹ
Complexity note: The time complexity is O(n) because we are constructing the string in a single pass, and the space complexity is also O(n) due to the string storage.
- 1If n is odd, a string of 'a's is sufficient.
- 2If n is even, use 'a's and one 'b' to ensure odd counts.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.