Untitled

mail@pastecode.io avatar
unknown
java
11 days ago
1.7 kB
2
Indexable
Never
import java.util.*;

public class Solution {

    // Function to return the minimum number of swaps required to balance the brackets
    public static int minimumSwaps(String brackets) {
        int swaps = 0;
        int imbalance = 0;

        // Convert the string to a character array for efficiency
        char[] arr = brackets.toCharArray();

        // Variables to track positions
        int n = arr.length;
        int countLeft = 0, countRight = 0;

        // Loop through the array
        for (int i = 0; i < n; i++) {
            if (arr[i] == '(') {
                countLeft++;
                if (imbalance > 0) {
                    // Swap the '(' with the previous ')'
                    swaps += imbalance;
                    imbalance--;
                }
            } else {
                countRight++;
                imbalance = countRight - countLeft;
            }
        }

        // If the number of open and close brackets are not equal, return -1
        if (countLeft != countRight) {
            return -1;
        }

        return swaps;
    }

    public static void main(String[] args) {
        // Sample test cases
        String test1 = "))()(()(";
        String test2 = "()())";
        String test3 = "(())";
        String test4 = ")(";

        System.out.println("Test case 1: " + test1 + " -> Minimum Swaps: " + minimumSwaps(test1)); // Output: 1
        System.out.println("Test case 2: " + test2 + " -> Minimum Swaps: " + minimumSwaps(test2)); // Output: -1
        System.out.println("Test case 3: " + test3 + " -> Minimum Swaps: " + minimumSwaps(test3)); // Output: 0
        System.out.println("Test case 4: " + test4 + " -> Minimum Swaps: " + minimumSwaps(test4)); // Output: 1
    }
}
Leave a Comment