MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / minFlips

Method minFlips

MinNumberOfFlips.java:2–22  ·  view source on GitHub ↗
(String S)

Source from the content-addressed store, hash-verified

1class Solution {
2 public int minFlips(String S) {
3 // Code here
4 int flips=0;
5// idea is to calculate string flips when the string starts from 1 and then use (length - calculated) to get the flips when the string starts from 0
6// finally return the minimum
7 for(int i=0;i<S.length();i++)
8 {
9// If there is a 0 at even index then we need to flip it
10 if(i%2==0)
11 {
12 if(S.charAt(i)=='0') flips++;
13 }
14// If there is a 1 at odd index then we need to flip it
15 else if(i%2!=0)
16 {
17 if(S.charAt(i)=='1') flips++;
18 }
19 }
20// minmum flips would either be the flips in making string start with 1 or with 0
21 return Math.min(flips,S.length()-flips);
22 }
23}
24
25

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected