#459

Repeated Substring Pattern

Easy
StringString MatchingString MatchingPattern Recognition
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages the properties of string concatenation. By concatenating the string with itself and removing the first and last characters, we can check if the original string appears in this new string, which indicates a repeated pattern.

⚙️

Algorithm

3 steps
  1. 1Step 1: Concatenate the string with itself to form a new string.
  2. 2Step 2: Remove the first and last characters of this new string.
  3. 3Step 3: Check if the original string exists in this modified string. If it does, return true; otherwise, return false.
solution.py3 lines
1def repeatedSubstringPattern(s):
2    ss = s + s
3    return s in ss[1:-1]

Complexity note: The time complexity is O(n) because we are creating a new string that is twice the length of the original. Checking for the substring takes linear time as well.

  • 1The problem can often be reduced to checking for patterns in strings, which is a common theme in string manipulation problems.
  • 2Understanding how string concatenation and substring searching works can lead to efficient solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.