KatInterview

Find a Block Repeated Back-to-Back in a Token List

StringsAuto-graded · 25 test cases
MediumAuto-gradedStringsstringsarrayssliding-window

Last 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 length block_len counts as a single occurrence, so the answer is True whenever block_len <= len(tokens).
  • Return False if block_len <= 0 or times <= 0.
  • Return False if block_len > len(tokens).
  • Return False if block_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

  • tokens is a list of strings. It may be long, so aim for time linear in its length.
  • Normal inputs have block_len >= 1 and times >= 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.