Given a 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.
Input: str = “11100011”
Largest sub-string divisible by 2 is “111000”.
Input: str = “1111”
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 straight forward 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. The time complexity of this approach will be O(N).
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.