LeetCode 2488: Count Subarrays With Median K
Problem Description
Explanation
To solve this problem, we can iterate over all subarrays of the given array nums
. For each subarray, we calculate the median and check if it equals the given integer k
. To efficiently calculate the median, we sort the subarray and find the middle element(s) based on the length of the subarray. By keeping track of the count of subarrays with median equal to k
, we can return the final result.
Algorithm:
- Initialize a variable
result
to keep track of the count of subarrays with median equal tok
. - Iterate over all subarrays of
nums
. - For each subarray, sort it and calculate the median.
- If the median is equal to
k
, increment theresult
. - Return the final
result
.
Time Complexity:
The time complexity of this approach is O(n^3) where n is the length of the input array nums
.
Space Complexity: The space complexity is O(1) as we are not using any extra space that scales with the input size.
Solutions
class Solution {
public int countSubarraysWithMedianK(int[] nums, int k) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i; j < nums.length; j++) {
int[] subarray = Arrays.copyOfRange(nums, i, j + 1);
Arrays.sort(subarray);
int median = (subarray.length % 2 == 0) ? subarray[subarray.length / 2 - 1] : subarray[subarray.length / 2];
if (median == k) {
result++;
}
}
}
return result;
}
}
Loading editor...