Knowledge Guide
HomeDSACompany Practice

easy Repeated Substring Pattern

Problem Statement

Given a string s, return true if it can be formed by taking any substring of it and appending multiple copies of the substring together.

A substring is a contiguous sequence of characters in the string.

Examples

Try it yourself

Try solving this question here:

✅ Solution Repeated Substring Pattern

Problem Statement

Given a string s, return true if it can be formed by taking any substring of it and appending multiple copies of the substring together.

A substring is a contiguous sequence of characters in the string.

Examples

  • Example 1:

    • Input: s = "bcdbcdbcdbcd"
    • Expected Output: true
    • Justification: The input string can be formed by repeating the substring "bcd" three times.
  • Example 2:

    • Input: s = "abcdabcd"
    • Expected Output: true
    • Justification: The input string is the result of the substring "abcd" repeated twice.
  • Example 3:

    • Input: s = "aabaaba"
    • Expected Output: false
    • Justification: There's no single substring that, when repeated, forms the input string.

Solution

To solve this problem, we can utilize the concept of string manipulation and iteration. The intuition behind the solution is that if the string can indeed be constructed by repeating a substring, then this pattern should be identifiable by analyzing the structure of the string itself. Essentially, we'll try to find a smaller, repeating pattern within the string that, when extended, recreates the original string.

The most effective approach involves checking each possible substring length from 1 up to half the length of the string (since a repeating substring would be at most half the length of the original string). For each possible length, we replicate the substring and check if it matches the original string. This method is both straightforward and efficient for identifying repeating patterns within strings.

Step-by-Step Algorithm

  1. Determine the length of the input string (s): Calculate the length of s and store it. This length will be used to limit the possible lengths of the repeating substring.

  2. Iterate over possible substring lengths: Loop from 1 up to half the length of s. The rationale is that a repeating substring can be at most half the length of s, because to repeat, the substring needs to appear at least twice.

  3. Check divisibility: For each length i, check if the total length of s is divisible by i. This step ensures that s can be evenly divided into substrings of length i.

  4. Extract and repeat the substring: If the length is divisible, extract a substring of length i starting from the beginning of s. Repeat this substring enough times so that the concatenated result has the same length as s.

  5. Compare the constructed string with the original: Check if the repeated substring, when concatenated together, equals the original string s. If they match, it means s can indeed be formed by repeating a substring, and you return true.

  6. Continue the iteration: If no match is found, continue the iteration with the next possible length.

  7. Return false: If the loop finishes without finding any repeating substring pattern that can form s, return false.

Algorithm Walkthrough

Let's consider the input: s = "bcdbcdbcdbcd"

  1. Length Calculation:

    • The length of s is 12.
  2. Iteration Over Possible Substring Lengths:

    • The possible lengths to check are 1 to 6 (half of 12).
  3. Length 1 (i=1):

    • Check if 12 is divisible by 1 (yes).
    • Repeat "b" 12 times.
    • The result "bbbbbbbbbbbb" does not match s.
  4. Length 2 (i=2):

    • Check if 12 is divisible by 2 (yes).
    • Repeat "bc" 6 times.
    • The result "bcbcbcbcbcbc" does not match s.
  5. Length 3 (i=3):

    • Check if 12 is divisible by 3 (yes).
    • Repeat "bcd" 4 times.
    • The result "bcdbcdbcdbcd" matches s.
    • Return true because we found that s can be formed by repeating "bcd".

Code

java
public class Solution {

  // Method to check if the string can be formed by repeating a substring
  public boolean repeatedSubstringPattern(String s) {
    int len = s.length();
    // Loop over possible substring lengths, up to half the length of s
    for (int i = len / 2; i >= 1; i--) {
      if (len % i == 0) { // Only consider i if it's a divisor of len
        String pattern = s.substring(0, i);
        StringBuilder sb = new StringBuilder();
        // Repeat the pattern to match the length of s
        for (int j = 0; j < len / i; j++) {
          sb.append(pattern);
        }
        if (sb.toString().equals(s)) { // Check if the repeated pattern matches s
          return true;
        }
      }
    }
    return false; // Return false if no repeating pattern is found
  }

  public static void main(String[] args) {
    Solution solution = new Solution();
    // Example 1
    System.out.println(solution.repeatedSubstringPattern("bcdbcdbcdbcd")); // true
    // Example 2
    System.out.println(solution.repeatedSubstringPattern("abcdabcd")); // true
    // Example 3
    System.out.println(solution.repeatedSubstringPattern("aabaaba")); // false
  }
}

Complexity Analysis

  • Time Complexity: in the worst case, because for each substring length up to n/2, we're constructing a new string and comparing it to the original string, each operation taking time.
  • Space Complexity: , where n is the length of the input string. This is because we are creating a new string to compare with the original string.
🤖 Don't fully get this? Learn it with Claude

Stuck on Repeated Substring Pattern? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Repeated Substring Pattern** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Repeated Substring Pattern** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Repeated Substring Pattern**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Repeated Substring Pattern**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes