Taro Logo

Minimum Time to Revert Word to Initial State II

#11 Most AskedHard
0 views
Topics:
Strings

You are given a 0-indexed string word and an integer k.

At every second, you must perform the following operations:

  • Remove the first k characters of word.
  • Add any 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 <= 106
  • 1 <= k <= word.length
  • word consists only of lowercase English letters.

Solution


Clarifying Questions

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:

  1. What is the maximum length of the string `word` and the range of values for `k`?
  2. Are the characters appended to the end restricted to lowercase English letters, or can they be any characters, and do they have to match the original characters being removed?
  3. If `k` is greater than or equal to the length of the word, does a single operation always revert the word to its initial state?
  4. What should be returned if `k` is 0 or invalid, or is `k` guaranteed to be a positive integer such that $1 e k e ext{length of word}$?
  5. Can the word revert to its initial state in fewer operations by matching a proper suffix of the current word with a prefix of the initial word?

Brute Force Solution

Approach

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:

  1. Begin by assuming you need to perform just one chopping operation to fix the text.
  2. Simulate chopping off that specific amount of letters from the beginning of the modified text.
  3. Look at what remains of the text and glue a fresh batch of letters to the end to see if it matches the original starting text.
  4. If the modified text does not match the original version, erase your simulation and try chopping off a larger chunk of letters.
  5. Repeat this trial-and-error process by testing every possible amount of letters you could chop off, moving forward one step at a time.
  6. Stop as soon as you find a tested amount that successfully restores the exact original text.
  7. If no partial match works, resort to chopping off the entire word and starting completely fresh, which always guarantees a successful restoration.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n²) – The input size n is the length of the word, and the cost is driven by the trial-and-error process of testing every possible chop size from 1 up to n. For each of the n possible chop sizes, we simulate removing characters from the front and comparing the remaining suffix of length roughly n minus k against the prefix of the original word. In the worst case, this comparison takes linear time proportional to the remaining length for each of the n steps. Summing these comparison costs yields approximately n * (n - 1) / 2 total operations, which simplifies to O(n²).
Space Complexity
O(N) – To solve this efficiently using advanced string matching techniques like the KMP algorithm or Z-algorithm, we must maintain an auxiliary prefix function or Z-array of size N, where N represents the length of the input word. This extra array stores intermediate string-matching results to evaluate potential prefix alignments during the trial-and-error simulation. Additionally, a few primitive integer variables are used to keep track of loop indices and chopping amounts. Since the dominant memory allocation is the auxiliary array of size N, the space scales linearly with the input length. Consequently, simplifying this memory usage to Big O notation yields O(N).

Optimal Solution

Approach

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:

  1. Imagine you have a long word and you are allowed to chop off a fixed number of letters from the front at a time.
  2. Instead of guessing blindly, look at the end of the word and see if any part of it mirrors the very beginning of the word.
  3. Find the longest overlapping section where the tail of the word matches the head.
  4. Calculate how many chops of your chosen size would be needed to clear out the non-matching parts and reveal that matching tail.
  5. If chopping by your set amount naturally lands you right at a point where the remaining tail lines up with the beginning, count that total number of chops.
  6. If your set amount does not line up perfectly, figure out the minimum number of full chops required to wipe out everything and start fresh.
  7. By focusing only on these overlapping tail-and-head patterns, you skip repetitive counting and instantly find the shortest path to your goal.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n) – To find the longest overlapping section where the tail matches the head efficiently, we utilize the Z-algorithm or KMP failure function, which computes pattern matches in a single pass. For a word of length n, this matching process evaluates each character at most a constant number of times. We then iterate through valid suffix starting points spaced by the given chop size, each taking constant time. This leads to approximately n operations for the prefix function calculation plus n divided by the chop size for the validation steps, which simplifies to O(n).
Space Complexity
O(N) – To find the overlapping tail-and-head patterns and determine the shortest path, the optimal solution requires building an auxiliary Z-array or KMP failure function array of size N, where N is the length of the input word. This extra array stores the lengths of matching prefixes and suffixes for every position in the string. A few primitive integer variables are also used to keep track of indices and counts, consuming constant auxiliary space. Because the Z-array scales directly with the length of the input, the total space complexity simplifies linearly to Big O of N.

Edge Cases

String length is less than or equal to k
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Prefix function or Z-array values will immediately identify valid transition points without needing to simulate all operations.
0/45 completed