0

I have been asked this question where I am asked to find the Nth number in the sequence. The sequence goes like this 555 35 1315 11131115 31133115 1321232115.

The sequence is a count of each character in the string. Let's say I start with 555, then since I have three occurances of '5', the next number would be 35. Similarly, since I have one occurance of 3, and one occurance of 5, the next number would be 1315.

Now, I was asked this question where I have to get the nth number of such sequence with input being any random number. I have suggested a bruteforce approach, or if there are a fixed set of numbers, then we could cache the results. I want to know if there is a better way to code this? or is there any existing algorithm for such a problem statement?

Sai Kumar
  • 201
  • 2
  • 8
  • 1
    This is known as the [look-and-say sequence](https://www.rosettacode.org/wiki/Look-and-say_sequence) or [Morris sequence](https://stackoverflow.com/questions/3908513/code-golf-morris-sequence). – John Kugelman Feb 23 '22 at 15:20
  • 3
    Other than bruteforcing, I don’t think there’s any approach in `O(N)` time or better – Abhinav Mathur Feb 23 '22 at 15:23
  • @JohnKugelman thanks for pointing out for the algoritms. But the question that still remains is to find the nth sequence in the stream. – Sai Kumar Feb 23 '22 at 15:29
  • Was the asker unhappy with the "brute force" solution you suggested? – John Kugelman Feb 23 '22 at 15:30
  • @JohnKugelman yep. this was in an interview and the interviewer was quite sure that there is a better way of doing this. – Sai Kumar Feb 23 '22 at 15:32

1 Answers1

1

The length of the numbers in the sequence grows exponentially (unless you start with 22). According to Wikipedia, each number is about 30% longer than the last.

Because of this exponential growth, the time required to iteratively generate (brute force) and output the nth number is in O(length(input) + length(output)), except 22, and you can't get complexity less than that.

Maybe the interviewer had a problem with your specific brute force implementation.

If you were asked for the first 10 digits of the Nth number, or something like that, then there would be a more interesting answer... but I think that would be too hard for an interview.

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87