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.
1#include <stdio.h>
2#include <string.h>
3
4int minSwaps(char *s) {
5 int balance = 0, swaps = 0;
6
7 for (int i = 0; i < strlen(s); i++) {
8 if (s[i] == '[') {
9 balance++;
10 } else {
11 balance--;
12 }
13
14 if (balance < 0) {
15 swaps++;
16 balance += 2;
17 }
18 }
19 return swaps;
20}
21
22int main() {
23 char s[] = "][][";
24 printf("Minimum swaps: %d\n", minSwaps(s));
25 return 0;
26}
This solution maintains a balance count by iterating over the characters of the string. It increases the balance for each opening bracket '[' encountered and decreases it for each closing bracket ']'. Whenever the balance goes negative, a swap is needed to make balance non-negative, hence the count of swaps is incremented along with a correction of balance at that point. This provides the minimum number of swaps needed.
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.
Two pointers are initialized at the start and end of the string. The inner mismatched brackets are swapped until the string becomes balanced. The solution ensures that excessive closing brackets found earlier are balanced by swapping them with opening brackets found later in the string.