Taro Logo

Minimum Time to Revert Word to Initial State I

Medium
Asked by:
Sprinklr
1 view
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 <= 50
  • 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 what is the valid range for the integer $k$?
  2. When we append $k$ characters to the end of the word during an operation, can they be completely arbitrary characters, or do they have to match the original characters from earlier in the sequence?
  3. What constitutes the 'initial state'—does the entire string need to be identical to the starting `word`, or just a prefix of it?
  4. If the word is already in its initial state before any operations are performed, should the function return 0?
  5. Is it guaranteed that we can always revert the word back to its initial state within a finite number of operations (e.g., within the length of the string divided by $k$), or is it possible that no solution exists?

Brute Force Solution

Approach

The problem asks for the minimum positive number of operations to revert a word to its initial state, where each operation drops the first k characters and appends any k characters. At step t, the suffix of the original string starting at index t * k shifts to the beginning. If this remaining suffix matches the corresponding prefix of the original string, the remaining characters can be chosen to perfectly recreate the original word.

Here's how the algorithm would work step-by-step:

  1. Determine the total length of the word.
  2. Iterate through the elapsed seconds starting from 1 up to the maximum required time.
  3. Calculate the index where the remaining un-removed characters start after the current number of operations.
  4. Check if the remaining characters have already shifted past the end of the word, which allows freely rebuilding the entire word.
  5. Otherwise, compare the suffix of remaining characters to the prefix of the original word of the same length.
  6. Return the first step count where a match is found.

Code Implementation

def minimum_time_to_revert_word(word: str, k: int) -> int:
    word_length = len(word)
    # Check each possible time step starting from 1
    for step in range(1, (word_length + k - 1) // k + 1):
        remaining_start = step * k
        # If all original characters have shifted out, word can be fully recreated
        if remaining_start >= word_length:
            return step
        # Compare the remaining suffix with the prefix of the same length
        if word[remaining_start:] == word[:word_length - remaining_start]:
            return step
    return (word_length + k - 1) // k

Big(O) Analysis

Time Complexity
O(n^2 / k) – There are at most n / k steps checked, and each step compares substrings of length at most n, where n is the length of the string.
Space Complexity
O(n) – Slicing strings creates temporary substring copies proportional to the length of the string n.

Optimal Solution

Approach

To find the minimum time needed to restore a word to its starting state, the optimal approach works backwards from the end of the word. Instead of checking every single possibility from the beginning, it looks for the largest overlapping section where the tail of the current word matches the head of the original word.

Here's how the algorithm would work step-by-step:

  1. Look at the word you currently have and think about chopping off a specific chunk of letters from the very beginning.
  2. Count how many chunks you had to remove to get rid of that section.
  3. Check if the remaining part of the word, which has now shifted to the front, matches the very beginning of the original word.
  4. If they do not match, try removing a slightly larger chunk from the beginning and check again.
  5. Keep repeating this process until you find a remaining piece that successfully matches the start of the original word, or until you have removed enough chunks that you are essentially starting over completely.
  6. Once you find a valid matching piece, the number of removal steps you took to reach this point is your final answer.

Code Implementation

def minimum_time_to_initial(word: str, chunk_size: int) -> int:
    total_length = len(word)
    removal_steps = 1

    # Iterate backwards through possible valid starting positions for the suffix match.
    for current_index in range(chunk_size, total_length, chunk_size):
        if word[current_index:] == word[:total_length - current_index]:
            # We found the minimal valid suffix that matches the prefix, so this step count is optimal.
            return removal_steps

        removal_steps += 1

    # If no smaller suffix matches, we must remove the entire word and start fresh.
    return removal_steps

Big(O) Analysis

Time Complexity
O(n²) – To find the minimum time to revert the word, the algorithm iterates backwards through the string from the end by steps of size k, checking suffixes against prefixes of length n minus i. For each of the n divided by k possible starting positions, we may need to compare up to n characters of the remaining suffix with the original word head. This nested check across the decreasing suffix lengths results in approximately n times n divided by (2k) operations in the worst case. Simplifying this proportional cost removes the constant factors and yields a final time complexity of O(n²).
Space Complexity
O(1) – The algorithm only uses a few primitive variables to keep track of indices, loop counters, and string slicing lengths during the iteration process. No dynamic data structures, hash maps, or recursive call stacks are created. Since the memory consumption remains constant regardless of how long the input word is, the auxiliary space complexity is O(1).

Edge Cases

String length is less than or equal to k
How to Handle:
The solution must correctly handle this by requiring only one operation since removing the first k characters leaves a string of length zero or less, allowing any k characters to be appended.
Word is already periodic and matches the suffix early
How to Handle:
The algorithm should check prefixes from the first possible operation count and return the minimum operations without needing to exhaustively simulate every step.
Value of k is 1
How to Handle:
The approach must correctly evaluate shifting character by character, which represents the maximum number of potential operations up to the length of the word.
Value of k is greater than the length of the word
How to Handle:
The implementation needs to ensure it safely handles the boundary condition where the entire word is removed in a single operation.
All characters in the word are identical
How to Handle:
The logic must correctly identify that shifting by k may instantly align with the repeating pattern, potentially returning a minimal operation count of 1.
Maximum length constraints up to the problem limits
How to Handle:
The solution must avoid inefficient string slicing or quadratic comparisons in favor of an optimal linear time check using string hashing or Z-algorithm structures.
No partial overlap matches until the final complete shift
How to Handle:
The code must iterate up to the maximum possible operations and default to the ceiling division of the word length by k if no intermediate match is found.
Appended characters happen to match the required suffix by coincidence
How to Handle:
The check must strictly verify that the remaining unmodified suffix of the current word matches the prefix of the original word of equivalent length.