Skip to content

Commit

Permalink
Create 16. Count Subarrays With Median K.py
Browse files Browse the repository at this point in the history
  • Loading branch information
SamirPaulb committed Dec 14, 2022
1 parent 0abae6d commit 256445b
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions 19_HashMap/16. Count Subarrays With Median K.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# https://leetcode.com/problems/count-subarrays-with-median-k/
# https://youtu.be/QZzDioqkRhU

class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
pos = nums.index(k)
cnt = defaultdict(int)
cnt[0] = 1
c = 0
for i in range(pos + 1, len(nums)):
c += 1 if nums[i] > k else -1
cnt[c] += 1

ans = cnt[0] + cnt[1]
c = 0
for i in range(pos - 1, -1, -1):
c += 1 if nums[i] < k else -1
ans += cnt[c] + cnt[c + 1]
# print(cnt)
return ans

0 comments on commit 256445b

Please sign in to comment.