Longest Substring of 1's after removing one character
Last Updated :
23 Jul, 2025
Given a binary string S of length N, the task is to find the longest substring consisting of '1's only present in the string after deleting a character from the string.
Examples:
Input: S = "1101"
Output: 3
Explanation:
Removing S[0], S modifies to "101". Longest possible substring of '1's is 1.
Removing S[1], S modifies to "101". Longest possible substring of '1's is 1.
Removing S[2], S modifies to "111". Longest possible substring of '1's is 3.
Removing S[3], S modifies to "110". Longest possible substring of '1's is 2.
Therefore, longest substring of '1's that can be obtained is 3.
Input: S = "011101101"
Output: 5
Method 1: The idea is to traverse the string and search for '0's in the given string. For every character which is found to be '0', add the length of its adjacent substrings of '1'. Print the maximum of all such lengths obtained.
Below is the implementation of the above approach:
C++
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to calculate the length of the
// longest substring of '1's that can be
// obtained by deleting one character
int longestSubarray(string s)
{
// Add '0' at the end
s += '0';
// Iterator to traverse the string
int i;
// Stores maximum length
// of required substring
int res = 0;
// Stores length of substring of '1'
// preceding the current character
int prev_one = 0;
// Stores length of substring of '1'
// succeeding the current character
int curr_one = 0;
// Counts number of '0's
int numberOfZeros = 0;
// Traverse the string S
for (i = 0; i < s.length(); i++) {
// If current character is '1'
if (s[i] == '1') {
// Increase curr_one by one
curr_one += 1;
}
// Otherwise
else {
// Increment numberofZeros by one
numberOfZeros += 1;
// Count length of substring
// obtained y concatenating
// preceding and succeeding substrings of '1'
prev_one += curr_one;
// Store maximum size in res
res = max(res, prev_one);
// Assign curr_one to prev_one
prev_one = curr_one;
// Reset curr_one
curr_one = 0;
}
}
// If string contains only one '0'
if (numberOfZeros == 1) {
res -= 1;
}
// Return the answer
return res;
}
// Driver Code
int main()
{
string S = "1101";
cout << longestSubarray(S);
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.Arrays;
class GFG{
// Function to calculate the length of the
// longest substring of '1's that can be
// obtained by deleting one character
static int longestSubarray(String s)
{
// Add '0' at the end
s += '0';
// Iterator to traverse the string
int i;
// Stores maximum length
// of required substring
int res = 0;
// Stores length of substring of '1'
// preceding the current character
int prev_one = 0;
// Stores length of substring of '1'
// succeeding the current character
int curr_one = 0;
// Counts number of '0's
int numberOfZeros = 0;
// Traverse the string S
for(i = 0; i < s.length(); i++)
{
// If current character is '1'
if (s.charAt(i) == '1')
{
// Increase curr_one by one
curr_one += 1;
}
// Otherwise
else
{
// Increment numberofZeros by one
numberOfZeros += 1;
// Count length of substring
// obtained y concatenating
// preceding and succeeding
// substrings of '1'
prev_one += curr_one;
// Store maximum size in res
res = Math.max(res, prev_one);
// Assign curr_one to prev_one
prev_one = curr_one;
// Reset curr_one
curr_one = 0;
}
}
// If string contains only one '0'
if (numberOfZeros == 1)
{
res -= 1;
}
// Return the answer
return res;
}
// Driver Code
public static void main (String[] args)
{
String S = "1101";
System.out.println(longestSubarray(S));
}
}
// This code is contributed by code_hunt
Python3
# Python3 program to implement
# the above approach
# Function to calculate the length of the
# longest substring of '1's that can be
# obtained by deleting one character
def longestSubarray(s):
# Add '0' at the end
s += '0'
# Iterator to traverse the string
i = 0
# Stores maximum length
# of required substring
res = 0
# Stores length of substring of '1'
# preceding the current character
prev_one = 0
# Stores length of substring of '1'
# succeeding the current character
curr_one = 0
# Counts number of '0's
numberOfZeros = 0
# Traverse the string S
for i in range(len(s)):
# If current character is '1'
if (s[i] == '1'):
# Increase curr_one by one
curr_one += 1
# Otherwise
else:
# Increment numberofZeros by one
numberOfZeros += 1
# Count length of substring
# obtained y concatenating
# preceding and succeeding
# substrings of '1'
prev_one += curr_one
# Store maximum size in res
res = max(res, prev_one)
# Assign curr_one to prev_one
prev_one = curr_one
# Reset curr_one
curr_one = 0
# If string contains only one '0'
if (numberOfZeros == 1):
res -= 1
# Return the answer
return res
# Driver Code
if __name__ == '__main__':
S = "1101"
print(longestSubarray(S))
# This code is contributed by ipg2016107
C#
// C# program to implement
// the above approach
using System;
class GFG
{
// Function to calculate the length of the
// longest substring of '1's that can be
// obtained by deleting one character
static int longestSubarray(String s)
{
// Add '0' at the end
s += '0';
// Iterator to traverse the string
int i;
// Stores maximum length
// of required substring
int res = 0;
// Stores length of substring of '1'
// preceding the current character
int prev_one = 0;
// Stores length of substring of '1'
// succeeding the current character
int curr_one = 0;
// Counts number of '0's
int numberOfZeros = 0;
// Traverse the string S
for(i = 0; i < s.Length; i++)
{
// If current character is '1'
if (s[i] == '1')
{
// Increase curr_one by one
curr_one += 1;
}
// Otherwise
else
{
// Increment numberofZeros by one
numberOfZeros += 1;
// Count length of substring
// obtained y concatenating
// preceding and succeeding
// substrings of '1'
prev_one += curr_one;
// Store maximum size in res
res = Math.Max(res, prev_one);
// Assign curr_one to prev_one
prev_one = curr_one;
// Reset curr_one
curr_one = 0;
}
}
// If string contains only one '0'
if (numberOfZeros == 1)
{
res -= 1;
}
// Return the answer
return res;
}
// Driver Code
public static void Main(String[] args)
{
String S = "1101";
Console.WriteLine(longestSubarray(S));
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// javascript program to implement
// the above approach
// Function to calculate the length of the
// longest substring of '1's that can be
// obtained by deleting one character
function longestSubarray(s)
{
// Add '0' at the end
s += '0';
// Iterator to traverse the string
let i;
// Stores maximum length
// of required substring
let res = 0;
// Stores length of substring of '1'
// preceding the current character
let prev_one = 0;
// Stores length of substring of '1'
// succeeding the current character
let curr_one = 0;
// Counts number of '0's
let numberOfZeros = 0;
// Traverse the string S
for(i = 0; i < s.length; i++)
{
// If current character is '1'
if (s[i] == '1')
{
// Increase curr_one by one
curr_one += 1;
}
// Otherwise
else
{
// Increment numberofZeros by one
numberOfZeros += 1;
// Count length of substring
// obtained y concatenating
// preceding and succeeding
// substrings of '1'
prev_one += curr_one;
// Store maximum size in res
res = Math.max(res, prev_one);
// Assign curr_one to prev_one
prev_one = curr_one;
// Reset curr_one
curr_one = 0;
}
}
// If string contains only one '0'
if (numberOfZeros == 1)
{
res -= 1;
}
// Return the answer
return res;
}
// Driver code
let S = "1101";
document.write(longestSubarray(S));
// This code is contributed by splevel62.
</script>
Time Complexity: O(N)
Auxiliary Space: O(1) as we are not using any extra space.
Method 2: Alternate approach to solve the problem is to use sliding window technique for finding the maximum length of substring containing only '1's after deleting a single character. Follow the steps below to solve the problem:
- Initialize 3 integer variables i, j, with 0 and k with 1
- Iterate over the characters of the string S.
- For every character traversed, check if it is '0' or not. If found to be true, decrement k by 1.
- If k < 0 and character at ith index is '0', increment k and i by one
- Increment j by one.
- Finally, print the length j - i - 1 after complete traversal of the string.
Below is the implementation of the above approach:
C++
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to calculate the length of the
// longest substring of '1's that can be
// obtained by deleting one character
int longestSubarray(string s)
{
// Initializing i and j as left and
// right boundaries of sliding window
int i = 0, j = 0, k = 1;
for (j = 0; j < s.size(); ++j) {
// If current character is '0'
if (s[j] == '0')
// Decrement k by one
k--;
// If k is less than zero and character
// at ith index is '0'
if (k < 0 && s[i++] == '0')
k++;
}
// Return result
return j - i - 1;
}
// Driver Code
int main()
{
string S = "011101101";
cout << longestSubarray(S);
return 0;
}
Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG{
// Function to calculate the length of the
// longest subString of '1's that can be
// obtained by deleting one character
static int longestSubarray(String s)
{
// Initializing i and j as left and
// right boundaries of sliding window
int i = 0, j = 0, k = 1;
for (j = 0; j < s.length(); ++j)
{
// If current character is '0'
if (s.charAt(j) == '0')
// Decrement k by one
k--;
// If k is less than zero and character
// at ith index is '0'
if (k < 0 && s.charAt(i++) == '0')
k++;
}
// Return result
return j - i - 1;
}
// Driver Code
public static void main(String[] args)
{
String S = "011101101";
System.out.print(longestSubarray(S));
}
}
// This code contributed by gauravrajput1
Python3
# Python3 program to implement
# the above approach
# Function to calculate the length of the
# longest substring of '1's that can be
# obtained by deleting one character
def longestSubarray(s):
# Initializing i and j as left and
# right boundaries of sliding window
i = 0
j = 0
k = 1
for j in range(len(s)):
# If current character is '0'
if (s[j] == '0'):
# Decrement k by one
k -= 1
# If k is less than zero and character
# at ith index is '0'
if (k < 0 ):
if s[i] == '0':
k += 1
i += 1
j += 1
# Return result
return j - i - 1
# Driver Code
if __name__ == "__main__" :
S = "011101101"
print(longestSubarray(S))
# This code is contributed by AnkThon
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to calculate the length of the
// longest subString of '1's that can be
// obtained by deleting one character
static int longestSubarray(string s)
{
// Initializing i and j as left and
// right boundaries of sliding window
int i = 0, j = 0, k = 1;
for(j = 0; j < s.Length; ++j)
{
// If current character is '0'
if (s[j] == '0')
// Decrement k by one
k -= 1;
// If k is less than zero and character
// at ith index is '0'
if (k < 0 && s[i++] == '0')
k++;
}
// Return result
return j - i - 1;
}
// Driver Code
public static void Main(string[] args)
{
string S = "011101101";
Console.Write(longestSubarray(S));
}
}
// This code is contributed by AnkThon
JavaScript
<script>
// Javascript Program to implement
// the above approach
// Function to calculate the length of the
// longest substring of '1's that can be
// obtained by deleting one character
function longestSubarray(s)
{
// Initializing i and j as left and
// right boundaries of sliding window
var i = 0, j = 0, k = 1;
for (j = 0; j < s.length; ++j) {
// If current character is '0'
if (s[j] == '0')
// Decrement k by one
k--;
// If k is less than zero and character
// at ith index is '0'
if (k < 0 && s[i++] == '0')
k++;
}
// Return result
return j - i - 1;
}
// Driver Code
var S = "011101101";
document.write( longestSubarray(S));
</script>
Time complexity: O(N)
Auxiliary Space: O(1) as we are not using any extra space.
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