KatInterview

Minimum Window Containing All Balanced Bracket Types

Arrays & HashingAuto-graded · 19 test cases
HardAuto-gradedArrays & Hashingarrayshash mapsliding window

Last 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 000
  • s contains 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.