702666. Count Subarrays with Same Min and Max

Easy

Count Subarrays with Same Min and Max

Summary

Given an array, count the number of subarrays where the minimum and maximum elements are the same. This problem involves arrays and mathematical concepts, requiring a clever approach to solve.

Detailed Explanation

To solve this problem, we can use a simple two-pointer technique. Initialize two pointers, left and right, to 0, representing the start and end of the subarray. Iterate through the array with the following steps:

  1. If the current element is less than or equal to the minimum and maximum elements in the current subarray (i.e., [arr[left], arr[right]]), increment left. This ensures that we are considering all possible subarrays where the minimum and maximum elements are the same.
  2. If the current element is greater than the minimum and maximum elements, update the minimum and maximum values if necessary and move right.
  3. Repeat steps 1-2 until right reaches the end of the array.

The time complexity for this algorithm is O(n), where n is the length of the input array. This is because we are iterating through the array once using two pointers. The space complexity is O(1) as we are not using any additional data structures that scale with the size of the input.

Here's a diagram illustrating the process:

  arr = [3, 5, 2, 7, 4]
  left   right
    ^       ^
  min: 3  max: 3
    |       |
 1. [3]     (increment left)
  min: 2  max: 5
    |       |
 2. [2, 5] (update min and max)
  min: 2  max: 7
    |       |
 3. [2, 5, 7] (move right)
  ...

Optimized Solutions

Java

View on GeeksforGeeks
public int countSubarrays(int[] arr) {
    int count = 0;
    int left = 0;
    int minMax = arr[0];
    for (int right = 0; right < arr.length; right++) {
        if (arr[right] <= minMax) {
            left = right;
            minMax = arr[right];
        }
        count += right - left + 1;
    }
    return count;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.