Code Logo

Repeated Substring Pattern

Published at25 Jul 2026
Medium 0 views
Like0

Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of that substring together. For example, "abab" can be made by repeating "ab" twice, but "aba" cannot.

The trick: concatenate s with itself, remove the first and last character, and check if s appears in the result. If s is a repeating pattern, the doubled string without the ends will contain s. This works because any repeating string s = pattern * k will appear at position p where p equals the pattern length.

Time complexity is O(n) for the contains check. Space is O(n) for the doubled string.

Example Input & Output

Example 1
Input
"abab"
Output
true
Explanation

"ab" repeated twice

Example 2
Input
"aba"
Output
false
Explanation

Cannot be formed by repeating a substring

Example 3
Input
"a"
Output
false
Explanation

Single char cannot be formed by repeating

Example 4
Input
""
Output
false
Explanation

Empty string

Example 5
Input
"abcabcabc"
Output
true
Explanation

"abc" repeated 3 times

Algorithm Flow

Recommendation Algorithm Flow for Repeated Substring Pattern
Recommendation Algorithm Flow for Repeated Substring Pattern

Solution Approach

function solution(s) {
  if (s.length <= 1) return false;
  return (s + s).substring(1, s.length * 2 - 1).indexOf(s) !== -1;
}

Best Answers

java
class Solution {
    public boolean solution(String s) {
        return s.length()>1&&(s+s).substring(1,2*s.length()-1).contains(s);
    }
}