Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIMinimum number of given operations required to convert a string to another...

Minimum number of given operations required to convert a string to another string

Given two strings S and T of equal length. Both strings contain only the characters ‘0’ and ‘1’. The task is to find the minimum number of operations to convert string S to T. There are 2 types of operations allowed on string S

  • Swap any two characters of the string.
  • Replace a ‘0’ with a ‘1’ or vice versa.

Examples: 

Input: S = “011”, T = “101” 
Output:
Swap the first and second character.

Input: S = “010”, T = “101” 
Output:
Swap the first and second character and replace the third character with ‘1’. 

Brute Force:

To solve this problem, we can use a greedy approach. We can iterate over both strings and keep track of the number of differences between the corresponding characters in both strings. Let diffCount be the count of differences between the corresponding characters in s and t.

We can perform the following operations to reduce the value of diffCount:

  1. Swap the two different characters in s and t.
  2. Replace a character in s or t with its complement.

We can choose the operation that reduces diffCount the most at each step. We repeat this process until diffCount becomes 0.

Here’s the step-by-step approach:

  1. Initialize diffCount to 0.
  2. Iterate over both strings and count the number of differences between the corresponding characters in both strings. Update diffCount accordingly.
  3. While diffCount is greater than 0:
  4. If diffCount is 2 or more, find the two different characters in s and t that occur at the same position and swap them. Update diffCount accordingly.
  5. f diffCount is 1, find the different character in s and t that occurs at the same position and replace it with its complement. Update diffCount accordingly.
  6. Repeat steps 2-5 until diffCount becomes 0.
  7. Return the number of operations performed.

Below is the implementation of the above approach:  

C




#include <stdio.h>
#include <string.h>
 
// Function to return the minimum operations
// of the given type required to convert
// string s to string t
int minOperations(char s[], char t[], int n)
{
    int diffCount = 0;
    for (int i = 0; i < n; i++) {
        if (s[i] != t[i]) {
            diffCount++;
        }
    }
 
    int operations = 0;
    while (diffCount > 0) {
        if (diffCount >= 2) {
            // Find the two different characters
            // in s and t that occur at the same position
            int pos1 = -1, pos2 = -1;
            for (int i = 0; i < n; i++) {
                if (s[i] != t[i]) {
                    if (pos1 == -1) {
                        pos1 = i;
                    }
                    else {
                        pos2 = i;
                        break;
                    }
                }
            }
 
            // Swap the two different characters
            char temp = s[pos1];
            s[pos1] = s[pos2];
            s[pos2] = temp;
 
            temp = t[pos1];
            t[pos1] = t[pos2];
            t[pos2] = temp;
 
            // Update the difference count
            diffCount -= 2;
            operations++;
        }
        else {
            // Find the different character in s and t
            // that occurs at the same position
            int pos = -1;
            for (int i = 0; i < n; i++) {
                if (s[i] != t[i]) {
                    pos = i;
                    break;
                }
            }
 
            // Replace the different character with its
            // complement
            s[pos] = (s[pos] == '0') ? '1' : '0';
 
            // Update the difference count
            diffCount--;
            operations++;
        }
    }
 
    return operations;
}
 
// Driver code
int main()
{
    char s[] = "010", t[] = "101";
    int n = strlen(s);
    printf("%d", minOperations(s, t, n));
 
    return 0;
}


C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the minimum operations
// of the given type required to convert
// string s to string t
int minOperations(string s, string t, int n)
{
    int diffCount = 0;
    for (int i = 0; i < n; i++) {
        if (s[i] != t[i]) {
            diffCount++;
        }
    }
 
    int operations = 0;
    while (diffCount > 0) {
        if (diffCount >= 2) {
            // Find the two different characters
            // in s and t that occur at the same position
            int pos1 = -1, pos2 = -1;
            for (int i = 0; i < n; i++) {
                if (s[i] != t[i]) {
                    if (pos1 == -1) {
                        pos1 = i;
                    } else {
                        pos2 = i;
                        break;
                    }
                }
            }
 
            // Swap the two different characters
            swap(s[pos1], s[pos2]);
            swap(t[pos1], t[pos2]);
 
            // Update the difference count
            diffCount -= 2;
            operations++;
        } else {
            // Find the different character in s and t
            // that occurs at the same position
            int pos = -1;
            for (int i = 0; i < n; i++) {
                if (s[i] != t[i]) {
                    pos = i;
                    break;
                }
            }
 
            // Replace the different character with its complement
            s[pos] = (s[pos] == '0') ? '1' : '0';
 
            // Update the difference count
            diffCount--;
            operations++;
        }
    }
 
    return operations;
}
 
 
// Driver code
int main()
{
    string s = "010", t = "101";
    int n = s.length();
    cout << minOperations(s, t, n);
 
    return 0;
}


Java




import java.util.*;
 
public class Main {
    // Function to return the minimum operations
    // of the given type required to convert
    // string s to string t
    static int minOperations(String s, String t, int n)
    {
        int diffCount = 0;
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) != t.charAt(i)) {
                diffCount++;
            }
        }
 
        int operations = 0;
        while (diffCount > 0) {
            if (diffCount >= 2) {
                // Find the two different characters
                // in s and t that occur at the same
                // position
                int pos1 = -1, pos2 = -1;
                for (int i = 0; i < n; i++) {
                    if (s.charAt(i) != t.charAt(i)) {
                        if (pos1 == -1) {
                            pos1 = i;
                        }
                        else {
                            pos2 = i;
                            break;
                        }
                    }
                }
 
                // Swap the two different characters
                char[] sChars = s.toCharArray();
                char[] tChars = t.toCharArray();
                char temp = sChars[pos1];
                sChars[pos1] = sChars[pos2];
                sChars[pos2] = temp;
                temp = tChars[pos1];
                tChars[pos1] = tChars[pos2];
                tChars[pos2] = temp;
                s = new String(sChars);
                t = new String(tChars);
 
                // Update the difference count
                diffCount -= 2;
                operations++;
            }
            else {
                // Find the different character in s and t
                // that occurs at the same position
                int pos = -1;
                for (int i = 0; i < n; i++) {
                    if (s.charAt(i) != t.charAt(i)) {
                        pos = i;
                        break;
                    }
                }
 
                // Replace the different character with its
                // complement
                char[] sChars = s.toCharArray();
                if (s.charAt(pos) == '0') {
                    sChars[pos] = '1';
                }
                else {
                    sChars[pos] = '0';
                }
                s = new String(sChars);
 
                // Update the difference count
                diffCount--;
                operations++;
            }
        }
 
        return operations;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String s = "010", t = "101";
        int n = s.length();
        System.out.println(minOperations(s, t, n));
    }
}


Python3




# Python implementation of the approach
 
# Function to return the minimum operations
# of the given type required to convert
# string s to string t
def minOperations(s, t, n):
    diffCount = 0
    for i in range(n):
        if s[i] != t[i]:
            diffCount += 1
 
    operations = 0
    while diffCount > 0:
        if diffCount >= 2:
            # Find the two different characters
            # in s and t that occur at the same position
            pos1, pos2 = -1, -1
            for i in range(n):
                if s[i] != t[i]:
                    if pos1 == -1:
                        pos1 = i
                    else:
                        pos2 = i
                        break
 
            # Swap the two different characters
            s = s[:pos1] + t[pos1] + s[pos1+1:pos2] + t[pos2] + s[pos2+1:]
            t = t[:pos1] + s[pos1] + t[pos1+1:pos2] + s[pos2] + t[pos2+1:]
 
            # Update the difference count
            diffCount -= 2
            operations += 1
        else:
            # Find the different character in s and t
            # that occurs at the same position
            pos = -1
            for i in range(n):
                if s[i] != t[i]:
                    pos = i
                    break
 
            # Replace the different character with its complement
            s = s[:pos] + ('1' if s[pos] == '0' else '0') + s[pos+1:]
 
            # Update the difference count
            diffCount -= 1
            operations += 1
 
    return operations
 
 
# Driver code
s = "010"
t = "101"
n = len(s)
print(minOperations(s, t, n))


C#




using System;
 
class GFG {
     
