Skip to main content

Repeated Substring Pattern

LeetCode 459 | Difficulty: Easy​

Easy

Problem Description​

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

Example 1:

Input: s = "abab"
Output: true
Explanation: It is the substring "ab" twice.

Example 2:

Input: s = "aba"
Output: false

Example 3:

Input: s = "abcabcabcabc"
Output: true
Explanation: It is the substring "abc" four times or the substring "abcabc" twice.

Constraints:

- `1 <= s.length <= 10^4`

- `s` consists of lowercase English letters.

Topics: String, String Matching


Approach​

String Processing​

Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.

When to use

Anagram detection, palindrome checking, string transformation, pattern matching.


Solutions​

Solution 1: C# (Best: 384 ms)​

MetricValue
Runtime384 ms
MemoryN/A
Date2018-04-04
Solution
public class Solution {
public bool RepeatedSubstringPattern(string s) {
int n = s.Length;
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n/2; i++)
{
if(n%i!=0) continue;
sb.Clear();
string substr = s.Substring(0,i);
while(sb.Length < n)
{
sb.Append(substr);
}
if(sb.ToString().Equals(s)) return true;
}
return false;
}
}

Complexity Analysis​

ApproachTimeSpace
Solution$O(n)$$O(1) to O(n)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.