DEV Community

Abhishek Singh
Abhishek Singh

Posted on

Minimum Swaps TO make binary String Alternating

**Examples:
Input: s = "111000"
Output: 1
Input: s = "010"
Output: 0

/* Here we simply need to check the below 4 cases:
1.if(no of 0s > no of 1s)
all odd position should be 0 if not count++;
2.if(no of 0s < no of 1s)
all odd position should be 1 if not count++;
3.if(Math.abs(0s-1s)>1)
return -1;// alternating not possible
4.if(both are equal in no)
return minimum of(both the arrangements);*/

Image description

`class Solution {
public int count(char f, String s){
int temp=0;
for(int i=0;i<s.length();i+=2){
if(s.charAt(i)==f) temp++;
}
return temp;
}
public int minSwaps(String s) {
int z=0,o=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='0')
z++;
else o++;
}
if(z-o==1){
return z-count('0',s);
}
else if(o-z==1){
return o-count('1',s);
}
else if(o-z==0)
return Math.min(count('1',s),count('0',s));
else return -1;
}

}`

Latest comments (0)