Count Subarrays Where Max Element Appears at Least K Times
Problem Statement
You are given an integer array nums and a positive integer k.
Let mx be the largest value in the whole array. Count how many contiguous subarrays contain mx at least k times.
An integer array nums and an integer k.
The number of subarrays in which the maximum element of nums appears at least k times (as a 64-bit integer).
The maximum is 3. The subarrays with at least two 3's are [1,3,2,3], [1,3,2,3,3], [3,2,3], [3,2,3,3], [2,3,3] and [3,3].
The maximum 4 appears only once in the whole array, so no subarray has it 3 times.
- • 1 ≤ nums.length ≤ 10^5
- • 1 ≤ nums[i] ≤ 10^6
- • 1 ≤ k ≤ 10^5
- • The answer can reach n(n+1)/2 ≈ 5·10^9, so it needs long long.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each start, grow until mx appears k times, then add n − end
Shrink while the window has k copies of mx; all starts before left work
Find mx. For each start, grow the end and count copies of mx. When the count reaches k, every longer subarray from this start also has at least k copies, so add n − end and move to the next start.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.