↓Skip to main content
  1. LeetCode/

LeetCode 459: Repeated Substring Pattern

·1 min· ·
LeetCode Easy String String-Matching Z-Algorithm Knuth-Morris-Pratt-Algorithm
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-24

  • Submissions: Accepted (first try)

Approach
#

Direct approach: for each length L dividing n, check s[:L] * (n // L) == s. Shorter: drop the first and last characters of s + s; if s still occurs, s equals one of its own nontrivial rotations, which means it has a repeating period (String Template 2).

My Attempts
#

Passed on the first try with s in s[1:] + s[:-1], which is the same string as (s + s)[1:-1].

Solution
#

class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        return s in (s + s)[1:-1]

Complexity
#

Time O(n²) worst case for the built-in search, space O(n).

Mistakes to Avoid
#

  • Remove both ends, or s is always found at the start or end of s + s.

Interview Explanation
#

If s repeats a substring, rotating it by the period gives itself, so I check whether s occurs in s + s with both ends trimmed. In an interview I would also mention enumerating divisors of the length as the period and verifying each.

Related

LeetCode 28: Find the Index of the First Occurrence in a String
·1 min
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 note: try matching needle at every start, or use str.find; index raises when not found
LeetCode 1446: Consecutive Characters
·1 min
LeetCode Easy String
LeetCode 1446 note: track the current run of equal characters in one pass, resetting to 1 on a change
LeetCode 1869: Longer Contiguous Segments of Ones than Zeros
·1 min
LeetCode Easy String
LeetCode 1869 note: find the longest run of 1s and of 0s and compare; split does it in one line
LeetCode 415: Add Strings
·2 mins
LeetCode Easy Math String Simulation
LeetCode 415 note: add digit by digit from the ends with two pointers, tracking the carry, and append any leftover carry after the loop
LeetCode 482: License Key Formatting
·2 mins
LeetCode Easy String
LeetCode 482 note: remove every dash and uppercase first, then cut groups of k from the end so only the first group may be shorter
LeetCode 290: Word Pattern
·1 min
LeetCode Easy Hash-Table String
LeetCode 290 note: pattern characters and words must correspond one to one; use two dicts or compare set sizes