Detect a Contiguous Block Inside an Integer Sequence
StringsAuto-graded · 22 test casesLast updated
Tests the ability to determine whether one integer array appears as an unbroken, in-order block inside a larger array using linear-time pattern matching.
Problem Statement
You have two integer arrays: pattern and stream. Your task is to decide whether pattern appears somewhere inside stream as a consecutive, uninterrupted block — meaning the same values, in the same order, with no elements in between.
Write a function find_block(pattern, stream) that returns True if such a block exists, and False otherwise.
Rules
- Every element of
patternmust appear instreamin the same relative order. - The elements of
patternmust occupy adjacent positions instream— no gaps allowed. - An empty
patternis considered to be present in anystream. - If
patternis longer thanstream, a match is impossible.
Constraints
1 <= len(pattern) <= 10^51 <= len(stream) <= 10^6- Each element is an integer in the range
[-10^9, 10^9]. - Elements may repeat within either array.
Examples
Example 1
Input: find_block([1, 2, 3], [5, 1, 2, 3, 9])
Output: True
Example 2
Input: find_block([1, 2, 3], [1, 3, 2, 3])
Output: False
Hints
Hint 1
Think of this as the classic substring search problem, just over integers instead of characters. What O(N + M) algorithm solves substring search?
Hint 2
Before scanning `stream`, preprocess `pattern` into a table that tells you, whenever a mismatch occurs at position i, how far back you can safely "rewind" in `pattern` without missing a valid match. This lets you scan `stream` from left to right, never moving backward.
Hint 3
For each index i in `pattern`, compute the length of the longest proper prefix of `pattern[0..i]` that is also a suffix of that same slice. Use that table to drive the fallback logic during the scan of `stream`.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is integer-array substring search. The question is whether pattern appears as a consecutive block anywhere inside stream, which is exactly what the Knuth–Morris–Pratt (KMP) algorithm answers in O(N + M) time.
Why a naive scan is too slow
A brute-force approach tries every possible starting offset in stream and compares up to len(pattern) elements at each one. In the worst case — think pattern = [1, 1, ..., 1, 2] against stream = [1, 1, ..., 1] — that costs O(N × M) comparisons, which at the given limits is around 10¹¹ operations, far too slow.
The waste comes from re-examining elements of stream we have already seen. KMP eliminates that waste entirely.
The KMP insight
When a partial match fails at position i in pattern, we already know what the last few elements of stream looked like — they matched the first i elements of pattern. Rather than throwing all of that away and starting from scratch, KMP asks: "What is the longest prefix of pattern that is still consistent with what I just read?" That answer is precomputed in the failure table (also called the LPS array), and it lets us slide pattern forward by the maximum safe amount without ever stepping backward in stream.
Two phases
Phase 1 — Build the failure table.
For each index i, lps[i] is the length of the longest proper prefix of pattern[0..i] that is also a suffix of pattern[0..i]. "Proper" means strictly shorter than the whole slice. The table is built by running the same match logic on pattern against itself, starting at index 1 (index 0 is excluded because a proper border cannot span the whole string).
Phase 2 — Scan stream.
Walk through stream once, maintaining matched: the number of leading pattern elements currently aligned with the tail of what has been read so far.
- If the next element matches
pattern[matched], incrementmatched. - If it does not, fall back:
matched = lps[matched - 1], and repeat until either a match is found ormatchedreaches 0. - If
matchedreacheslen(pattern), a full block has been found — returnTrue.
Why this is correct
The key invariant is: after processing each element of stream, matched is exactly the length of the longest prefix of pattern that is a suffix of the portion of stream read so far. The fallback step preserves this invariant because lps[matched - 1] is the next-longest candidate border, and shorter candidates are tried in decreasing order, so no valid alignment is ever skipped.
Edge cases
- Empty
pattern: returnTrueimmediately. patternlonger thanstream: returnFalseimmediately.- Overlapping repeats, e.g.
pattern = [1, 1, 2],stream = [1, 1, 1, 2]: the fallback tolps[matched - 1](not a reset to 0) correctly keeps the partially matched prefix alive, finding the match that a naive reset would miss. - No match at all: the scan exhausts
streamand returnsFalse. - Negative numbers and duplicates: KMP uses only equality comparisons, so neither causes any special handling.
Complexity
- Time: O(N + M) — building the LPS table is O(N); scanning
streamis O(M). In each loop,matchedcan increase by at most 1 per step, and eachwhileiteration strictly decreases it, so total decreases cannot exceed total increases — a classic amortised argument. - Space: O(N) — only the LPS table of length N is stored.
streamis read sequentially with no additional storage.
Full solution
from typing import List
def find_block(pattern: List[int], stream: List[int]) -> bool:
# An empty pattern is trivially present in any stream.
if not pattern:
return True
# A pattern longer than the stream can never fit.
if len(pattern) > len(stream):
return False
# --- Phase 1: build the failure (LPS) table for `pattern` ---
# lps[i] = length of the longest proper prefix of pattern[0..i]
# that is also a suffix of pattern[0..i].
lps = [0] * len(pattern)
matched = 0
for i in range(1, len(pattern)):
while matched > 0 and pattern[i] != pattern[matched]:
matched = lps[matched - 1]
if pattern[i] == pattern[matched]:
matched += 1
lps[i] = matched
# --- Phase 2: scan `stream` once using the failure table ---
matched = 0
for value in stream:
# Fall back through the failure table until we find a
# matching position or exhaust all options.
while matched > 0 and value != pattern[matched]:
matched = lps[matched - 1]
if value == pattern[matched]:
matched += 1
# All elements of `pattern` have been matched in order.
if matched == len(pattern):
return True
return False