← Questions

Count subarrays that match a comparison pattern

0
DatabricksCodingLast asked Sep 2024

A coding interview question asked in Databricks's online assessment, last asked Sep 2024. It tests arrays, string matching and sliding window.

A pattern of length m holds 1 (the next value is greater), 0 (equal) and -1 (smaller). Count the contiguous subarrays of length m + 1 whose consecutive comparisons match the pattern exactly.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • count_matches(numbers: list[int], pattern: list[int]) -> int

Example

count_matches([4, 1, 3, 4, 4, 5, 5, 1], [1, 0, -1])   ->  1    # only [4, 5, 5, 1]
count_matches([1, 2, 3, 4, 5, 6], [1, 1])              ->  4    # every window of three is increasing
count_matches([1, 4, 4, 1, 3, 5, 5, 3], [1, 0, -1])    ->  2    # [1, 4, 4, 1] and [3, 5, 5, 3]

Constraints

  • 1 <= len(pattern) < len(numbers).
  • For the follow-up, assume numbers can have up to 10^6 elements.

Clarifying questions

  • How large are the arrays? Is O(n × m) acceptable?
  • Can matches overlap? (Yes: count every start index.)
  • Are the values integers, and can they be negative?

What a strong answer covers

  • Converting numbers into its comparison sequence of length n − 1 once.
  • The direct approach: compare the pattern at every start, O(n × m).
  • The linear approach: string matching of the pattern inside the comparison sequence with KMP or the Z-function, O(n + m), counting overlapping matches.
  • Tests: no match, all matches, a pattern as long as the comparison sequence.

Follow-ups

  • Return the start indices of all matches.
  • The pattern can contain a wildcard that matches any comparison.
  • Count matches for many patterns at once (Aho-Corasick).

Where it's asked

What it tests

arrays · string matching · sliding window

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding