Count Subarrays With Median K — LeetCode 2488 Python Solution

HardArrayHash TablePrefix Sum
Problem
#2488
Pattern
Prefix Sum
Reading time
3 min

The 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.

Example

Input
nums = [3,2,1,4,5], k = 4
Output
3
Explanation
The subarrays that have a median equal to 4 are: [4], [4,5] and [1,4,5].

Python solution

Python
class Solution:
    def countSubarrays(self, nums: List[int], k: int) -> int:
        i = nums.index(k)
        cnt = Counter()
        ans = 1
        x = 0
        for v in nums[i + 1 :]:
            x += 1 if v > k else -1
            ans += 0 <= x <= 1
            cnt[x] += 1
        x = 0
        for j in range(i - 1, -1, -1):
            x += 1 if nums[j] > k else -1
            ans += 0 <= x <= 1
            ans += cnt[-x] + cnt[-x + 1]
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2488. Count Subarrays With Median K is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2488. Count Subarrays With Median K?
LeetCode 2488. Count Subarrays With Median K is rated Hard on LeetCode.
What is the time complexity of LeetCode 2488. Count Subarrays With Median K?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2488. Count Subarrays With Median K?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2488. Count Subarrays With Median K cover?
LeetCode 2488. Count Subarrays With Median K is tagged Array, Hash Table and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview