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: 3
💡 Note: At t=1: remove "ab", remaining = "cabc". "cabc" is not a prefix of "abcabc". At t=2: remove "abca", remaining = "bc". "bc" is not a prefix of "abcabc". At t=3: remove "abcabc", remaining = "". Empty string can always be reconstructed to original. Return 3.
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
Minimum Time to Revert Word to Initial State INPUT word = "abacaba" a 0 b 1 a 2 c 3 a 4 b 5 a 6 word = "abacaba" k = 3 Each Second: 1. Remove first k chars 2. Add any k chars to end Goal: Revert to initial state in minimum time > 0 ALGORITHM STEPS 1 Check Suffix Match For each t, check if word[t*k:] is prefix of original word 2 t=1: Remove "aba" Remaining: "caba" "caba" != prefix of "abacaba" c a b a NO 3 t=2: Remove "abacab" Remaining: "a" "a" IS prefix of "abacaba" a OK 4 Can Restore! Add "bacaba" (6 chars total) to get back "abacaba" a + b a c a b a FINAL RESULT Minimum Time Found! Time Progression: t = 0 "abacaba" t = 1 "caba???" t = 2 "abacaba" Output: 2 After 2 operations, word can revert to "abacaba" VERIFIED Minimum time = 2 Key Insight: String Matching Optimization: After t operations, the remaining suffix word[t*k:] must be a prefix of the original word. This is because we can only ADD characters at the end, so the remaining part must match the beginning. We iterate t from 1 and find the smallest t where word[t*k:] is a prefix of word (or t*k >= len(word)). TutorialsPoint - Minimum Time to Revert Word to Initial State I | String Matching Optimization
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