Repeated Word Subsequence Check

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

You are given a text string s, a pattern string t, and a positive integer k. Let P denote the virtual string produced by writing t back-to-back k times (t + t + ... + t, containing k * len(t) characters in total).

Return True if P occurs inside s as a subsequence, and False otherwise.

A string P of length m is a subsequence of s when there exist strictly increasing indices 0 <= i_0 < i_1 < ... < i_{m - 1} < len(s) such that s[i_j] == P[j] for every 0 <= j < m. Equivalently, you can form P by crossing out any subset of positions in s and reading the remaining characters from left to right.

Implement is_k_subsequence(s: str, t: str, k: int) -> bool. Because k can be up to 10^9, explicitly constructing the repeated string P in memory is not feasible.

Examples

Example 1

  • Input: s = "mpqrstmpr", t = "mpr", k = 2
  • Output: True
  • Explanation: Repeating "mpr" twice yields "mprmpr". Reading indices 0, 1, 3, 6, 7, 8 of "mpqrstmpr" (skipping 'q', 's', and 't') spells "mprmpr" in left-to-right order.

Example 2

  • Input: s = "xyxzxyx", t = "xyz", k = 2
  • Output: False
  • Explanation: Repeating "xyz" twice requires "xyzxyz". Indices 0, 1, 3 match the first copy "xyz", and indices 4, 5 match "xy", leaving no second 'z' anywhere after index 5.

Constraints

  • 1 <= len(s) <= 10^6
  • 1 <= len(t) <= 10^5
  • 1 <= k <= 10^9

