Trains the technique from
LeetCode 1963Minimum Number of Swaps to Make the String BalancedThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A jig printer stamps a tape of clamp marks; tape records them as a string of '[' and ']' characters.
The tape is balanced when, reading from the left, the number of ']' marks seen never rises above the number of '[' marks seen, and the two counts are equal once the whole tape has been read.
In one operation you may exchange the marks at any two positions of the tape; the two positions need not be next to each other. Return the smallest number of operations that leaves tape balanced.
The tape has even length and carries as many '[' marks as ']' marks, so a balanced arrangement is always reachable.
Example 1
Exchanging the two marks gives "[]", which is balanced.
Example 2
Exchanging position 0 with position 3 gives "[][]", which is balanced.
Example 3
Exchanging position 2 with position 4 gives "[][][]", which is balanced.
Example 4
The tape is already balanced, so no exchange is needed.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def min_swaps(tape: str) -> int:public int minSwaps(String tape)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.