Practice › Strings
Repeated Substring Pattern
Easy · Strings · Asked at Amazon, Google, Microsoft
Print YES if the string can be built by repeating one of its substrings two or more times (like abab = ab + ab), otherwise NO.
Input
A single line with the string (lowercase letters).
Output
YES or NO.
Constraints
- 1 ≤ length ≤ 10^5
Try every length L that divides n with L < n, and check whether s equals its first L letters repeated. A neat alternative: s is periodic exactly when s appears inside (s + s) with the first and last letters removed.
Example 1
Input
abab
Output
YES
Example 2
Input
aba
Output
NO
Hints
- If s is a block repeated k ≥ 2 times, the block length divides n and is at most n / 2.
- Shifting s by one block length gives s back.
- That happens exactly when s occurs inside s + s at a position other than 0 and n.
Approach
Form t = (s + s) without its first and last characters and search for s in t. If s = B repeated k ≥ 2 times, then s appears in s + s at position |B|, which survives the trimming. Conversely, finding s at some position 0 < p < n means s equals itself shifted by p, so it is periodic with a period dividing n. Use KMP (or the library find, fine here) for the search.
Complexity: O(n) with KMP · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int n = s.size();
// prefix function: s is periodic iff the smallest period n - pi[n-1] divides n and is < n
vector<int> pi(n, 0);
for (int i = 1; i < n; i++) {
int k = pi[i - 1];
while (k && s[i] != s[k]) k = pi[k - 1];
if (s[i] == s[k]) k++;
pi[i] = k;
}
int p = n - pi[n - 1];
cout << (pi[n - 1] > 0 && n % p == 0 ? "YES" : "NO") << "\n";
return 0;
}Python solution
s = input().strip()
print("YES" if s in (s + s)[1:-1] else "NO")Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
int n = s.length();
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int k = pi[i - 1];
while (k > 0 && s.charAt(i) != s.charAt(k)) k = pi[k - 1];
if (s.charAt(i) == s.charAt(k)) k++;
pi[i] = k;
}
int p = n - pi[n - 1];
System.out.println(pi[n - 1] > 0 && n % p == 0 ? "YES" : "NO");
}
}Solve Repeated Substring Pattern online · All practice problems