Minimum Window Containing All Balanced Bracket Types
Arrays & HashingAuto-graded · 19 test casesLast updated
Tests ability to use hash counting with a sliding window to find the shortest contiguous subarray that contains at least k complete pairs of each bracket type.
Minimum Window Covering All Bracket Pairs
You are given a string s consisting solely of the characters (, ), [, ], {, }, and a positive integer k.
A substring of s is called k-balanced if, for every bracket type ((), [], {}), the substring contains at least k opening and at least k closing brackets of that type.
Return the length of the shortest contiguous substring of s that is k-balanced. If no such substring exists, return -1.
Notes:
- The substring does not need to be properly nested — you only count raw occurrences.
- All three bracket types must be satisfied simultaneously; missing even one type makes the window invalid.
- If multiple substrings of the same minimum length exist, return the length (it is unique).
Constraints
1 ≤ len(s) ≤ 2 000scontains only the six characters(,),[,],{,}1 ≤ k ≤ 500
Examples
Example 1
Input: min_kbalanced_window('()[]{}()[]{}', 1)
Output: 6
Example 2
Input: min_kbalanced_window('((([[{{}}]]))', 2)
Output: 12
Example 3
Input: min_kbalanced_window('((((((', 1)
Output: -1
Hints
Hint 1
Use a sliding window (two pointers left/right) over the string. Maintain a hash map counting how many of each of the 6 bracket characters appear in the current window.
Hint 2
Track a 'satisfied' counter: a bracket character is satisfied when its count in the window reaches k. The window is k-balanced when all 6 characters are satisfied simultaneously.
Hint 3
When the window is k-balanced, record its length and then advance the left pointer (decrementing counts and updating satisfied) to try to shrink it, repeating until the window is no longer k-balanced.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key insight
This is a classic sliding window + hash counting problem extended to require satisfaction of 6 distinct characters at once.
We maintain a window [left, right] and a count map for all 6 bracket characters. We also track how many of those 6 characters have reached their threshold k (the satisfied counter). When satisfied == 6, the window is k-balanced.
Algorithm
- Expand
rightone step at a time; incrementcounts[s[right]]. - If
counts[s[right]]just hitk, incrementsatisfied. - While
satisfied == 6:- Record
right - left + 1as a candidate answer. - Decrement
counts[s[left]]; if it drops belowk, decrementsatisfied. - Advance
left.
- Record
- Return the best length found, or
-1.
Why it's correct
- Expanding
rightmonotonically means we never miss a valid window. - Shrinking
leftas far as possible while the window remains valid ensures we record the shortest window ending at eachright. - The
satisfiedcounter avoids re-scanning the hash map on every step, keeping each pointer movement O(1).
Complexity
- Time: O(n) — each character is added and removed from the window at most once.
- Space: O(1) — the hash map holds at most 6 keys regardless of input size.
from typing import List
from collections import defaultdict
def min_kbalanced_window(s: str, k: int) -> int:
need = 6 # six bracket characters must all reach count k
counts = defaultdict(int)
satisfied = 0
left = 0
best = float('inf')
n = len(s)
for right in range(n):
ch = s[right]
counts[ch] += 1
if counts[ch] == k:
satisfied += 1
while satisfied == need:
best = min(best, right - left + 1)
lch = s[left]
counts[lch] -= 1
if counts[lch] == k - 1:
satisfied -= 1
left += 1
return best if best != float('inf') else -1