VOOZH about

URL: https://www.geeksforgeeks.org/dsa/min-flips-of-continuous-characters-to-make-all-characters-same-in-a-string/

⇱ Min flips of continuous characters to make all characters same in a string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Min flips of continuous characters to make all characters same in a string

Last Updated : 29 Nov, 2023

Given a string consisting only of 1's and 0's. In one flip we can change any continuous sequence of this string. Find this minimum number of flips so the string consist of same characters only.
Examples:

Input : 00011110001110
Output : 2
We need to convert 1's sequence
so string consist of all 0's.
Input : 010101100011
Output : 4

Method 1 (Change in value encountered)
We need to find the min flips in string so all characters are equal. All we have to find numbers of sequence which consisting of 0's or 1's only. Then number of flips required will be half of this number as we can change all 0's or all 1's.


Output
2

Time Complexity: O(n) 
Auxiliary Space: O(1)

Method 2(Count continuous 0 and 1 )

We can count the number of continuous 0 and continuous 1.
Since we have to take minimum, we use min function to take value with less continuous number. And output it.

Procedure:- Take two variable to count continuous 0 and 1. If 0 is encountered increment countZero and skip 0's in continuation. Do same with 1 and its continuation. In the end the variables with less value is sent as output


Output
4

Time Complexity: O(n) 

Auxiliary Space: O(1)


This article is contributed by nuclode.

Comment
Article Tags: