LeetCode Problem

How to Solve Count Subarrays With Median K

To solve the problem of counting subarrays with median k, we can transform the array by marking values greater than k as 1, values less than k as -1, and k itself as 0. The task then reduces to finding subarrays where the cumulative sum is zero. This approach uses array scanning and hash lookup for efficient counting of valid subarrays.

GhostInterview Help

Need help with Count Subarrays With Median K without spending extra time grinding it?

GhostInterview can read Count Subarrays With Median K from a screenshot, generate the answer path, explain the complexity, and support solver-first interview workflows when you need direct help fast.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.

Problem #2488Array scanning plus hash lookupReviewed 2026-03-08
Difficulty
Hard
Primary pattern
Array scanning plus hash lookup
Answer-first problem summary
Step-by-step approach and complexity
GhostInterview solver workflow

To solve the problem of counting subarrays with median k, we can transform the array by marking values greater than k as 1, values less than k as -1, and k itself as 0. The task then reduces to finding subarrays where the cumulative sum is zero. This approach uses array scanning and hash lookup for efficient counting of valid subarrays.

Problem Statement

You are given an array nums of size n consisting of distinct integers from 1 to n and a positive integer k. Your task is to find how many non-empty subarrays in nums have a median equal to k.

A subarray's median is the middle value when the subarray is sorted. Since the array contains distinct integers, the problem becomes one of identifying subarrays where the position of k allows it to be the median. The challenge lies in efficiently counting such subarrays.

Examples

Example 1

Input: nums = [3,2,1,4,5], k = 4

Output: 3

The subarrays that have a median equal to 4 are: [4], [4,5] and [1,4,5].

Example 2

Input: nums = [2,3,1], k = 3

Output: 1

[3] is the only subarray that has a median equal to 3.

Constraints

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

Solution Approach

Array Transformation and Cumulative Sum

Convert the array into a new representation where each element is mapped to 1 if it is greater than k, -1 if it is smaller than k, and 0 if it equals k. This transformation helps in simplifying the problem to finding subarrays with a sum of zero using cumulative sum and hash table for fast lookup.

Prefix Sum and Hash Lookup

Use a running prefix sum while iterating through the array. For each index, track how many times this prefix sum has occurred using a hash table. A subarray with a zero median will have a prefix sum that repeats, so efficiently counting the valid subarrays relies on identifying such repeats.

Optimizing with Hash Map

A hash map stores the count of prefix sums. If the current prefix sum matches a previous sum, it indicates that there exists a subarray where the cumulative sum between these indices is zero. This approach drastically reduces the complexity compared to brute force methods.

Complexity Analysis

MetricValue
TimeDepends on the final approach
SpaceDepends on the final approach

The time complexity of the solution depends on the number of elements in the array and the efficiency of the hash map operations. With an optimal approach, the time complexity is O(n), where n is the size of the array. The space complexity also depends on the hash map, resulting in O(n) space for storing the prefix sums.

What Interviewers Usually Probe

  • The candidate effectively leverages the array transformation to simplify the median problem.
  • The candidate is comfortable using hash maps to track prefix sums and identify subarrays.
  • The candidate is able to explain the trade-off between brute force methods and the efficient use of prefix sums and hash lookups.

Common Pitfalls or Variants

Common pitfalls

  • Not recognizing that the problem can be reduced to finding subarrays with a sum of zero.
  • Misunderstanding the transformation of the array into 1, -1, and 0 values.
  • Failing to efficiently count subarrays with hash maps, leading to time complexity issues.

Follow-up variants

  • Consider adding duplicate values in the array and adjusting the approach accordingly.
  • Explore the possibility of applying the solution to non-distinct integer arrays.
  • Modify the problem to allow for non-zero medians in subarrays, which could require different transformation or counting logic.

How GhostInterview Helps

  • GhostInterview helps by guiding you through the process of transforming the array into a simpler form for counting subarrays.
  • It assists in recognizing when prefix sum and hash map techniques can optimize solutions.
  • The tool also explains the failure modes and trade-offs for common pitfalls, helping you avoid inefficient brute force solutions.

Topic Pages

FAQ

What is the optimal approach for solving 'Count Subarrays With Median K'?

The optimal approach is to transform the array using values 1, -1, and 0, then use a prefix sum and hash map to count subarrays with a sum of zero.

How do you handle large arrays in this problem?

For large arrays, the use of cumulative sum and hash maps ensures an O(n) time complexity, making the solution efficient even for the maximum input size.

What is the time complexity of the 'Count Subarrays With Median K' solution?

The time complexity is O(n) because the algorithm processes each element once and uses efficient hash map lookups for counting subarrays.

What are the key challenges in the 'Count Subarrays With Median K' problem?

The main challenge lies in transforming the array efficiently and using the right data structures, like hash maps, to track prefix sums and count valid subarrays.

How does the prefix sum technique work for this problem?

Prefix sum helps track the cumulative sum of transformed values. When a prefix sum repeats, it indicates the presence of a subarray with a zero sum, which corresponds to a valid subarray with median k.

GhostInterview Solver

Need direct help with Count Subarrays With Median K instead of spending more time grinding it?

Download GhostInterview when you want a LeetCode solver, not another long practice loop. Capture Count Subarrays With Median K from a screenshot, get the answer path and complexity, and use supported stealth workflows that stay outside captured layers.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.