KatInterview

811. Number of Subarrays with Bounded Maximum

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to count the number of contiguous non-empty subarrays where the maximum element falls within a given range [left, right]. A direct approach of checking every possible subarray would be too slow, given the input size can be up to 105. An O(N2) or O(N3) solution will time out. This suggests we need a more efficient, likely linear time, O(N) solution.

Solution

Number of Subarrays with Bounded Maximum in Python

class Solution:
    def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
        # The number of subarrays with maximum in [left, right] is
        # (number of subarrays with maximum <= right) - (number of subarrays with maximum < left).
        # which is equivalent to countAtMost(right) - countAtMost(left - 1).
        
        def countAtMost(k: int) -> int:
            """Counts subarrays where the maximum element is at most k."""
            ans = 0
            current_length = 0
            for num in nums:
                if num <= k:
                    # If num is within the bound, it extends the current valid window.
                    current_length += 1
                else:
                    # If num is greater than k, it breaks the window.
                    current_length = 0
                # For a valid window of length `current_length` ending at the current position,
                # there are `current_length` subarrays ending here with all elements <= k.
                ans += current_length
            return ans

        return countAtMost(right) - countAtMost(left - 1)

Number of Subarrays with Bounded Maximum in Java

class Solution {
    public int numSubarrayBoundedMax(int[] nums, int left, int right) {
        // The number of subarrays with maximum in [left, right] is
        // (number of subarrays with maximum <= right) - (number of subarrays with maximum < left).
        // which is equivalent to countAtMost(right) - countAtMost(left - 1).
        return countAtMost(nums, right) - countAtMost(nums, left - 1);
    }

    // Helper function to count subarrays where the maximum element is at most K.
    private int countAtMost(int[] nums, int k) {
        int ans = 0;
        int currentLength = 0;
        for (int num : nums) {
            if (num <= k) {
                // If num is within the bound, it can extend the current valid window.
                currentLength++;
            } else {
                // If num is greater than k, it breaks the window.
                currentLength = 0;
            }
            // For a valid window of length `currentLength` ending at the current position,
            // there are `currentLength` subarrays ending here with all elements <= k.
            ans += currentLength;
        }
        return ans;
    }
}

Number of Subarrays with Bounded Maximum in C++

class Solution {
public:
    int numSubarrayBoundedMax(vector<int>& nums, int left, int right) {
        return countAtMost(nums, right) - countAtMost(nums, left - 1);
    }

private:
    // Helper function to count subarrays where the maximum element is at most K.
    int countAtMost(vector<int>& nums, int k) {
        int ans = 0;
        int current_length = 0;
        for (int num : nums) {
            if (num <= k) {
                // If num is within the bound, it can extend the current valid window.
                current_length++;
            } else {
                // If num is greater than k, it breaks the window.
                current_length = 0;
            }
            // For a valid window of length `current_length` ending at the current position,
            // there are `current_length` subarrays ending here with all elements <= k.
            ans += current_length;
        }
        return ans;
    }
};

Number of Subarrays with Bounded Maximum in TypeScript

function numSubarrayBoundedMax(nums: number[], left: number, right: number): number {
    // Helper function to count subarrays where the maximum element is at most K.
    const countAtMost = (k: number): number => {
        let ans = 0;
        let currentLength = 0;
        for (const num of nums) {
            if (num <= k) {
                // If num is within the bound, it can extend the current valid window.
                currentLength++;
            } else {
                // If num is greater than k, it breaks the window.
                currentLength = 0;
            }
            // For a valid window of length `currentLength` ending at the current position,
            // there are `currentLength` subarrays ending here with all elements <= k.
            ans += currentLength;
        }
        return ans;
    };

    // The number of subarrays with maximum in [left, right] is
    // (number of subarrays with maximum <= right) - (number of subarrays with maximum < left).
    // which is equivalent to countAtMost(right) - countAtMost(left - 1).
    return countAtMost(right) - countAtMost(left - 1);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.