How to solve a question where the string is first circularly rotated by 1 letter, then by 2 letter and soon , at what time the modified string will be equal to original string? these strings are made up using 'a' and 'b' only.
for eg: aabaab is the string on first letter rotation it will become abaaba on second rotation it will become aabaab so answer is 2.
I tried to solve this question but could only do this only by brute force. https://pasteboard.co/Hz1WUBx.jpg
Any help will be appreciated.
Use prefix or z function, or suffix array, or hashes.
http://e-maxx.ru/algo/prefix_function
http://e-maxx.ru/algo/z_function
http://e-maxx.ru/algo/string_hashes
http://e-maxx.ru/algo/suffix_array
My current solution uses Z values to quickly check if a current step size is valid. However, I wasn't able to prove my runtime. Do you know what the intuition is behind the maximum number of steps being bounded by 2*n-1 where n is the length of the string? (http://oeis.org/search?q=3%2C2%2C7%2C4%2C3%2C6%2C15&sort=&language=english&go=Search)
Yes. You can move right border only O(n) times.
Anyway, read the article: http://e-maxx.ru/algo/z_function
To explain what is exactly asked from us; suppose the maximum number of strings that can be equal each one to their original selves at any certain time(let it be t) is x.Of course, there will be a time when they will all be equal to their original selves again.We just need to print the first time that this happens.
For a string s of length n, let nb be the minimum number of characters such that s will be equal to s rotated by nb letters.We can find it in O(n2) like this:
But that's too much since the n < = 105.
Turns out, nb is the length of the period of s !
A period of a string s is the smallest string m such that there exists an integer k > 0 where
s = m+m+m+m+... (k times)
.For s = "abaa" , nb = 4 and for s = "aabaab" , nb = 3.
This can be computed with the KMP algorithm in O(n).
Now that we calculated the length of the periods of all the strings, comes the second part of the problem.For a string s of length n, let it's period's length be nb.We need to find the minimum time t such that the number of letters moved from time 1 to t(in total) is a multiple of nb.
For a string of length n, the total number of letters moved at a time t is equal to:
t/n * (n*(n+1))/2 + t%n * (t*(t+1))/2
.We need to find for every string s, the couple (t, k) such that s is back to it's original self at times t, t+k, t+2*k... (k has to be minimum).
Then using these couples for all the strings, we need to find the maximum number of strings such that their times(the ones t+k, t+2*k ...) intersect and return the minimum instant of time that these strings intersect at.Don't forget the modulo 109 + 7 !
Honestly, I still haven't completely figured out how to find these couples nor how to do the last part in O(n).
Perhaps someone else can help?