Count and say

Strings (Advanced Algo) Medium Problems Hard
  • While the count-and-say problem seems abstract, it actually introduces the concept of run-length encoding, a simple form of data compression where sequences of the same data values are stored as a single data value and count
  • This concept is integral to numerous real-world applications, including computer graphics, where run-length encoding is used to compress image data keeping the file sizes minimal
  • This is reminiscent of the way the "count-and-say" sequence works, by 'compressing' consecutive elements into count/value pairs

The count-and-say sequence is a sequence of digit strings defined by the following recursive formula:


  • countAndSay(1) = "1"
  • For n > 1, countAndSay(n) is generated by describing countAndSay(n-1) in terms of the frequency and value of consecutive identical digits.


For example:

  • "1" is read as "one 1" or "11".
  • "11" is read as "two 1s" or "21".
  • "21" is read as "one 2, then one 1" or "1211".
  • "1211" is read as "one 1, one 2, then two 1s" or "111221".
  • "111221" is read as "three 1s, two 2s, then one 1" or "312211".


Given a positive integer n, return the nth term of the count-and-say sequence.

Examples:

Input: n = 4


Output: "1211"


Explanation:

countAndSay(1) = "1"

countAndSay(2) is described as "one 1" = "11"

countAndSay(3) is described as "two 1s" = "21"

countAndSay(4) is described as "one 2, then one 1" = "1211"

Input: n = 1


Output: "1"


Explanation:

This is the base case where countAndSay(1) is "1".

Input: n = 5

Constraints

  • 1 <= n <= 30

Hints

  • "Start with ""1"" as the base case. Iterate from 2 to n, constructing the next sequence by: Scanning the previous sequence character by character. Counting consecutive characters. Appending the count and character to form the new sequence. Repeat this process until reaching n."

Company Tags

Qualcomm Boston Consulting Group Ubisoft Docker McKinsey & Company HCL Technologies Snowflake PwC Etsy Cloudflare NVIDIA Stripe Electronic Arts Cerner Goldman Sachs Ernst & Young Roche Philips Healthcare Morgan Stanley Zoho Medtronic Roblox Oracle Dropbox Mastercard Google Microsoft Amazon Meta Apple Netflix Adobe