459. Repeated Substring Pattern – Solution [Brute-Force to Best]

Here’s the question link on Leetcode 459. Repeated Substring Pattern:

https://leetcode.com/problems/repeated-substring-pattern/description

Brute Force: Try Every Possible Substring

The idea is to try every possible length of a repeating substring.

If the substring is repeated, its length must divide the length of the original string.

For example, if the string has length 6, possible repeating substring lengths are 1, 2, and 3.

We can:

  1. Try every possible length that divides n.
  2. Take the prefix of that length.
  3. Repeat it until we get a string of length n.
  4. Compare it with the original string.
class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        int n = s.size();

        for(int len = 1; len <= n / 2; len++) {
            if(n % len != 0)
                continue;

            string pattern = s.substr(0, len);
            string temp = "";

            while(temp.size() < n)
                temp += pattern;

            if(temp == s)
                return true;
        }

        return false;
    }
};
459. Repeated Substring Pattern Brute Force Solution

Optimal: String Concatenation Trick

Here’s a neat trick!

What if we concatenate the string with itself?

s = "abab";

s + s = "abababab";

Now remove the first and last characters:

"bababa"

Notice that the original string "abab" still exists inside it!

Let’s try another example:

s = "aba"

s + s = "abaaba"

After removing first and last:
"baab"

Here, "aba" does not exist.

Why does this work?

If a string is made by repeating a smaller substring, it will remain the same after rotating it by the length of that repeating substring.

For example:

"abab" → "abab"

The string is unchanged after rotating it by 2 positions.

By concatenating the string with itself, we get all possible rotations as substrings. Removing the first and last characters excludes the two original copies.

So, if s still exists inside the remaining string, it has a repeating pattern.

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        string temp = s + s;

        return temp.substr(1, temp.size() - 2).find(s) != string::npos;
    }
};
459. Repeated Substring Pattern Optimal Solution

Leave a Reply