Step-by-step walkthrough

  1. Understand subsequences, scale limits, and the examples

    We receive a text string s (up to 10^6 characters), a pattern t (up to 10^5 characters), and a repeat count k (up to 10^9). We want to return True when t written k times in a row (t + t + ... + t) appears inside s as a subsequence, and False otherwise.

    Matching a subsequence means picking strictly increasing indices in s from left to right while skipping any unneeded characters in between. Because each index of s can be used at most once, copy 2 of t must begin strictly to the right of where copy 1 ends.

    Look at why k up to 10^9 changes how we approach the problem: - The virtual pattern length k * len(t) can reach 10^14. Allocating t * k in RAM would demand roughly 100 terabytes and crash with MemoryError before we inspect a single character. - Even when len(s) >= k * len(t), all k copies must complete before s runs out, as in Example 2 (s = "xyxzxyx", t = "xyz", k = 2):

    s = "x  y  x  z  x  y  x"
         ^  ^     ^  ^  ^
         x  y     z  x  y  (still need a second 'z', and s has ended -> False)
    
  2. Prune impossible lengths in O(1) time

    Every character in the k-fold pattern consumes its own distinct index in s. That gives us an immediate constant-time filter: - Compute total_needed = k * len(t). - Whenever total_needed > len(s), s is physically too short to hold k copies of t, so we return False in O(1) time without touching s.

    We also include a defensive guard for total_needed == 0 (covering k == 0 or t == ""), since an empty pattern matches every string:

    target_len = len(t)
    total_needed = k * target_len
    
    if total_needed == 0:
        # Empty repeated string is always a subsequence of `s`.
        result = True
    elif total_needed > len(s):
        # Cannot fit `total_needed` characters inside a shorter string `s`.
        result = False
    

    Python integers grow to arbitrary precision automatically, so k * target_len never overflows even at 10^14 (in C++ or Java, store total_needed in a 64-bit long long / long).

  3. Why greedy left-to-right matching is always optimal

    As we walk through s from left to right looking for the next required character, should we always match the earliest occurrence we encounter, or could waiting for a later occurrence ever help?

    Grabbing the earliest match is always safe. Suppose we currently need 'm', and 'm' appears in s at index 1 and again at index 5:

    Index in s:    0   1   2   3   4   5   6   7   8
    Characters:    q   m   p   r   s   m   p   r   t
                       ^               ^
                 early match         later match
                 leaves s[2..8]      leaves only s[6..8]
    

    If some valid subsequence matched 'm' at index 5 and found all remaining characters inside s[6..8], swapping that 'm' to index 1 keeps every character in s[6..8] strictly to the right of index 1. Taking the earliest match leaves the longest possible suffix of s for everything still needed, so a single greedy pass finds a valid subsequence whenever one exists.

  4. Simulate `t` repeated `k` times with wrap-around indexing

    Rather than building t + t + ... + t, let an integer matched count how many characters of the virtual repeated string we have matched so far (0, 1, ..., total_needed - 1). Which character of t do we need next?

    Watch how matched % len(t) cycles cleanly across t = "mpr" (target_len = 3):

    Copy number:       |--- Copy 1 ---|--- Copy 2 ---|--- Copy 3 ---|
    matched:             0    1    2  |  3    4    5 |  6    7    8
    matched % 3:         0    1    2  |  0    1    2 |  0    1    2
    t[matched % 3]:     'm'  'p'  'r' | 'm'  'p'  'r'| 'm'  'p'  'r'
    

    Each time matched hits a multiple of target_len, matched % target_len wraps straight back to 0 for the start of the next copy—requiring O(1) memory.

  5. Write the single-pass scan

    Combine the O(1) length check, wrap-around indexing, and greedy scan into one loop over s. Whenever ch == t[matched % target_len], increment matched; as soon as matched == total_needed, all k copies are matched and we return True.

    def is_k_subsequence(s: str, t: str, k: int) -> bool:
        target_len = len(t)
        # Virtual length of `t` repeated `k` times; we never materialize `t * k` in memory.
        total_needed = k * target_len
    
        # Defensive base case: 0 needed characters (e.g., k == 0 or empty t) always fit.
        if total_needed == 0:
            return True
    
        # Each matched character consumes a distinct position in `s`, so `s` must be long enough.
        if total_needed > len(s):
            return False
    
        # matched: count of characters from virtual string (t + t + ... + t) matched in `s` so far
        matched = 0
        for ch in s:
            # Modulo wraps `matched` back to 0..target_len-1 at the start of each copy of `t`.
            wanted_char = t[matched % target_len]
            if ch == wanted_char:
                matched += 1
                # Return immediately once all `k` copies of `t` have been matched in order.
                if matched == total_needed:
                    return True
    
        return False
    
  6. Trace both examples and a length-pruned case

    Let's walk through three inputs step by step:

    Case 1 (Example 1): s = "mpqrstmpr", t = "mpr", k = 2 -> total_needed = 6 <= 9
      i=0 ('m'): wants t[0]='m' -> match! matched = 1
      i=1 ('p'): wants t[1]='p' -> match! matched = 2
      i=2 ('q'): wants t[2]='r' -> skip
      i=3 ('r'): wants t[2]='r' -> match! matched = 3 (Copy 1 complete!)
      i=4 ('s'): wants t[0]='m' -> skip
      i=5 ('t'): wants t[0]='m' -> skip
      i=6 ('m'): wants t[0]='m' -> match! matched = 4
      i=7 ('p'): wants t[1]='p' -> match! matched = 5
      i=8 ('r'): wants t[2]='r' -> match! matched = 6 == 6 -> returns True!
    
    Case 2 (Example 2): s = "xyxzxyx", t = "xyz", k = 2 -> total_needed = 6 <= 7
      'x' (matched=1), 'y' (matched=2), 'x' (skip), 'z' (matched=3, Copy 1 done),
      'x' (matched=4), 'y' (matched=5), 'x' (skip)
      End of s with matched = 5 < 6 -> returns False
    
    Case 3 (Length pruned): s = "mpr", t = "mpr", k = 2 -> total_needed = 6 > len(s) = 3
      Fails total_needed > len(s) immediately -> returns False
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def is_k_subsequence(s: str, t: str, k: int) -> bool:
        target_len = len(t)
        # Virtual length of `t` repeated `k` times; we never materialize `t * k` in memory.
        total_needed = k * target_len
    
        # Defensive base case: 0 needed characters (e.g., k == 0 or empty t) always fit.
        if total_needed == 0:
            return True
    
        # Each matched character consumes a distinct position in `s`, so `s` must be long enough.
        if total_needed > len(s):
            return False
    
        # matched: count of characters from virtual string (t + t + ... + t) matched in `s` so far
        matched = 0
        for ch in s:
            # Modulo wraps `matched` back to 0..target_len-1 at the start of each copy of `t`.
            wanted_char = t[matched % target_len]
            if ch == wanted_char:
                matched += 1
                # Return immediately once all `k` copies of `t` have been matched in order.
                if matched == total_needed:
                    return True
    
        return False
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine walking once down a long warehouse aisle (s) trying to pick the items on a short packing slip (t) k times in sequence. A subsequence (a string formed by matching characters at strictly increasing positions in s, skipping any unwanted characters in between) means you only ever walk forward down the aisle without turning around. Rather than printing a gigantic k-page packing list, you combine a greedy algorithm (making the locally best choice at every step—grabbing each needed item at the earliest shelf where it appears so the maximum aisle remains ahead) with modular arithmetic (computing the remainder matched % len(t) so your finger wraps back to index 0 of t each time a copy finishes).

Why do obvious shortcuts fail? Allocating t * k when len(t) = 10^5 and k = 10^9 tries to construct a 10^14-character string (~100 terabytes of RAM), crashing immediately. Comparing character frequency tables in s and t also falls short: "aabb" holds two 'a's and two 'b's, yet "ab" repeated twice ("abab") is not a subsequence of "aabb" because both 'a's occur before the first 'b'.

Here is how the single pass with wrap-around indexing runs on Example 1 (s = "mpqrstmpr", t = "mpr", k = 2, total_needed = 6):

