Subarray Balance
Rohan, a data scientist, is analyzing customer purchase data. He wants to find the most 'balanced' subarray of a fixed length k. A subarray is considered balanced if the absolute difference between the count of two specific items, say item 'A' and item 'B', is minimized. Given a string s representing the sequence of purchased items and an integer k, find the minimum possible absolute difference between the counts of 'A' and 'B' in any subarray of length k.
Input
The first line contains two integers n and k (2 <= k <= n <= 200000). The second line contains a string s of length n consisting of uppercase English letters.
Output
Print a single integer, the minimum absolute difference between the counts of 'A' and 'B' in any subarray of length k.
Constraints
2 <= k <= n <= 200000 s contains uppercase English letters.
Example 1
5 3 ABABA
1
Subarrays of length 3 are 'ABA' (2 A's, 1 B, diff 1), 'BAB' (1 A, 2 B's, diff 1), 'ABA' (2 A's, 1 B, diff 1). Min diff is 1.
Example 2
7 4 AAABABB
0
Subarrays: 'AAAB'(3A,1B,d2), 'AABA'(3A,1B,d2), 'ABAB'(2A,2B,d0), 'BABB'(1A,3B,d2). Min diff is 0.
Hints
Similar problems
- Longest Subarray with Distinct ElementsHard
- Count Subarrays with Distinct ElementsMedium
- Longest Subarray with At Most K Distinct ElementsMedium
- Minimum Window SubstringHard
- Distinct Subarrays with Bounded SumHard
- Longest Subarray with Equal Number of Zeroes and OnesHard
More topics: Hash Map and Hashing problems, Two Pointers problems, Sliding Window problems
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
5 3 ABABA
7 4 AAABABB