PPractick

DSA interview question

Count and Say

Hard · Algorithms · Topics: string, simulation

The problem

You're building a toy "data compression" utility for an embedded systems team — the simplest possible run-length encoding demo used in onboarding material for new hires. The classic illustrative example is the count-and-say sequence: each term is generated by "reading off" the previous term, describing consecutive runs of the same digit as (count)(digit). Your task: given n, generate the n-th term of this sequence.

The sequence starts:1 11 (one 1) 21 (two 1s) 1211 (one 2, one 1) 111221 (one 1, one 2, two 1s) 312211 (three 1s, two 2s, one 1)

Function signature

string countAndSay(int n);

Test cases

Input nOutputExplanation
1"1"Base case
2"11""one 1" → "11"
3"21""two 1s" → "21"
4"1211""one 2, one 1" → "1211"
5"111221""one 1, one 2, two 1s" → "111221"
6"312211""three 1s, two 2s, one 1" → "312211"
7"13112221"One more iteration applied to "312211"

How interviewers phrase it

Clarifying questions to ask

  1. Is n 1-indexed (i.e., n=1 returns "1")? (Standard convention — confirm.)
  2. What's the expected range of n? (LeetCode constraints: 1 <= n <= 30 — small range, since the string length grows roughly exponentially with n, so don't worry about extreme optimization here, but mention the growth rate awareness.)
  3. Should digits be assumed single-digit only, or could counts exceed 9 (e.g., ten consecutive same digits) requiring multi-digit counts? (For n <= 30, this won't happen in practice, but worth flagging as an edge case to be aware of.)
  4. Any specific output format expectations (string vs vector of digits)?

Follow-ups to expect

  1. "What's the time/space complexity, and how does the string length grow with n?"
  2. "Can you do this without using extra string concatenation overhead (e.g., StringBuilder-style efficient builds)?"
  3. "What if counts could exceed 9 (multi-digit run lengths)? How would your code change?"
  4. "Can you do this iteratively without recursion, and what are the tradeoffs?"
  5. "Is there a closed-form or pattern-based shortcut to skip directly to term n without generating all previous terms?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in