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 >= 2 times 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 s is a lowercase English letter ('a'–'z').
  • Using s itself once (k = 1) does not count; consequently, any 1-character string returns False, whereas any string of 2 or more identical letters returns True.

Step-by-step walkthrough

  1. Understand what counts as a repetition

    Given a non-empty lowercase string s of length n (1 <= n <= 10^4), we must return True if there is a shorter non-empty substring block that can be repeated 2 or more times back-to-back to form s (s == block * k with k >= 2), and False otherwise.

    Three quick observations anchor our intuition:

    • Single-character strings ("m") are always False, because repeating any non-empty block at least twice produces at least 2 characters.
    • All-identical strings of length >= 2 ("kk", "zzzz") are True, using the 1-character block ("k" twice or "z" four times).
    • Partial leftovers are False: "xyxyxyx" (length 7) repeats "xy" three and a half times, which does not tile s with whole copies.
  2. Brute force: test divisor block lengths

    If s consists of k >= 2 copies of block, two properties must hold:

    1. block must begin at index 0 (so block == s[:block_len]), and
    2. block_len must divide n evenly (n % block_len == 0) with 1 <= block_len <= n // 2.

    Checking only divisor lengths up to n // 2 already avoids testing all O(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 False
    

    Because an integer n <= 10,000 has at most 64 divisors, this loop runs in O(n * divisors(n)) time and serves well as a brute-force reference in tests.py. Even better, a clean rotation property lets us test every non-trivial shift in one substring search.

  3. Key idea: double the string and trim both ends

    Join two copies of s into doubled = s + s. Every window of length n inside doubled is a cyclic rotation of s (moving the first shift letters of s to 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! -> True
    

    Compare 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! -> False
    

    Slicing off index 0 destroys the trivial match at the left end, and slicing off index 2n - 1 destroys the trivial match at the right end. Only genuine rotations (1 <= shift <= n - 1) survive inside interior.

  4. Why matching inside the trimmed double is exact

    Let's confirm why s in (s + s)[1:-1] evaluates to True if and only if s is formed by repeating a smaller block:

    • Direction 1 (Repeated block -> found in interior): Suppose s consists of k >= 2 copies of block of length m = len(block). Then doubled = s + s consists of 2k copies of block in a row. Starting right after the first block (at index m of doubled) gives k consecutive blocks — an exact copy of s! Since k >= 2, 1 <= m <= n // 2 < n, so this copy begins after index 0 and ends before index 2n - 1, placing it completely inside interior = doubled[1:-1].
    • Direction 2 (Found in interior -> repeated block): Suppose s matches inside interior, corresponding to some index shift in doubled with 1 <= shift <= n - 1. That means rotating s left by shift slots leaves s unchanged! Even if shift does not divide n directly — say s = "xyxyxy" (n = 6) matched at shift = 4 — rotating by 4 a second time wraps around 6 ((4 + 4) % 6 = 2), which also leaves s unchanged! Repeating a step of shift around a circle of size n always reaches g = gcd(shift, n), where the greatest common divisor (gcd) is the largest positive integer dividing both shift and n. Because g divides n and 1 <= g <= shift < n, s partitions evenly into n // g >= 2 identical copies of s[:g].
  5. 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!)  False
    

    Look closely at "xyxyxyx": where the two copies meet in doubled, "xyxyxyx" + "xyxyxyx" creates "xx" at the seam, preventing "xyxyxyx" (where 'x' and 'y' strictly alternate) from matching at any interior shift!

  6. 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):

  1. On "xyxy": doubled = "xyxyxyxy", and trimming both ends gives interior = "yxyxyx". Checking "xyxy" in "yxyxyx" finds "xyxy" starting at index 1 ("y[xyxy]x"), so we return True.
  2. On "pqp": doubled = "pqppqp", and trimming both ends gives interior = "qppq". Checking "pqp" in "qppq" finds no match, so we return False.

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). Building s + s and slicing [1:-1] each copy O(n) characters once, and CPython's in operator 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 doubled allocates a 2n-character string and interior allocates a (2n - 2)-character slice.

Edge cases

  • Single character ("m"): Returns False (caught immediately by len(s) < 2, and (s + s)[1:-1] is "" anyway).
  • One repeated letter ("kk", "zzzz", "bbbbbbb"): Returns True even when n is odd or prime, using the 1-letter block repeated n times.
  • Incomplete trailing block ("xyxyxyx"): Returns False because 7 is not divisible by 2; in doubled, the "xx" seam between copies stops "xyxyxyx" from matching inside interior.
  • Repeating block contains internal repeats of s[0] ("xyxxyx", "xxzxxz"): Returns True using 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 length n, so any prime-length string containing two or more distinct letters returns False.
  • Near-miss at maximum length ("x" * 9999 + "y"): Returns False after checking all shifts within fractions of a millisecond.

Common mistakes

  • Checking s in (s + s) without slicing off the ends: s always matches at index 0, returning True on every input!
  • Trimming only one end ((s + s)[1:] or (s + s)[:-1]): Keeping the right end preserves the trivial match at index n, and keeping the left end preserves index 0, so both still return True unconditionally.
  • Testing block_len up to n instead of n // 2 in a divisor loop: Allowing block_len == n repeats s once (s * 1 == s), turning every string True.
  • Counting character frequencies (Counter(s)): Equal or divisible letter counts (such as "xxyy") do not mean the letters repeat in the same order ("xxyy" is False).
  • Checking s[i] == s[i - d] without requiring n % d == 0: On "xyxyxyx" (n = 7, d = 2), s[i] == s[i - 2] holds for every i >= 2, yet "xy" does not tile length 7 evenly.

Alternative approaches

  • Divisor prefix check (O(n * divisors(n)) time, O(1) extra space when compared index-by-index): Loop d from 1 to n // 2; whenever n % d == 0, test all(s[i] == s[i - d] for i in range(d, n)). Since n <= 10^4 has at most 64 divisors, this runs quickly with zero string allocations.
  • Knuth-Morris-Pratt (KMP) prefix table (O(n) time guaranteed, O(n) space): Computes the longest border of s in one linear scan and checks whether the implied period divides n.

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, where lps[i] stores the length of the longest proper prefix (a prefix strictly shorter than the substring itself) of s[:i + 1] that also appears as a suffix of s[:i + 1]. Let border = lps[n - 1] and period = n - border; s is formed by repeating a shorter block if and only if border > 0 and n % 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 1 in s + 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_shift equals the shortest unit's length whenever first_shift < len(s) (returning s[:first_shift], such as "mno" for "mnomnomnomno", or "" when first_shift == len(s) or len(s) < 2). Using KMP, period = n - lps[n - 1] directly yields the shortest unit s[:period] whenever lps[n - 1] > 0 and n % 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 (2n characters) alongside interior = doubled[1:-1] (2n - 2 characters) briefly holds roughly 4n extra characters in memory — around 4 GB of peak overhead for a 1 GB ASCII input! KMP likewise needs an n-entry integer array (4 GB to 8 GB at n = 10^9). To keep auxiliary space strictly O(1) on massive strings or memory-mapped files, iterate over proper divisors d of n and compare s[i] == s[i - d] in place for d <= i < n using two integer indices, allocating zero extra buffers.

Follow-up questions

Similar questions

More Beaconfire interview questions

All 1 Beaconfire questions →