Today, in an interview, I was asked this programming question:
Given a string, w, following two operations are performed alternatively per day.
- Remove last
mcharacters fromwand prepend them tow.mis less than length ofw. - Remove last
ncharacters fromwand prepend them tow.nis less than length ofw.
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.
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.