#3034

Number of Subarrays That Match a Pattern I

Medium
ArrayRolling HashString MatchingHash FunctionHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a single pass through the nums array while maintaining a count of valid subarrays based on the pattern. This reduces the need for nested loops and improves efficiency.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a count to 0 and a variable to track the length of valid subarrays.
  2. 2Step 2: Iterate through nums while checking conditions based on the pattern.
  3. 3Step 3: If a condition is satisfied, increment the length of the valid subarray.
  4. 4Step 4: If a condition fails, reset the length and check if it matches the pattern.
  5. 5Step 5: Return the total count of valid subarrays.
solution.py18 lines
1# Full working Python code
2
3def count_matching_subarrays(nums, pattern):
4    count = 0
5    m = len(pattern)
6    n = len(nums)
7    valid_length = 0
8    for i in range(n - 1):
9        if i < n - 1 and (pattern[valid_length] == 1 and nums[i + 1] > nums[i] or 
10                           pattern[valid_length] == 0 and nums[i + 1] == nums[i] or 
11                           pattern[valid_length] == -1 and nums[i + 1] < nums[i]):
12            valid_length += 1
13            if valid_length == m:
14                count += 1
15        else:
16            valid_length = 0
17    return count
18

Complexity note: The time complexity is O(n) because we only traverse the nums array once, checking conditions based on the pattern without nested loops.

  • 1Understanding the pattern conditions is crucial for matching subarrays.
  • 2The optimal solution leverages a single pass to reduce time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.