Problem · Array
Subarray Counting
note - feel free to see the Problem Source section below for the original problem description and example explanation ;)
Imagine you have a list of numbers and a smaller list called pattern, which describes how the numbers should change. The pattern only contains three types of instructions:
Your job is to find how many stretches of consecutive numbers in the big list follow this exact pattern. Just make sure the solution isn't too slow—though it doesn’t need to be perfect, it should work efficiently enough.
Examples
01 · Example 1
numbers = [4, 1, 3, 4, 4, 5, 5, 1] pattern = [1, 0, -1] return = 1
Let’s explore some possible subarrays of length 3. We don't need to check the subarray starting at numbers[0]—there's no number before the first element to compare!
Subarray [1, 3, 4] doesn’t match. The pattern starts with 1, meaning the first number should be larger than the one before it, but numbers[1] = 1 is less than numbers[0] = 4.
Subarray [3, 4, 4] fails because the pattern says 0 for the second number, meaning it should stay the same, but numbers[3] = 4 is greater than numbers[2] = 3.
Subarray [4, 4, 5] doesn’t work either. The pattern ends with -1, meaning the last number should be smaller than the previous one, but numbers[5] = 5 is greater than numbers[4] = 4.
Subarray [4, 5, 5] also doesn’t match for the same reason.
Finally, subarray [5, 5, 1] perfectly matches the pattern:
numbers[5] > numbers[4], as the pattern starts with 1.
numbers[6] = numbers[5], following the 0 in the pattern.
numbers[7] < numbers[6], just as the pattern ends with -1.
This subarray is the match we’re looking for!
Constraints
🍇🍇More Databricks problems
- Fastest SF CommutePHONE SCREEN · Seen May 2026
- Find First Anagram IndexPHONE SCREEN · Seen Apr 2026
- Minimize CommuteOA · Seen Apr 2026
- Difference Between Sums of PositionsSeen Sep 2024
- Longest Common Prefix of Number PairsSeen Sep 2024
- Write 'L' on MatrixSeen Sep 2024
- Binary String RequestsSeen Aug 2024
- Bounding Diagonal WeightsSeen Aug 2024
public int subarrayCounting(int[] numbers, int[] pattern) {
// write your code here
}
numbers[4, 1, 3, 4, 4, 5, 5, 1]
pattern[1, 0, -1]
expected1
sign in to submit