We will find a way, we always have.

-interstellar

Problem Solving/๋ฆฌํŠธ์ฝ”๋“œ

[LeetCode] 3036. Number of Subarrays That Match a Pattern II

Redddy 2024. 2. 11. 21:41

๐Ÿ”ˆ ๋ฌธ์ œ

You are given a 0-indexed integer array nums of size n, and a 0-indexed integer array pattern of size m consisting of integers -1, 0, and 1.

A subarray nums[i..j] of size m + 1 is said to match the pattern if the following conditions hold for each element pattern[k]:

  • nums[i + k + 1] > nums[i + k] if pattern[k] == 1.
  • nums[i + k + 1] == nums[i + k] if pattern[k] == 0.
  • nums[i + k + 1] < nums[i + k] if pattern[k] == -1.

Return the count of subarrays in nums that match the pattern.

 

๐Ÿ’ซ ์˜ˆ์‹œ

Input: nums = [1,2,3,4,5,6], pattern = [1,1]
Output: 4
Explanation: The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern.
Hence, there are 4 subarrays in nums that match the pattern.

๐ŸŽฑ ์ œํ•œ

  • 2 <= n == nums.length <= 106
  • 1 <= nums[i] <= 109
  • 1 <= m == pattern.length < n
  • -1 <= pattern[i] <= 1

 

๐Ÿ“š ๋ฌธ์ œ ํ’€์ด

 

๋ฌธ์ œ๋ฅผ ์ •๋ฆฌํ•ด๋ณด์ž๋ฉด nums ์—์„œ pattern ์˜ ๋“ฑ์žฅ ํšŸ์ˆ˜๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค. 

nums ๋ž‘ pattern ์ด๋ž‘ ๋ฐ”๋กœ ๋งค์นญ์ด ๋˜๋„๋ก nums[i] < nums[i+1] ์ด๋ฉด 1, nums[i] == nums[i+1] ์ด๋ฉด 0, nums[i] > nums[i+1] ์ด๋ฉด -1 ์ธ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ๋งŒ๋“ ๋‹ค์Œ ์ด ๋ฐฐ์—ด์—์„œ pattern์˜ ๋“ฑ์žฅ ํšŸ์ˆ˜๋Š” KMP ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•˜์—ฌ ๋น ๋ฅด๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

๐Ÿ’ป ์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution:
    def countMatchingSubarrays(self, nums: List[int], pattern: List[int]) -> int:
        n = len(nums)
        pre = []
 
 
        for i in range(n-1):
            if nums[i] < nums[i+1]:
                pre.append(1)
            elif nums[i] > nums[i+1]:
                pre.append(-1)
            else:
                pre.append(0)
        
        # kmp
        m = len(pattern)
        fail = [0]*m
        i = 0
 
        for j in range(1, m):
            while i > 0 and pattern[i] != pattern[j]:
                i = fail[i-1]
            
            if pattern[i] == pattern[j]:
                i += 1
                fail[j] = i
        
        res = 0
        i = 0
        for j in range(n-1):
            while i > 0 and pre[j] != pattern[i]:
                i = fail[i-1]
            
            if pattern[i] == pre[j]:
                i += 1
                if i == len(pattern):
                    res += 1
                    i = fail[i-1]
 
        return res
cs

 

๐Ÿ”— ๋ฌธ์ œ๋งํฌ 

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com