search
HomeBackend DevelopmentC++Minimum number of moves required to place all 0's before 1's in a binary string

Minimum number of moves required to place all 0s before 1s in a binary string

Problem Statement

We are given a binary string str and we are asked to remove the minimum number of characters from the string so that we can put all zeros before 1's.

Example

enter

str = ‘00110100111’

Output

3

illustrate

Here, we can achieve output 3 in two ways.

We can remove arr[2], arr[3] and arr[5] or arr[4], arr[6] and arr[7] from the string.

enter

str = ‘001101011’

Output

2

illustrate

We can remove arr[4] and arr[6] and put all zeros before ones.

enter

str = ‘000111’

Output

0

illustrate

In the given string, all zeros have been placed before 1, so we don't need to remove any characters from the given string.

method 1

In the first method, we will use two arrays. The first array stores all 1's on the left and the other array stores all 0's on the right. After that, we can add the elements at i-th index in both arrays and find the minimum sum.

algorithm

  • Step 1 - Define a named list of "zeros" and "ones" of length n, where n is the length of the string that we can get using the size() method.

  • Step 2 - If the first character in the given string is "1", store 1 at the 0th index of the "ones" array; otherwise, store 0.

  • Step 3 - Use a for loop to start traversing from the second element of the string. In the for loop, Ones[i] is initialized with the value obtained by adding Ones[i-1] to 1 or 0 based on the character of the string at index i.

  • Step 4 - Store either 1 or 0 at Zeros[n-1] depending on the last character in the given string.

  • Step 5 - Use a for loop to traverse the string starting from the second last character and update the value of the zero list based on the string characters.

  • Step 6 - Define the "min_zeros_to_remove" variable and initialize it with the maximum integer value.

  • Step 7 - Now, loop through the "zero" and "one" lists. Access values ​​from the "i 1" index in the zero list and the "I" index in the "one" list. After that, add these two elements.

  • Step 8 - If the value of "min_zeros_to_remove" is less than the current value of the "min_zeros_to_remove" variable, change its value to the sum of the two array elements.

  • Step 9 - Return the result value.

Example

#include <bits/stdc++.h>
using namespace std;

int minimumZeroRemoval(string str){
   int n = str.size();
   // arrays to store the prefix sums of zeros and ones
   vector<int> zeros(n);
   vector<int> ones(n);
   // compute total number of 1s at the left of each index
   ones[0] = (str[0] == '1') ? 1 : 0;
   for (int i = 1; i < n; i++) {
      ones[i] = ones[i - 1] + ((str[i] == '1') ? 1 : 0);
   }
   // compute total number of 0s at the right of each index
   zeros[n - 1] = (str[n - 1] == '0') ? 1 : 0;
   for (int i = n - 2; i >= 0; i--){
      zeros[i] = zeros[i + 1] + ((str[i] == '0') ? 1 : 0);
   }
   // do the sum of zeros and ones for each index and return the minimum value
   int min_zeros_to_remove = INT_MAX;
   for (int i = 0; i < n - 1; i++){
      min_zeros_to_remove = min(min_zeros_to_remove, zeros[i + 1] + ones[i]);
   }
   return min_zeros_to_remove;
}
int main() {
   string str = "00110100111";
   int count = minimumZeroRemoval(str);
   cout << "The minimum number of zeros required to remove from the given string is - " << count;
   return 0;
}

Output

The minimum number of zeros required to remove from the given string is - 3
  • Time complexity - O(N) because we need a for loop to iterate over strings and lists of size N.

  • Space Complexity - O(N) because we use two lists to store the counts of 1 and 0.

Method 2

This method is an optimized version of the first method. Here, instead of a list, we use two variables to store the count of 1s and 0s.

algorithm

  • Step 1 - Define the "zeros_right" variable and initialize it with 0.

  • Step 2 - Loop through the string, count the total number of "0" characters in the given string, and update the value of the "zero_right" variable accordingly.

  • Step 3 - Define the "ones_left" variable and initialize it to 0.

  • Step 4 - Use a for loop to iterate through the string. If the character at index i in the string is "1", increase the value of the "ones_left" variable by 1. Otherwise, reduce the value of the "zeros_right" variable by 1.

  • Step 5 - If "zeros_right Ones_left" is less than the current value of the "res" variable, update the value of the "res" variable.

Example

#include <bits/stdc++.h>
using namespace std;

// function to remove zeros from the string to place all zeros before 1.
int minimumZeroRemoval(string str){
   // counting the total number of zeros in the given string
   int zeros_right = 0;
   for (int i = 0; i < str.size(); i++) {
      if (str[i] == '0')
      zeros_right += 1;
   }
   // variable to store the number of ones from left
   int ones_left = 0;
   // Size of the string
   int len = str.size();
   // variable to store the final result
   int result = INT_MAX;
   // Traverse the string from left to right
   for (int i = 0; i < len; i++){
      // If the current character is '1', then increment ones_left by 1 else, decrement zeros_right by 1
      if (str[i] == '1') {
         ones_left += 1;
      } else {
         zeros_right -= 1;
      }
      // Store the minimum result and zeros_right + ones_left in result
      result = min(result, zeros_right + ones_left);
   }
   // Return the final result
   return result;
}
int main() {
   string str = "001101011";
   int count = minimumZeroRemoval(str);
   cout << "The minimum number of zeros required to remove from the given string is - " << count;
   return 0;
}

