Given two binary string M and N of equal length, the task is to find a minimum number of operations (swaps) required to convert string N to M.
Input: str1 = "1101", str2 = "1110" Output: 1 Swap last and second last element in the binary string, so that it become 1101 Input: str1 = "1110000", str2 = "0001101" Output: 3
Approach: Initialize the counter and Iterate over the M such that if any non-equal elements found in both binary strings, increment the counter. In the end, if the counter is even then print the result/2 because for one swap two elements are non-identical.
Suppose S1 = “10” and S2 = “01”, so two pairs are non-identical, the count = 2 and as the count is even, so number of swaps are count/2, i.e. 1. Even count determines that there are chances to swap the elements.
Below is the implementation of the above approach:
Time Complexity: O(n)
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Minimum swaps required to make a binary string alternating
- Minimum swaps required to make a binary string divisible by 2^k
- Minimum given operations required to convert a given binary string to all 1's
- Minimum operations required to convert a binary string to all 0s or all 1s
- Minimum adjacent swaps required to Sort Binary array
- Minimum number of swaps required to make the string K periodic
- Minimum number of adjacent swaps to convert a string into its given anagram
- Minimum number of swaps to make two binary string equal
- Minimum number of given operations required to convert a string to another string
- Minimum number of subsequences required to convert one string to another
- Minimum number of subsequences required to convert one string to another using Greedy Algorithm
- Minimum flips required to keep all 1s together in a Binary string
- Minimum number of operations required to sum to binary string S
- Minimum cuts required to convert a palindromic string to a different palindromic string
- Minimum steps to convert one binary string to other only using negation