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 indices0, 1, 3, 6, 7, 8of"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". Indices0, 1, 3match the first copy"xyz", and indices4, 5match"xy", leaving no second'z'anywhere after index5.
Constraints
1 <= len(s) <= 10^61 <= len(t) <= 10^51 <= k <= 10^9
Step-by-step walkthrough
Understand subsequences, scale limits, and the examples
We receive a text string
s(up to10^6characters), a patternt(up to10^5characters), and a repeat countk(up to10^9). We want to returnTruewhentwrittenktimes in a row (t + t + ... + t) appears insidesas a subsequence, andFalseotherwise.Matching a subsequence means picking strictly increasing indices in
sfrom left to right while skipping any unneeded characters in between. Because each index ofscan be used at most once, copy2oftmust begin strictly to the right of where copy1ends.Look at why
kup to10^9changes how we approach the problem: - The virtual pattern lengthk * len(t)can reach10^14. Allocatingt * kin RAM would demand roughly 100 terabytes and crash withMemoryErrorbefore we inspect a single character. - Even whenlen(s) >= k * len(t), allkcopies must complete beforesruns 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)Prune impossible lengths in O(1) time
Every character in the
k-fold pattern consumes its own distinct index ins. That gives us an immediate constant-time filter: - Computetotal_needed = k * len(t). - Whenevertotal_needed > len(s),sis physically too short to holdkcopies oft, so we returnFalseinO(1)time without touchings.We also include a defensive guard for
total_needed == 0(coveringk == 0ort == ""), 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 = FalsePython integers grow to arbitrary precision automatically, so
k * target_lennever overflows even at10^14(in C++ or Java, storetotal_neededin a 64-bitlong long/long).Why greedy left-to-right matching is always optimal
As we walk through
sfrom 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 insat index1and again at index5: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 index5and found all remaining characters insides[6..8], swapping that'm'to index1keeps every character ins[6..8]strictly to the right of index1. Taking the earliest match leaves the longest possible suffix ofsfor everything still needed, so a single greedy pass finds a valid subsequence whenever one exists.Simulate `t` repeated `k` times with wrap-around indexing
Rather than building
t + t + ... + t, let an integermatchedcount how many characters of the virtual repeated string we have matched so far (0, 1, ..., total_needed - 1). Which character oftdo we need next?Watch how
matched % len(t)cycles cleanly acrosst = "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
matchedhits a multiple oftarget_len,matched % target_lenwraps straight back to0for the start of the next copy—requiringO(1)memory.Write the single-pass scan
Combine the
O(1)length check, wrap-around indexing, and greedy scan into one loop overs. Wheneverch == t[matched % target_len], incrementmatched; as soon asmatched == total_needed, allkcopies are matched and we returnTrue.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 FalseTrace 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 FalseComplete 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, andO(1)wheneverk * |t| > |s|. Multiplyingk * len(t)and comparing it tolen(s)takes constant time. Whentotal_needed <= len(s), we scansat 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 * kis never allocated.
Edge cases
- Huge
k(k = 10^9): Wheneverk * len(t) > len(s)(guaranteed oncek > 10^6, sincelen(t) >= 1andlen(s) <= 10^6),total_needed > len(s)returnsFalseinO(1)time without scannings. - Characters in
tabsent froms(s = "abcabc",t = "abd",k = 1):matchedstalls waiting for'd'and the loop ends withmatched < total_needed, returningFalse. tlonger thans(s = "ab",t = "abc",k = 1): Rejected immediately bytotal_needed > len(s).- Exact-length fit (
s = "abcabc",t = "abc",k = 2): Every character ofsmatches and the last character hitsmatched == total_needed, returningTrue. - Adjacent copies attempting to share a boundary character (
s = "aababa",t = "aba",k = 2): Copy 1 consumes indices0, 2, 3("aba"), and the loop moves past index3before seeking copy 2's opening'a', returningFalserather than reusings[3]. - Zero repetitions (
k = 0) or emptyt(defensive guard): Handled up front byif total_needed == 0: return True, preventing modulo-by-zero inmatched % target_len.
Common mistakes
- Materializing
t * kin memory:t * kraisesMemoryErrororOverflowErroron largekbefore any scan begins. - Searching for contiguous substrings (
s.find(t, pos)): Subsequences allow arbitrary skipped characters inside a copy ("m_p_r"matches"mpr"), whereass.findrequires 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
sfrom index0per copy: Verifyingtfits once does not meankcopies fit; copy2must appear strictly after copy1ends. - 32-bit integer overflow in C++ or Java:
k * t.length()can reach10^14, overflowing a 32-bitint(~2.1 * 10^9) unless stored in a 64-bit integer (long long/long) or written ask > s.length() / t.length().
Alternative approaches
- Two explicit counters instead of
%(O(|s|)time,O(1)space): Maintaint_idx(0 .. len(t) - 1) andcopies_done(0 .. k). Onch == t[t_idx], incrementt_idx; whent_idx == len(t), resett_idx = 0and incrementcopies_done, returningTrueoncecopies_done == k. This avoids integer division inside the loop in low-level languages. - Frequency pre-filter (
O(|s| + |t|)): Counting characters insandtcan reject inputs wherecount_s[c] < k * count_t[c], though the single-pass greedy scan already finishes inO(|s|)time withO(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
kcopies oftfit as a subsequence, every smaller count< kautomatically fits too, since(k - 1)copies form a prefix ofkcopies). Run the greedy wrap-around scan acrosssonce without returning early to count total matched characterstotal_matched, storemax_k = total_matched // len(t), and answer any querykinO(1)time viak <= 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 everychinsincrementingmatchedwheneverch == t[matched % len(t)], and returnmatched // len(t)inO(|s|)time andO(1)space. Because taking the earliest match at every step always leaves the longest possible suffix ofs, no valid subsequence can complete more copies oft; binary searching onkalso works inO(|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 ins(O(|s|)preprocessing time and space). To test(t, k)after rejectingk * |t| > |s|, startcurr_pos = -1and for each of thek * |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 thancurr_pos) inO(log |s|)time. Total query time isO(k * |t| * log |s|), which beatsO(|s|)wheneverk * |t|is much smaller than|s|across many queries with varyingt.
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?
- How would you compute the largest integer k >= 0 for which k back-to-back copies of t still form a subsequence of s?
- 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?
Similar questions
- Minimum Sprinklers Needed to Water a Linear Garden
- 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