Output

The minimum number of zeros required to remove from the given string is - 2
  • Time Complexity - O(N), when we iterate over the string.

  • Space Complexity - O(1) since we only use constant space.

in conclusion

The user learned two ways to remove the minimum number of characters from a given binary string. The code for the second approach is more readable because we use variables to store the count of zeros and ones instead of using a list.

The above is the detailed content of Minimum number of moves required to place all 0's before 1's in a binary string. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
The C   Community: Resources, Support, and DevelopmentThe C Community: Resources, Support, and DevelopmentApr 13, 2025 am 12:01 AM

C Learners and developers can get resources and support from StackOverflow, Reddit's r/cpp community, Coursera and edX courses, open source projects on GitHub, professional consulting services, and CppCon. 1. StackOverflow provides answers to technical questions; 2. Reddit's r/cpp community shares the latest news; 3. Coursera and edX provide formal C courses; 4. Open source projects on GitHub such as LLVM and Boost improve skills; 5. Professional consulting services such as JetBrains and Perforce provide technical support; 6. CppCon and other conferences help careers

C# vs. C  : Where Each Language ExcelsC# vs. C : Where Each Language ExcelsApr 12, 2025 am 12:08 AM

C# is suitable for projects that require high development efficiency and cross-platform support, while C is suitable for applications that require high performance and underlying control. 1) C# simplifies development, provides garbage collection and rich class libraries, suitable for enterprise-level applications. 2)C allows direct memory operation, suitable for game development and high-performance computing.

The Continued Use of C  : Reasons for Its EnduranceThe Continued Use of C : Reasons for Its EnduranceApr 11, 2025 am 12:02 AM

C Reasons for continuous use include its high performance, wide application and evolving characteristics. 1) High-efficiency performance: C performs excellently in system programming and high-performance computing by directly manipulating memory and hardware. 2) Widely used: shine in the fields of game development, embedded systems, etc. 3) Continuous evolution: Since its release in 1983, C has continued to add new features to maintain its competitiveness.

The Future of C   and XML: Emerging Trends and TechnologiesThe Future of C and XML: Emerging Trends and TechnologiesApr 10, 2025 am 09:28 AM

The future development trends of C and XML are: 1) C will introduce new features such as modules, concepts and coroutines through the C 20 and C 23 standards to improve programming efficiency and security; 2) XML will continue to occupy an important position in data exchange and configuration files, but will face the challenges of JSON and YAML, and will develop in a more concise and easy-to-parse direction, such as the improvements of XMLSchema1.1 and XPath3.1.

Modern C   Design Patterns: Building Scalable and Maintainable SoftwareModern C Design Patterns: Building Scalable and Maintainable SoftwareApr 09, 2025 am 12:06 AM

The modern C design model uses new features of C 11 and beyond to help build more flexible and efficient software. 1) Use lambda expressions and std::function to simplify observer pattern. 2) Optimize performance through mobile semantics and perfect forwarding. 3) Intelligent pointers ensure type safety and resource management.

C   Multithreading and Concurrency: Mastering Parallel ProgrammingC Multithreading and Concurrency: Mastering Parallel ProgrammingApr 08, 2025 am 12:10 AM

C The core concepts of multithreading and concurrent programming include thread creation and management, synchronization and mutual exclusion, conditional variables, thread pooling, asynchronous programming, common errors and debugging techniques, and performance optimization and best practices. 1) Create threads using the std::thread class. The example shows how to create and wait for the thread to complete. 2) Synchronize and mutual exclusion to use std::mutex and std::lock_guard to protect shared resources and avoid data competition. 3) Condition variables realize communication and synchronization between threads through std::condition_variable. 4) The thread pool example shows how to use the ThreadPool class to process tasks in parallel to improve efficiency. 5) Asynchronous programming uses std::as

C   Deep Dive: Mastering Memory Management, Pointers, and TemplatesC Deep Dive: Mastering Memory Management, Pointers, and TemplatesApr 07, 2025 am 12:11 AM

C's memory management, pointers and templates are core features. 1. Memory management manually allocates and releases memory through new and deletes, and pay attention to the difference between heap and stack. 2. Pointers allow direct operation of memory addresses, and use them with caution. Smart pointers can simplify management. 3. Template implements generic programming, improves code reusability and flexibility, and needs to understand type derivation and specialization.

C   and System Programming: Low-Level Control and Hardware InteractionC and System Programming: Low-Level Control and Hardware InteractionApr 06, 2025 am 12:06 AM

C is suitable for system programming and hardware interaction because it provides control capabilities close to hardware and powerful features of object-oriented programming. 1)C Through low-level features such as pointer, memory management and bit operation, efficient system-level operation can be achieved. 2) Hardware interaction is implemented through device drivers, and C can write these drivers to handle communication with hardware devices.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor