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.

Input & Output

Example 1 — Basic Case
$ Input: word = "abacaba", k = 3
Output: 2
💡 Note: At t=1: remove "aba", remaining = "caba". "caba" is not a prefix of "abacaba". At t=2: remove "abacab", remaining = "a". "a" is a prefix of "abacaba". Return 2.
Example 2 — Immediate Match
$ Input: word = "abcabc", k = 2
Output: 1
💡 Note: At t=1: remove "ab", remaining = "cabc". Need to check if we can form "abcabc" by adding characters. Since "cabc" doesn't match prefix, we continue checking until we find a match.
Example 3 — Complete Removal
$ Input: word = "abc", k = 1
Output: 3
💡 Note: At t=1: remove "a", remaining = "bc". At t=2: remove "ab", remaining = "c". At t=3: remove "abc", remaining = "". Empty string can always be reconstructed to original.

Constraints

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

Visualization

Tap to expand
Word Reversion Process: "abacaba", k = 3Input: "abacaba"Remove k=3 chars each timet=1: Remove "aba" → "caba""caba" ≠ prefix ✗t=2: Remove "abacab" → "a""a" = prefix ✓Result: 2Can add "bacaba"to make "abacaba"Minimum time = 2 seconds
Understanding the Visualization
1
Input
Original word and removal count k
2
Process
Remove k characters, check if suffix can form original
3
Output
Minimum time when word can revert
Key Takeaway
🎯 Key Insight: The word reverts when its remaining suffix matches a prefix of the original word
Asked in
Google 15 Microsoft 12 Amazon 8
12.0K Views
Medium Frequency
~15 min Avg. Time
245 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