Largest sub-string of a binary string divisible by 2
Last Updated :
28 Oct, 2022
Given binary string str of length N, the task is to find the longest sub-string divisible by 2. If no such sub-string exists then print -1.
Examples:
Input: str = “11100011”
Output: 111000
Largest sub-string divisible by 2 is “111000”.
Input: str = “1111”
Output: -1
There is no sub-string of the given string
which is divisible by 2.
Naive approach: A naive approach will be to generate all such sub-strings and check if they are divisible by 2. The time complexity of this approach will be O(N3).
Better approach: A straightforward approach will be to remove characters from the end of the string while the last character is 1. The moment a 0 is encountered, the current string will be divisible by 2 as it ends at a 0.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string largestSubStr(string s)
{
while (s.size() and s[s.size() - 1] == '1' )
s.pop_back();
if (s.size() == 0)
return "-1" ;
else
return s;
}
int main()
{
string s = "11001" ;
cout << largestSubStr(s);
return 0;
}
|
Java
class GFG
{
static String largestSubStr(String s)
{
while (s.length() != 0 &&
s.charAt(s.length() - 1 ) == '1' )
s = s.substring( 0 , s.length() - 1 );
if (s.length() == 0 )
return "-1" ;
else
return s;
}
public static void main (String[] args)
{
String s = "11001" ;
System.out.println(largestSubStr(s));
}
}
|
Python3
def largestSubStr(s) :
while ( len (s) and s[ len (s) - 1 ] = = '1' ) :
s = s[: len (s) - 1 ];
if ( len (s) = = 0 ) :
return "-1" ;
else :
return s;
if __name__ = = "__main__" :
s = "11001" ;
print (largestSubStr(s));
|
C#
using System;
class GFG
{
static string largestSubStr( string s)
{
while (s.Length != 0 &&
s[s.Length - 1] == '1' )
s = s.Substring(0, s.Length - 1);
if (s.Length == 0)
return "-1" ;
else
return s;
}
public static void Main ()
{
string s = "11001" ;
Console.WriteLine(largestSubStr(s));
}
}
|
Javascript
<script>
function largestSubStr(s)
{
while (s.length && s[s.length - 1] == '1' )
s = s.substring(0,s.length-1);;
if (s.length == 0)
return "-1" ;
else
return s;
}
var s = "11001" ;
document.write( largestSubStr(s));
</script>
|
Time Complexity: O(n), where n is the length of the string s
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...