Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Minimum number of characters to be removed to make a binary string alternate
Next article icon

Minimum number of replacements to make the binary string alternating | Set 2

Last Updated : 22 Apr, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary string str, the task is to find the minimum number of characters in the string that have to be replaced in order to make the string alternating (i.e. of the form 01010101… or 10101010…).
Examples: 
 

Input: str = “1100” 
Output: 2 
Replace 2nd character with ‘0’ and 3rd character with ‘1’
Input: str = “1010” 
Output: 0 
The string is already alternating. 
 

 

We have discussed one approach in Number of flips to make binary string alternate. In this post a better approach is discussed.
Approach: For the string str, there can be two possible solutions. Either the resultant string can be 
 

  1. 010101… or
  2. 101010…

In order to find the minimum replacements, count the number of replacements to convert the string in type 1 and store it in count then minimum replacement will be min(count, len – count) where len is the length of the string. len – count is the number of replacements to convert the string in type 2.
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 number of
// characters of the given binary string
// to be replaced to make the string alternating
int minReplacement(string s, int len)
{
    int ans = 0;
    for (int i = 0; i < len; i++) {
 
        // If there is 1 at even index positions
        if (i % 2 == 0 && s[i] == '1')
            ans++;
 
        // If there is 0 at odd index positions
        if (i % 2 == 1 && s[i] == '0')
            ans++;
    }
    return min(ans, len - ans);
}
 
// Driver code
int main()
{
    string s = "1100";
    int len = s.size();
    cout << minReplacement(s, len);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
class GFG {
 
    // Function to return the minimum number of
    // characters of the given binary string
    // to be replaced to make the string alternating
    static int minReplacement(String s, int len)
    {
        int ans = 0;
        for (int i = 0; i < len; i++) {
 
            // If there is 1 at even index positions
            if (i % 2 == 0 && s.charAt(i) == '1')
                ans++;
 
            // If there is 0 at odd index positions
            if (i % 2 == 1 && s.charAt(i) == '0')
                ans++;
        }
        return Math.min(ans, len - ans);
    }
 
    // Driver code
    public static void main(String args[])
    {
        String s = "1100";
        int len = s.length();
        System.out.print(minReplacement(s, len));
    }
}
 
 

Python3




# Python3 implementation of the approach.
 
# Function to return the minimum number of
# characters of the given binary string
# to be replaced to make the string alternating
def minReplacement(s, length):
 
    ans = 0
    for i in range(0, length):
 
        # If there is 1 at even index positions
        if i % 2 == 0 and s[i] == '1':
            ans += 1
 
        # If there is 0 at odd index positions
        if i % 2 == 1 and s[i] == '0':
            ans += 1
     
    return min(ans, length - ans)
 
# Driver code
if __name__ == "__main__":
 
    s = "1100"
    length = len(s)
    print(minReplacement(s, length))
         
# This code is contributed by Rituraj Jain
 
 

C#




// C# implementation of the approach
using System;
 
class GFG
{
 
    // Function to return the minimum number of
    // characters of the given binary string
    // to be replaced to make the string alternating
    static int minReplacement(String s, int len)
    {
        int ans = 0;
        for (int i = 0; i < len; i++)
        {
 
            // If there is 1 at even index positions
            if (i % 2 == 0 && s[i] == '1')
                ans++;
 
            // If there is 0 at odd index positions
            if (i % 2 == 1 && s[i] == '0')
                ans++;
        }
        return Math.Min(ans, len - ans);
    }
 
    // Driver code
    public static void Main(String []args)
    {
        String s = "1100";
        int len = s.Length;
        Console.Write(minReplacement(s, len));
    }
}
 
// This code contributed by Rajput-Ji
 
 

PHP




<?php
// PHP implementation of the approach
 
// Function to return the minimum number of
// characters of the given binary string
// to be replaced to make the string alternating
function minReplacement($s, $len)
{
    $ans = 0;
    for ($i = 0; $i < $len; $i++)
    {
 
        // If there is 1 at even index positions
        if ($i % 2 == 0 && $s[$i] == '1')
            $ans++;
 
        // If there is 0 at odd index positions
        if ($i % 2 == 1 && $s[$i] == '0')
            $ans++;
    }
    return min($ans, $len - $ans);
}
 
// Driver code
$s = "1100";
$len = strlen($s);
echo minReplacement($s, $len);
 
// This code is contributed by chandan_jnu
?>
 
 

Javascript




<script>
 
 
// Javascript implementation of the approach
 
// Function to return the minimum number of
// characters of the given binary string
// to be replaced to make the string alternating
function minReplacement(s, len)
{
    var ans = 0;
    for (var i = 0; i < len; i++) {
 
        // If there is 1 at even index positions
        if (i % 2 == 0 && s[i] == '1')
            ans++;
 
        // If there is 0 at odd index positions
        if (i % 2 == 1 && s[i] == '0')
            ans++;
    }
    return Math.min(ans, len - ans);
}
 
// Driver code
var s = "1100";
var len = s.length;
document.write(minReplacement(s, len));
 
 
</script>
 
 
Output: 
2

 

Time Complexity: O(len), where len is the length of the given string. We are traversing till len.

Auxiliary Space: O(1), as we are not using any extra space.



Next Article
Minimum number of characters to be removed to make a binary string alternate
author
spp____
Improve
Article Tags :
  • DSA
  • Mathematical
  • Strings
Practice Tags :
  • Mathematical
  • Strings

Similar Reads

  • Minimum number of flips with rotation to make binary string alternating
    Given a binary string S of 0s and 1s. The task is to make the given string a sequence of alternate characters by using the below operations: Remove some prefix from the start and append it to the end.Flip some or every bit in the given string. Print the minimum number of bits to be flipped to make t
    11 min read
  • Minimum number of characters to be removed to make a binary string alternate
    Given a binary string, the task is to find minimum number of characters to be removed from it so that it becomes alternate. A binary string is alternate if there are no two consecutive 0s or 1s.Examples : Input : s = "000111" Output : 4 We need to delete two 0s and two 1s to make string alternate. I
    4 min read
  • Minimum swaps required to make a binary string alternating
    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 : 000111Output : 1Explanation : Swap index 2 and
    11 min read
  • Number of flips to make binary string alternate | Set 1
    Given a binary string, that is it contains only 0s and 1s. We need to make this string a sequence of alternate characters by flipping some of the bits, our goal is to minimize the number of bits to be flipped. Examples : Input : str = “001” Output : 1 Minimum number of flips required = 1 We can flip
    8 min read
  • Minimize the number of replacements to get a string with same number of 'a', 'b' and 'c' in it
    Given a string consisting of only three possible characters 'a', 'b' or 'c'. The task is to replace characters of the given string with 'a', 'b' or 'c' only such that there is the equal number of characters of 'a', 'b' and 'c' in the string. The task is to minimize the number of replacements and pri
    15 min read
  • Minimum number of operations required to maximize the Binary String
    Given a binary string S, the task is to find the minimum number of swaps required to be performed to maximize the value represented by S. Examples: Input: S = "1010001" Output: 1 Explanation: Swapping S[2] and S[7], modifies the string to 1110000, thus, maximizing the number that can be generated fr
    7 min read
  • Minimum substring reversals required to make given Binary String alternating
    Given a binary string S of length N, the task is to count the minimum number substrings of S that is required to be reversed to make the string S alternating. If it is not possible to make string alternating, then print "-1". Examples: Input: S = "10001110"Output: 2Explanation:In the first operation
    7 min read
  • Minimum replacements to make adjacent characters unequal in a ternary string | Set-2
    Given a string of ‘0’, ‘1’, and ‘2’. The task is to find the minimum number of replacements such that the adjacent characters are not equal. Examples: Input: s = “201220211” Output: 2 Resultant string after changes is 201210210 Input: s = “0120102” Output: 0 Approach: The problem has been solved usi
    15+ min read
  • Number of alternating substrings from a given Binary String
    Given a binary string of size N, the task is to count the number of alternating substrings that are present in the string S. Examples: Input: S = "0010"Output: 7Explanation: All the substring of the string S are: {"0", "00", "001", "0010", "0", "01", "010", "1", "10", "0"}Strings that are alternatin
    13 min read
  • Minimum number of characters to be replaced to make a given string Palindrome
    Given string str, the task is to find the minimum number of characters to be replaced to make a given string palindrome. Replacing a character means replacing it with any single character in the same position. We are not allowed to remove or add any characters. If there are multiple answers, print t
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences