Skip to content

Commit 38e8cee

Browse files
authored
Create count-subarrays-with-median-k.cpp
1 parent 2ab758e commit 38e8cee

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

C++/count-subarrays-with-median-k.cpp

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
// freq table, prefix sum
5+
class Solution {
6+
public:
7+
int countSubarrays(vector<int>& nums, int k) {
8+
const int idx = distance(cbegin(nums), find(cbegin(nums), cend(nums), k));
9+
unordered_map<int, int> lookup;
10+
for (int i = idx, curr = 0; i >= 0; --i) {
11+
curr += nums[i] == k ? 0 : (nums[i] < k ? -1 : +1);
12+
++lookup[curr];
13+
}
14+
int result = 0;
15+
for (int i = idx, curr = 0; i < size(nums); ++i) {
16+
curr += nums[i] == k ? 0 : (nums[i] < k ? -1 : +1);
17+
result += lookup[-curr] + lookup[-(curr - 1)];
18+
}
19+
return result;
20+
}
21+
};

0 commit comments

Comments
 (0)