We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Minimum Time to Revert Word to Initial State I

Difficulty: Medium


Problem Description

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 and add any k characters to the end of word. The goal is to return the minimum time greater than zero required for word to revert to its initial state.


Key Insights

  • The operations of removing and adding characters are cyclic.
  • The challenge lies in determining how many iterations are needed to bring the string back to its original form.
  • A brute-force method of simulating each second would be inefficient.
  • We can use the properties of strings and periodicity to optimize the solution.

Space and Time Complexity

Time Complexity: O(n) where n is the length of the string, as we may need to check every substring.
Space Complexity: O(n) for storing the modified strings if necessary, but can be optimized further.


Solution

To solve this problem, we can employ a string matching technique. The idea is to utilize a loop that simulates the removal and addition of characters while keeping track of how many seconds it takes to revert to the original form. We can use a rolling hash or simply check for periodicity by keeping track of the current state of the string after each second. When the current state matches the original state, we return the time taken.

  1. Initialize a variable to count the seconds.
  2. Create a loop that continues until the current state of the string matches the original.
  3. In each iteration, remove the first k characters and add any k characters to the end.
  4. Check if the string has reverted to its initial state, if so, return the count of seconds.

Code Solutions

def minTimeToRevert(word: str, k: int) -> int:
    original = word
    n = len(word)
    seconds = 0
    
    while True:
        seconds += 1
        # Remove the first k characters
        word = word[k:] + word[:k]  # Here we simulate the addition of characters
        if word == original:
            return seconds
← Back to All Questions