    // Function to return the minimum operations
    // of the given type required to convert
    // string s to string t
    static int minOperations(string s, string t, int n) {
        int diffCount = 0;
        for (int i = 0; i < n; i++) {
            if (s[i] != t[i]) {
                diffCount++;
            }
        }
 
        int operations = 0;
        while (diffCount > 0) {
            if (diffCount >= 2) {
                // Find the two different characters
                // in s and t that occur at the same position
                int pos1 = -1, pos2 = -1;
                for (int i = 0; i < n; i++) {
                    if (s[i] != t[i]) {
                        if (pos1 == -1) {
                            pos1 = i;
                        } else {
                            pos2 = i;
                            break;
                        }
                    }
                }
 
                // Swap the two different characters
                char[] sArr = s.ToCharArray();
                char[] tArr = t.ToCharArray();
                char temp = sArr[pos1];
                sArr[pos1] = sArr[pos2];
                sArr[pos2] = temp;
                s = new string(sArr);
                temp = tArr[pos1];
                tArr[pos1] = tArr[pos2];
                tArr[pos2] = temp;
                t = new string(tArr);
 
                // Update the difference count
                diffCount -= 2;
                operations++;
            } else {
                // Find the different character in s and t
                // that occurs at the same position
                int pos = -1;
                for (int i = 0; i < n; i++) {
                    if (s[i] != t[i]) {
                        pos = i;
                        break;
                    }
                }
 
                // Replace the different character with its complement
                char[] sArr = s.ToCharArray();
                sArr[pos] = sArr[pos] == '0' ? '1' : '0';
                s = new string(sArr);
 
                // Update the difference count
                diffCount--;
                operations++;
            }
        }
 
        return operations;
    }
 
    // Driver code
    static public void Main() {
        string s = "010", t = "101";
        int n = s.Length;
        Console.WriteLine(minOperations(s, t, n));
    }
}
// This code is contributed by sarojmcy2e


Javascript




// JavaScript implementation of the approach
 
// Function to return the minimum operations
// of the given type required to convert
// string s to string t
function minOperations(s, t, n) {
let diffCount = 0;
for (let i = 0; i < n; i++) {
if (s[i] !== t[i]) {
diffCount += 1;
}
}
let operations = 0;
while (diffCount > 0) {
    if (diffCount >= 2) {
        // Find the two different characters
        // in s and t that occur at the same position
        let pos1 = -1, pos2 = -1;
        for (let i = 0; i < n; i++) {
            if (s[i] !== t[i]) {
                if (pos1 === -1) {
                    pos1 = i;
                } else {
                    pos2 = i;
                    break;
                }
            }
        }
 
        // Swap the two different characters
        s = s.substring(0, pos1) + t.charAt(pos1) + s.substring(pos1+1, pos2) + t.charAt(pos2) + s.substring(pos2+1);
        t = t.substring(0, pos1) + s.charAt(pos1) + t.substring(pos1+1, pos2) + s.charAt(pos2) + t.substring(pos2+1);
 
        // Update the difference count
        diffCount -= 2;
        operations += 1;
    } else {
        // Find the different character in s and t
        // that occurs at the same position
        let pos = -1;
        for (let i = 0; i < n; i++) {
            if (s[i] !== t[i]) {
                pos = i;
                break;
            }
        }
 
        // Replace the different character with its complement
        s = s.substring(0, pos) + (s.charAt(pos) === '0' ? '1' : '0') + s.substring(pos+1);
 
        // Update the difference count
        diffCount -= 1;
        operations += 1;
    }
}
 
return operations;
}
 
// Driver code
let s = "010";
let t = "101";
let n = s.length;
console.log(minOperations(s, t, n));


Output

2

Time Complexity: O(n^2) due to the nested loops used to generate all possible swaps and replacements.

Auxiliary Space: O(1)

Approach: Find 2 values for the string S, the number of indices that have 0 but should be 1 and the number of indices that have 1 but should be 0. The result would be the maximum of these 2 values since we can use swaps on the minimum of these 2 values and the remaining unmatched characters can be inverted i.e. ‘0’ can be changed to ‘1’ and ‘1’ can be changed to ‘0’.

Below is the implementation of the above approach:  

C




#include <stdio.h>
#include <string.h>
 
// Function to return the minimum operations
// of the given type required to convert
// string s to string t
int minOperations(char* s, char* t, int n)
{
    int ct0 = 0, ct1 = 0;
    for (int i = 0; i < n; i++) {
 
        // Characters are already equal
        if (s[i] == t[i])
            continue;
 
        // Increment count of 0s
        if (s[i] == '0')
            ct0++;
 
        // Increment count of 1s
        else
            ct1++;
    }
 
    return (ct0 > ct1) ? ct0 : ct1;
}
 
// Driver code
int main()
{
    char s[] = "010";
    char t[] = "101";
    int n = strlen(s);
    printf("%d", minOperations(s, t, n));
 
    return 0;
}


