# Solution For Count Subarrays With Median K

Problem Statement:
Given an array of integers nums and an integer k, return the number of contiguous subarrays where the median equals k.
The median of a subarray is the middle element when the elements are sorted in non-decreasing order. If the subarray has an odd length, the middle element is the median. If there is an even number of elements in the subarray, the median is the average of the two middle elements.

Example 1:
Input: nums = [1,1,3], k = 2
Output: 0
Explanation: The median of the 2 subarrays [1,1] and [1,3] is 1, which is not equal to k.

Example 2:
Input: nums = [1,2,3,4,5], k = 3
Output: 3
Explanation: There are 3 subarrays with a median equal to 3: [1,2,3], [2,3,4], and [3,4,5].

Approach:
To solve the given problem statement, we can start by iterating over all contiguous subarrays of sizes n, where n is the length of the given array nums. We can then calculate the median of each of the subarrays and compare it with k. If the median is equal to k, we can increment the count.

To calculate the median of the subarray, we can sort the subarray in non-decreasing order and calculate the median accordingly. If the length of the subarray is odd, the median will be the middle element. If the length of the subarray is even, the median will be the average of the two middle elements.

Algorithm:
1. Initialize a count variable to 0.
2. Iterate over all subarrays of size n, where n is the length of the given array nums.
3. Sort the current subarray in non-decreasing order.
4. Calculate the median of the subarray using the above-mentioned approach.
5. If the median of the subarray is equal to k, increment the count.
6. Return the count.

Code:

class Solution {
public:
int countSubArraysWithMedianK(vector& nums, int k) {
int n = nums.size(), count = 0;
for(int i = 0; i < n; i++) {
for(int j = i; j < n; j++) {
vector sub(nums.begin()+i, nums.begin()+j+1);
sort(sub.begin(), sub.end());
int median = 0;
if(sub.size() % 2 == 0) median = (sub[sub.size()/2-1] + sub[sub.size()/2])/2;
else median = sub[sub.size()/2];
if(median == k) count++;
}
}
return count;
}
};

Time Complexity: O(n^3 log n), as we are iterating over all subarrays of size n and sorting each subarray, which takes O(n log n) time.

Space Complexity: O(n) as we are storing each subarray in the vector of size n.

## Step by Step Implementation For Count Subarrays With Median K

```class Solution {
public int countSubarrays(int[] arr, int k) {
int n = arr.length;
// Create a multi set to store frequencies of
// difference of median from elements
TreeMap map =
new TreeMap<>();

// Initialize result
int cnt = 0;

// Initialize running sum of elements
int sum = 0;

// Traverse the given array
for (int i = 0; i < n; i++)
{
// Increase frequency of
// current running sum
sum += arr[i];

// If running sum is 0, then
// there are no subarrays starting
// from index 'i'.
if (sum == k)
cnt++;

// Look for previous running sum
// that is equal to running sum - k
if (map.containsKey(sum - k))
cnt += map.get(sum - k);

// Insert running sum into hash map
increment(map, sum);
}
return cnt;
}

// Function to insert value with its
// frequency into the multimap
static void increment(TreeMap map,
int key)
{
// If key is already present,
// incrementing its value
if (map.containsKey(key)) {
int c = map.get(key);
map.put(key, c + 1);
}

// If key is not present,
// insert it with value as 1
else
map.put(key, 1);
}
}```
```def countSubarraysWithMedianK(arr, k):

n = len(arr)

# Find sum of first subarray
# and initialize count
sum = 0
for i in range(n):
sum += arr[i]
if sum == k:
count++

# Iterate through remaining elements
for i in range(1, n):
sum += (arr[i] - arr[i-1])

# If sum is equal to k,
# then increment count
if sum == k:
count++

return count```
```/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var countSubarrays = function(nums, k) {
// create an empty map
let map = {};

// initialize count of subarrays with median k
let count = 0;

// loop through the array
for(let i=0; iint findMedian(vector& arr, int k)
{
int n = arr.size();
sort(arr.begin(), arr.end());
return arr[(n-1)/2];
}

// Function to find number of subarrays
// with median k
int countSubarrays(vector& arr, int n, int k)
{
// Initialize result
int cnt = 0;

// Find median of first subarray
// and compare with remaining
// subarrays
int median = findMedian(arr, k);

// Compare medians found so far
for (int i=k; iGiven an array of integers and a number k, find the number of subarrays with median k.

A subarray is defined as a contiguous subset of the array.

The median of a subarray is defined as the median of the elements in the subarray.

Example 1:

Input: nums = [1,2,3,4,5], k = 3
Output: 2
Explanation: There are 2 subarrays with median 3: [1,2,3] and [3,4,5]
Example 2:

Input: nums = [1,2,1,3,4], k = 3
Output: 4
Explanation: There are 4 subarrays with median 3: [1,2,1,3], [2,1,3], [1,3,4], [3,4].```

## Top 100 Leetcode Practice Problems In Java

Get 30% Off Instantly!
[gravityforms id="5" description="false" titla="false" ajax="true"]