Skip to content
Related Articles

Related Articles

Minimum swaps required to make a binary string divisible by 2^k
  • Last Updated : 17 Jan, 2020
GeeksforGeeks - Summer Carnival Banner

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: 6
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 more 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 its 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 for 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:

  • Initialise 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 
Output:
6

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :