Count Subarrays With Median K - Problem
Challenge: You're given an array 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
Array: [3, 2, 1, 4, 5] Target k = 4Transform relative to k=4-13 < 4-12 < 4-11 < 404 = 4+15 > 4Use prefix sums to count balanced subarrays⚖️ Key: Subarray has median k if balanced around k
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
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
67.2K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen