Minimize hamming distance in Binary String by setting only one K size substring bits
Last Updated :
10 Aug, 2021
Given two binary strings S and T of length N and a positive integer K. Initially, all characters of T are '0'. The task is to find the minimum Hamming distance after choosing a substring of size K and making all elements of string T as '1' only once.
Examples:
Input: S = "101", K = 2
Output: 1
Explanation: Initially string T = "000", one possible way is to change all 0s in range [0, 1] to 1. Thus string T becomes "110" and the hamming distance between S and T is 2 which is the minimum possible.
Input: S = "1100", K=3
Output: 1
Naive Approach: The simplest approach is to consider every substring of size K and make all the elements as 1 and then check the hamming distance with string, S. After checking all the substrings, print the minimum hamming distance.
Time Complexity: O(N×K)
Auxiliary Space: O(1)
Approach: This problem can be solved by creating a prefix array sum which stores the prefix sum of the count of ones in the string S. Follow the steps below to solve the problem:
- Create a prefix sum array pref[] of string S by initializing pref[0] as 0 updating pref[i] as pref[i-1] +(S[i] - '0') for every index i.
- Store the total count of ones in the string, S in a variable cnt.
- Initialize a variable ans as cnt to store the required result.
- Iterate in the range [0, N-K] using the variable i
- Initialize a variable val as pref[i+K-1] - pref[i-1] to store the count of ones in the substring S[i, i+K-1].
- Create two variables A and B to store the hamming distance outside the current substring and the hamming distance inside the current substring and initialize A with cnt - K and B with K - val.
- Update the value of ans with the minimum of ans and (A + B).
- Print the value of ans as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find minimum Hamming
// Distance after atmost one operation
int minimumHammingDistance(string S, int K)
{
// Store the size of the string
int n = S.size();
// Store the prefix sum of 1s
int pref[n];
// Create Prefix Sum array
pref[0] = S[0] - '0';
for (int i = 1; i < n; i++)
pref[i] = pref[i - 1] + (S[i] - '0');
// Initialize cnt as number of ones
// in string S
int cnt = pref[n - 1];
// Store the required result
int ans = cnt;
// Traverse the string, S
for (int i = 0; i < n - K; i++) {
// Store the number of 1s in the
// substring S[i, i+K-1]
int value = pref[i + K - 1]
- (i - 1 >= 0 ? pref[i - 1] : 0);
// Update the answer
ans = min(ans, cnt - value + (K - value));
}
// Return the result
return ans;
}
// Driver Code
int main()
{
// Given Input
string s = "101";
int K = 2;
// Function Call
cout << minimumHammingDistance(s, K);
return 0;
}
Java
// Java program for the above approach
public class GFG
{
// Function to find minimum Hamming
// Distance after atmost one operation
static int minimumHammingDistance(String S, int K)
{
// Store the size of the string
int n = S.length();
// Store the prefix sum of 1s
int []pref = new int [n];
// Create Prefix Sum array
pref[0] = S.charAt(0) - '0';
for (int i = 1; i < n; i++)
pref[i] = pref[i - 1] + (S.charAt(i) - '0');
// Initialize cnt as number of ones
// in string S
int cnt = pref[n - 1];
// Store the required result
int ans = cnt;
// Traverse the string, S
for (int i = 0; i < n - K; i++) {
// Store the number of 1s in the
// substring S[i, i+K-1]
int value = pref[i + K - 1] - (i - 1 >= 0 ? pref[i - 1] : 0);
// Update the answer
ans = Math.min(ans, cnt - value + (K - value));
}
// Return the result
return ans;
}
// Driver Code
public static void main(String args[])
{
// Given Input
String s = "101";
int K = 2;
// Function Call
System.out.println(minimumHammingDistance(s, K));
}
}
// This code is contributed by SoumikMondal
Python3
# Py program for the above approach
# Function to find minimum Hamming
# Distance after atmost one operation
def minimumHammingDistance(S, K):
# Store the size of the string
n = len(S)
# Store the prefix sum of 1s
pref = [0] * n
# Create Prefix Sum array
pref[0] = ord(S[0]) - ord('0')
for i in range(1,n):
pref[i] = pref[i - 1] + (ord(S[i]) - ord('0'))
# Initialize cnt as number of ones
# in string S
cnt = pref[n - 1]
# Store the required result
ans = cnt
# Traverse the string, S
for i in range(n - K):
# Store the number of 1s in the
# substring S[i, i+K-1]
value = pref[i + K - 1] - (pref[i-1] if (i - 1) >= 0 else 0)
# Update the answer
ans = min(ans, cnt - value + (K - value))
# Return the result
return ans
# Driver Code
if __name__ == '__main__':
# Given Input
s = "101"
K = 2
# Function Call
print (minimumHammingDistance(s, K))
# This code is contributed by mohit kumar 29.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to find minimum Hamming
// Distance after atmost one operation
static int minimumHammingDistance(string S, int K)
{
// Store the size of the string
int n = S.Length;
// Store the prefix sum of 1s
int []pref = new int [n];
// Create Prefix Sum array
pref[0] = (int)S[0] - 48;
for (int i = 1; i < n; i++)
pref[i] = pref[i - 1] + ((int)S[i] - 48);
// Initialize cnt as number of ones
// in string S
int cnt = pref[n - 1];
// Store the required result
int ans = cnt;
// Traverse the string, S
for (int i = 0; i < n - K; i++) {
// Store the number of 1s in the
// substring S[i, i+K-1]
int value = pref[i + K - 1] - (i - 1 >= 0 ? pref[i - 1] : 0);
// Update the answer
ans = Math.Min(ans, cnt - value + (K - value));
}
// Return the result
return ans;
}
// Driver Code
public static void Main()
{
// Given Input
string s = "101";
int K = 2;
// Function Call
Console.Write(minimumHammingDistance(s, K));
}
}
// This code is contributed by SURENDRA_GANGWAR.
JavaScript
<script>
// JavaScript program for the above approach
// Function to find minimum Hamming
// Distance after atmost one operation
function minimumHammingDistance(S, K)
{
// Store the size of the string
let n = S.length;
// Store the prefix sum of 1s
let pref = new Array(n);
// Create Prefix Sum array
pref[0] = S[0] - '0';
for (let i = 1; i < n; i++)
pref[i] = pref[i - 1] + (S[i] - '0');
// Initialize cnt as number of ones
// in string S
let cnt = pref[n - 1];
// Store the required result
let ans = cnt;
// Traverse the string, S
for (let i = 0; i < n - K; i++) {
// Store the number of 1s in the
// substring S[i, i+K-1]
let value = pref[i + K - 1] - (i - 1 >= 0 ? pref[i - 1] : 0);
// Update the answer
ans = Math.min(ans, cnt - value + (K - value));
}
// Return the result
return ans;
}
// Driver Code
// Given Input
let s = "101";
let K = 2;
// Function Call
document.write(minimumHammingDistance(s, K));
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Maximum number of set bits count in a K-size substring of a Binary String Given a binary string S of size N and an integer K. The task is to find the maximum number of set bit appears in a substring of size K. Examples: Input: S = "100111010", K = 3 Output: 3 Explanation: The substring "111" contains 3 set bits. Input:S = "0000000", K = 4 Output: 0 Explanation: S doesn't
10 min read
Minimize count of 0s in Binary String by changing K-size substring to 1s at most Q times Given a binary string S having N characters and two integers K and Q, the task is to find the minimum number of remaining zeroes after at most Q operations, such that in each operation, choose any substring of size at most K and change all its elements to 1. Example: Input: S = 000111, K = 2, Q = 1O
15+ min read
Minimize cost of swapping set bits with unset bits in a given Binary string Given a binary string S of size N, the task is to find the minimum cost by swapping every set bit with an unset bit such that the cost of swapping pairs of bits at indices i and j is abs(j - i). Note: A swapped bit can't be swapped twice and the count of set bit in the given binary string is at most
12 min read
Maximize value of Binary String in K steps by performing XOR of Substrings Given a binary string S of size N, the task is to find the maximum possible value in exactly K step, where in each step, perform XOR of two substrings of S (possibly intersecting, possibly the same, possibly non-intersecting). Examples: Input: string S ="1010010", K = 2Output: "1111110"Explanation:I
15 min read
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
Find the minimum number of distinct Substrings formed by 0s in Binary String Given two integers N and M, the task is to output the minimum number of different substrings that can be formed using the Binary String of length N having M number of set bits. Note: Two substrings let say S[x, y] and S[a, b] are different. If either x != a or y != b. Examples: Input: N = 3, M = 1Ou
6 min read
Count of setbits in bitwise OR of all K length substrings of given Binary String Given a binary string str of length N, the task is to find the number of setbits in the bitwise OR of all the K length substrings of string str. Examples: Input: N = 4, K = 3, str = "1111"Output: 3Explanation: All 3-sized substrings of S are:"111" and "111". The OR of these strings is "111". Therefo
8 min read
Maximize non-overlapping Substrings by splitting String into groups with K or (K+1) 1s Given a binary string S of length N and an integer K, the task is to find the maximum number of non-overlapping substrings that can be obtained by splitting it as per the following conditions: Each substring of the string contains K or K+1 number of 1. At most consecutive K substrings can contain th
10 min read
Maximum bitwise OR one of any two Substrings of given Binary String Given a binary string str, the task is to find the maximum possible OR value of any two substrings of the binary string str. Examples: Input: str = "1110010"Output: "1111110"Explanation: On choosing the substring "1110010" and "11100" we get the OR value as "1111110" which is the maximum value. Inpu
8 min read