Count Segments Whose Exact Minimum and Maximum Match Two Bounds

Quick Overview

Count contiguous subarrays whose minimum and maximum equal the two specified values, including separate index occurrences.

Count Segments Whose Exact Minimum and Maximum Match Two Bounds

Company: PhonePe

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Other

### Problem Count nonempty contiguous subarrays of `nums` whose minimum is exactly minK and whose maximum is exactly maxK. Return the number of index intervals as long long. ```cpp class Solution { public: long long countSubarrays(vector<int>& nums, int minK, int maxK); }; ``` ### Examples **Example 1:** ```text Input: nums = [2,4,2], minK = 2, maxK = 4 Output: 3 Explanation: Intervals [0,1],[1,2], and[0,2] include both required extrema. ``` **Example 2:** ```text Input: nums = [3,3], minK = 3, maxK = 3 Output: 3 Explanation: Both singletons and the pair have minimum and maximum3. ``` ### Constraints - `2 <= nums.length <= 100000`. - `1 <= nums[i], minK, maxK <= 1000000`. ### Clarifying Questions - Is staying within the two bounds sufficient? No; both exact extrema must occur. - Can the bounds be equal? Yes. - Are identical value sequences at different indices separate subarrays? Yes. - What if `minK > maxK`? No nonempty subarray can satisfy both extrema, so the count is zero. ```hint Check the boundary Compare a subarray that stays inside the range with one that actually contains both required extremes. ```

Overview: Count contiguous subarrays whose minimum and maximum equal the two specified values, including separate index occurrences.

PhonePe logo
PhonePe
Source window: 0–3 months · as of Oct 21, 2026
hardSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Count nonempty contiguous subarrays of nums whose minimum is exactly minK and whose maximum is exactly maxK. Return the number of index intervals as long long.

class Solution {
public:
    long long countSubarrays(vector<int>& nums, int minK, int maxK);
};

Examples

Example 1:

Input: nums = [2,4,2], minK = 2, maxK = 4
Output: 3
Explanation: Intervals [0,1],[1,2], and[0,2] include both required extrema.

Example 2:

Input: nums = [3,3], minK = 3, maxK = 3
Output: 3
Explanation: Both singletons and the pair have minimum and maximum3.

Constraints

  • 2 <= nums.length <= 100000 .
  • 1 <= nums[i], minK, maxK <= 1000000 .

Clarifying Questions Guidance

  • Is staying within the two bounds sufficient? No; both exact extrema must occur.
  • Can the bounds be equal? Yes.
  • Are identical value sequences at different indices separate subarrays? Yes.
  • What if minK > maxK ? No nonempty subarray can satisfy both extrema, so the count is zero.