File: generate-a-string-with-characters-that-have-odd-counts/solution.py

Date: 2026-06-06

Time: 16:54

Purpose

This file solves LeetCode 1374 — Generate a String With Characters That Have Odd Counts. It constructs a string of length n where every distinct character appears an odd number of times. The solution is one of hundreds of LeetCode solutions in this repo, each following the same Solution class convention.

Key Components

Solution.generateTheString(self, n: int) -> str — The only method. It exploits a simple observation: if n is odd, a single character repeated n times satisfies the constraint (one character, appearing an odd number of times). If n is even, it uses two characters — "a" repeated n-1 times (odd) and one "b" (also odd: 1 is odd).

Patterns

Dependencies

Imports: None. The solution uses only Python builtins (string multiplication, modulo).

Imported by: The test_solution.py in the same directory imports this Solution class. The massive "Imported By" list in the prompt is misleading — those are unrelated test files in sibling problem directories; they import their own local solution.py, not this one.

Flow

1. Check if n is odd.

2. If odd → return "a" * n. One character, one odd count. Done.

3. If even → return "a" * (n - 1) + "b". Two characters: a appears n-1 times (odd, since n is even), b appears 1 time (odd).

Total string length is always exactly n. Every distinct character count is odd. Both branches execute in O(n) time due to string allocation.

Invariants

Error Handling

None. The method assumes valid input per the problem constraints. No exceptions are raised or caught. Invalid inputs (e.g., n=0 or negative) would produce degenerate results — an empty string for n=0, or an error from negative string multiplication returning empty — but those are outside the problem's contract.

Topics to Explore

Beliefs