Minimize String length by deleting Substring of same character when K flips are allowed
Last Updated :
03 Nov, 2022
Given a binary string consisting of '0' and '1' only and an integer K, the task is to minimize the string as far as possible by deleting a substring of the same character, when you can flip at most K characters.
Examples:
Input: S = "0110", K = 2
Output: 0
Explanation: We can make two '0' s into '1' or vice versa.
So we can delete all the four characters and
the remaining size of the string is 0
Input: S = "111", K = 1
Output: 0
Approach: To solve the problem follow the below idea:
As we have to minimize the string by deleting characters so we have to delete the maximum length of substring consisting of equal letters. So, we can understand the minimum length will range from 1 to the size of the string(let's say n).
Now if we apply binary search on this range of length and check for a shorter length until it is out of range, we can get the answer.
Follow the steps to solve the problem:
- At first, for the binary search, we will define our range from Low = 1 to High = n(size of string).
- Then after finding the mid we will keep passing the mid to check function to get one of the possible answers and keep incrementing the low to mid+1 as we want the maximum length
- In the check function, first, we will create an array of sizes to 2 to count '0' and '1'.
- Then, we will count '0' and '1' and store in that count array, and if the minimum of the count of both elements is less than K that means we can change those characters to the same character to increase the goodness of the string.
- After that will slide the window by mid(limit) size and decrease the count of the first element of the window as the window is not there anymore and increase the count of the new element as it is the new and last element of the window
- Now, we will check again the minimum of the count of '0' s and '1's, if it is less than or equals to K, then return true otherwise false
- We will store every possible answer to the ans variable and when low ? high the loop will terminate and we have our maximum possible length for deletion stored in ans variable.
- Now we will subtract the maximum length from the size of the array to get the size of our minimized string
Below is the implementation for the above approach.
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
bool check(string s, int K, int limit)
{
// Count array for counting
// '0's and '1's
int count[2] = { 0 };
// Counting '0' and '1's in
// window size
for (int i = 0; i < limit; i++) {
count[s[i] - '0']++;
}
// If the minimum of '0's count and
// '1's count less than or equals to
// k it is one of the possible
// answer, return true
if (K >= min(count[0], count[1]))
return true;
// Sliding the window
for (int i = 0; i + limit < s.size(); i++) {
// Decrementing the count of first
// element as window is slided
count[s[i] - '0']--;
// Incrementing the count of new
// element as this is the last
// element of new window
count[s[i + limit] - '0']++;
// Checking the minimum count of
// '0's and '1's because it is
// the new window
if (K >= min(count[0], count[1]))
return true;
}
// If the above conditions are not
// fulfilled return false
return false;
}
void solve(string s, int n, int K)
{
// Defining range 1 to n
int Low = 1, High = n;
// Initializing ans to 0
int ans = 0;
while (Low <= High) {
// Calculating mid
int mid = Low + (High - Low) / 2;
// Passing the mid to
// check function
if (check(s, K, mid)) {
// We got one of the possible
// answers so storing it in
// ans variable
ans = max(ans, mid);
// Also incrementing the low
// to check whether there is
// any maximum length string
// with maximum goodness
// present or not
Low = mid + 1;
}
else {
// Decrementing the high
High = mid - 1;
}
}
// Printing the ans
cout << "Minimum length after deletion is: ";
int res = n - ans;
cout << res;
}
// Driver Code
int main()
{
// Given input
string s = "0110";
int K = 2;
int n = s.size();
// Function call
solve(s, n, K);
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
class GFG {
static boolean check(String s, int K, int limit)
{
// Count array for counting
// '0's and '1's
int[] count = new int[2];
// Counting '0' and '1's in
// window size
for (int i = 0; i < limit; i++) {
count[s.charAt(i) - '0']++;
}
// If the minimum of '0's count and
// '1's count less than or equals to
// k it is one of the possible
// answer, return true
if (K >= Math.min(count[0], count[1]))
return true;
// Sliding the window
for (int i = 0; i + limit < s.length(); i++) {
// Decrementing the count of first
// element as window is slided
count[s.charAt(i) - '0']--;
// Incrementing the count of new
// element as this is the last
// element of new window
count[s.charAt(i + limit) - '0']++;
// Checking the minimum count of
// '0's and '1's because it is
// the new window
if (K >= Math.min(count[0], count[1]))
return true;
}
// If the above conditions are not
// fulfilled return false
return false;
}
static void solve(String s, int n, int K)
{
// Defining range 1 to n
int Low = 1, High = n;
// Initializing ans to 0
int ans = 0;
while (Low <= High) {
// Calculating mid
int mid = Low + (High - Low) / 2;
// Passing the mid to
// check function
if (check(s, K, mid)) {
// We got one of the possible
// answers so storing it in
// ans variable
ans = Math.max(ans, mid);
// Also incrementing the low
// to check whether there is
// any maximum length string
// with maximum goodness
// present or not
Low = mid + 1;
}
else {
// Decrementing the high
High = mid - 1;
}
}
// Printing the ans
System.out.print(
"Minimum length after deletion is: ");
int res = n - ans;
System.out.println(res);
}
public static void main(String[] args)
{
// Given input
String s = "0110";
int K = 2;
int n = s.length();
// Function call
solve(s, n, K);
}
}
// This code is contributed by lokeshmvs21.
Python3
# python3 code for the above approach:
def check(s, K, limit) :
# Count array for counting
# '0's and '1's
count=[0, 0]
# Counting '0' and '1's in
# window size
# for (i=0 i < limit i++):
for i in range(0,limit):
count[int(s[i])] += 1
# If the minimum of '0's count and
# '1's count less than or equals to
# k it is one of the possible
# answer, return true
if (K >= min(count[0],count[1])):
return True
# Sliding the window
for i in range(0,(len(s)-limit)):
count[s[i] - '0'] -= 1
# Decrementing the count of first
# element as window is slided
# Incrementing the count of new
# element as this is the last
# element of new window
count[s[i + limit] - '0'] += 1
# Checking the minimum count of
# '0's and '1's because it is
# the new window
if (K >= min(count[0], count[1])):
return True
# If the above conditions are not
# fulfilled return false
return False
def solve(s, n, K):
# Defining range 1 to n
Low = 1
High = n
# Initializing ans to 0
ans = 0
while (Low <= High):
# Calculating mid
mid = int(Low + (High - Low) / 2)
# Passing the mid to
# check function
if(check(s, K, mid) is True) :
# We got one of the possible
# answers so storing it in
# ans variable
ans = max(ans, mid)
# Also incrementing the low
# to check whether there is
# any maximum length string
# with maximum goodness
# present or not
Low = mid + 1
else:
# Decrementing the high
High = mid - 1
# Printing the ans
res=n - ans
print("Minimum length after deletion is:",res)
# Driver Code
# Given input
s="0110"
K=2
n=len(s)
# Function call
solve(s, n, K)
# this code is contributed by ksam24000
C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG
{
static bool check(string s, int K, int limit)
{
// Count array for counting
// '0's and '1's
int[] count = new int[2];
// Counting '0' and '1's in
// window size
for (int i = 0; i < limit; i++) {
count[s[i] - '0']++;
}
// If the minimum of '0's count and
// '1's count less than or equals to
// k it is one of the possible
// answer, return true
if (K >= Math.Min(count[0], count[1]))
return true;
// Sliding the window
for (int i = 0; i + limit < s.Length; i++) {
// Decrementing the count of first
// element as window is slided
count[s[i] - '0']--;
// Incrementing the count of new
// element as this is the last
// element of new window
count[s[i + limit] - '0']++;
// Checking the minimum count of
// '0's and '1's because it is
// the new window
if (K >= Math.Min(count[0], count[1]))
return true;
}
// If the above conditions are not
// fulfilled return false
return false;
}
static void solve(string s, int n, int K)
{
// Defining range 1 to n
int Low = 1, High = n;
// Initializing ans to 0
int ans = 0;
while (Low <= High) {
// Calculating mid
int mid = Low + (High - Low) / 2;
// Passing the mid to
// check function
if (check(s, K, mid)) {
// We got one of the possible
// answers so storing it in
// ans variable
ans = Math.Max(ans, mid);
// Also incrementing the low
// to check whether there is
// any maximum length string
// with maximum goodness
// present or not
Low = mid + 1;
}
else {
// Decrementing the high
High = mid - 1;
}
}
// Printing the ans
Console.Write( "Minimum length after deletion is: ");
int res = n - ans;
Console.WriteLine(res);
}
// Driver code
public static void Main(String[] args)
{
// Given input
string s = "0110";
int K = 2;
int n = s.Length;
// Function call
solve(s, n, K);
}
}
// This code is contributed by code_hunt.
JavaScript
// JS code for the above approach:
function check(s, K, limit) {
// Count array for counting
// '0's and '1's
let count = [0, 0];
// Counting '0' and '1's in
// window size
for (let i = 0; i < limit; i++) {
count[s[i] - '0'] = count[s[i] - '0'] + 1;
}
// If the minimum of '0's count and
// '1's count less than or equals to
// k it is one of the possible
// answer, return true
if (K >= Math.min(count[0], count[1]))
return true;
// Sliding the window
for (let i = 0; i + limit < s.length; i++) {
// Decrementing the count of first
// element as window is slided
count[s[i] - '0']--;
// Incrementing the count of new
// element as this is the last
// element of new window
count[s[i + limit] - '0']++;
// Checking the minimum count of
// '0's and '1's because it is
// the new window
if (K >= Math.min(count[0], count[1]))
return true;
}
// If the above conditions are not
// fulfilled return false
return false;
}
function solve(s, n, K) {
// Defining range 1 to n
let Low = 1, High = n;
// Initializing ans to 0
let ans = 0;
while (Low <= High) {
// Calculating mid
let mid = Math.floor(Low + (High - Low) / 2);
console.log("mid : ", mid);
// Passing the mid to
// check function
if (check(s, K, mid)) {
// We got one of the possible
// answers so storing it in
// ans variable
ans = Math.max(ans, mid);
// Also incrementing the low
// to check whether there is
// any maximum length string
// with maximum goodness
// present or not
Low = mid + 1;
}
else {
// Decrementing the high
High = mid - 1;
}
}
// Printing the ans
let res = n - ans;
console.log("Minimum length after deletion is:", res);
}
// Driver Code
// Given input
let s = "0110";
let K = 2;
let n = s.length;
// Function call
solve(s, n, K);
// This code is contributed by adityamaharshi21
OutputMinimum length after deletion is: 0
Time Complexity: O(N * logN), as the size of the string, is N and we are applying binary search that has logN complexity. So complexity O(N*logN).
Auxiliary Space: O(1)
Similar Reads
Minimize flips to make binary string as all 1s by flipping characters in substring of size K repeatedly Given a binary string S of size N and an integer K, the task is to find the minimum number of operations required to make all characters as 1s in the binary string by flipping characters in the substring of size K. If it is not possible to do so, then print "-1". Examples: Input: S = "00010110 ", K
7 min read
Minimize length of string by replacing K pairs of distinct adjacent characters Given string str of length N, the task is to find the minimum length to which the given string can be reduced by replacing any pair of non-equal adjacent characters with a single character at most K times. Examples: Input: str = "aabc", K =1Output: 3Explanation: Replace "bc" with a single character
5 min read
Minimum steps to delete a string by deleting substring comprising of same characters Given string str. You are allowed to delete only some contiguous characters if all the characters are the same in a single operation. The task is to find the minimum number of operations required to completely delete the string. Examples: Input: str = "abcddcba" Output: 4 Explanation: Delete dd, the
7 min read
Minimize flips to make substrings of size K same and alternative Given a binary string S of length N, the task is to minimize the count of operations required to find a binary string T of the same length N such that: In one operation, it is allowed to flip any bit, i.e. convert 0 to 1 or vice versa.In the binary string T, choose a number K, such that: N is perfec
9 min read
Minimum moves to make String Palindrome incrementing all characters of Substrings Given a string S of length N, the task is to find the minimum number of moves required to make a string palindrome where in each move you can select any substring and increment all the characters of the substring by 1. Examples: Input: S = "264341"Output: 2?Explanation: We can perform the following
6 min read
Minimize cost to convert given string into concatenation of equal substrings of length K Given a string S of length N consisting of lowercase letters and an integer K, where N % K = 0, the task is to find the minimum cost to convert the given string into a concatenated string of the same K-length substrings by performing the following operations: A character can be replaced with another
8 min read