Sponsored
Sponsored
This approach involves traversing the string and counting the balance between opening and closing brackets. You increase a count when you find an opening bracket and decrease the count when you find a closing bracket. If at any point the count goes negative, a swap is needed to balance out the string, and the swap count is incremented. The final swap count will be the required number of swaps to make the string balanced.
Time Complexity: O(n), where n is the length of string s.
Space Complexity: O(1), as no extra space is used aside from a few variables.
1def min_swaps(s):
2 balance = 0
3 swaps = 0
4
5 for ch in s:
6 balance += 1 if
The Python function loops over the string, updating the balance and counting swaps whenever the balance indicates an excess closing bracket.
This approach uses two pointers to traverse the string efficiently. One pointer starts from the beginning of the string, and the other starts at the end. Using these pointers, swaps are performed when an excessive number of closing brackets on one side can be paired with an opening bracket on the other side.
Time Complexity: O(n), where n is the length of string s, due to traversing the string once.
Space Complexity: O(1), as we're only using constants amount of space for pointers and variables.
The JavaScript solution applies the two-pointer paradigm from opposite ends of the string, conducting efficient swaps such that misplaced brackets are realigned efficiently till balance is reached.