You are given a 0-indexed string word and an integer k.
At every second, you must perform the following operations:
k characters of word.k characters to the end of word.Note that you do not necessarily need to add the same characters that you removed. However, you must perform both operations at every second.
Return the minimum time greater than zero required for word to revert to its initial state.
Example 1:
Input: word = "abacaba", k = 3 Output: 2 Explanation: 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.
Example 2:
Input: word = "abacaba", k = 4 Output: 1 Explanation: 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.
Example 3:
Input: word = "abcbabcd", k = 2 Output: 4 Explanation: 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.
Constraints:
1 <= word.length <= 1061 <= k <= word.lengthword consists only of lowercase English letters.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a text that gets modified over time, and you want to figure out the fastest way to return it to its original form by repeatedly chopping off the front part and adding new letters to the end. The brute force strategy involves testing every single possible number of steps to see which one successfully restores the original text in the fewest tries.
Here's how the algorithm would work step-by-step:
def minimum_time_to_revert(word, chunk_size):
word_length = len(word)
# Iterate through every possible number of chopping steps from one up to the full word length
for chop_count in range(1, word_length + 1):
start_index = chop_count * chunk_size
if start_index >= word_length:
return chop_count
# Check if the remaining suffix matches the prefix of the original word to confirm restoration
if word[start_index:] == word[:word_length - start_index]:
return chop_count
# If no partial match works, chopping off the entire word guarantees a successful restoration
return (word_length + chunk_size - 1) // chunk_size
Instead of checking every single step of destroying and rebuilding a word from scratch, the optimal strategy finds overlapping patterns at the tail end of the word. By identifying how much of the ending already matches the beginning, we can figure out the fastest way to chop off the wrong parts and finish the job in fewer chunks.
Here's how the algorithm would work step-by-step:
class Solution:
def minimumTimeToInitialState(self, word: str, chunk_size: int) -> int:
word_length = len(word)
kmp_table = [0] * word_length
index_pointer = 0
# Build KMP prefix function to find overlapping tail and head patterns efficiently.
for current_index in range(1, word_length):
while index_pointer > 0 and word[current_index] != word[index_pointer]:
index_pointer = kmp_table[index_pointer - 1]
if word[current_index] == word[index_pointer]:
index_pointer += 1
kmp_table[current_index] = index_pointer
matching_length = kmp_table[-1]
while matching_length > 0 and (word_length - matching_length) % chunk_size != 0:
matching_length = kmp_table[matching_length - 1]
# Calculate minimum chops required when tail alignment does not land perfectly.
if (word_length - matching_length) % chunk_size == 0:
return (word_length - matching_length) // chunk_size
# Fallback to full reset chops if overlapping tail patterns do not cleanly align.
return (word_length + chunk_size - 1) // chunk_size| Case | How to Handle |
|---|---|
| String length is less than or equal to k | The algorithm should return 1 since removing the entire word allows appending any characters to form the initial state in a single step. |
| k is equal to 1 on a string with all identical characters | The solution must correctly calculate that 1 operation is needed because shifting by 1 character leaves the suffix matching the prefix of length n-1. |
| k is large relative to the string length such that n is less than k | Since removing k characters clears the entire string, 1 operation is always sufficient to reconstruct the word by appending the original string. |
| No partial prefix matches exist anywhere in the string | The algorithm will increment operations until it reaches ceil(n / k), where n is the word length and the entire word is cleared. |
| Maximum length strings up to 500,000 characters | The solution must utilize linear-time string matching algorithms like KMP or Z-algorithm to avoid time limit exceeded errors. |
| Already matching suffixes at valid step intervals | Prefix function or Z-array values will immediately identify valid transition points without needing to simulate all operations. |