Open In App

Minimum swaps required to make a binary string divisible by 2^k

Last Updated : 24 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary string S of length N and an integer K, the task is to find the minimum number of adjacent swaps required to make the binary string divisible by 2K. If it is not possible then print -1.

Examples:  

Input: S = “100111”, K = 2 
Output:
Swapping the right-most zero 3 times 
to the right, we get “101110”. 
Swapping the second right-most zero 
3 times to the right, we get “111100”.
Input: S = “1011”, K = 2 
Output: -1  

Method 1: An approach will be swapping from the right-most zero. So, let’s rephrase the problem to something simpler. The minimum number of swaps are required such that at least K consecutive zeros are made available at the right end. 
One way will be to simulate the swapping. Starting from the right-most zero, swap it till it has 1 at its right, and it’s not the end of the string. This will be performed for the K rightmost zeros. The time complexity of this approach will be O(N * K).

Method 2: The key to performing better here will be to avoid doing the simulation. 
Observation:  

Among the K right-most zeros, each zero will need to be swapped X number of times, where X is the number of 1s to the right of that zero. 
 

Thus, for the K right-most zeros, the task is to find the sum of the number of 1s to the right of each of them.

Algorithm:  

  • Initialize variable c_zero = 0, c_one = 0 and ans = 0.
  • Run a loop from i = N – 1 to i = 0
    • If S[i] = 0 then update c_zero = c_zero + 1 and ans = ans + c_one.
    • If S[i] = 1 then update c_one = c_one + 1.
    • If c_zero = K then break.
  • If c_zero < K then return -1.
  • Finally, return the ans.

Thus, the time complexity of this approach will be O(N).

Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the minimum swaps required
int findMinSwaps(string s, int k)
{
    // To store the final answer
    int ans = 0;
 
    // To store the count of one and zero
    int c_one = 0, c_zero = 0;
 
    // Loop from end of the string
    for (int i = s.size() - 1; i >= 0; i--) {
 
        // If s[i] = 1
        if (s[i] == '1')
            c_one++;
 
        // If s[i] = 0
        if (s[i] == '0')
            c_zero++, ans += c_one;
 
        // If c_zero = k
        if (c_zero == k)
            break;
    }
 
    // If the result can't
    // be achieved
    if (c_zero < k)
        return -1;
 
    // Return the final answer
    return ans;
}
 
// Driver code
int main()
{
    string s = "100111";
    int k = 2;
 
    cout << findMinSwaps(s, k);
 
    return 0;
}


Java




// Java implementation of the approach
 
class GFG
{
     
    // Function to return the minimum swaps required
    static int findMinSwaps(String s, int k)
    {
        // To store the final answer
        int ans = 0;
     
        // To store the count of one and zero
        int c_one = 0, c_zero = 0;
     
        // Loop from end of the string
        for (int i = s.length() - 1; i >= 0; i--)
        {
     
            // If s[i] = 1
            if (s.charAt(i) == '1')
                c_one++;
     
            // If s[i] = 0
            if (s.charAt(i) == '0')
            {
                c_zero++;
                ans += c_one;
            }
     
            // If c_zero = k
            if (c_zero == k)
                break;
        }
     
        // If the result can't
        // be achieved
        if (c_zero < k)
            return -1;
     
        // Return the final answer
        return ans;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        String s = "100111";
        int k = 2;
     
        System.out.println(findMinSwaps(s, k));
     
    }
}
 
// This code is contributed by AnkitRai01


Python3




# Python3 implementation of the approach
 
# Function to return the minimum swaps required
def findMinSwaps(s, k) :
 
    # To store the final answer
    ans = 0;
 
    # To store the count of one and zero
    c_one = 0; c_zero = 0;
 
    # Loop from end of the string
    for i in range(len(s)-1, -1, -1) :
 
        # If s[i] = 1
        if (s[i] == '1') :
            c_one += 1;
 
        # If s[i] = 0
        if (s[i] == '0') :
            c_zero += 1;
            ans += c_one;
 
        # If c_zero = k
        if (c_zero == k) :
            break;
 
    # If the result can't
    # be achieved
    if (c_zero < k) :
        return -1;
 
    # Return the final answer
    return ans;
 
# Driver code
if __name__ == "__main__" :
 
    s = "100111";
    k = 2;
 
    print(findMinSwaps(s, k));
 
# This code is contributed by AnkitRai01


C#




// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function to return the minimum swaps required
    static int findMinSwaps(string s, int k)
    {
        // To store the final answer
        int ans = 0;
     
        // To store the count of one and zero
        int c_one = 0, c_zero = 0;
     
        // Loop from end of the string
        for (int i = s.Length - 1; i >= 0; i--)
        {
     
            // If s[i] = 1
            if (s[i] == '1')
                c_one++;
     
            // If s[i] = 0
            if (s[i] == '0')
            {
                c_zero++;
                ans += c_one;
            }
     
            // If c_zero = k
            if (c_zero == k)
                break;
        }
     
        // If the result can't
        // be achieved
        if (c_zero < k)
            return -1;
     
        // Return the final answer
        return ans;
    }
     
    // Driver code
    public static void Main()
    {
        string s = "100111";
        int k = 2;
     
        Console.WriteLine(findMinSwaps(s, k));
    }
}
 
