Find a Block Repeated Back-to-Back in a Token List
StringsAuto-graded · 25 test casesLast updated
Decide whether a list of tokens contains a block of a given length repeated a given number of times in a row, testing period detection with a linear scan.
Back-to-Back Block Repeats
You receive a list of string tokens tokens and two integers, block_len and times.
A block is any run of block_len neighbouring tokens. Decide whether some block occurs times times in a row, with each copy starting exactly where the previous copy ended. In other words, there must be a start index i such that the slice tokens[i : i + block_len * times] is the same block of length block_len written out times times.
Return True if such a position exists, otherwise False.
Rules
- Tokens are indivisible. Compare whole tokens for equality, never individual characters. For example,
["ab", "c"]and["a", "bc"]are different. - The copies must be adjacent, with no gaps and no tokens between them.
- If
times == 1, any block of lengthblock_lencounts as a single occurrence, so the answer isTruewheneverblock_len <= len(tokens). - Return
Falseifblock_len <= 0ortimes <= 0. - Return
Falseifblock_len > len(tokens). - Return
Falseifblock_len * times > len(tokens), since the repeated stretch cannot fit. - An empty list always gives
False.
Function
Implement has_block_repeated(tokens, block_len, times) -> bool.
Constraints
tokensis a list of strings. It may be long, so aim for time linear in its length.- Normal inputs have
block_len >= 1andtimes >= 1. Out-of-range values must follow the rules above. - Tokens are compared by exact string equality.
Examples
Example 1
Input: has_block_repeated(['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'], 3, 3)
Output: True
Example 2
Input: has_block_repeated(['x', 'y', 'x', 'y', 'x', 'y'], 2, 2)
Output: True
Example 3
Input: has_block_repeated(['a', 'b', 'a', 'b', 'c'], 2, 3)
Output: False
Hints
Hint 1
A stretch made of `times` copies of one block of length `block_len` has period `block_len`: each token equals the token `block_len` positions later.
Hint 2
You do not need to extract or compare whole blocks. Count how many consecutive indices `j` satisfy `tokens[j] == tokens[j + block_len]`.
Hint 3
You need `(times - 1) * block_len` consecutive matching indices. Reset your counter to zero on any mismatch, and handle `times == 1` and the size checks before scanning.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A stretch of tokens that consists of one block repeated times times has period block_len: every token equals the token block_len positions after it, for all positions except those in the last copy.
So we need (times - 1) * block_len consecutive indices j where tokens[j] == tokens[j + block_len].
- Handle the degenerate cases first:
- Return
Falseifblock_len <= 0,times <= 0, orblock_len > n. - Return
Trueiftimes == 1, because any block counts once. - Return
Falseifblock_len * times > n, because the stretch cannot fit.
- Return
- Scan
jfrom0ton - block_len - 1. Keep a counterstreakof consecutive indices wheretokens[j] == tokens[j + block_len]. - Reset
streakto0on a mismatch. - Return
Trueas soon asstreakreaches(times - 1) * block_len. - If the scan ends without that, return
False.
Why it is correct
- If a repeated stretch exists: suppose it starts at
i. Every token in the firsttimes - 1copies equals the tokenblock_lenpositions later, since both come from the same place in the block. That gives(times - 1) * block_lenconsecutive matches starting ati, so the streak reaches the threshold. - If the streak reaches the threshold: suppose it ends at index
e, and leti = e - needed + 1. Thentokens[j] == tokens[j + block_len]for everyjin[i, i + needed). By induction, copytequals copyt - 1for eachtfrom 1 totimes - 1, so all copies are equal. The stretch ends ate + block_len <= n - 1, so it fits inside the list. - Resetting on a mismatch is safe: a mismatch at
jmeans no valid stretch can include the comparison atj, so restarting right after it loses no candidate.
Complexity
- Time: O(n) token comparisons, independent of
block_len. Each comparison costs up to the length of the strings compared. Mapping each distinct string to an integer first makes every comparison O(1). - Space: O(1) extra.
Reference solution
from typing import List
def has_block_repeated(tokens: List[str], block_len: int, times: int) -> bool:
n = len(tokens)
if block_len <= 0 or times <= 0 or block_len > n:
return False
if times == 1:
return True
if block_len * times > n:
return False
needed = (times - 1) * block_len
streak = 0
for j in range(n - block_len):
if tokens[j] == tokens[j + block_len]:
streak += 1
if streak >= needed:
return True
else:
streak = 0
return False