✅BEST | GREEDY | JAVA | Explained🔥🔥🔥
Variables:\nbalance: Tracks the balance between [ and ]. Positive means more [ than ], negative means more ] than [.\nunbalanced: Tracks how many unbalanced clo
**Variables:**\nbalance: Tracks the balance between [ and ]. Positive means more [ than ], negative means more ] than [.\nunbalanced: Tracks how many unbalanced closing brackets (]) have been encountered so far.\n\n**Traverse the String:**\nAs we iterate over the string:\nFor each [, we increase the balance.\nFor each ], we decrease the balance.\nIf at any point, the balance becomes negative, it means we have more ] than [ so far, which indicates an unbalanced part.\n\n**Counting Swaps:**\nWhenever the balance goes negative, we record it by incrementing the unbalanced counter.\nSince one swap can fix two unbalanced brackets, the number of swaps required is half the total number of unbalanced closing brackets (]).\n\n**Time Complexity:**\nThe solution traverses the string exactly once, so the time complexity is O(n), where n is the length of the string.\n\n**Space Complexity:**\nThe space complexity is O(1), as we only use a few integer variables for tracking balance and swaps.\n\n# Code\n```java []\nclass Solution {\n    public int minSwaps(String s) {\n        int balance = 0;\n        int swaps = 0;\n        int unbalanced = 0;  // Tracks the number of unbalanced \']\'\n        \n        // Traverse through the string\n        for (int i = 0; i < s.length(); i++) {\n            if (s.charAt(i) == \'[\') {\n                balance++;  // Increase balance for \'[\'\n            } else {\n                balance--;  // Decrease balance for \']\'\n            }\n            \n            // If balance goes negative, we have unbalanced \']\' \n            if (balance < 0) {\n                unbalanced++;  // We need to fix this unbalanced part\n                balance = 0;  // Reset balance for the next segment\n            }\n        }\n        \n        // Calculate the minimum number of swaps needed\n        // We need to swap half of the remaining unmatched brackets\n        // Use integer division and add 1 to round up for odd numbers\n        swaps = (unbalanced + 1) / 2;\n        \n        return swaps;\n    }\n}\n```
['Java']