Trains the technique from
LeetCode 2488Count Subarrays With Median KThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A log holds the readings readings, which are the whole numbers from 1 up to the log's length, each appearing exactly once. A number k in that same range is also given.
The middle reading of a stretch of neighbouring entries is found by putting the stretch in increasing order and taking the entry in the centre. Where the stretch holds an even number of entries, take the earlier of the two central ones.
Return how many stretches have k as their middle reading.
Example 1
The reading 2 sits at the far end. On its own it is the middle. With the 3 before it the ordered pair is 2, 3 and the earlier central entry is 2. With 1, 5 and 3 before it the ordered four are 1, 2, 3, 5 and the earlier central entry is again 2. The other two stretches put 3 in the middle instead.
Example 2
Five stretches work: 3 on its own; 3 with 4; 2, 3 and 4; 2, 3, 4 and 5; and the whole log. In each of them the entries above 3 either match those below in number or run one ahead.
Example 3
Only the single entry 2 has 2 in the middle. The pair orders to 1, 2 and its earlier central entry is 1.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def count_subarrays(readings: list[int], k: int) -> int:public int countSubarrays(int[] readings, int k)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.