Advertisement

Count Subarrays With Median K - LeetCode 2488 Solution

Count Subarrays With Median K - Complete Solution Guide

Count Subarrays With Median K is LeetCode problem 2488, a Hard level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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 . Note : The median of an array is the middle element after sorting the array in ascending order. If the array is of even length, the median is the left middle element. For example, the median of [2,3,1,4] is 2 , and the median of [8,4,3,5,1] is 4 . A subarray is a contiguous part of an array. Example 1: Input:

Detailed Explanation

The problem asks us to count the number of non-empty subarrays within a given array `nums` whose median is equal to a specified value `k`. The `nums` array contains distinct integers from 1 to n. The median of a subarray is the middle element after sorting the subarray. If the subarray has an even length, the median is the left middle element. The core task is to efficiently identify and count all such subarrays.

Solution Approach

The solution efficiently counts subarrays with median `k` using a balance-based approach and a hash map (or array in C) to store the frequency of balances encountered to the left of `k`. First, it finds the index of `k` in the array. Then, it iterates from the element just to the left of `k` backwards to the beginning of the array, calculating the 'balance' (number of elements greater than `k` minus the number of elements less than `k`) for each subarray ending just before `k`. These balances and their frequencies are stored. Next, the solution iterates from `k` to the end of the array, calculating the balance for each subarray starting at `k`. For each of these subarrays, it checks what balance would be required on the left side of `k` to achieve a total balance of 0 (odd length subarray with `k` as the median) or 1 (even length subarray with `k` as the median). The count of such subarrays is incremented by the number of times those required balances appear in the precomputed frequencies from the left side.

Step-by-Step Algorithm

  1. Step 1: Find the index `k_idx` of `k` in `nums`. Return 0 if `k` is not found.
  2. Step 2: Create a hash map (or appropriately sized array in C) called `freq` to store the frequency of balances encountered to the left of `k`. Initialize `freq[0]` to 1, representing the empty subarray to the left of `k`.
  3. Step 3: Iterate backwards from `k_idx - 1` to 0. For each element `nums[i]`, update the `balance`: increment if `nums[i] > k`, decrement if `nums[i] < k`. Update `freq[balance]` to reflect the count of subarrays ending at index `i` with the given balance.
  4. Step 4: Initialize a counter `ans` to 0 and `balance` to 0.
  5. Step 5: Iterate from `k_idx` to the end of the array `nums`. For each element `nums[j]`, update the `balance` as in step 3.
  6. Step 6: Calculate the target balance values needed on the left to create a total balance of 0 and 1: `target_for_0 = -balance` and `target_for_1 = 1 - balance`.
  7. Step 7: Increment `ans` by the frequency of `target_for_0` and `target_for_1` in `freq`. This is the number of subarrays ending at index `j` with median `k`.
  8. Step 8: Return `ans`.

Key Insights

  • Insight 1: The core idea is to iterate through all possible subarrays and check their median, but this would lead to a higher time complexity. Instead, we look for subarrays containing `k`.
  • Insight 2: We can optimize by focusing on the relationship between elements greater than and less than `k` within the subarray. If the number of elements greater than `k` equals the number of elements less than `k`, the subarray has an odd length and `k` is the median. If the number of elements greater than `k` is one more than the number of elements less than `k`, the subarray has an even length and `k` is the median.
  • Insight 3: We use a balance (num_greater - num_less) concept to track whether k is the median. We can precompute and store frequencies of balances on the left side of k to speed up counting when processing elements to the right of k.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(n)

Topics

This problem involves: Array, Hash Table, Prefix Sum.

Companies

Asked at: Confluent, thoughtspot.