By: Saurav

2018-03-10 08:23:00 UTC

The count-and-say sequence is the sequence of integers with the first five terms as following:

1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"
Example 2:

Input: 4
Output: "1211"


For this question, we need to take the last number in the sequence and build our new number on it. For example for 21 we read the number of 2 and number of 1 and print it out as 1211.

We can use an array to hold elements till then but that will take extra space and more lines of code.

A recursive approach is as follows:

def count_and_say(n)
  return "1" if n == 1 
  str = count_and_say(n-1)
  count = 1 
  current = str[0]
  final_str = ""
  (1..str.length-1).each do |i|
    if str[i] != current
      final_str += count.to_s
      final_str += current
      current = str[i]
      count = 1
      count += 1
  final_str += count.to_s
  final_str += current
  return final_str

Let me know what you think!
twitter: sprakash24oct

Owned & Maintained by Saurav Prakash

If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :)