Repeated Substring Pattern - Problem

Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.

In other words, determine if the string is made up of a repeating pattern where the same substring is repeated 2 or more times consecutively to form the entire string.

Example: The string "abcabcabc" can be constructed by repeating the substring "abc" three times, so it returns true. However, "abcabcab" cannot be formed by repeating any substring, so it returns false.

Input & Output

Example 1 — Simple Repeat
$ Input: s = "abab"
Output: true
💡 Note: The string can be constructed by repeating "ab" twice: "ab" + "ab" = "abab"
Example 2 — Triple Repeat
$ Input: s = "aba"
Output: false
💡 Note: No substring can be repeated to form "aba". Single characters don't count as patterns.
Example 3 — Long Pattern
$ Input: s = "abcabcabcabc"
Output: true
💡 Note: The pattern "abc" is repeated 4 times to form the string

Constraints

  • 1 ≤ s.length ≤ 104
  • s consists of lowercase English letters

Visualization

Tap to expand
Repeated Substring Pattern INPUT String s = "abab" a idx 0 b idx 1 a idx 2 b idx 3 Looking for repeating pattern ab ab Potential pattern: "ab" Input Values s = "abab" length = 4 ALGORITHM STEPS 1 Concatenate s + s Create: "abab" + "abab" "abababab" 2 Remove first & last Slice [1 : -1] "bababa" 3 Search for s Find "abab" in result "bababa" Found at index 1! 4 Return result Found --> true FINAL RESULT Pattern Verification Substring: "ab" ab + ab = "abab" OK Output true Key Insight: If a string s has a repeating pattern, then s will always be found in (s + s)[1:-1]. By removing the first and last characters, we break the original but preserve internal matches only if a true repeating pattern exists. Time: O(n), Space: O(n). TutorialsPoint - Repeated Substring Pattern | String Concatenation Trick Approach
Asked in
Google 15 Amazon 12 Facebook 8
125.0K Views
Medium Frequency
~15 min Avg. Time
3.2K 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