Magicsheet logo

Count Subarrays Where Max Element Appears at Least K Times

Medium
62.5%
Updated 8/1/2025

Count Subarrays Where Max Element Appears at Least K Times

What is this problem about?

The "Count Subarrays Where Max Element Appears at Least K Times interview question" is an optimization challenge. You are given an array and an integer k. You first find the maximum element in the entire array. Your task is to count the total number of subarrays that contain this maximum element at least k times.

Why is this asked in interviews?

Companies like Meta, Amazon, and Bloomberg use the "Count Subarrays Where Max Element coding problem" to test a candidate's ability to use the Sliding Window technique on more complex conditions. A brute-force approach would be O(N2)O(N^2), but the sliding window allows for an O(N)O(N) solution. It evaluations your ability to maintain a frequency count while expanding and shrinking a window.

Algorithmic pattern used

This problem follows the Sliding Window and Two Pointers pattern.

  1. Identify Max: Find the maximum value MM in the input array.
  2. Initialize: Use two pointers, left and right, and a counter countMax for occurrences of MM in the current window.
  3. Expand: Move the right pointer. If arr[right] == M, increment countMax.
  4. Shrink and Count: While countMax >= k:
    • Every subarray starting at left and ending at or after right is a valid subarray. There are n - right such subarrays. Add this to your total result.
    • Move the left pointer. If arr[left] == M, decrement countMax.
  5. Sum: Return the total count.

Example explanation

Array: [1, 3, 2, 3, 3], k=2k=2. Max is 3.

  • right moves to index 3 (second '3'): countMax = 2.
  • Valid subarrays starting at index 0 and ending at index 3 or 4: [1,3,2,3], [1,3,2,3,3]. (Count += 2).
  • Move left to index 1. arr[0] was not 3, so countMax is still 2.
  • Valid subarrays starting at index 1: [3,2,3], [3,2,3,3]. (Count += 2). ... and so on.

Common mistakes candidates make

  • O(N2)O(N^2) Simulation: Checking every subarray, which is too slow.
  • Incorrect Formula: Failing to realize that if a window [left,right][left, right] is valid, then all windows [left,rightn1][left, right \dots n-1] are also valid.
  • Multiple Maxima: Forgetting that "max element" refers to the value, not a specific index (multiple 3s in the example).

Interview preparation tip

Master the "Sliding Window interview pattern." It is the most common optimization for subarray problems. Practice identifying when a condition is "monotonic"—meaning if it's true for a window, it remains true as you expand it.

Similar Questions