Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String
Last Updated :
23 Jul, 2025
Given a binary string S of size N, the task is to maximize the sum of the count of consecutive 0s present at the start and end of any of the rotations of the given string S.
Examples:
Input: S = "1001"
Output: 2
Explanation:
All possible rotations of the string are:
"1001": Count of 0s at the start = 0; at the end = 0. Sum= 0 + 0 = 0.
"0011": Count of 0s at the start = 2; at the end = 0. Sum = 2 + 0=2
"0110": Count of 0s at the start = 1; at the end = 1. Sum= 1 + 1 = 2.
"1100": Count of 0s at the start = 0; at the end = 2. Sum = 0 + 2 = 2
Therefore, the maximum sum possible is 2.
Input: S = "01010"
Output: 2
Explanation:
All possible rotations of the string are:
"01010": Count of 0s at the start = 1; at the end = 1. Sum= 1+1=1
"10100": Count of 0s at the start = 0; at the end = 2. Sum= 0+2=2
"01001": Count of 0s at the start = 1; at the end = 0. Sum= 1+0=1
"10010": Count of 0s at the start = 0; at the end = 1. Sum= 0+1=1
"00101": Count of 0s at the start = 2; at the end = 0. Sum= 2+0=2
Therefore, the maximum sum possible is 2.
Naive Approach: The simplest idea is to generate all rotations of the given string and for each rotation, count the number of 0s present at the beginning and end of the string and calculate their sum. Finally, print the maximum sum obtained.
Algorithm:
- Initialize a counter variable c0 to 0 to count the frequency of 0s in the given string.
- Traverse the string and for each character, if it is 0, increment the value of c0 by 1.
- If the value of c0 is equal to the length of the string n, it means that all the characters in the string are 0, so the maximum sum of consecutive 0s present at the start and end of the string will be n. Print n and return.
- Concatenate the string with itself and store it in a new string s.
- Initialize a variable mx to 0 to store the maximum sum of consecutive 0s present at the start and end of a string in any rotation of the given string.
- Generate all rotations of the string s using a loop that iterates from 0 to n-1.
- For each rotation, initialize two variables cs and ce to 0 to store the number of consecutive 0s at the start and end of the string, respectively.
- Traverse the rotated string from the current index i to i+n-1, and for each character, if it is 0, increment the value of cs by 1, else break out of the loop.
- Traverse the rotated string from the current index i+n-1 to i, and for each character, if it is 0, increment the value of ce by 1, else break out of the loop.
- Calculate the sum of cs and ce and store it in a variable val.
- Update the value of mx to the maximum of its current value and val.
- After the loop ends, the value of mx will contain the maximum sum of consecutive 0s present at the start and end of a string in any rotation of the given string. Print mx.
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 the maximum sum of
// consecutive 0s present at the start
// and end of a string present in any
// of the rotations of the given string
void findMaximumZeros(string str, int n)
{
// Check if all the characters
// in the string are 0
int c0 = 0;
// Iterate over characters
// of the string
for (int i = 0; i < n; ++i) {
if (str[i] == '0')
c0++;
}
// If the frequency of '1' is 0
if (c0 == n) {
// Print n as the result
cout << n;
return;
}
// Concatenate the string
// with itself
string s = str + str;
// Stores the required result
int mx = 0;
// Generate all rotations of the string
for (int i = 0; i < n; ++i) {
// Store the number of consecutive 0s
// at the start and end of the string
int cs = 0;
int ce = 0;
// Count 0s present at the start
for (int j = i; j < i + n; ++j) {
if (s[j] == '0')
cs++;
else
break;
}
// Count 0s present at the end
for (int j = i + n - 1; j >= i; --j) {
if (s[j] == '0')
ce++;
else
break;
}
// Calculate the sum
int val = cs + ce;
// Update the overall
// maximum sum
mx = max(val, mx);
}
// Print the result
cout << mx;
}
// Driver Code
int main()
{
// Given string
string s = "1001";
// Store the size of the string
int n = s.size();
findMaximumZeros(s, n);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to find the maximum sum of
// consecutive 0s present at the start
// and end of a string present in any
// of the rotations of the given string
static void findMaximumZeros(String str, int n)
{
// Check if all the characters
// in the string are 0
int c0 = 0;
// Iterate over characters
// of the string
for(int i = 0; i < n; ++i)
{
if (str.charAt(i) == '0')
c0++;
}
// If the frequency of '1' is 0
if (c0 == n)
{
// Print n as the result
System.out.print(n);
return;
}
// Concatenate the string
// with itself
String s = str + str;
// Stores the required result
int mx = 0;
// Generate all rotations of the string
for(int i = 0; i < n; ++i)
{
// Store the number of consecutive 0s
// at the start and end of the string
int cs = 0;
int ce = 0;
// Count 0s present at the start
for(int j = i; j < i + n; ++j)
{
if (s.charAt(j) == '0')
cs++;
else
break;
}
// Count 0s present at the end
for(int j = i + n - 1; j >= i; --j)
{
if (s.charAt(j) == '0')
ce++;
else
break;
}
// Calculate the sum
int val = cs + ce;
// Update the overall
// maximum sum
mx = Math.max(val, mx);
}
// Print the result
System.out.print(mx);
}
// Driver Code
public static void main(String[] args)
{
// Given string
String s = "1001";
// Store the size of the string
int n = s.length();
findMaximumZeros(s, n);
}
}
// This code is contributed by susmitakundugoaldanga
Python3
# Python3 program for the above approach
# Function to find the maximum sum of
# consecutive 0s present at the start
# and end of a string present in any
# of the rotations of the given string
def findMaximumZeros(st, n):
# Check if all the characters
# in the string are 0
c0 = 0
# Iterate over characters
# of the string
for i in range(n):
if (st[i] == '0'):
c0 += 1
# If the frequency of '1' is 0
if (c0 == n):
# Print n as the result
print(n)
return
# Concatenate the string
# with itself
s = st + st
# Stores the required result
mx = 0
# Generate all rotations of the string
for i in range(n):
# Store the number of consecutive 0s
# at the start and end of the string
cs = 0
ce = 0
# Count 0s present at the start
for j in range(i, i + n):
if (s[j] == '0'):
cs += 1
else:
break
# Count 0s present at the end
for j in range(i + n - 1, i - 1, -1):
if (s[j] == '0'):
ce += 1
else:
break
# Calculate the sum
val = cs + ce
# Update the overall
# maximum sum
mx = max(val, mx)
# Print the result
print(mx)
# Driver Code
if __name__ == "__main__":
# Given string
s = "1001"
# Store the size of the string
n = len(s)
findMaximumZeros(s, n)
# This code is contributed by ukasp.
C#
// C# program for the above approach
using System;
class GFG{
// Function to find the maximum sum of
// consecutive 0s present at the start
// and end of a string present in any
// of the rotations of the given string
static void findMaximumZeros(string str, int n)
{
// Check if all the characters
// in the string are 0
int c0 = 0;
// Iterate over characters
// of the string
for(int i = 0; i < n; ++i)
{
if (str[i] == '0')
c0++;
}
// If the frequency of '1' is 0
if (c0 == n)
{
// Print n as the result
Console.Write(n);
return;
}
// Concatenate the string
// with itself
string s = str + str;
// Stores the required result
int mx = 0;
// Generate all rotations of the string
for(int i = 0; i < n; ++i)
{
// Store the number of consecutive 0s
// at the start and end of the string
int cs = 0;
int ce = 0;
// Count 0s present at the start
for(int j = i; j < i + n; ++j)
{
if (s[j] == '0')
cs++;
else
break;
}
// Count 0s present at the end
for(int j = i + n - 1; j >= i; --j)
{
if (s[j] == '0')
ce++;
else
break;
}
// Calculate the sum
int val = cs + ce;
// Update the overall
// maximum sum
mx = Math.Max(val, mx);
}
// Print the result
Console.Write(mx);
}
// Driver Code
public static void Main(string[] args)
{
// Given string
string s = "1001";
// Store the size of the string
int n = s.Length;
findMaximumZeros(s, n);
}
}
// This code is contributed by AnkThon
JavaScript
<script>
// Javascript program for the above approach
// Function to find the maximum sum of
// consecutive 0s present at the start
// and end of a string present in any
// of the rotations of the given string
function findMaximumZeros(str, n)
{
// Check if all the characters
// in the string are 0
var c0 = 0;
var i;
// Iterate over characters
// of the string
for (i = 0; i < n; ++i) {
if (str[i] == '0')
c0++;
}
// If the frequency of '1' is 0
if (c0 == n) {
// Print n as the result
document.write(n);
return;
}
// Concatenate the string
// with itself
var s = str + str;
// Stores the required result
var mx = 0;
var j;
// Generate all rotations of the string
for (i = 0; i < n; ++i) {
// Store the number of consecutive 0s
// at the start and end of the string
var cs = 0;
var ce = 0;
// Count 0s present at the start
for (j = i; j < i + n; ++j) {
if (s[j] == '0')
cs++;
else
break;
}
// Count 0s present at the end
for (j = i + n - 1; j >= i; --j) {
if (s[j] == '0')
ce++;
else
break;
}
// Calculate the sum
var val = cs + ce;
// Update the overall
// maximum sum
mx = Math.max(val, mx);
}
// Print the result
document.write(mx);
}
// Driver Code
// Given string
var s = "1001";
// Store the size of the string
var n = s.length;
findMaximumZeros(s, n);
</script>
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: The idea is to find the maximum number of consecutive 0s in the given string. Also, find the sum of consecutive 0s at the start and the end of the string, and then print the maximum out of them.
Follow the steps below to solve the problem:
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 the maximum sum of
// consecutive 0s present at the start
// and end of any rotation of the string str
void findMaximumZeros(string str, int n)
{
// Stores the count of 0s
int c0 = 0;
for (int i = 0; i < n; ++i) {
if (str[i] == '0')
c0++;
}
// If the frequency of '1' is 0
if (c0 == n) {
// Print n as the result
cout << n;
return;
}
// Stores the required sum
int mx = 0;
// Find the maximum consecutive
// length of 0s present in the string
int cnt = 0;
for (int i = 0; i < n; i++) {
if (str[i] == '0')
cnt++;
else {
mx = max(mx, cnt);
cnt = 0;
}
}
// Update the overall maximum sum
mx = max(mx, cnt);
// Find the number of 0s present at
// the start and end of the string
int start = 0, end = n - 1;
cnt = 0;
// Update the count of 0s at the start
while (str[start] != '1' && start < n) {
cnt++;
start++;
}
// Update the count of 0s at the end
while (str[end] != '1' && end >= 0) {
cnt++;
end--;
}
// Update the maximum sum
mx = max(mx, cnt);
// Print the result
cout << mx;
}
// Driver Code
int main()
{
// Given string
string s = "1001";
// Store the size of the string
int n = s.size();
findMaximumZeros(s, n);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to find the maximum sum of
// consecutive 0s present at the start
// and end of any rotation of the string str
static void findMaximumZeros(String str, int n)
{
// Stores the count of 0s
int c0 = 0;
for(int i = 0; i < n; ++i)
{
if (str.charAt(i) == '0')
c0++;
}
// If the frequency of '1' is 0
if (c0 == n)
{
// Print n as the result
System.out.print(n);
return;
}
// Stores the required sum
int mx = 0;
// Find the maximum consecutive
// length of 0s present in the string
int cnt = 0;
for(int i = 0; i < n; i++)
{
if (str.charAt(i) == '0')
cnt++;
else
{
mx = Math.max(mx, cnt);
cnt = 0;
}
}
// Update the overall maximum sum
mx = Math.max(mx, cnt);
// Find the number of 0s present at
// the start and end of the string
int start = 0, end = n - 1;
cnt = 0;
// Update the count of 0s at the start
while (str.charAt(start) != '1' && start < n)
{
cnt++;
start++;
}
// Update the count of 0s at the end
while (str.charAt(end) != '1' && end >= 0)
{
cnt++;
end--;
}
// Update the maximum sum
mx = Math.max(mx, cnt);
// Print the result
System.out.println(mx);
}
// Driver Code
public static void main (String[] args)
{
// Given string
String s = "1001";
// Store the size of the string
int n = s.length();
findMaximumZeros(s, n);
}
}
// This code is contributed by sanjoy_62
Python3
# Python3 program for the above approach
# Function to find the maximum sum of
# consecutive 0s present at the start
# and end of any rotation of the string str
def findMaximumZeros(string, n):
# Stores the count of 0s
c0 = 0
for i in range(n):
if (string[i] == '0'):
c0 += 1
# If the frequency of '1' is 0
if (c0 == n):
# Print n as the result
print(n, end = "")
return
# Stores the required sum
mx = 0
# Find the maximum consecutive
# length of 0s present in the string
cnt = 0
for i in range(n):
if (string[i] == '0'):
cnt += 1
else:
mx = max(mx, cnt)
cnt = 0
# Update the overall maximum sum
mx = max(mx, cnt)
# Find the number of 0s present at
# the start and end of the string
start = 0
end = n - 1
cnt = 0
# Update the count of 0s at the start
while (string[start] != '1' and start < n):
cnt += 1
start += 1
# Update the count of 0s at the end
while (string[end] != '1' and end >= 0):
cnt += 1
end -= 1
# Update the maximum sum
mx = max(mx, cnt)
# Print the result
print(mx, end = "")
# Driver Code
if __name__ == "__main__":
# Given string
s = "1001"
# Store the size of the string
n = len(s)
findMaximumZeros(s, n)
# This code is contributed by AnkThon
C#
// C# program for the above approach
using System;
class GFG{
// Function to find the maximum sum of
// consecutive 0s present at the start
// and end of any rotation of the string str
static void findMaximumZeros(string str, int n)
{
// Stores the count of 0s
int c0 = 0;
for(int i = 0; i < n; ++i)
{
if (str[i] == '0')
c0++;
}
// If the frequency of '1' is 0
if (c0 == n)
{
// Print n as the result
Console.Write(n);
return;
}
// Stores the required sum
int mx = 0;
// Find the maximum consecutive
// length of 0s present in the string
int cnt = 0;
for(int i = 0; i < n; i++)
{
if (str[i] == '0')
cnt++;
else
{
mx = Math.Max(mx, cnt);
cnt = 0;
}
}
// Update the overall maximum sum
mx = Math.Max(mx, cnt);
// Find the number of 0s present at
// the start and end of the string
int start = 0, end = n - 1;
cnt = 0;
// Update the count of 0s at the start
while (str[start] != '1' && start < n)
{
cnt++;
start++;
}
// Update the count of 0s at the end
while (str[end] != '1' && end >= 0)
{
cnt++;
end--;
}
// Update the maximum sum
mx = Math.Max(mx, cnt);
// Print the result
Console.Write(mx);
}
// Driver Code
static public void Main ()
{
// Given string
string s = "1001";
// Store the size of the string
int n = s.Length;
findMaximumZeros(s, n);
}
}
// This code is contributed by avijitmondal1998
JavaScript
<script>
//Javascript program for
//the above approach
// Function to find the maximum sum of
// consecutive 0s present at the start
// and end of any rotation of the string str
function findMaximumZeros(str, n)
{
// Stores the count of 0s
var c0 = 0;
for (var i = 0; i < n; ++i) {
if (str[i] == '0')
c0++;
}
// If the frequency of '1' is 0
if (c0 == n) {
// Print n as the result
document.write( n);
return;
}
// Stores the required sum
var mx = 0;
// Find the maximum consecutive
// length of 0s present in the string
var cnt = 0;
for (var i = 0; i < n; i++) {
if (str[i] == '0')
cnt++;
else {
mx = Math.max(mx, cnt);
cnt = 0;
}
}
// Update the overall maximum sum
mx = Math.max(mx, cnt);
// Find the number of 0s present at
// the start and end of the string
var start = 0, end = n - 1;
cnt = 0;
// Update the count of 0s at the start
while (str[start] != '1' && start < n) {
cnt++;
start++;
}
// Update the count of 0s at the end
while (str[end] != '1' && end >= 0) {
cnt++;
end--;
}
// Update the maximum sum
mx = Math.max(mx, cnt);
// Print the result
document.write( mx);
}
var s = "1001";
// Store the size of the string
var n = s.length;
findMaximumZeros(s, n);
// This code is contributed by SoumikMondal
</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