Detect Strings Formed by Repeating a Block
Easy · Coding & Algorithms · Machine Learning Engineer · Technical Screen
Problem Statement
Implement is_repeated_pattern(s: str) -> bool. Given a non-empty string s of lowercase letters, determine whether s can be written as k consecutive copies of some shorter non-empty block (s == block * k for an integer k >= 2).
Return True if at least one such repeating block exists, or False if no shorter substring tiles s evenly.
Examples
Example 1
- Input:
s = "xyxy" - Output:
True - Explanation: Joining two copies of the 2-letter block
"xy"reconstructs"xyxy".
Example 2
- Input:
s = "pqp" - Output:
False - Explanation: A 3-character string can only be tiled
k >= 2times by a 1-character block, and three copies of'p'gives"ppp", not"pqp".
Example 3
- Input:
s = "mnomnomnomno" - Output:
True - Explanation: Four copies of
"mno"(or two copies of"mnomno") produce"mnomnomnomno".
Constraints
1 <= len(s) <= 10^4- Every character in
sis a lowercase English letter ('a'–'z'). - Using
sitself once (k = 1) does not count; consequently, any 1-character string returnsFalse, whereas any string of2or more identical letters returnsTrue.
Step-by-step walkthrough
Understand what counts as a repetition
Given a non-empty lowercase string
sof lengthn(1 <= n <= 10^4), we must returnTrueif there is a shorter non-empty substringblockthat can be repeated 2 or more times back-to-back to forms(s == block * kwithk >= 2), andFalseotherwise.Three quick observations anchor our intuition:
- Single-character strings (
"m") are alwaysFalse, because repeating any non-emptyblockat least twice produces at least2characters. - All-identical strings of length >= 2 (
"kk","zzzz") areTrue, using the 1-character block ("k"twice or"z"four times). - Partial leftovers are
False:"xyxyxyx"(length7) repeats"xy"three and a half times, which does not tileswith whole copies.
- Single-character strings (
Brute force: test divisor block lengths
If
sconsists ofk >= 2copies ofblock, two properties must hold:blockmust begin at index0(soblock == s[:block_len]), andblock_lenmust dividenevenly (n % block_len == 0) with1 <= block_len <= n // 2.
Checking only divisor lengths up to
n // 2already avoids testing allO(n^2)substrings:def is_repeated_by_divisors(s: str) -> bool: n = len(s) for block_len in range(1, n // 2 + 1): if n % block_len == 0: candidate_block = s[:block_len] copies = n // block_len if candidate_block * copies == s: return True return FalseBecause an integer
n <= 10,000has at most64divisors, this loop runs inO(n * divisors(n))time and serves well as a brute-force reference intests.py. Even better, a clean rotation property lets us test every non-trivial shift in one substring search.Key idea: double the string and trim both ends
Join two copies of
sintodoubled = s + s. Every window of lengthninsidedoubledis a cyclic rotation ofs(moving the firstshiftletters ofsto the back):s = "xyxy" (n = 4) doubled = s + s = "xyxyxyxy" ^^^^ <- trivial copy 1 at index 0 (shift 0) ^^^^ <- trivial copy 2 at index 4 (shift n) Trim the first and last character -> interior = doubled[1:-1]: doubled : x [ y x y x y x ] y interior : y x y x y x ^ ^ ^ ^ <- "xyxy" STILL appears at shift 2! -> TrueCompare that against the non-repeating string
s = "pqp"(n = 3):s = "pqp" (n = 3) doubled : p [ q p p q ] p interior : q p p q <- "pqp" does NOT appear anywhere! -> FalseSlicing off index
0destroys the trivial match at the left end, and slicing off index2n - 1destroys the trivial match at the right end. Only genuine rotations (1 <= shift <= n - 1) survive insideinterior.Why matching inside the trimmed double is exact
Let's confirm why
s in (s + s)[1:-1]evaluates toTrueif and only ifsis formed by repeating a smaller block:- Direction 1 (Repeated block -> found in
interior): Supposesconsists ofk >= 2copies ofblockof lengthm = len(block). Thendoubled = s + sconsists of2kcopies ofblockin a row. Starting right after the first block (at indexmofdoubled) giveskconsecutive blocks — an exact copy ofs! Sincek >= 2,1 <= m <= n // 2 < n, so this copy begins after index0and ends before index2n - 1, placing it completely insideinterior = doubled[1:-1]. - Direction 2 (Found in
interior-> repeated block): Supposesmatches insideinterior, corresponding to some indexshiftindoubledwith1 <= shift <= n - 1. That means rotatingsleft byshiftslots leavessunchanged! Even ifshiftdoes not dividendirectly — says = "xyxyxy"(n = 6) matched atshift = 4— rotating by4a second time wraps around6((4 + 4) % 6 = 2), which also leavessunchanged! Repeating a step ofshiftaround a circle of sizenalways reachesg = gcd(shift, n), where the greatest common divisor (gcd) is the largest positive integer dividing bothshiftandn. Becausegdividesnand1 <= g <= shift < n,spartitions evenly inton // g >= 2identical copies ofs[:g].
- Direction 1 (Repeated block -> found in
Trace tricky cases step by step
Let's trace five representative inputs, including near-misses:
s len doubled interior s in interior? result ----------- --- ---------------- -------------- -------------- ------ "m" 1 "mm" "" no False "pqp" 3 "pqppqp" "qppq" no False "xyxy" 4 "xyxyxyxy" "yxyxyx" yes (at idx 1) True "xyxxyx" 6 "xyxxyxxyxxyx" "yxxyxxyxxy" yes (at idx 2) True "xyxyxyx" 7 "xyxyxyxxyxyxyx" "yxyxyxxyxyxy" no ("xx" seam!) FalseLook closely at
"xyxyxyx": where the two copies meet indoubled,"xyxyxyx" + "xyxyxyx"creates"xx"at the seam, preventing"xyxyxyx"(where'x'and'y'strictly alternate) from matching at any interior shift!Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def is_repeated_pattern(s: str) -> bool: # A string of length 0 or 1 cannot be formed by 2 or more non-empty copies. if len(s) < 2: return False # doubled: two copies of s back-to-back, e.g. "xyxy" -> "xyxyxyxy". # In doubled, s always appears trivially at index 0 and at index len(s). doubled = s + s # Slice off the very first and very last character so neither trivial copy # (at index 0 or index len(s)) remains whole; only shifts 1..len(s)-1 survive. interior = doubled[1:-1] # Searching for s inside interior tests whether shifting s by some k in 1..len(s)-1 # reproduces s, which holds if and only if s is built of >= 2 repeated blocks. return s in interior✅ Submit now — all tests should pass.
Intuition & how it works
Imagine printing s evenly around a circular wheel of n slots and turning the wheel by 1, 2, ..., n - 1 slots. If s is built by stamping a shorter block multiple times — such as "mnomno" — turning the wheel by one stamp's width (3 slots) lines every letter right back up with the original s; if s has no repeating block, no partial turn ever reproduces s. Forming doubled = s + s lays all cyclic shifts (rotations that take characters off the front and wrap them onto the back) out flat in one string, and trimming the first and last characters (interior = doubled[1:-1]) breaks the 0-slot and n-slot trivial alignments so s in interior checks every genuine partial rotation at once.
A naive approach tries every substring s[i:j] by repeating it out to length n, testing O(n^2) candidates and spending O(n) per check for O(n^3) total work. Another frequent pitfall is guessing the block width from the next appearance of s[0]: on "xyxxyx", s[0] = 'x' reappears at index 2, tricking that heuristic into testing "xy" and returning False when the true repeating block is "xyx" (length 3). Checking s in (s + s)[1:-1] never guesses block boundaries and tests every non-trivial rotation cleanly.
Walk through s = "xyxy" (n = 4) versus s = "pqp" (n = 3):
- On
"xyxy":doubled = "xyxyxyxy", and trimming both ends givesinterior = "yxyxyx". Checking"xyxy" in "yxyxyx"finds"xyxy"starting at index1("y[xyxy]x"), so we returnTrue. - On
"pqp":doubled = "pqppqp", and trimming both ends givesinterior = "qppq". Checking"pqp" in "qppq"finds no match, so we returnFalse.
Complexity
- Time: O(n) in CPython on long strings (and O(n^2) worst-case if backed by a naive character-by-character substring search), where
n = len(s). Buildings + sand slicing[1:-1]each copyO(n)characters once, and CPython'sinoperator runs the Two-Way linear-time string-matching algorithm on long patterns (see the first follow-up for an explicit algorithm guaranteed to run in O(n) in every language). - Space: O(n), because
doubledallocates a2n-character string andinteriorallocates a(2n - 2)-character slice.
Edge cases
- Single character (
"m"): ReturnsFalse(caught immediately bylen(s) < 2, and(s + s)[1:-1]is""anyway). - One repeated letter (
"kk","zzzz","bbbbbbb"): ReturnsTrueeven whennis odd or prime, using the 1-letter block repeatedntimes. - Incomplete trailing block (
"xyxyxyx"): ReturnsFalsebecause7is not divisible by2; indoubled, the"xx"seam between copies stops"xyxyxyx"from matching insideinterior. - Repeating block contains internal repeats of
s[0]("xyxxyx","xxzxxz"): ReturnsTrueusing the 3-letter block ("xyx"or"xxz"), where greedy prefix heuristics fail. - Prime length with mixed characters (
"pqp","abcde"): Only a 1-letter block divides a prime lengthn, so any prime-length string containing two or more distinct letters returnsFalse. - Near-miss at maximum length (
"x" * 9999 + "y"): ReturnsFalseafter checking all shifts within fractions of a millisecond.
Common mistakes
- Checking
s in (s + s)without slicing off the ends:salways matches at index0, returningTrueon every input! - Trimming only one end (
(s + s)[1:]or(s + s)[:-1]): Keeping the right end preserves the trivial match at indexn, and keeping the left end preserves index0, so both still returnTrueunconditionally. - Testing
block_lenup toninstead ofn // 2in a divisor loop: Allowingblock_len == nrepeatssonce (s * 1 == s), turning every stringTrue. - Counting character frequencies (
Counter(s)): Equal or divisible letter counts (such as"xxyy") do not mean the letters repeat in the same order ("xxyy"isFalse). - Checking
s[i] == s[i - d]without requiringn % d == 0: On"xyxyxyx"(n = 7,d = 2),s[i] == s[i - 2]holds for everyi >= 2, yet"xy"does not tile length7evenly.
Alternative approaches
- Divisor prefix check (
O(n * divisors(n))time,O(1)extra space when compared index-by-index): Loopdfrom1ton // 2; whenevern % d == 0, testall(s[i] == s[i - d] for i in range(d, n)). Sincen <= 10^4has at most64divisors, this runs quickly with zero string allocations. - Knuth-Morris-Pratt (KMP) prefix table (
O(n)time guaranteed,O(n)space): Computes the longest border ofsin one linear scan and checks whether the implied period dividesn.
Follow-up questions
- How can you guarantee strict linear O(n) runtime without depending on how the language's built-in substring search is implemented? Construct the Knuth-Morris-Pratt (KMP) prefix table
lps, wherelps[i]stores the length of the longest proper prefix (a prefix strictly shorter than the substring itself) ofs[:i + 1]that also appears as a suffix ofs[:i + 1]. Letborder = lps[n - 1]andperiod = n - border;sis formed by repeating a shorter block if and only ifborder > 0andn % period == 0, which runs in guaranteed O(n) time using simple array indexing. - If the function needed to return the smallest repeating unit itself (or an empty string when none exists), how would you modify the algorithm? Locate the earliest match index starting at offset
1ins + s:first_shift = (s + s).find(s, 1). Because every valid rotation shift is a positive multiple of the shortest repeating block's length,first_shiftequals the shortest unit's length wheneverfirst_shift < len(s)(returnings[:first_shift], such as"mno"for"mnomnomnomno", or""whenfirst_shift == len(s)orlen(s) < 2). Using KMP,period = n - lps[n - 1]directly yields the shortest units[:period]wheneverlps[n - 1] > 0andn % period == 0. - What is the peak memory overhead on multi-gigabyte strings, and how could you solve the problem in O(1) extra space? Allocating
doubled = s + s(2ncharacters) alongsideinterior = doubled[1:-1](2n - 2characters) briefly holds roughly4nextra characters in memory — around4 GBof peak overhead for a1 GBASCII input! KMP likewise needs ann-entry integer array (4 GBto8 GBatn = 10^9). To keep auxiliary space strictly O(1) on massive strings or memory-mapped files, iterate over proper divisorsdofnand compares[i] == s[i - d]in place ford <= i < nusing two integer indices, allocating zero extra buffers.
Follow-up questions
- How can you guarantee strict linear O(n) runtime without depending on how the language's built-in substring search is implemented?
- If the function needed to return the smallest repeating unit itself (or an empty string when none exists), how would you modify the algorithm?
- What is the peak memory overhead on multi-gigabyte strings, and how could you solve the problem in O(1) extra space?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array