Count Subarrays With Median K - 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 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] is 2, and the median of [8,4,3,5,1] is 4.
  • A subarray is a contiguous part of an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,2,1], k = 2
Output: 3
💡 Note: Three subarrays have median 2: [2] (median=2), [3,2] (sorted=[2,3], median=2), [2,1] (sorted=[1,2], median=1... wait, let me recalculate. [2] median=2, [3,2] sorted=[2,3] median=2, [2,1] sorted=[1,2] median=1. Actually [3,2,1] sorted=[1,2,3] median=2. So subarrays: [2], [3,2], [3,2,1] = 3 total.
Example 2 — Single Element
$ Input: nums = [2,1,3], k = 1
Output: 1
💡 Note: Only one subarray has median 1: [1] itself. Other subarrays containing 1 have different medians when sorted.
Example 3 — Multiple Valid
$ Input: nums = [1,3,2,4], k = 3
Output: 2
💡 Note: Two subarrays have median 3: [3] (median=3) and [1,3,2] (sorted=[1,2,3], left-middle median=2... wait, that's wrong. Let me recalculate: [3] median=3, [1,3,2] sorted=[1,2,3] median=2 (left-middle), [3,2] sorted=[2,3] median=2, [1,3,2,4] sorted=[1,2,3,4] median=2. Actually only [3] and [3,2,4] work... let me be more careful.

Constraints

  • n == nums.length
  • 1 ≤ n ≤ 105
  • 1 ≤ nums[i], k ≤ n
  • All integers in nums are distinct

Visualization

Tap to expand
Count Subarrays With Median KInput: nums = [3,2,1], k = 2321index 0index 1index 2Valid subarrays with median = 2:• [2] → median = 2 ✓• [3,2] → sorted [2,3] → median = 2 ✓• [3,2,1] → sorted [1,2,3] → median = 2 ✓Output: 3 subarraysTransform to balance problem for O(n) solution
Understanding the Visualization
1
Input
Array nums and target value k
2
Process
Find subarrays where k is the median after sorting
3
Output
Count of valid subarrays
Key Takeaway
🎯 Key Insight: Transform median problem to counting balanced subarrays using +1/-1 mapping
Asked in
Google 15 Facebook 12 Amazon 8
23.4K Views
Medium Frequency
~30 min Avg. Time
867 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