s:                 m    p    q    r    s    t    m    p    r
matched before:    0    1    2    2    3    3    3    4    5
wanted t[m % 3]:  'm'  'p'  'r'  'r'  'm'  'm'  'm'  'p'  'r'
action:           HIT  HIT  skip HIT  skip skip HIT  HIT  HIT -> matched = 6 == total_needed -> True!

Complexity

  • Time: O(|s|) in the worst case, and O(1) whenever k * |t| > |s|. Multiplying k * len(t) and comparing it to len(s) takes constant time. When total_needed <= len(s), we scan s at most once, doing one constant-time remainder lookup and character comparison per step.
  • Space: O(1) auxiliary space. Only scalar variables (target_len, total_needed, matched, wanted_char) are stored; t * k is never allocated.

Edge cases

  • Huge k (k = 10^9): Whenever k * len(t) > len(s) (guaranteed once k > 10^6, since len(t) >= 1 and len(s) <= 10^6), total_needed > len(s) returns False in O(1) time without scanning s.
  • Characters in t absent from s (s = "abcabc", t = "abd", k = 1): matched stalls waiting for 'd' and the loop ends with matched < total_needed, returning False.
  • t longer than s (s = "ab", t = "abc", k = 1): Rejected immediately by total_needed > len(s).
  • Exact-length fit (s = "abcabc", t = "abc", k = 2): Every character of s matches and the last character hits matched == total_needed, returning True.
  • Adjacent copies attempting to share a boundary character (s = "aababa", t = "aba", k = 2): Copy 1 consumes indices 0, 2, 3 ("aba"), and the loop moves past index 3 before seeking copy 2's opening 'a', returning False rather than reusing s[3].
  • Zero repetitions (k = 0) or empty t (defensive guard): Handled up front by if total_needed == 0: return True, preventing modulo-by-zero in matched % target_len.

Common mistakes

  • Materializing t * k in memory: t * k raises MemoryError or OverflowError on large k before any scan begins.
  • Searching for contiguous substrings (s.find(t, pos)): Subsequences allow arbitrary skipped characters inside a copy ("m_p_r" matches "mpr"), whereas s.find requires contiguous blocks.
  • Checking character frequencies without order: Having >= k * count(ch) of each letter is necessary, never sufficient ("aabb" vs "abab").
  • Restarting the scan of s from index 0 per copy: Verifying t fits once does not mean k copies fit; copy 2 must appear strictly after copy 1 ends.
  • 32-bit integer overflow in C++ or Java: k * t.length() can reach 10^14, overflowing a 32-bit int (~2.1 * 10^9) unless stored in a 64-bit integer (long long / long) or written as k > s.length() / t.length().

Alternative approaches

  • Two explicit counters instead of % (O(|s|) time, O(1) space): Maintain t_idx (0 .. len(t) - 1) and copies_done (0 .. k). On ch == t[t_idx], increment t_idx; when t_idx == len(t), reset t_idx = 0 and increment copies_done, returning True once copies_done == k. This avoids integer division inside the loop in low-level languages.
  • Frequency pre-filter (O(|s| + |t|)): Counting characters in s and t can reject inputs where count_s[c] < k * count_t[c], though the single-pass greedy scan already finishes in O(|s|) time with O(1) space.

Follow-up questions

  • Suppose s and t stay fixed while thousands of queries ask about different repetition counts k. How can you answer each query in O(1) time after preprocessing? Exploit monotonicity (if k copies of t fit as a subsequence, every smaller count < k automatically fits too, since (k - 1) copies form a prefix of k copies). Run the greedy wrap-around scan across s once without returning early to count total matched characters total_matched, store max_k = total_matched // len(t), and answer any query k in O(1) time via k <= max_k.
  • How would you compute the largest integer k >= 0 for which k back-to-back copies of t still form a subsequence of s? Use that exact unbounded single pass: start matched = 0, iterate over every ch in s incrementing matched whenever ch == t[matched % len(t)], and return matched // len(t) in O(|s|) time and O(1) space. Because taking the earliest match at every step always leaves the longest possible suffix of s, no valid subsequence can complete more copies of t; binary searching on k also works in O(|s| log(|s| / |t|)) time.
  • If s is indexed once into sorted position lists per character, what is the runtime of a (t, k) query, and when is that faster than scanning s? Build positions[ch] mapping each distinct character to its sorted index list in s (O(|s|) preprocessing time and space). To test (t, k) after rejecting k * |t| > |s|, start curr_pos = -1 and for each of the k * |t| needed characters run binary search (bisect_right(positions[ch], curr_pos)—halving the sorted index list to jump to the earliest index strictly greater than curr_pos) in O(log |s|) time. Total query time is O(k * |t| * log |s|), which beats O(|s|) whenever k * |t| is much smaller than |s| across many queries with varying t.

Follow-up questions

Similar questions

More Quince interview questions

All 2 Quince questions →