Minimum Time to Revert Word to Initial State I - 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.

Example: If word = "abacaba" and k = 3, after one operation we have "acaba" + "abc" = "acabaabc". We need to find the minimum operations to get back to "abacaba".

Input & Output

example_1.py — Basic Case
$ Input: word = "abacaba", k = 3
Output: 2
💡 Note: At t=1: Remove "aba" → "caba", need to add "aba" to get "cabaaba" ≠ "abacaba". At t=2: Remove "abacab" → "a", can add "bacaba" to get "abacaba" ✓
example_2.py — Single Character
$ Input: word = "aa", k = 1
Output: 2
💡 Note: At t=1: Remove "a" → "a", need "a" == "a" but we need full word. At t=2: Remove "aa" → "", can build "aa" from scratch.
example_3.py — Immediate Match
$ Input: word = "abab", k = 2
Output: 1
💡 Note: At t=1: Remove "ab" → "ab", and "ab" matches prefix "ab" of original word, so we can add "ab" to get "abab".

Visualization

Tap to expand
a b ac a b acut herec a b a≠ prefix matcha✓ matches prefix "a"🎯 Key InsightWe only need to check ifremaining suffix matchesa prefix of the original!
Understanding the Visualization
1
Original Film Strip
We start with the complete sequence 'abacaba'
2
Cut First k Frames
Remove first 3 characters: 'aba|caba' → 'caba'
3
Check Reconstruction
Can 'caba' + 3 new frames = 'abacaba'? Need 'caba' to match some prefix
4
Find Match
At step 2, 'a' matches prefix 'a', so we can reconstruct!
Key Takeaway
🎯 Key Insight: Instead of trying all possible character additions, we just check if the remaining suffix can naturally extend to form the original word by matching its prefix pattern.

Time & Space Complexity

Time Complexity
⏱️
O(n²)

We check at most n/k positions, each requiring O(n) string comparison

n
2n
Quadratic Growth
Space Complexity
O(1)

Only using constant extra space for variables

n
2n
Linear Space

Constraints

  • 1 ≤ word.length ≤ 105
  • 1 ≤ k ≤ word.length
  • word consists only of lowercase English letters
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
28.5K Views
Medium Frequency
~25 min Avg. Time
890 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