Count Subarrays With Median K Problem
Description
LeetCode Problem 2488.
You are given an array nums of size n consisting of distinct integers from 1 to n and a positive integer k.
Return the number of non-empty subarrays in nums that have a median equal to k.
Note:
- The median of an array is the middle element after sorting the array in ascending order. If the array is of even length, the median is the left middle element.
- For example, the median of
[2,3,1,4]is2, and the median of[8,4,3,5,1]is4.
- For example, the median of
- A subarray is a contiguous part of an array.
Example 1:
Input: nums = [3,2,1,4,5], k = 4
Output: 3
Explanation: The subarrays that have a median equal to 4 are: [4], [4,5] and [1,4,5].
Example 2:
Input: nums = [2,3,1], k = 3
Output: 1
Explanation: [3] is the only subarray that has a median equal to 3.
Constraints:
n == nums.length1 <= n <= 10^51 <= nums[i], k <= n- The integers in
numsare distinct.
Solution
Approach: Balance counting around k
Find the position i of k. Any subarray whose median is k must contain index i, so it is a stretch to the left of i joined with a stretch to the right of i.
Give each element a balance: +1 if it is larger than k, -1 if it is smaller. Because the array is a permutation, k appears once. A subarray containing k has median k exactly when the sum of its balances (not counting k itself) is 0 (odd length) or 1 (even length, since the left-middle element is the median).
Walk right from i and keep a running balance x; each right part with x in {0, 1} is a valid subarray that starts at i, and we record every x in a counter. Then walk left from i with its own balance x; a left part with x in {0, 1} is valid on its own, and it combines with each recorded right part whose balance is -x or 1 - x. Start the answer at 1 for the subarray [k] alone.
Complexity: time O(n); space O(n).
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
i = nums.index(k)
cnt = Counter()
ans = 1
x = 0
for v in nums[i + 1 :]:
x += 1 if v > k else -1
ans += 0 <= x <= 1
cnt[x] += 1
x = 0
for j in range(i - 1, -1, -1):
x += 1 if nums[j] > k else -1
ans += 0 <= x <= 1
ans += cnt[-x] + cnt[-x + 1]
return ans