- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Given an array of n integers containing only 0 and 1. Find the minimum toggles (switch from 0 to 1 or vice-versa) required such the array the array become partitioned, i.e., it has first 0s then 1s.

If arr[] = {1, 0, 0, 1, 1, 1, 0} then 2 toggle is required i.e. toggle first one and last zero.

- If we observe the question, then we will find that there will definitely exist a point from 0 to n-1 where all elements left to that point should contains all 0’s and right to point should contains all 1’s
- Those indices which don’t obey this law will have to be removed. The idea is to count all 0s from left to right.

#include <bits/stdc++.h> using namespace std; int getMinToggles(int *arr, int n) { int zeroCnt[n + 1] = {0}; for (int i = 1; i <= n; ++i) { if (arr[i - 1] == 0) { zeroCnt[i] = zeroCnt[i - 1] + 1; } else { zeroCnt[i] = zeroCnt[i - 1]; } } int result = n; for (int i = 1; i <= n; ++i) { result = min(result, i - zeroCnt[i] + zeroCnt[n] - zeroCnt[i]); } return result; } int main() { int arr[] = {1, 0, 0, 1, 1, 1, 0}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Minimum toggles = " << getMinToggles(arr, n) << endl; return 0; }

When you compile and execute above program. It generates following output −

Minimum toggles = 2

- Related Questions & Answers
- XOR counts of 0s and 1s in binary representation in C++
- Check if a string has m consecutive 1s or 0s in Python
- Print n 0s and m 1s such that no two 0s and no three 1s are together in C Program
- Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python
- Minimum flips in two binary arrays so that their XOR is equal to another array in C++.
- Minimum flips to make all 1s in left and 0s in right in C++
- Check if the binary representation of a number has equal number of 0s and 1s in blocks in Python
- Count all 0s which are blocked by 1s in binary matrix in C++
- Add minimum number to an array so that the sum becomes even in C++?
- Find the minimum value to be added so that array becomes balanced in C++
- Find minimum value to assign all array elements so that array product becomes greater in C++
- Check if a binary string has a 0 between 1s or not in C++
- Program to find number m such that it has n number of 0s at end in Python
- Add minimum number to an array so that the sum becomes even in C programming
- Count permutations that are first decreasing then increasing in C++

Advertisements