← Questions
Count subarrays that match a comparison pattern
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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
numberscan 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
numbersinto its comparison sequence of lengthn − 1once. - 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
- Databricks · Online assessment · Last asked Sep 2024Timed online coding test
What it tests
arrays · string matching · sliding window
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
