Problem
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 innums _that have amedian 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.
Examples
Example 1
| |
Example 2
| |
Constraints
n == nums.length1 <= n <= 10^51 <= nums[i], k <= n- The integers in
numsare distinct.
Solution
Method 1 – Prefix Sum and Hash Map
Intuition
The key is to count subarrays where the number of elements greater than k equals the number of elements less than k, with k as the median. We can map the array to +1 (greater than k), -1 (less than k), and 0 (equal to k), and use prefix sums and a hash map to count valid subarrays.
Approach
- Find the index of k in nums (since all elements are distinct).
- For each prefix ending at or before the index of k, compute the prefix sum, and count the frequency of each sum in a hash map.
- For each prefix starting at the index of k, compute the prefix sum, and for each sum, add the count of that sum and (sum-1) from the hash map to the answer.
- Return the total count.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n), since we scan the array twice and use hash maps for prefix sums. - 🧺 Space complexity:
O(n), for the hash map storing prefix sum counts.