Input: word ="abacaba", k =3Output: 2Explanation: At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac".At the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state.
Input: word ="abacaba", k =4Output: 1Explanation: At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state.
Input: word ="abcbabcd", k =2Output: 4Explanation: At every second, we will remove the first 2 characters of word, and add the same characters to the end of word.After 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state.It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state.
Every operation is equivalent to rotating the string left by k positions and then replacing the last k characters. The string reverts to its initial state when, after t operations, the rotation brings the string back to its original order. This happens when t * k is a multiple of n (word length). The minimum t > 0 is n / gcd(n, k).
classSolution {
public:int minTimeToRevert(string word, int k) {
int n = word.size();
int g = gcd(n, k);
return n / g;
}
intgcd(int a, int b) {
return b ==0? a : gcd(b, a % b);
}
};
1
2
3
4
5
6
7
8
9
10
funcminTimeToRevert(wordstring, kint) int {
n:= len(word)
returnn/gcd(n, k)
}
funcgcd(a, bint) int {
forb!=0 {
a, b = b, a%b }
returna}
1
2
3
4
5
6
7
8
9
classSolution {
publicintminTimeToRevert(String word, int k) {
int n = word.length();
return n / gcd(n, k);
}
privateintgcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
1
2
3
4
5
6
7
classSolution {
funminTimeToRevert(word: String, k: Int): Int {
val n = word.length
return n / gcd(n, k)
}
privatefungcd(a: Int, b: Int): Int = if (b ==0) a else gcd(b, a % b)
}
1
2
3
4
5
classSolution:
defminTimeToRevert(self, word: str, k: int) -> int:
from math import gcd
n: int = len(word)
return n // gcd(n, k)
1
2
3
4
5
6
7
8
9
impl Solution {
pubfnmin_time_to_revert(word: String, k: i32) -> i32 {
fngcd(a: i32, b: i32) -> i32 {
if b ==0 { a } else { gcd(b, a % b) }
}
let n = word.len() asi32;
n / gcd(n, k)
}
}