#2488

Count Subarrays With Median K

Hard
LeetCode ↗

Approaches

💡

Intuition

Time O(n²)Space O(1)

The brute force approach checks all possible subarrays to see if their median equals k. This is straightforward but inefficient for large arrays since it examines every combination.

⚙️

Algorithm

3 steps
  1. 1Step 1: Iterate through all possible starting points of subarrays.
  2. 2Step 2: For each starting point, iterate through all possible ending points to form subarrays.
  3. 3Step 3: For each subarray, sort it and check if the median equals k.
solution.py13 lines
1def countSubarrays(nums, k):
2    count = 0
3    for i in range(len(nums)):
4        for j in range(i, len(nums)):
5            subarray = nums[i:j+1]
6            if median(subarray) == k:
7                count += 1
8    return count
9
10def median(arr):
11    arr.sort()
12    n = len(arr)
13    return arr[n // 2] if n % 2 != 0 else arr[n // 2 - 1]

Complexity note: This complexity arises because we check every possible subarray, which results in a nested loop. Each subarray requires sorting, leading to O(n log n) for each check.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.