Count Subarrays Where Max Element Appears at Least K Times

Count the subarrays in which the largest value of the whole array appears at least k times.

Given an array of positive integers nums and a positive integer k, count the subarrays in which the largest value of the whole array appears at least k times. A subarray is a run of one or more neighbouring elements of the array.

Example 1
Input: nums = [1, 3, 2, 3, 3], k = 2
Output: 6
Explanation: the subarrays are [1, 3, 2, 3], [1, 3, 2, 3, 3], [3, 2, 3], [3, 2, 3, 3], [2, 3, 3] and [3, 3].
Example 2
Input: nums = [1, 4, 2, 1], k = 3
Output: 0
Explanation: the largest value, 4, appears only once, so no subarray can hold it three times.
Solution

The Idea

Think of [1, 3, 2, 3, 3] as scores from five games in a row. The best score is 3, and you want to know how many stretches of games in a row contain that best score at least twice. A stretch of games in a row is exactly a subarray.

Only one value matters here: the largest one, 3. The 1 and the 2 never decide anything; they only make a subarray longer. The array has 15 subarrays, and six of them hold two or more 3s. Checking 15 is easy, but an array of 100,000 numbers has about 5 billion subarrays. How can we count the good ones without looking at each?

Fix where the subarray ends and look at its possible starts. Take the subarrays that end at index 3, the second 3. Starting at index 3 gives [3], and starting at index 2 gives [2, 3]. Both hold one 3. Starting at index 1 gives [3, 2, 3], and index 0 gives [1, 3, 2, 3]. Both hold two.

Moving the start to the left only adds numbers, so the count of 3s can grow but never shrink. That means the good starts always form a block at the front: index 0 up to some point, and nothing after it. To count them, we only need to know where that block ends.

Look at the picture below. The blue box is a window: the numbers from a start position left to the end position right. Its left edge sits at the leftmost start that gives fewer than two 3s, so every start before left is a good one.

The array 1, 3, 2, 3, 3 with k = 2. In the row right = 3, the window starts at left = 2 and holds one 3, so starts 0 to 1 are good: adds 2. In the row right = 4, the window is only index 4, left = 4, so starts 0 to 3 are good: adds 4. Total 6.

In the row labelled right = 3, the window is [2, 3] with left = 2, and it holds one 3. The orange starts, 0 to 1, each give two 3s, so this end adds 2. In the row labelled right = 4, the window shrinks to the last 3 alone, so left = 4. Starts 0 to 3 are orange, and this end adds 4.

The ends at index 0, 1 and 2 add nothing, because [1, 3, 2] holds only one 3. So the total is 2 + 4 = 6, the answer to Example 1. The number of good subarrays ending at right is simply left.

A window whose two edges only ever move to the right is called a sliding window. Here it lets us count whole blocks of subarrays in one step, instead of listing them.

Solution Approach

Turning that idea into code means settling four things: how to find the largest value, how to count the subarrays for each end, how to move the window's left edge, and which type can hold the answer.

Finding the largest value

Which value are we counting? The largest value of the whole array, not the largest of each subarray. In Example 2 we count 4s, even when looking at [2, 1], whose own largest value is 2. So one pass over the array finds it, and it is called max from here on.

Counting by the end of the subarray

Why not check every subarray? The simple way picks each start with one loop, and inside it a second loop extends the end one step at a time while counting copies of max. For an array of n numbers that takes about n²/2 steps, around 5 billion for 100,000 numbers.

Instead, one loop moves the end right from the first index to the last. For each end, the good starts are the block 0 to left - 1, so left is added to the answer in one step.

Moving the left edge

When does left move? The window keeps count, the number of copies of max between left and right. When the new number at right is max and count reaches k, move left forward until it has passed one copy, leaving k - 1 copies.

At that point the window starting at left is one copy short, and the one starting at left - 1 has exactly k. Does left ever need to move back? No. For the next end, the starts before left only gain numbers, so they stay good. Both edges only move forward.

Holding the answer

How large can the answer get? If all n numbers are equal and k is 1, every subarray counts, and there are n × (n + 1) / 2 of them. For 100,000 numbers that is 5,000,050,000, more than twice 2,147,483,647, the largest value a Java int can hold. So the answer is kept in a long.

Java Solution

The method countSubarrays works in these steps:

  1. First, find the largest value, max, with one loop over nums that starts from nums[0].
  2. Set up the window: left starts at 0, count (the copies of max in the window) starts at 0, and the answer result, a long, starts at 0.
  3. A second loop moves right from the first index to the last. When nums[right] equals max, add one to count.
  4. Inside that loop, a while loop runs as long as count equals k. If nums[left] is max, take one off count; either way, move left one place forward.
  5. Add left to result, which counts the starts 0 to left - 1 for this right.
  6. When the loop over right is done, return result.

The main method runs both examples, three equal numbers with k = 2, a single number with k = 1, and 100,000 equal numbers with k = 1.

Java
import java.util.Arrays;

public class CountSubarraysWhereMaxAppearsKTimes {

    public static long countSubarrays(int[] nums, int k) {
        int max = nums[0];
        for (int x : nums) {
            max = Math.max(max, x);
        }
        long result = 0;
        int left = 0;
        int count = 0;                        // copies of max in nums[left..right]
        for (int right = 0; right < nums.length; right++) {
            if (nums[right] == max) {
                count++;
            }
            while (count == k) {              // shrink until the window has k - 1 copies
                if (nums[left] == max) {
                    count--;
                }
                left++;
            }
            result += left;                   // starts 0 .. left-1 all give >= k copies
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(countSubarrays(new int[] {1, 3, 2, 3, 3}, 2));
        System.out.println(countSubarrays(new int[] {1, 4, 2, 1}, 3));
        System.out.println(countSubarrays(new int[] {5, 5, 5}, 2));
        System.out.println(countSubarrays(new int[] {7}, 1));
        int[] same = new int[100000];
        Arrays.fill(same, 9);
        System.out.println(countSubarrays(same, 1));
    }
}

Running it prints:

Output
6
0
3
1
5000050000

Example 1 gives 6, the 2 + 4 from the picture, and Example 2 gives 0 because count never reaches 3. Look at the third line, 3, from [5, 5, 5] with k = 2. The end at index 0 adds 0, index 1 adds 1 for [5, 5], and index 2 adds 2 for [5, 5] and [5, 5, 5].

The single number 7 with k = 1 prints 1: the array itself is the only subarray. The last line, 5000050000, is every one of the 100,000 × 100,001 / 2 subarrays. Kept in an int instead of a long, result would pass 2,147,483,647 and jump down to large negative numbers, which is called overflow. The same input then returns 705082704, exactly 4,294,967,296 short of the true count.

Complexity

The work is one pass to find max, plus one pass of the window, in which each edge moves forward only.

  • Time: O(n), because the first loop reads each of the n numbers once, right visits each index once, and left never moves back, so all the while loops together move it at most n times.
  • Space: O(1), because the method keeps only max, left, right, count and result, with no extra array or map.

The same step of adding all the starts before left at once is used in Number of Substrings Containing All Three Characters.