Leetcode Problem 2488. Count Subarrays With Median K

2488. Count Subarrays With Median K

Leetcode Solutions

Prefix Sum and HashMap Approach

  1. Initialize a new array arr of the same length as nums.
  2. Replace each element in nums with -1, 0, or 1 in arr based on the comparison with k.
  3. Initialize a hashmap book_pre to store the frequency of prefix sums.
  4. Initialize variables agg to keep track of the current prefix sum and ans to store the count of valid subarrays.
  5. Iterate through arr and update agg with the current element.
  6. If the current element is 0 (i.e., we found k), set check to True.
  7. If check is True, increment ans by the count of agg and agg-1 in book_pre.
  8. If check is False, increment the count of agg in book_pre.
  9. Return ans.
UML Thumbnail

Two Pointers and Sorting Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...