Repeated Substring Pattern - Problem
Pattern Recognition Challenge: Given a string
Think of it like a wallpaper pattern - can you find a basic repeating unit that, when tiled together, creates the entire design? For example,
Goal: Return
Key Insight: The repeating substring's length must be a divisor of the total string length, and it must appear consistently throughout the entire string.
s, determine if it can be constructed by taking a substring of it and repeating that substring multiple times to form the entire string.Think of it like a wallpaper pattern - can you find a basic repeating unit that, when tiled together, creates the entire design? For example,
"abcabcabc" can be constructed by repeating "abc" three times, while "abcabcab" cannot be formed by any repeating pattern.Goal: Return
true if the string follows a repeated pattern, false otherwise.Key Insight: The repeating substring's length must be a divisor of the total string length, and it must appear consistently throughout the entire string.
Input & Output
example_1.py โ Basic Repeating Pattern
$
Input:
s = "abab"
โบ
Output:
true
๐ก Note:
The string "abab" can be constructed by repeating "ab" twice: "ab" + "ab" = "abab". The pattern "ab" has length 2, which divides the total length 4 evenly.
example_2.py โ Non-Repeating Pattern
$
Input:
s = "aba"
โบ
Output:
false
๐ก Note:
The string "aba" cannot be formed by repeating any substring. While "a" appears multiple times, "aba" is not "a" repeated, and no other substring can be repeated to form "aba".
example_3.py โ Longer Repeating Pattern
$
Input:
s = "abcabcabcabc"
โบ
Output:
true
๐ก Note:
The string can be constructed by repeating "abc" four times, or "abcabc" two times. Since at least one valid repeating pattern exists, the answer is true.
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Wall
We have a wall (string) and need to determine if it's made of repeating tiles
2
Try Different Tile Sizes
Test each possible tile size from 1 to half the wall length
3
Check Pattern Alignment
For each tile size, verify if repeating it recreates the entire wall
4
Use the Mirror Trick
Advanced: Place two walls side by side - if made of tiles, the original pattern appears in the middle
Key Takeaway
๐ฏ Key Insight: A string has a repeating pattern if and only if we can find a substring that, when repeated multiple times, recreates the entire original string. The concatenation trick provides an elegant O(n) solution!
Time & Space Complexity
Time Complexity
O(n)
Modern string search algorithms (like KMP) used by built-in functions run in linear time
โ Linear Growth
Space Complexity
O(n)
Space needed to store the concatenated string of length 2n
โก Linearithmic Space
Constraints
- 1 โค s.length โค 104
- s consists of lowercase English letters only
- The repeating pattern must appear at least twice
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code