KatInterview

459. Repeated Substring Pattern

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method Explanation

There are a few ways to solve this problem, ranging from straightforward iteration to clever string manipulation. We'll explore three main approaches.

Solution

Repeated Substring Pattern in Python

class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        # Create a new string by concatenating s with itself.
        ss = s + s
        
        # If s is made of a repeating substring, it will be present
        # in the middle part of ss. The middle part is ss without
        # its first and last characters.
        # Python's slicing ss[1:-1] achieves this.
        
        # For example, if s = "abab":
        # ss = "abababab"
        # ss[1:-1] = "bababa"
        # "abab" in "bababa" is True.
        
        # If s = "aba":
        # ss = "abaaba"
        # ss[1:-1] = "baab"
        # "aba" in "baab" is False.
        
        # A single character string like "a" would give ss="aa", ss[1:-1]="",
        # "a" in "" is False, which is correct.
        # The problem constraints state 1 <= s.length, so we don't need to handle empty string.
        return s in ss[1:-1]

Repeated Substring Pattern in Java

class Solution {
    public boolean repeatedSubstringPattern(String s) {
        // Concatenate the string with itself.
        String t = s + s;
        
        // If s can be constructed by a repeating substring,
        // s must be a substring of t, but not at the beginning or end.
        // We can check if s exists in the middle part of t.
        // The middle part is t without its first and last characters.
        // t.substring(1, t.length() - 1) gives us this middle part.
        
        // For example, if s = "abab", t = "abababab".
        // t.substring(1, 7) is "bababa". "abab" is in "bababa", so it returns true.
        // If s = "aba", t = "abaaba".
        // t.substring(1, 5) is "baab". "aba" is not in "baab", so it returns false.
        if (s.length() <= 1) {
            return false;
        }
        return t.substring(1, t.length() - 1).contains(s);
    }
}

Repeated Substring Pattern in C++

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        // The string s can be formed by a repeated substring if and only if
        // it is a non-trivial rotation of itself.
        // A string s of length n is a rotation of itself by p positions (0 < p < n)
        // if and only if s is a substring of (s+s) starting at an index other than 0.
        
        // Create a new string t = s + s.
        string t = s + s;
        
        // If s has a repeated substring pattern, s = sub * k where k > 1.
        // Let len(sub) = p. Then len(s) = n = p * k.
        // t = sub * (2k). s will appear in t at index 0, p, 2p, ...
        // Since k > 1, p = n/k < n. So s will appear at index p where 0 < p < n.
        // Conversely, if s appears in t at index p where 0 < p < n,
        // it implies s is a rotation of itself, which means it's formed by
        // repetitions of a smaller string of length gcd(n, p).
        // Since gcd(n, p) < n, s has a repeated substring pattern.

        // We can check this by finding s in a modified version of t.
        // We remove the first and last characters of t to ensure we don't match
        // the original s at the beginning or the second s at its start.
        // The modified string is t from index 1 to 2*n-2.
        if (s.length() <= 1) {
            return false;
        }
        
        // t.substr(1, t.length() - 2) extracts the string t from index 1 with length 2*n-2.
        string t_sub = t.substr(1, t.length() - 2);
        
        // string::npos is returned by find if the substring is not found.
        return t_sub.find(s) != string::npos;
    }
};

Repeated Substring Pattern in TypeScript

function repeatedSubstringPattern(s: string): boolean {
    // Concatenate the string s with itself to form a new string t.
    const t = s + s;
    
    // If s is formed by a repeating substring, it must be present
    // in the string t, excluding the very first and very last characters.
    // This is because if s = sub * k (k>1), then t = sub * 2k.
    // The original string s appears in t at indices that are multiples
    // of sub's length. Since k>1, at least one such multiple will be
    // greater than 0 and less than s.length.
    // This means s will be found within t after removing its first and last char.
    
    // For example, s = "abab", t = "abababab".
    // t.slice(1, -1) -> "bababa". "abab" is a substring of "bababa", so it returns true.
    // For example, s = "aba", t = "abaaba".
    // t.slice(1, -1) -> "baab". "aba" is not a substring of "baab", so it returns false.
    
    // The slice(1, -1) method extracts a substring from index 1 up to (but not including) the last character.
    if (s.length <= 1) {
        return false;
    }
    return t.slice(1, -1).includes(s);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.