2
$\begingroup$

I've been working on the following challenge on LeetCode:


Problem: Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.


During my exploration, I stumbled upon an interesting solution:

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

I'm working to comprehend why this solution works.

Firstly, let's consider a string $x$ that can be constructed with a repeated substring pattern. In this case, $x$ takes the form:

$$x=SS\dots S$$

where $S$ is not an empty string, and there are more than two occurrences of $S$.

Now, if we concatenate two instances of $x$ and remove the first and last elements, we get:

$$y=ASS\dots SB$$

This string $y$ includes the original string $x$, and the function returns true.

However, I need to know how to demonstrate why the function returns false when the string does not have the specified form.

$\endgroup$

1 Answer 1

2
$\begingroup$

Instead of proving that the function returns false when the string is not of the specified form, let us use the contraposition.

Let $s = a_1…a_n$ be the string and assume that the function returns true. That means that $s$ is a substring of $a_2a_3…a_na_1a_2…a_{n-1}$. Since $s$ is of length $n$, that means that there exists $k\in\{2, …, n\}$ such that: $$s = a_ka_{k+1}…a_na_1…a_{k-1}$$

Let $u = a_k…a_n$ and $v = a_1…a_{k-1}$. Then neither $u$ nor $v$ is empty and $s = uv = vu$.

Suppose (without loss of generality) that $|u| \leqslant |v|$ and let us prove by induction on $|u| + |v|$ that there exists $w$ and $m_1$, $m_2$ such that $u=w^{m_1}$ and $v = w^{m_2}$:

  • if $|u| + |v| = 2$, then $u$ and $v$ are one-letter words and the result is direct with $w = u$ and $m_1 = m_2 = 1$;

  • otherwise, since $uv = vu$ and $|u| \leqslant |v|$, that means that $u$ is a prefix of $v$, and there exists $v'$ such that $v = uv'$.

    • If $v' = \varepsilon$, then $w = u$ and $m_1 = m_2 = 1$ are suitable.
    • Otherwise $uuv' = uv'u$, so $uv' = v'u$. Using induction hypothesis, there exists $w$ and $m_1$ and $m_2'$ such that $u = w^{m_1}$ and $v' = w^{m_2'}$. Then $v = uv' = w^{m_1+m_2'}$.

Since $s = uv$, then $s = w^{m_1+m_2}$, and $w$ is a proper substring of $s$, because $m_1 +m_2 > 1$.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.