← Google bank

Google · Question 18 · Strings

Count and Say

StringsPythoncode⏱ O(n*2^n)💾 O(2^n)
Product-based

Problem

Given an integer n, generate the nth term of the count-and-say sequence.

Approach

Iteratively build the string by counting consecutive characters.

Time O(n*2^n)Space O(2^n)

How it works

  1. 1Start with base '1'.
  2. 2For each iteration, count consecutive chars and form the new string.
  3. 3Use nested loops to process the current string.
  4. 4Return the result after n iterations.

Sample input / output

Input:
4
Output:
1211

Constraints

1 <= n <= 30.

Solution — read it, then walk it

Time O(n*2^n)Space O(2^n)Loops 3Branches 1Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeatyesnoSTARTnresult = "1"for _ in range(n - 1)temp = ""i = 0while i < len(result)count = 1while i + 1 <len(result) andresult[i] == result[…i += 1count += 1temp += str(count) +result[i]i += 1result = tempRETURN resultDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it))print(countAndSay(n))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/23

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits