Magicsheet logo

Generate a String With Characters That Have Odd Counts

Easy
12.5%
Updated 8/1/2025

Asked by 1 Company

Topics

Generate a String With Characters That Have Odd Counts

What is this problem about?

The Generate a String With Characters That Have Odd Counts coding problem is a very simple string construction task. You are given an integer n. You need to return a string of length n such that every character in the string appears an odd number of times. You can use any lowercase English letters.

Why is this asked in interviews?

Companies like Google might ask this as a quick warm-up or "fizz-buzz" style question. It tests your basic understanding of parity (odd vs. even) and your ability to construct a simple algorithm that satisfies a loose constraint. The String interview pattern here is trivial, but it evaluates if you can find the simplest possible valid solution without over-engineering.

Algorithmic pattern used

This problem relies on basic Math (Parity) and Simulation.

  1. If n is odd: A single character repeated n times works because n itself is odd. Example: "a" * n.
  2. If n is even: You cannot use just one character, as its count would be even. However, n-1 is odd, and 1 is odd. So, you can use one character n-1 times, and a different character 1 time. Example: "a" * (n - 1) + "b".

Example explanation

If n = 4 (even):

  • 41=34 - 1 = 3.
  • Use 'a' 3 times: "aaa".
  • Use 'b' 1 time: "b".
  • Result: "aaab". (Counts: a=3, b=1. Both are odd).

If n = 5 (odd):

  • Use 'a' 5 times: "aaaaa".
  • Result: "aaaaa". (Count: a=5. Odd).

Common mistakes candidates make

  • Over-engineering: Trying to use 26 different characters or complex alternating patterns when using just 1 or 2 characters is sufficient.
  • Zero check: Assuming n could be 0, though problem constraints usually state n1n \ge 1. (0 is an even number, but a string of length 0 has no characters to have counts of).
  • String immutability: Using a loop to append characters one by one instead of using built-in string repetition features (e.g., String.repeat() in JS, "a" * n in Python).

Interview preparation tip

When a problem says "Return any valid string," always aim for the simplest possible construction. Don't build a complex pattern if a string of mostly identical characters satisfies the rules.

Similar Questions