// This code is contributed by AnkitRai01


Javascript




<script>
 
// Javascript implementation of the approach
 
// Function to return the minimum swaps required
function findMinSwaps(s, k)
{
    // To store the final answer
    var ans = 0;
 
    // To store the count of one and zero
    var c_one = 0, c_zero = 0;
 
    // Loop from end of the string
    for (var i = s.length - 1; i >= 0; i--) {
 
        // If s[i] = 1
        if (s[i] == '1')
            c_one++;
 
        // If s[i] = 0
        if (s[i] == '0')
            c_zero++, ans += c_one;
 
        // If c_zero = k
        if (c_zero == k)
            break;
    }
 
    // If the result can't
    // be achieved
    if (c_zero < k)
        return -1;
 
    // Return the final answer
    return ans;
}
 
// Driver code
var s = "100111";
var k = 2;
document.write( findMinSwaps(s, k));
 
</script>


Output: 

6

 

Time Complexity: O(|s|)

Auxiliary Space: O(1)



Similar Reads

Minimum number of swaps required to make a number divisible by 60
Given an integer N , the task is to find the minimum number of swaps required to make N divisible by 60. If not possible, then print "-1".Examples: Input: N = 603 Output: 2 Explanation: Two swap operations are required: In the first swap (0, 3): 630 In the second swap (6, 3): 360 Now 360 is divisible by 60. Therefore the minimum two swaps are requi
10 min read
Minimum adjacent swaps of digits required to make N divisible by K
Given two integers N and K, the task is to calculate the minimum number of adjacent swaps of digits required to make the integer N divisible by K. Examples: Input: N = 12345, K = 2Output: 1Explanation: The digits at index 3 and t can be swapped so that the resulting integer is N = 12354, which is divisible by 2. Hence, the required number of adjace
12 min read
Minimum swaps required to make a binary string alternating
You are given a binary string of even length (2N) and an equal number of 0's (N) and 1's (N). What is the minimum number of swaps to make the string alternating? A binary string is alternating if no two consecutive elements are equal. Examples: Input : 000111Output : 1Explanation : Swap index 2 and index 5 to get 010101 Input : 1010Output : 0 You m
11 min read
Minimum adjacent swaps required to make a binary string alternating
Given a binary string S of size N, the task is to find the number of minimum adjacent swaps required to make the string alternate. If it is not possible to do so, then print -1. Examples: Input: S = "10011"Output: 1Explanation:Swap index 2 and index 3 and the string becomes 10101 . Input: S = "110100"Output: 2Explanation: First, swap index 1 and in
11 min read
Minimum row or column swaps required to make every pair of adjacent cell of a Binary Matrix distinct
Given a binary matrix M[][] of dimensions N x N, the task is to make every pair of adjacent cells in the same row or column of the given matrix distinct by swapping the minimum number of rows or columns. Examples Input: M[][] = {{0, 1, 1, 0}, {0, 1, 1, 0}, {1, 0, 0, 1}, {1, 0, 0, 1}}, N = 4Output: 2Explanation: Step 1: Swapping the 2nd and 3rd rows
13 min read
Minimum number of swaps required to make the string K periodic
Given a string S of length N, and an array A, consisting of lowercase letters. Also given a positive integer K. the task is to find the minimum number of swaps required (between S and A) to make string S K periodic.Note: A string is said to be K periodic if for each position i in the string S[i] = S[i+K].In one move, only one character of S can be
10 min read
Minimum swaps required between two strings to make one string strictly greater than the other
Given two strings A and B of length M and N respectively, the task is to find the minimum swapping of two characters required to make string A lexicographically greater than the string B. Examples: Input: A = "1432", B = "789", M = 4, N = 3Output: 1Explanation:One possible way is to swap characters at index 0 of both the strings. Therefore, A modif
9 min read
Minimum swaps required to convert one binary string to another
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. Examples: 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
5 min read
Minimum swaps to reach permuted array with at most 2 positions left swaps allowed
Given a permuted array of length N of first N natural numbers, we need to tell the minimum number of swaps required in the sorted array of first N natural number to reach given permuted array where a number can be swapped with at most 2 positions left to it. If it is not possible to reach permuted array by above swap condition then print not possib
14 min read
Minimum number of swaps to make two binary string equal
Given two binary strings of equal length, the task is to find the minimum number of swaps to make them equal. Swapping between two characters from two different strings is only allowed, return -1 if strings can't be made equal. Examples: Input: s1 = "0011", s2 = "1111" Output: 1Explanation:Swap s1[0] and s2[1].After swaps1 = 1011 and s2 = 1011 Inpu
12 min read