Minimum Toggle to Partition
JavaView on GFG
Time: O(n)
Space: O(1)
Advertisement
Intuition
The implementation evaluates toggle cost by using global counts and running prefix counts while scanning possible partition points. For a split, it computes cost for the pattern left=0 and right=1: flip all 1s seen on the left plus all 0s remaining on the right. The minimum across splits (and baseline uniform cases considered in code) is returned.
Algorithm
- 1Count total zeros (cnt_total_0) and ones (cnt_total_1) in the whole array.
- 2Initialise prefix counts till_cnt_0 and till_cnt_1 as 0.
- 3Initialise minToggles with baseline values used in implementation.
- 4Scan array from left to right, updating prefix counts at each element.
- 5For each prefix boundary, compute toggles = till_cnt_1 + (cnt_total_0 - till_cnt_0).
- 6Update minToggles with the minimum observed value.
- 7Return minToggles.
Example Walkthrough
Input: arr = [1, 0, 1, 0]
- 1.Totals: zeros=2, ones=2.
- 2.After processing prefix [1], till_cnt_1=1, till_cnt_0=0 -> cost = 1 + (2-0) = 3.
- 3.After prefix [1,0], till_cnt_1=1, till_cnt_0=1 -> cost = 1 + (2-1) = 2.
- 4.Continue all boundaries and keep the minimum cost.
Output: 2
Common Pitfalls
- •The formula shown is specifically for left=0, right=1 partition cost; changing target pattern needs a different expression.
- •Be consistent with whether split is before or after current index when updating prefix counts.
- •Duplicates and already-uniform arrays should still be handled by baseline minimum initialization.
Minimum Toggle to Partition.java
Java
// Approach: Count total zeros/ones, then scan once while treating each position as a partition boundary.
// Compute toggles for making left all 0s and right all 1s using prefix counts and take the minimum.
// Also compare with uniform-array conversions considered in the implementation.
// Time: O(n) Space: O(1)
class Solution {
int minToggle(int[] arr) {
int cnt_total_0 = 0;
int cnt_total_1 = 0;
for (int bit : arr) {
if (bit == 0) {
cnt_total_0++;
}else {
cnt_total_1++;
}
}
int till_cnt_0 = 0;
int till_cnt_1 = 0;
int minToggles = Integer.MAX_VALUE;
//Case 1 ---> left side all 1s and right side all 1s
minToggles = Math.min(minToggles, cnt_total_0);
//Case 2 ---> left side all 0s and right side all 0s
minToggles = Math.min(minToggles, cnt_total_0);
for (int bit : arr) {
if (bit == 0) {
till_cnt_0++;
}else {
till_cnt_1++;
}
//Case 3 ---> left side all 0s and right side all 1s
minToggles = Math.min(minToggles, (till_cnt_1 + (cnt_total_0 - till_cnt_0)));
}
return minToggles;
}
}
Advertisement
Was this solution helpful?