KatInterview

Detect a Contiguous Block Inside an Integer Sequence

StringsAuto-graded · 22 test cases
HardAuto-gradedStringsKMPpattern matchingarrays

Last 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 pattern must appear in stream in the same relative order.
  • The elements of pattern must occupy adjacent positions in stream — no gaps allowed.
  • An empty pattern is considered to be present in any stream.
  • If pattern is longer than stream, a match is impossible.

Constraints

  • 1 <= len(pattern) <= 10^5
  • 1 <= 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`.