Practice › Hashing & Two Pointers
Count Subarrays with Fixed Bounds
Hard · Hashing & Two Pointers · Asked at Amazon, Google, Microsoft
Print the number of contiguous subarrays whose minimum is exactly minK and whose maximum is exactly maxK.
Input
First line: n minK maxK. Second line: n integers.
Output
The number of such subarrays.
Constraints
- 2 ≤ n ≤ 10^5
- 1 ≤ a[i], minK, maxK ≤ 10^6
Scan once, remembering the last index of minK, the last index of maxK and the last index of a value outside [minK, maxK]. A subarray ending at i is valid if it starts after the last bad index and at or before both of the other two — add max(0, min(lastMin, lastMax) − lastBad).
Example 1
Input
6 1 5 1 3 5 2 7 5
Output
2
Example 2
Input
4 1 1 1 1 1 1
Output
10
Hints
- A value outside [minK, maxK] can never be inside a valid subarray — it splits the array.
- For a subarray ending at i, it must start after the last bad index.
- It must also contain the last minK and the last maxK seen so far.
Approach
Track lastBad, lastMin and lastMax (all −1 at first). At each index update them. The valid starts for subarrays ending at i are lastBad + 1 … min(lastMin, lastMax), so add max(0, min(lastMin, lastMax) − lastBad). This works even when minK = maxK. The total can pass 2^31, so use 64 bits.
Complexity: O(n) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
long long mn, mx;
cin >> n >> mn >> mx;
long long lastMin = -1, lastMax = -1, lastBad = -1, count = 0;
for (long long i = 0; i < n; i++) {
long long x;
cin >> x;
if (x < mn || x > mx) lastBad = i;
if (x == mn) lastMin = i;
if (x == mx) lastMax = i;
count += max(0LL, min(lastMin, lastMax) - lastBad);
}
cout << count << "\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n, mn, mx = data[0], data[1], data[2]
last_min = last_max = last_bad = -1
count = 0
for i, x in enumerate(data[3 : 3 + n]):
if x < mn or x > mx:
last_bad = i
if x == mn:
last_min = i
if x == mx:
last_max = i
count += max(0, min(last_min, last_max) - last_bad)
print(count)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
long mn = (long) in.nval;
in.nextToken();
long mx = (long) in.nval;
long lastMin = -1, lastMax = -1, lastBad = -1, count = 0;
for (long i = 0; i < n; i++) {
in.nextToken();
long x = (long) in.nval;
if (x < mn || x > mx) lastBad = i;
if (x == mn) lastMin = i;
if (x == mx) lastMax = i;
count += Math.max(0, Math.min(lastMin, lastMax) - lastBad);
}
System.out.println(count);
}
}Solve Count Subarrays with Fixed Bounds online · All practice problems