Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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:
[2,3,1,4] is 2, and the median of [8,4,3,5,1] is 4.Example 1:
Input: nums = [3,2,1,4,5], k = 4 Output: 3 Explanation: The subarrays that have a median equal to 4 are: [4], [4,5] and [1,4,5].
Example 2:
Input: nums = [2,3,1], k = 3 Output: 1 Explanation: [3] is the only subarray that has a median equal to 3.
Constraints:
n == nums.length1 <= n <= 1051 <= nums[i], k <= nnums are distinct.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
[3,2,1,4,5] 4
[2,3,1] 3
number-of-subarrays-with-bounded-maximum)number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold)sum-of-imbalance-numbers-of-all-subarrays)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2488: Count Subarrays With Median K
class Solution {
public int countSubarrays(int[] nums, int k) {
int n = nums.length;
int i = 0;
for (; nums[i] != k; ++i) {
}
int[] cnt = new int[n << 1 | 1];
int ans = 1;
int x = 0;
for (int j = i + 1; j < n; ++j) {
x += nums[j] > k ? 1 : -1;
if (x >= 0 && x <= 1) {
++ans;
}
++cnt[x + n];
}
x = 0;
for (int j = i - 1; j >= 0; --j) {
x += nums[j] > k ? 1 : -1;
if (x >= 0 && x <= 1) {
++ans;
}
ans += cnt[-x + n] + cnt[-x + 1 + n];
}
return ans;
}
}
// Accepted solution for LeetCode #2488: Count Subarrays With Median K
func countSubarrays(nums []int, k int) int {
i, n := 0, len(nums)
for nums[i] != k {
i++
}
ans := 1
cnt := make([]int, n<<1|1)
x := 0
for j := i + 1; j < n; j++ {
if nums[j] > k {
x++
} else {
x--
}
if x >= 0 && x <= 1 {
ans++
}
cnt[x+n]++
}
x = 0
for j := i - 1; j >= 0; j-- {
if nums[j] > k {
x++
} else {
x--
}
if x >= 0 && x <= 1 {
ans++
}
ans += cnt[-x+n] + cnt[-x+1+n]
}
return ans
}
# Accepted solution for LeetCode #2488: Count Subarrays With Median K
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
i = nums.index(k)
cnt = Counter()
ans = 1
x = 0
for v in nums[i + 1 :]:
x += 1 if v > k else -1
ans += 0 <= x <= 1
cnt[x] += 1
x = 0
for j in range(i - 1, -1, -1):
x += 1 if nums[j] > k else -1
ans += 0 <= x <= 1
ans += cnt[-x] + cnt[-x + 1]
return ans
// Accepted solution for LeetCode #2488: Count Subarrays With Median K
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2488: Count Subarrays With Median K
// class Solution {
// public int countSubarrays(int[] nums, int k) {
// int n = nums.length;
// int i = 0;
// for (; nums[i] != k; ++i) {
// }
// int[] cnt = new int[n << 1 | 1];
// int ans = 1;
// int x = 0;
// for (int j = i + 1; j < n; ++j) {
// x += nums[j] > k ? 1 : -1;
// if (x >= 0 && x <= 1) {
// ++ans;
// }
// ++cnt[x + n];
// }
// x = 0;
// for (int j = i - 1; j >= 0; --j) {
// x += nums[j] > k ? 1 : -1;
// if (x >= 0 && x <= 1) {
// ++ans;
// }
// ans += cnt[-x + n] + cnt[-x + 1 + n];
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #2488: Count Subarrays With Median K
function countSubarrays(nums: number[], k: number): number {
const i = nums.indexOf(k);
const n = nums.length;
const cnt = new Array((n << 1) | 1).fill(0);
let ans = 1;
let x = 0;
for (let j = i + 1; j < n; ++j) {
x += nums[j] > k ? 1 : -1;
ans += x >= 0 && x <= 1 ? 1 : 0;
++cnt[x + n];
}
x = 0;
for (let j = i - 1; ~j; --j) {
x += nums[j] > k ? 1 : -1;
ans += x >= 0 && x <= 1 ? 1 : 0;
ans += cnt[-x + n] + cnt[-x + 1 + n];
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.