Count Subarrays Between Min and Max

Count Fixed-Bound Subarrays — Satisfying MinK and MaxK

Problem Statement

You are given an array of integers nums and two integers minK and maxK.

A fixed-bound subarray of nums is a subarray that satisfies the following conditions:

  • The minimum value in the subarray is equal to minK.

  • The maximum value in the subarray is equal to maxK.

Your task is to return the number of fixed-bound subarrays in nums.

Example 1:

Input: nums = [1, 3, 5, 2, 7, 5], minK = 1, maxK = 5

Output: 2

Explanation: The fixed-bound subarrays are [1, 3, 5] and [1, 3, 5, 2].

Best Technique – Sliding Window + Boundary Tracking

This problem can be tricky because you need to ensure the subarray contains both the minimum and maximum values exactly. We can efficiently solve this using a sliding window technique, maintaining boundaries to ensure that the subarrays stay valid.

Different Approaches:

Approach 1: Brute Force with Set Tracking

We could try every possible subarray and check if it meets the conditions. This involves using a Set to track the minimum and maximum values of each subarray. If the subarray contains both minK and maxK, we count it.

public static int countFixedBoundSubarrays(int[] nums, int minK, int maxK) { int n = nums.length; int result = 0; for (int i = 0; i < n; i++) { Set<Integer> seen = new HashSet<>(); for (int j = i; j < n; j++) { seen.add(nums[j]); if (seen.contains(minK) && seen.contains(maxK)) { result++; } } } return result; }

Approach 2: HashMap with Frequency Counting (Improved Brute Force)

To optimize the brute force solution, we can use a HashMap to keep track of element frequencies in the subarray. This way, we don’t need to recompute the set for every subarray from scratch.

public static int countFixedBoundSubarraysWithMap(int[] nums, int minK, int maxK) { int result = 0; for (int i = 0; i < nums.length; i++) { Map<Integer, Integer> freq = new HashMap<>(); for (int j = i; j < nums.length; j++) { freq.put(nums[j], freq.getOrDefault(nums[j], 0) + 1); if (freq.containsKey(minK) && freq.containsKey(maxK)) { result++; } } } return result; }

Approach 3: Optimized Sliding Window with Boundary Tracking

Instead of checking every subarray, we can maintain a sliding window that dynamically checks for valid subarrays. We'll use two variables left and right to define the window, and track the number of valid subarrays as the window expands and contracts.

public static int countFixedBoundSubarraysOptimized(int[] nums, int minK, int maxK) { int result = 0; int left = 0; int lastMinK = -1; int lastMaxK = -1; int n = nums.length; for (int right = 0; right < n; right++) { if (nums[right] < minK || nums[right] > maxK) { left = right + 1; // Reset the window continue; } if (nums[right] == minK) lastMinK = right; if (nums[right] == maxK) lastMaxK = right; if (lastMinK != -1 && lastMaxK != -1) { result += Math.min(lastMinK, lastMaxK) - left + 1; } } return result; } 

⚠️Common Pitfalls:

  • Not properly resetting the sliding window when encountering values outside the valid range.

  • Forgetting to track the last occurrences of minK and maxK.

  • Misunderstanding the relationship between subarrays and their valid bounds.

📊Time and Space Complexity:

ApproachTime Complexity    Space Complexity
Brute Force      O(n²)      O(n)
HashMap      O(n²)      O(n)
Optimized Sliding Window      O(n)      O(n)

🌍Real-World Applications:

  • Range-based queries: In applications where you need to check conditions within a specific range (e.g., in a list of user actions).

  • Data Validation: Checking whether all required conditions (min and max values) are met in a sequence of data.

  • Sliding Window Problems: Common in areas like text processing, searching for patterns, or analyzing time-series data.


I hope you found this article insightful! Keep exploring, keep learning, and don’t forget to check back daily for more exciting problem breakdowns. If you know someone who would benefit from this, share it with them and help them grow too! That’s it for today—see you in the next post!

                                                                                                                                         Signing off!! 

                                                                                                Master DSA One Problem at a Time :)

Comments

Popular posts from this blog

Divisible Drama — Who’s In, Who’s Out?

Trailing Zeros in Factorial – How Many and Why?

Minimum equal sum