#459

Repeated Substring Pattern

Easy Doubling trick / LPS

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Decide whether s can be built by repeating one of its substrings two or more times.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: is the string some block repeated 2+ times?

Why this works: if it is, the leftover after removing the longest border (lps[n-1]) is the block length, and it divides n.

Example: "abcabc"

lps last = 3 → block length 6 - 3 = 36 % 3 = 0 → true ("abc")

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using (s + s).contains(s) without trimming the ends — it's always true.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: String Pattern Matching
🎬 Episodes 18–19: video coming soon