#3031
Minimum Time to Revert Word to Initial State II
HardStringRolling HashString MatchingHash FunctionString MatchingZ-functionPrefix-Suffix Problems
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses the Z-function to find the longest prefix which is also a suffix. This allows us to determine how many complete cycles of k can fit into the string, leading to a much faster solution.
⚙️
Algorithm
3 steps- 1Step 1: Compute the Z-function for the string, which gives lengths of substrings starting from each position that match the prefix of the string.
- 2Step 2: Find the longest suffix that is also a prefix and whose length is a multiple of k.
- 3Step 3: Calculate the minimum time as the length of the string divided by k minus the length of the longest matching prefix-suffix divided by k.
solution.py22 lines
1# Full working Python code
2
3def z_function(s):
4 z = [0] * len(s)
5 l, r, n = 0, 0, len(s)
6 for i in range(1, n):
7 if i <= r:
8 z[i] = min(r - i + 1, z[i - l])
9 while i + z[i] < n and s[z[i]] == s[i + z[i]]:
10 z[i] += 1
11 if i + z[i] - 1 > r:
12 l, r = i, i + z[i] - 1
13 return z
14
15def min_time_to_revert(word, k):
16 n = len(word)
17 z = z_function(word)
18 max_suffix_prefix = 0
19 for i in range(n):
20 if z[i] % k == 0:
21 max_suffix_prefix = max(max_suffix_prefix, z[i])
22 return (n - max_suffix_prefix) // kℹ
Complexity note: The time complexity is O(n) because we compute the Z-function in linear time, and finding the maximum suffix-prefix is also linear. The space complexity is O(n) due to the storage of the Z-array.
- 1Understanding the Z-function is crucial for optimizing string problems.
- 2Identifying patterns in string manipulation can lead to more efficient algorithms.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.