human
Minimum number of swaps required such that a given substring consists of exactly K 1 s | Function to find the minimum number of swaps required such that the substring { s [ l ] , . . , s [ r ] } consists of exactly k 1 s.
Store the size of the string.
Store the total number of 1 s and 0 s in the entire string.
Traverse the string S to find the frequency of 1 and 0.
Store the number of 1 s and 0 s in the substring s [ l , r ].
Traverse the substring S [ l , r ] to find the frequency of 1 s and 0 s in it.
Store the count of 1 s and 0 s outside substring s [ l , r ].
Check if the sum of the substring is at most K.
Store number of 1 s required.
Check if there are enough 1 s remaining to be swapped.
If the count of 1 s in the substring exceeds k.
Store the number of 0 s required.
Check if there are enough 0 s remaining to be swapped.
In all other cases , print - 1.
Driver Code"
Solution in Python:
assistant
#Here is code to minimum number of swaps required such that a given substring consists of exactly K 1 s and the other steps required.
 def minimumSwaps ( s , l , r , k ) :
	n = len ( s )
	tot_ones , tot_zeros = 0 , 0
	for i in range ( 0 , len ( s ) ) :
		if ( s [ i ] == '1' ) :
			tot_ones += 1
		else :
			tot_zeros += 1
	ones , zeros , Sum = 0 , 0 , 0
	for i in range ( l - 1 , r ) :
		if ( s [ i ] == '1' ) :
			ones += 1
			Sum += 1
		else :
			zeros += 1
	rem_ones = tot_ones - ones
	rem_zeros = tot_zeros - zeros
	if ( k >= Sum ) :
		rem = k - Sum
		if ( zeros >= rem and rem_ones >= rem ) :
			return rem
	elif ( k < Sum ) :
		rem = Sum - k
		if ( ones >= rem and rem_zeros >= rem ) :
			return rem
	return - 1
S = "110011111000101"
L , R , K = 5 , 8 , 2
print ( minimumSwaps ( S , L , R , K ) )