What would be the optimum approach for this string problem?

43 Views Asked by At

Today, in an interview, I was asked this programming question:

Given a string, w, following two operations are performed alternatively per day.

  1. Remove last m characters from w and prepend them to w. m is less than length of w.
  2. Remove last n characters from w and prepend them to w. n is less than length of w.

Find how many days would it take to get back w if we start to perform the above operations.

For example, if w is abcde and m is 2 and n is 3, then

original w: abcde after m op, w: deabc after n op, w: abcde

stop since new string abcde is same as the original string w = abcde

My approach was the brute force one where I had a loop and was performing both of the above operation and was continuously checking if the new w is same as the original w. However, this approach is definitely not scalable.

1

There are 1 best solutions below

0
On

The following method should be a great improvement over brute force in the case where the characters of the string are distinct. In the case where the characters are not distinct, it at least provides an upper bound.

Assume the string consists of the integers $1$ through $N$ in sequence, so $N$ is the length of the string. Apply the operations 1 and 2 to the string. Interpret the resulting string of integers as a permutation of the original string. Write this permutation as a product of disjoint cycles. The period of the permutation is the least common multiple of the lengths of the cycles.