You are given a string s of lowercase letters. Decide whether s is made of one shorter block written two or more times in a row, with nothing else in between or after.
Return true if such a block exists, and false otherwise. The block must be shorter than s itself.
Example 1
Input: s = "abaaba" Output: true Why: it is "aba" written twice
2 more examples and the constraints
Example 2
Input: s = "abcab" Output: false Why: no shorter block rebuilds it
Example 3
Input: s = "zzzz" Output: true Why: "z" four times (or "zz" twice)
Constraints
- 1 ≤ length of s ≤ 10,000
- s has only lowercase English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every block lengthO(n · d)
- Search in the doubled stringO(n) to O(n²)
- KMP prefix tableO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Worst case for 10,000 letters | Verdict |
|---|---|---|---|
| Try every block length | O(n · d) | Passes; easy to explain | |
| Search in the doubled string | O(n) to O(n²) | Passes; neat one-liner | |
| KMP prefix table | O(n) | Best; linear, guaranteed |
n = length of s, d = number of divisors of n (at most 64 here).
Edge cases to test
- A single letter. "q" has no shorter block, so the answer is false.
- One letter repeated. "zzzz" is true; the block can be one letter.
- Prime length. Only a one-letter block can fit, so "xyzxy" is false.
- A border that is not a period. "aabaabaa" starts and ends with "aabaa", but 8 − 5 = 3 does not divide 8: false.
Common mistakes
- Counting the whole string as its own block, so every input returns true.
- Checking only that the last lps value is positive, which wrongly accepts "abcab".
- Trying block lengths that do not divide the length of s.
How to talk through it
- 1Clarify. Must the block repeat at least twice? Is a one-letter string a repetition?
- 2Give the simple check. Try each block length that divides n and rebuild s from it; say it is O(n · d).
- 3Mention the doubled string. A repeat survives a shift by one block, so s appears inside (s + s) without its ends.
- 4Code the prefix table. Build lps, then test L > 0 and n % (n − L) == 0; explain why n − L is the period.
- 5Test out loud. Run a single letter, "zzzz" and "aabaabaa" before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?