C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the minimum operations
// of the given type required to convert
// string s to string t
int minOperations(string s, string t, int n)
{
    int ct0 = 0, ct1 = 0;
    for (int i = 0; i < n; i++) {
 
        // Characters are already equal
        if (s[i] == t[i])
            continue;
 
        // Increment count of 0s
        if (s[i] == '0')
            ct0++;
 
        // Increment count of 1s
        else
            ct1++;
    }
 
    return max(ct0, ct1);
}
 
// Driver code
int main()
{
    string s = "010", t = "101";
    int n = s.length();
    cout << minOperations(s, t, n);
 
    return 0;
}


Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Function to return the minimum
// operations of the given type required
// to convert string s to string t
static int minOperations(String s,
                        String t, int n)
{
    int ct0 = 0, ct1 = 0;
    for (int i = 0; i < n; i++)
    {
 
        // Characters are already equal
        if (s.charAt(i) == t.charAt(i))
            continue;
 
        // Increment count of 0s
        if (s.charAt(i) == '0')
            ct0++;
 
        // Increment count of 1s
        else
            ct1++;
    }
 
    return Math.max(ct0, ct1);
}
 
// Driver code
public static void main(String args[])
{
    String s = "010", t = "101";
    int n = s.length();
    System.out.println(minOperations(s, t, n));
}
}
 
// This code is contributed by
// Surendra_Gangwar


Python3




# Python 3 implementation of the approach
 
# Function to return the minimum operations
# of the given type required to convert
# string s to string t
def minOperations(s, t, n):
 
    ct0 = 0
    ct1 = 0
    for i in range(n):
 
        # Characters are already equal
        if (s[i] == t[i]):
            continue
 
        # Increment count of 0s
        if (s[i] == '0'):
            ct0 += 1
 
        # Increment count of 1s
        else:
            ct1 += 1
 
    return max(ct0, ct1)
 
# Driver code
if __name__ == "__main__":
     
    s = "010"
    t = "101"
    n = len(s)
    print(minOperations(s, t, n))
 
# This code is contributed by ita_c


Javascript




<script>
 
// JavaScript implementation of the approach
 
// Function to return the minimum operations
// of the given type required to convert
// string s to string t
function minOperations(s, t, n)
{
    var ct0 = 0,
    ct1 = 0;
    for(var i = 0; i < n; i++)
    {
        // Characters are already equal
        if (s[i] === t[i])
            continue;
         
        // Increment count of 0s
        if (s[i] === "0")
            ct0++;
             
        // Increment count of 1s
        else
            ct1++;
    }
    return Math.max(ct0, ct1);
}
 
// Driver code
var s = "010",
t = "101";
var n = s.length;
 
document.write(minOperations(s, t, n));
 
// This code is contributed by rdtank
 
</script>


C#




// C# implementation of the approach
using System;
class GFG
{
 
// Function to return the minimum operations
// of the given type required to convert
// string s to string t
static int minOperations(string s, 
                         string t, int n)
{
    int ct0 = 0, ct1 = 0;
    for (int i = 0; i < n; i++)
    {
 
        // Characters are already equal
        if (s[i] == t[i])
            continue;
 
        // Increment count of 0s
        if (s[i] == '0')
            ct0++;
 
        // Increment count of 1s
        else
            ct1++;
    }
 
    return Math.Max(ct0, ct1);
}
 
// Driver code
public static void Main()
{
    string s = "010", t = "101";
    int n = s.Length;
    Console.Write(minOperations(s, t, n));
}
}
 
// This code is contributed
// by Akanksha Rai


PHP




<?php
// PHP implementation of the approach
 
// Function to return the minimum operations
// of the given type required to convert
// string s to string t
function minOperations($s, $t, $n)
{
    $ct0 = 0 ; $ct1 = 0;
    for ($i = 0; $i < $n; $i++)
    {
 
        // Characters are already equal
        if ($s[$i] == $t[$i])
            continue;
 
        // Increment count of 0s
        if ($s[$i] == '0')
            $ct0++;
 
        // Increment count of 1s
        else
            $ct1++;
    }
 
    return max($ct0, $ct1);
}
 
// Driver code
$s = "010"; $t = "101";
$n = strlen($s);
echo minOperations($s, $t, $n);
 
// This code is contributed by Ryuga
?>


Output

2

Time Complexity: O(N)

Auxiliary Space: O(1) it is using constant space for variables

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments