Minimum number of swaps required such that a given substring consists of exactly K 1s
Last Updated :
23 Jul, 2025
Given a binary string S of size N and three positive integers L, R, and K, the task is to find the minimum number of swaps required to such that the substring {S[L], .. S[R]} consists of exactly K 1s. If it is not possible to do so, then print "-1".
Examples:
Input: S = "110011111000101", L = 5, R = 8, K = 2
Output: 2
Explanation:
Initially, the substring {S[5], .. S[8]} = "1111" consists of 4 1s.
Swap (S[5], S[3]) and (S[6], S[4]).
Modified string S = "111100111000101" and {S[5], .. S[8]} = "0011".
Therefore, 2 swaps are required.
Input: S = "01010101010101", L = 3, R = 7, K = 8
Output: -1
Approach: The idea is to count the number of 1s and 0s present in the substring and outside the substring, {S[L], ..., S[R]}. Then, check if enough 1s or 0s are present outside that range which can be swapped such that the substring contains exactly K 1s.
Follow the steps below to solve the problem:
- Store the frequency of 1s and 0s in the string S in cntOnes and cntZeros respectively.
- Also, store the frequency of 1s and 0s in the substring S[L, R] in ones and zeros respectively.
- Find the frequency of 1s and 0s outside the substring S[L, R] using the formula: (rem_ones = cntOnes - ones) and rem_zero = (cntZeros - zeros).
- If k ? ones, then do the following:
- Initialize rem = (K - ones), which denotes the number of 1s required to make the sum equal to K.
- If zeros ? rem and rem_ones ? rem, print the value of rem as the result.
- Otherwise, if K < ones, then do the following:
- Initialize rem = (ones - K), which denotes the number of 0s required to make the sum equal to K.
- If ones ? rem and rem_zeros ? rem, print the value of rem as the result.
- In all other cases, print -1.
Below is the implementation of the above approach:
C++
// CPP program for the above approach
#include<bits/stdc++.h>
using namespace std;
// Function to find the minimum number
// of swaps required such that the
// substring {s[l], .., s[r]} consists
// of exactly k 1s
int minimumSwaps(string s, int l, int r, int k)
{
// Store the size of the string
int n = s.length();
// Store the total number of 1s
// and 0s in the entire string
int tot_ones = 0, tot_zeros = 0;
// Traverse the string S to find
// the frequency of 1 and 0
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '1')
tot_ones++;
else
tot_zeros++;
}
// Store the number of 1s and
// 0s in the substring s[l, r]
int ones = 0, zeros = 0, sum = 0;
// Traverse the substring S[l, r]
// to find the frequency of 1s
// and 0s in it
for (int i = l - 1; i < r; i++)
{
if (s[i] == '1')
{
ones++;
sum++;
}
else
zeros++;
}
// Store the count of 1s and
// 0s outside substring s[l, r]
int rem_ones = tot_ones - ones;
int rem_zeros = tot_zeros - zeros;
// Check if the sum of the
// substring is at most K
if (k >= sum)
{
// Store number of 1s required
int rem = k - sum;
// Check if there are enough 1s
// remaining to be swapped
if (zeros >= rem && rem_ones >= rem)
return rem;
}
// If the count of 1s in the substring exceeds k
else if (k < sum)
{
// Store the number of 0s required
int rem = sum - k;
// Check if there are enough 0s
// remaining to be swapped
if (ones >= rem && rem_zeros >= rem)
return rem;
}
// In all other cases, print -1
return -1;
}
// Driver Code
int main()
{
string S = "110011111000101";
int L = 5, R = 8, K = 2;
cout<<minimumSwaps(S, L, R, K);
}
// This code is contributed bgangwar59.
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to find the minimum number
// of swaps required such that the
// substring {s[l], .., s[r]} consists
// of exactly k 1s
static int minimumSwaps(
String s, int l, int r, int k)
{
// Store the size of the string
int n = s.length();
// Store the total number of 1s
// and 0s in the entire string
int tot_ones = 0, tot_zeros = 0;
// Traverse the string S to find
// the frequency of 1 and 0
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '1')
tot_ones++;
else
tot_zeros++;
}
// Store the number of 1s and
// 0s in the substring s[l, r]
int ones = 0, zeros = 0, sum = 0;
// Traverse the substring S[l, r]
// to find the frequency of 1s
// and 0s in it
for (int i = l - 1; i < r; i++) {
if (s.charAt(i) == '1') {
ones++;
sum++;
}
else
zeros++;
}
// Store the count of 1s and
// 0s outside substring s[l, r]
int rem_ones = tot_ones - ones;
int rem_zeros = tot_zeros - zeros;
// Check if the sum of the
// substring is at most K
if (k >= sum) {
// Store number of 1s required
int rem = k - sum;
// Check if there are enough 1s
// remaining to be swapped
if (zeros >= rem && rem_ones >= rem)
return rem;
}
// If the count of 1s in the substring exceeds k
else if (k < sum) {
// Store the number of 0s required
int rem = sum - k;
// Check if there are enough 0s
// remaining to be swapped
if (ones >= rem && rem_zeros >= rem)
return rem;
}
// In all other cases, print -1
return -1;
}
// Driver Code
public static void main(String[] args)
{
String S = "110011111000101";
int L = 5, R = 8, K = 2;
System.out.println(
minimumSwaps(S, L, R, K));
}
}
Python3
# Python3 program for the above approach
# Function to find the minimum number
# of swaps required such that the
# substring {s[l], .., s[r]} consists
# of exactly k 1s
def minimumSwaps(s, l, r, k) :
# Store the size of the string
n = len(s)
# Store the total number of 1s
# and 0s in the entire string
tot_ones, tot_zeros = 0, 0
# Traverse the string S to find
# the frequency of 1 and 0
for i in range(0, len(s)) :
if (s[i] == '1') :
tot_ones += 1
else :
tot_zeros += 1
# Store the number of 1s and
# 0s in the substring s[l, r]
ones, zeros, Sum = 0, 0, 0
# Traverse the substring S[l, r]
# to find the frequency of 1s
# and 0s in it
for i in range(l - 1, r) :
if (s[i] == '1') :
ones += 1
Sum += 1
else :
zeros += 1
# Store the count of 1s and
# 0s outside substring s[l, r]
rem_ones = tot_ones - ones
rem_zeros = tot_zeros - zeros
# Check if the sum of the
# substring is at most K
if (k >= Sum) :
# Store number of 1s required
rem = k - Sum
# Check if there are enough 1s
# remaining to be swapped
if (zeros >= rem and rem_ones >= rem) :
return rem
# If the count of 1s in the substring exceeds k
elif (k < Sum) :
# Store the number of 0s required
rem = Sum - k
# Check if there are enough 0s
# remaining to be swapped
if (ones >= rem and rem_zeros >= rem) :
return rem
# In all other cases, print -1
return -1
S = "110011111000101"
L, R, K = 5, 8, 2
print(minimumSwaps(S, L, R, K))
# This code is contributed by divyeshrabadiya07.
C#
// C# program to implement
// the above approach
using System;
class GFG
{
// Function to find the minimum number
// of swaps required such that the
// substring {s[l], .., s[r]} consists
// of exactly k 1s
static int minimumSwaps(string s, int l, int r, int k)
{
// Store the size of the string
int n = s.Length;
// Store the total number of 1s
// and 0s in the entire string
int tot_ones = 0, tot_zeros = 0;
// Traverse the string S to find
// the frequency of 1 and 0
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '1')
tot_ones++;
else
tot_zeros++;
}
// Store the number of 1s and
// 0s in the substring s[l, r]
int ones = 0, zeros = 0, sum = 0;
// Traverse the substring S[l, r]
// to find the frequency of 1s
// and 0s in it
for (int i = l - 1; i < r; i++)
{
if (s[i] == '1')
{
ones++;
sum++;
}
else
zeros++;
}
// Store the count of 1s and
// 0s outside substring s[l, r]
int rem_ones = tot_ones - ones;
int rem_zeros = tot_zeros - zeros;
// Check if the sum of the
// substring is at most K
if (k >= sum)
{
// Store number of 1s required
int rem = k - sum;
// Check if there are enough 1s
// remaining to be swapped
if (zeros >= rem && rem_ones >= rem)
return rem;
}
// If the count of 1s in the substring exceeds k
else if (k < sum)
{
// Store the number of 0s required
int rem = sum - k;
// Check if there are enough 0s
// remaining to be swapped
if (ones >= rem && rem_zeros >= rem)
return rem;
}
// In all other cases, print -1
return -1;
}
// Driver Code
public static void Main(String[] args)
{
string S = "110011111000101";
int L = 5, R = 8, K = 2;
Console.Write(minimumSwaps(S, L, R, K));
}
}
// This code is contributed by splevel62.
JavaScript
<script>
// javascript program for the above approach
// Function to find the minimum number
// of swaps required such that the
// substring {s[l], .., s[r]} consists
// of exactly k 1s
function minimumSwaps(s , l , r , k)
{
// Store the size of the string
var n = s.length;
// Store the total number of 1s
// and 0s in the entire string
var tot_ones = 0, tot_zeros = 0;
// Traverse the string S to find
// the frequency of 1 and 0
for (i = 0; i < s.length; i++) {
if (s.charAt(i) == '1')
tot_ones++;
else
tot_zeros++;
}
// Store the number of 1s and
// 0s in the substring s[l, r]
var ones = 0, zeros = 0, sum = 0;
// Traverse the substring S[l, r]
// to find the frequency of 1s
// and 0s in it
for (var i = l - 1; i < r; i++) {
if (s.charAt(i) == '1') {
ones++;
sum++;
}
else
zeros++;
}
// Store the count of 1s and
// 0s outside substring s[l, r]
var rem_ones = tot_ones - ones;
var rem_zeros = tot_zeros - zeros;
// Check if the sum of the
// substring is at most K
if (k >= sum) {
// Store number of 1s required
var rem = k - sum;
// Check if there are enough 1s
// remaining to be swapped
if (zeros >= rem && rem_ones >= rem)
return rem;
}
// If the count of 1s in the substring exceeds k
else if (k < sum) {
// Store the number of 0s required
var rem = sum - k;
// Check if there are enough 0s
// remaining to be swapped
if (ones >= rem && rem_zeros >= rem)
return rem;
}
// In all other cases, print -1
return -1;
}
// Driver Code
var S = "110011111000101";
var L = 5, R = 8, K = 2;
document.write(
minimumSwaps(S, L, R, K));
// This code is contributed by 29AjayKumar
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem