Minimum Time to Revert Word to Initial State II - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: word = "abcab", k = 2
Output: 3
💡 Note: At t=1: remove "ab" → "cab", can't restore. At t=2: remove "abca" → "b", can't restore. At t=3: remove all → "", can add "abcab" to restore original.
Example 2 — Early Return
$ Input: word = "abab", k = 2
Output: 2
💡 Note: At t=1: remove "ab" → "ab", can add "ab" to get "abab". But this doesn't work. At t=2: remove "abab" → "", can restore by adding "abab".
Example 3 — Single Character
$ Input: word = "a", k = 1
Output: 1
💡 Note: At t=1: remove "a" → "", can add "a" to restore original word.

Constraints

  • 1 ≤ word.length ≤ 106
  • 1 ≤ k ≤ word.length
  • word consists only of lowercase English letters

Visualization

Tap to expand
Minimum Time to Revert Word to Initial State II INPUT String word = "abcab" a 0 b 1 c 2 a 3 b 4 k = 2 (remove/add) Each second: 1. Remove first k chars 2. Add any k chars to end n = 5 (word length) KMP Failure Function Find suffix = prefix matches ALGORITHM STEPS 1 Compute KMP Table Build failure function for word a b c a b 0 0 0 1 2 2 Check t*k positions t=1: pos=2, t=2: pos=4 3 Find suffix match word[t*k:] is prefix of word? t=1: "cab" vs "abc" - NO t=2: "b" vs "a" - NO 4 Compute min time ceil(n/k) if no early match ceil(5/2) = 3 seconds t=3: all chars replaced Can rebuild "abcab" FINAL RESULT State transitions: t=0: abcab t=1: cab?? t=2: b???? t=3: ????? --> abcab Output: 3 OK - Verified! After 3 seconds, we can freely add chars to form the original "abcab" Key Insight: KMP failure function helps find positions where word[t*k:] matches a prefix of word. If suffix starting at position t*k equals the prefix of word, we can revert in t seconds by adding the right k chars. If no such position exists, minimum time is ceil(n/k) when all original characters are removed. TutorialsPoint - Minimum Time to Revert Word to Initial State II | KMP String Matching Approach
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen