<p>You are given an integer array <code>nums</code> and two integers <code>minK</code> and <code>maxK</code>.</p>

<p>A <strong>fixed-bound subarray</strong> of <code>nums</code> is a subarray that satisfies the following conditions:</p>

<ul>
	<li>The <strong>minimum</strong> value in the subarray is equal to <code>minK</code>.</li>
	<li>The <strong>maximum</strong> value in the subarray is equal to <code>maxK</code>.</li>
</ul>

<p>Return <em>the <strong>number</strong> of fixed-bound subarrays</em>.</p>

<p>A <strong>subarray</strong> is a <strong>contiguous</strong> part of an array.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,3,5,2,7,5], minK = 1, maxK = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> The fixed-bound subarrays are [1,3,5] and [1,3,5,2].
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,1,1,1], minK = 1, maxK = 1
<strong>Output:</strong> 10
<strong>Explanation:</strong> Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= nums[i], minK, maxK &lt;= 10<sup>6</sup></code></li>
</ul>

"""
 x x x 1 x x 5 x x x 1 x x 5 x x 5 x 1
 x x x 1 x x 5
   x x 1 x x 5
     x 1 x x 5
       1 x x 5   4
       --------------
       1 x x 5 x    8
       1 x x 5 x x   12
       1 x x 5 x x x   16
             5 x x x 1   23
      ------------------------
             5 x x x 1 x  30
"""
class Solution:
    def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:
        proc = [[]]
        for n in nums:
            if n <= maxK and n >= minK:
                proc[-1].append(n)
                continue
            else:
                if len(proc[-1]) != 0:
                    proc.append([])
        # for each list in proc, we can ensure minK <= proc[i] <= maxK
        same = 2
        if minK == maxK:
            same = 1
        def helper(arr):
            nonlocal minK, maxK, same
            dd = defaultdict(int)
            res = 0
            if len(arr) == 0:
                return 0
            l = 0
            r = 0
            while r < len(arr):
                if arr[r] in [minK, maxK]:
                    dd[arr[r]]+=1
                if len(dd) == same:
                    while True:
                        if arr[l] in dd:
                            if dd[arr[l]] == 1:
                                break
                            dd[arr[l]] -= 1
                        l+=1
                    res += (l+1)
                r+=1
            return res
        res = 0
        for p in proc:
            res += helper(p) 
        return res
781