The at most k trick
27 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A standard variable-size sliding window struggles when asked to count subarrays with exactly k distinct integers or exactly k odd numbers, because multiple left positions can satisfy == k for the same right. The at-most-k trick turns any monotonic 'exactly k' counting problem into the difference of two simple windows: exactly(k) = atMost(k) - atMost(k - 1).
Why 'exactly k' is tricky and how exactly(k) = atMost(k) − atMost(k − 1) fixes it
The at-most-k trick counts subarrays with exactly k distinct values as atMost(k) - atMost(k - 1), because one sliding window cannot count "exactly k" directly. Consider nums = [1, 2, 1, 2, 3] and k = 2 distinct integers.
int[] nums = {1, 2, 1, 2, 3};long atMost2 = atMost(nums, 2); // 12 subarrays with <= 2 distinctlong atMost1 = atMost(nums, 1); // 5 subarrays with <= 1 distinctlong exactly2 = atMost2 - atMost1; // 7 subarrays with exactly 2 distinctWhen right = 3 ([1, 2, 1, 2]), the subarrays [1, 2, 1, 2], [2, 1, 2], and [1, 2] all have exactly 2 distinct integers! If a single left pointer shrinks past index 0, it loses the ability to count index 0 for right = 3 while also needing index 0 if right continued with 1.
By contrast, counting subarrays with at most k distinct integers is effortless because "having ≤ k distinct integers" is downward-closed: if nums[left .. right] has ≤ k distinct values, then every subarray ending at right and starting at i in left .. right also has ≤ k distinct values! That contributes right - left + 1 valid subarrays ending at right.
Since the set of subarrays with ≤ k items is the disjoint union of subarrays with ≤ k - 1 items and subarrays with exactly k items, subtracting the two counts leaves only the subarrays with exactly k items:
exactly(k) = atMost(k) - atMost(k - 1)
- In atMost(k), for each right we shrink left while metric > k, then add (right - left + 1) to total count.
- Guard k < 0 inside atMost(k) by returning 0 immediately (important when k == 0 so atMost(k - 1) is atMost(-1)).
- Use a long for the total subarray count when n can be 10^5, since n(n + 1)/2 can reach ~5 * 10^9.
Subarrays with k distinct values
In Subarrays with K Different Integers, given int[] nums and int k, we want the number of good subarrays that contain exactly k different integers.
- Write atMostKDistinct(nums, k): if k <= 0 return 0.
- Expand right, updating freq and distinct.
- Shrink left while distinct > k.
- Add right - left + 1 to the running total.
- Return atMostKDistinct(nums, k) - atMostKDistinct(nums, k - 1).
Example 1 · Subarrays with K Different Integers
import java.util.HashMap;import java.util.Map;
public class SubarraysWithKDistinctDemo { public static int subarraysWithKDistinct(int[] nums, int k) { return atMostK(nums, k) - atMostK(nums, k - 1); }
private static int atMostK(int[] nums, int k) { if (k <= 0) { return 0; } Map<Integer, Integer> freq = new HashMap<>(); int left = 0; int count = 0;
for (int right = 0; right < nums.length; right++) { freq.put(nums[right], freq.getOrDefault(nums[right], 0) + 1); while (freq.size() > k) { int out = nums[left++]; if (freq.get(out) == 1) { freq.remove(out); } else { freq.put(out, freq.get(out) - 1); } } count += right - left + 1; } return count; }
public static void main(String[] args) { int[] a = {1, 2, 1, 2, 3}; System.out.println("Exactly 2 distinct in [1,2,1,2,3]: " + subarraysWithKDistinct(a, 2)); int[] b = {1, 2, 1, 3, 4}; System.out.println("Exactly 3 distinct in [1,2,1,3,4]: " + subarraysWithKDistinct(b, 3)); }}Exactly 2 distinct in [1,2,1,2,3]: 7 Exactly 3 distinct in [1,2,1,3,4]: 3
What this code does
- For [1, 2, 1, 2, 3], atMostK(a, 2) = 12 and atMostK(a, 1) = 5, so 12 - 5 = 7 subarrays have [exactly] 2 distinct integers.
- Each call to atMostK runs in O(n) time, so the total runtime is O(n).
We write a single helper atMostKDistinct(int[] nums, int k):
- Maintain a frequency map (or
int[nums.length + 1]when 1 ≤ nums[i] ≤ n) andint distinct = 0. - For each
right, incrementfreq[nums[right]]; if it becomes1, incrementdistinct. while (distinct > k), decrementfreq[nums[left++]]; if it drops to0, decrementdistinct.- Add
right - left + 1tocount. ThensubarraysWithKDistinct(nums, k)is simply a one-liner:return atMostKDistinct(nums, k) - atMostKDistinct(nums, k - 1);.
Count of nice subarrays and binary subarrays with sum
The same identity solves two more classic interview problems: counting exactly k odd numbers, and counting a binary sum.
Example 2 · Count Number of Nice Subarrays (exactly k odd numbers)
public class NiceSubarraysDemo { public static int numberOfSubarrays(int[] nums, int k) { return atMostKOdds(nums, k) - atMostKOdds(nums, k - 1); }
private static int atMostKOdds(int[] nums, int k) { if (k < 0) { return 0; } int left = 0; int odds = 0; int count = 0; for (int right = 0; right < nums.length; right++) { odds += nums[right] & 1; while (odds > k) { odds -= nums[left++] & 1; } count += right - left + 1; } return count; }
public static void main(String[] args) { int[] nums1 = {1, 1, 2, 1, 1}; System.out.println("Nice subarrays (k=3): " + numberOfSubarrays(nums1, 3)); int[] nums2 = {2, 2, 2, 1, 2, 2, 1, 2, 2, 2}; System.out.println("Nice subarrays (k=2): " + numberOfSubarrays(nums2, 2)); }}Nice subarrays (k=3): 2 Nice subarrays (k=2): 16
What this code does
- Using (nums[i] & 1) treats odd numbers as 1 and even numbers as 0, reducing the problem to non-negative subarray sums.
- Unlike a prefix-sum HashMap which uses O(n) space, the at-most-k sliding window uses O(1) extra space.
Example 3 · Binary Subarrays With Sum (handling goal == 0 safely)
public class BinarySubarraysWithSumDemo { public static int numSubarraysWithSum(int[] nums, int goal) { return atMostSum(nums, goal) - atMostSum(nums, goal - 1); }
private static int atMostSum(int[] nums, int maxSum) { if (maxSum < 0) { return 0; } int left = 0; int sum = 0; int count = 0; for (int right = 0; right < nums.length; right++) { sum += nums[right]; while (sum > maxSum) { sum -= nums[left++]; } count += right - left + 1; } return count; }
public static void main(String[] args) { int[] a = {1, 0, 1, 0, 1}; System.out.println("Goal 2 in [1,0,1,0,1]: " + numSubarraysWithSum(a, 2)); int[] zeroes = {0, 0, 0, 0, 0}; System.out.println("Goal 0 in [0,0,0,0,0]: " + numSubarraysWithSum(zeroes, 0)); }}Goal 2 in [1,0,1,0,1]: 4 Goal 0 in [0,0,0,0,0]: 15
What this code does
- When goal = 0, numSubarraysWithSum calls atMostSum(zeroes, 0) - atMostSum(zeroes, -1).
- Because atMostSum returns 0 immediately when maxSum < 0, it avoids an infinite or out-of-bounds while (sum > -1) loop.
- Count Number of Nice Subarrays: A subarray is nice if it contains exactly k odd numbers. Since adding/removing an element changes the odd count by
nums[i] & 1(0 or 1, never negative!), we writeatMostKOdd(nums, k)and returnatMostKOdd(nums, k) - atMostKOdd(nums, k - 1). - Binary Subarrays With Sum: Given a binary array
nums(0s and1s) and an integergoal, count subarrays with sum equal togoal. Since all elements are non-negative (0or1), we writeatMostSum(nums, goal) - atMostSum(nums, goal - 1)in O(n) time and O(1) space—even cleaner than a prefix-sum HashMap!
Next step
Check your understanding
10 quick questions