

- 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
Minimum toggles to partition a binary array so that it has first 0s then 1s in C++
Problem statement
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.
Example
If arr[] = {1, 0, 0, 1, 1, 1, 0} then 2 toggle is required i.e. toggle first one and last zero.
Algorithm
- 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.
Example
#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 −
Output
Minimum toggles = 2
- Related Questions & Answers
- Check if a string has m consecutive 1s or 0s in Python
- Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python
- Check if the binary representation of a number has equal number of 0s and 1s in blocks in Python
- XOR counts of 0s and 1s in binary representation in C++
- Print n 0s and m 1s such that no two 0s and no three 1s are together in C Program
- 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++
- Program to find number m such that it has n number of 0s at end in Python
- Count all 0s which are blocked by 1s in binary matrix in C++
- Find the index of first 1 in an infinite sorted array of 0s and 1s 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++
- Python - List Initialization with alternate 0s and 1s
Advertisements