Minimum swaps required to make a binary string alternating
Last Updated :
22 Dec, 2022
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 : 000111
Output : 1
Explanation : Swap index 2 and index 5 to get 010101
Input : 1010
Output : 0
You may count the numbers of 1's at odd and even positions or 0's at odd and even positions in the string. The result would not change because they complete each other.
In the following solution, we will count the 1's.
- Count the number of ones at the odd positions and even positions of the string. Let their count be odd_1 and even_1 respectively.
- We will always swap a 1 with a 0 (other swaps are pointless). So we need to transfer all the 1s to be only on even positions or only on odd positions. To do so we need min(odd_1, even_1) swaps which is the answer.
This solution Is possible because you are promised that odd_1 + even_1 = N and odd_0 + even_0 = N. also as a result of that we can see that odd_1 + odd_0 = N and even_1 + even_0 = N because on a string of even length there is the same amount of chars in even and odd positions.
Below is the implementation of the above approach:
C++
// CPP implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// returns the minimum number of swaps
// of a binary string
// passed as the argument
// to make it alternating
int countMinSwaps(string st)
{
// counts number of ones at odd
// and even positions
int odd_1 = 0, even_1 = 0;
for (int i = 0; i < st.length(); i++) {
if (st[i] == '1') {
if (i % 2 == 0)
even_1++;
else {
odd_1++;
}
}
}
// calculates the minimum number of swaps
return min(odd_1, even_1);
}
// Driver code
int main()
{
string st = "000111";
cout << countMinSwaps(st) << endl;
return 0;
}
// This code is contributed by tamircohen2468
Java
// Java implementation of the approach
class GFG {
// returns the minimum number of swaps
// of a binary string
// passed as the argument
// to make it alternating
static int countMinSwaps(String st)
{
// counts number of ones at odd
// and even positions
int odd_1 = 0, even_1 = 0;
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) == '1') {
if (i % 2 == 0)
even_1++;
else
odd_1++;
}
}
// calculates the minimum number of swaps
return Math.min(odd_1, even_1);
}
// Driver code
public static void main(String[] args)
{
String st = "000111";
System.out.println(countMinSwaps(st));
}
}
// This code is contributed by tamircohen2468
Python3
# Python3 implementation of the
# above approach
# returns the minimum number of swaps of a binary string
# passed as the argument to make it alternating
def countMinSwaps(st):
# counts number of ones at odd
# and even positions
odd_1, even_1 = 0, 0
for i in range(0, len(st)):
if st[i] == "1":
if i % 2 == 0:
even_1 += 1
else:
odd_1 += 1
# calculates the minimum number of swaps
return min(odd_1, even_1)
# Driver code
if __name__ == "__main__":
st = "000111"
print(countMinSwaps(st))
# This code is contributed by tamircohen2468
C#
// C# implementation of the approach
using System;
public class GFG {
// returns the minimum number of swaps
// of a binary string
// passed as the argument
// to make it alternating
public static int countMinSwaps(string st)
{
// counts number of ones at odd
// and even positions
int odd_1 = 0, even_1 = 0;
for (int i = 0; i < st.Length; i++) {
if (st[i] == '1') {
if (i % 2 == 0) {
even_1++;
}
else {
odd_1++;
}
}
}
// calculates the minimum number of swaps
return Math.Min(odd_1, even_1);
}
// Driver code
public static void Main(string[] args)
{
string st = "000111";
Console.WriteLine(countMinSwaps(st));
}
}
// This code is contributed by tamircohen2468
PHP
<?php
// PHP implementation of the approach
// returns the minimum number of swaps
// of a binary string passed as the
// argument to make it alternating
function countMinSwaps($st)
{
// counts number of ones at odd
// and even positions
$odd_1 = 0;
$even_1 = 0;
for ($i = 0; $i < strlen($st); $i++)
{
if ($st[$i] == '1')
{
if ($i % 2 == 0)
{
$even_1++;
}
else {
$odd_1++;
}
}
}
// calculates the minimum number of swaps
return min($odd_1, $even_1);
}
// Driver code
$st = "000111";
echo (countMinSwaps($st));
// This code is contributed by tamircohen2468
?>
JavaScript
<script>
// Javascript implementation of the approach
// returns the minimum number of swaps
// of a binary string
// passed as the argument
// to make it alternating
function countMinSwaps(st)
{
// counts number of ones at odd
// and even positions
let odd_1 = 0, even_1 = 0;
for (let i = 0; i < st.length; i++)
{
if (st[i] === '1')
{
if (i % 2 === 0)
{
even_1++;
}
else
{
odd_1++;
}
}
}
// calculates the minimum number of swaps
return Math.min(odd_1, even_1);
}
let st = "000111";
document.write(countMinSwaps(st));
// This code is contributed by tamircohen2468
</script>
Complexity Analysis:
- Time Complexity: O(n) // n is the length of the string
- Auxiliary Complexity: O(1) // since there is no extra array used so constant space is used
Approach for odd and even length string :
Let the string length be N.
In this approach, we will consider three cases :
- The answer is impossible when the total number of ones > the total number of zeroes + 1 or the total number of zeroes > the total number of ones + 1.
- The string is of even length :
We will count the number of ones on odd positions (odd_1) and the number of ones on even positions (even_1) then the answer is min (odd_1, even_1), same as before. - The string is of odd length :
Here we consider two cases :- the total number of ones > total number of zeroes (then we have put ones in even positions) so, the answer is the number of ones at odd positions.
- the total number of zeroes > total number of ones (then we have put zeroes in even positions) so, the answer is the number of zeroes at odd positions.
Implementation:
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// function to count minimum swaps
// required to make binary string
// alternating
int countMinSwaps(string s)
{
// stores total number of ones
int odd_1 = 0, even_1 = 0;
// stores total number of zeroes
int odd_0 = 0, even_0 = 0;
for (int i = 0; i < s.size(); i++) {
if (i % 2 == 0) {
if (s[i] == '1') {
even_1++;
}
else {
even_0++;
}
}
else {
if (s[i] == '1') {
odd_1++;
}
else {
odd_0++;
}
}
}
// Total amount of 1's - Total amount of 0's
int chars_diff = (odd_1 + even_1) - (odd_0 + even_0);
// Even length String
if (chars_diff == 0) {
return min(odd_1, even_1);
}
// More 1's the 0's, 1's needs to be on even
// positions
else if (chars_diff == 1) {
return odd_1;
}
// More 0's the 1's, 0's needs to be on even
// positions
else if (chars_diff == -1) {
return odd_0;
}
// impossible condition
return -1;
}
// Driver code
int main()
{
string s = "111000";
cout << countMinSwaps(s);
return 0;
}
// This code is contributed by tamircohen2468
Java
// Java implementation of the above approach
import java.util.*;
class GFG {
// function to count minimum swaps
// required to make binary String
// alternating
static int countMinSwaps(String s)
{
// stores total number of ones
int odd_1 = 0, even_1 = 0;
// stores total number of zeroes
int odd_0 = 0, even_0 = 0;
for (int i = 0; i < s.length(); i++) {
if (i % 2 == 0) {
if (s.charAt(i) == '1') {
even_1++;
}
else {
even_0++;
}
}
else {
if (s.charAt(i) == '1') {
odd_1++;
}
else {
odd_0++;
}
}
}
// Total amount of 1's - Total amount of 0's
int chars_diff
= (odd_1 + even_1) - (odd_0 + even_0);
// Even length String
if (chars_diff == 0) {
return Math.min(odd_1, even_1);
}
// More 1's the 0's, 1's needs to be on even
// positions
else if (chars_diff == 1) {
return odd_1;
}
// More 0's the 1's, 0's needs to be on even
// positions
else if (chars_diff == -1) {
return odd_0;
}
// impossible condition
return -1;
}
// Driver code
public static void main(String[] args)
{
String s = "111000";
System.out.print(countMinSwaps(s));
}
}
// This code is contributed by tamircohen2468
Python3
# Python implementation of the above approach
# function to count minimum swaps
# required to make binary string
# alternating
def countMinSwaps(s):
# stores total number of ones
odd_1 = 0
even_1 = 0
# stores total number of zeroes
odd_0 = 0
even_0 = 0
for i in range(len(s)):
if i % 2 == 0:
if s[i] == '1':
even_1 += 1
else:
even_0 += 1
else:
if s[i] == '1':
odd_1 += 1
else:
odd_0 += 1
# Total amount of 1's - Total amount of 0's
chars_diff = (odd_1 + even_1) - (odd_0 + even_0)
# Even length String
if chars_diff == 0:
return min(odd_1, even_1)
# More 1's the 0's, 1's needs to be on even positions
elif chars_diff == 1:
return odd_1
# More 0's the 1's, 0's needs to be on even positions
elif chars_diff == -1:
return odd_0
# Impossible condition
return -1
if __name__ == '__main__':
# Driver code
s = "111000"
print(countMinSwaps(s))
# This code is contributed by tamircohen2468
C#
// C# implementation of the above approach
using System;
class GFG {
// Function to count minimum swaps
// required to make binary String
// alternating
static int countMinSwaps(string s)
{
// stores total number of ones
int odd_1 = 0, even_1 = 0;
// stores total number of zeroes
int odd_0 = 0, even_0 = 0;
for (int i = 0; i < s.Length; i++) {
if (i % 2 == 0) {
if (s[i] == '1') {
even_1++;
}
else {
even_0++;
}
}
else {
if (s[i] == '1') {
odd_1++;
}
else {
odd_0++;
}
}
}
// Total amount of 1's - Total amount of 0's
int chars_diff
= (odd_1 + even_1) - (odd_0 + even_0);
// Even length String
if (chars_diff == 0) {
return Math.Min(odd_1, even_1);
}
// More 1's the 0's, 1's needs to be on even
// positions
else if (chars_diff == 1) {
return odd_1;
}
// More 0's the 1's, 0's needs to be on even
// positions
else if (chars_diff == -1) {
return odd_0;
}
// impossible condition
return -1;
}
// Driver code
public static void Main(String[] args)
{
string s = "111000";
Console.Write(countMinSwaps(s));
}
}
// This code is contributed by tamircohen2468
JavaScript
<script>
// JavaScript implementation of the above approach
// function to count minimum swaps
// required to make binary String
// alternating
function countMinSwaps(s)
{
// stores total number of ones
var odd_1 = 0, even_1 = 0;
// stores total number of zeroes
var odd_0 = 0, even_0 = 0;
for (var i = 0; i < s.length; i++) {
if (i % 2 === 0) {
if (s.charAt(i) === '1') {
even_1++;
}
else {
even_0++;
}
}
else {
if (s.charAt(i) === '1') {
odd_1++;
}
else {
odd_0++;
}
}
}
// Total amount of 1's - Total amount of 0's
var chars_diff = (odd_1 + even_1) - (odd_0 + even_0);
// Even length String
if (chars_diff === 0) {
return Math.min(odd_1, even_1);
}
// More 1's the 0's, 1's needs to be on even
// positions
else if (chars_diff === 1) {
return odd_1;
}
// More 0's the 1's, 0's needs to be on even
// positions
else if (chars_diff === -1) {
return odd_0;
}
// impossible condition
return -1;
}
// Driver code
var s = "111000";
document.write(countMinSwaps(s));
// This code is contributed by tamircohen2468
</script>
complexity Analysis:
- Time Complexity: O(N)
- Auxiliary Complexity: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem