Solution For Minimum Number Of Swaps To Make The String Balanced
Problem: Given a string with only characters ‘[’ and ‘]’, we have to find the minimum number of swaps required to make the string balanced. A string is considered balanced if it consists of alternating brackets, such as “[[]]” or “[][[]]”.
Approach:
To solve this problem we can use stack data structure. We need to traverse the string from left to right and for every opening bracket, we push its index onto the stack. If we encounter a closing bracket, we check if the stack is not empty and if the top of the stack is an opening bracket of the same type. If it is, we pop the opening bracket from the stack, and the current closing bracket is paired with it, otherwise, we push the index of the current closing bracket onto the stack. Once we have processed the whole string, the stack should only contain the indices of unmatched opening brackets.
Now, to make the given string balanced, we need to swap the unmatched opening brackets with unmatched closing brackets. We can calculate the number of unmatched opening and closing brackets using the stack size and return half of it as the minimum number of swaps required.
Code:
“`python
def min_swaps_to_balance(s: str) -> int:
stack = []
for i, c in enumerate(s):
if c == ‘[‘:
stack.append(i)
else:
if stack and s[stack[-1]] == ‘[‘:
stack.pop()
else:
stack.append(i)
return len(stack) // 2
“`
Time Complexity: O(n) where n is the length of the given string.
Space Complexity: O(n) as we are using a stack to store the indices.
Step by Step Implementation For Minimum Number Of Swaps To Make The String Balanced
public int minSwaps(String s) { int n = s.length(); // Count the number of zeroes and ones in the string int count_0 = 0, count_1 = 0; for (int i = 0; i < n; i++) { if (s.charAt(i) == '0') count_0++; else count_1++; } // If the number of zeroes and ones are equal, no swaps required if (count_0 == count_1) return 0; // If the number of zeroes and ones are not equal, find the minimum number of swaps required int min_swaps = Math.abs(count_0 - count_1); // Traverse the string and count the number of consecutive ones and zeroes int curr_count_0 = 0, curr_count_1 = 0; for (int i = 0; i < n; i++) { // If the current character is '0' if (s.charAt(i) == '0') { curr_count_0++; // If the number of zeroes is more than the number of ones, update the minimum number of swaps if (i + 1 < n && curr_count_0 > curr_count_1) min_swaps = Math.min(min_swaps, curr_count_0 - curr_count_1); } // If the current character is '1' else { curr_count_1++; // If the number of ones is more than the number of zeroes, update the minimum number of swaps if (i + 1 < n && curr_count_1 > curr_count_0) min_swaps = Math.min(min_swaps, curr_count_1 - curr_count_0); } } return min_swaps; }
def minimumSwaps(s): # Create a list of tuples consisting of # all the possible swaps that can be made swaps = [] for i in range(len(s)): for j in range(i+1, len(s)): if s[i] == 'R' and s[j] == 'B': swaps.append((i, j)) if s[i] == 'B' and s[j] == 'R': swaps.append((i, j)) # Function to check if the string is balanced # after making all the swaps def isBalanced(s, swaps): for swap in swaps: i, j = swap s[i], s[j] = s[j], s[i] left = 0 right = 0 for k in range(len(s)): if s[k] == 'R': left += 1 else: right += 1 if left != right: s[i], s[j] = s[j], s[i] return False return True # Function to find the minimum number of swaps # required to make the string balanced def minSwaps(s): swaps = [] for i in range(len(s)): for j in range(i+1, len(s)): if s[i] == 'R' and s[j] == 'B': swaps.append((i, j)) if s[i] == 'B' and s[j] == 'R': swaps.append((i, j)) # Variable to keep track of the minimum number # of swaps required min_swaps = len(swaps) # Find all the permutations of the swaps list # and check if the string is balanced # after making those swaps for i in range(len(swaps)): if isBalanced(s, swaps[:i] + swaps[i+1:]): min_swaps = min(min_swaps, i) return min_swaps # Driver code s = "BRBRR" print(minSwaps(s))
function minimumNumberOfSwaps(s) { // Your code here }
int minimumNumberOfSwaps(string s) { // Create an array of pairs where first // element is string and second element // is position of first 'b' in the string int n = s.length(); pairarr[n]; for (int i = 0; i < n; i++) { arr[i] = make_pair(s.substr(i), s.substr(i).find('b')); } // Sort the array by second element so that // correct position of first 'b' is obtained sort(arr, arr+n); // To keep track of visited elements. Initialize // all elements as not visited or false. vector vis(n, false); // Initialize result int ans = 0; // Traverse array for (int i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos if (vis[i] || arr[i].second == i) continue; // find out the number of node in // this cycle and add in ans int cycle_size = 0; int j = i; while (!vis[j]) { vis[j] = 1; // move to next node j = arr[j].second; cycle_size++; } // Update answer by adding a reduced cycle if(cycle_size > 0) { ans += (cycle_size - 1); } } // Return result return ans; }
public class Solution { public int MinimumSwaps(string s) { // Your code goes here } }