Count Subarrays With Median K - Problem
Challenge: You're given an array
What makes this interesting: The median is the middle element when the subarray is sorted. For even-length arrays, we take the left middle element. For example:
•
•
Since all numbers are distinct and from 1 to n, we can use clever transformations to avoid sorting each subarray!
nums of size n containing distinct integers from 1 to n and a target integer k. Your task is to count how many contiguous subarrays have k as their median.What makes this interesting: The median is the middle element when the subarray is sorted. For even-length arrays, we take the left middle element. For example:
•
[2,3,1,4] sorted becomes [1,2,3,4] → median is 2 (left middle)•
[8,4,3,5,1] sorted becomes [1,3,4,5,8] → median is 4 (middle)Since all numbers are distinct and from 1 to n, we can use clever transformations to avoid sorting each subarray!
Input & Output
example_1.py — Basic case
$
Input:
nums = [3,2,1,4,5], k = 4
›
Output:
3
💡 Note:
Valid subarrays: [4] (median=4), [3,4,5] (sorted: [3,4,5], median=4), [2,3,4,5] (sorted: [2,3,4,5], median=3 - wait, this is wrong). Actually: [4], [1,4], [1,4,5] have median 4.
example_2.py — Edge case with k at boundary
$
Input:
nums = [2,3,1], k = 3
›
Output:
1
💡 Note:
Only subarray [2,3,1] has median 3 when sorted to [1,2,3]. The middle element is 2, not 3. Actually, only [3] has median 3.
example_3.py — Single element
$
Input:
nums = [1], k = 1
›
Output:
1
💡 Note:
The only subarray [1] has median 1, which equals k.
Constraints
- n == nums.length
- 1 ≤ n ≤ 105
- 1 ≤ nums[i], k ≤ n
- All integers in nums are distinct
Visualization
Tap to expand
Understanding the Visualization
1
Find the Target
Locate k in the array - this must be in every valid subarray
2
Transform Evidence
Convert each element to +1 (heavier than k), -1 (lighter than k), or 0 (equals k)
3
Count Balanced Sections
Use prefix sums to efficiently count subarrays where k would be the median
Key Takeaway
🎯 Key Insight: Transform the problem from sorting subarrays to counting balanced prefix sums around k
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code