Java Program to Find Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String


In this problem, we will write Java code to find the maximum sum of consecutive zeros at the start and end of any string rotation. First, we will use a naïve approach to solve the problem, which generates all rotations of the binary string and counts the starting and ending consecutive zeros. After that, we will learn an optimized algorithm that counts the maximum consecutive zeros.

Problem statement – Here, we have a string of size N containing only 0 and 1 characters. We need to find the maximum sum of consecutive zeros at the start and end of any rotation of the given string.

Sample examples

Input

str = ‘001’

Output

2

Explanation – Let’s calculate the sum of starting and ending zeros in each rotation.

  • In ‘001’, starting consecutive zeros are 2, and the ending zeros are01. So, final sum is 2.

  • In ‘011’, starting consecutive zeros are 1, and ending zeros are 1. So, final sum is 2.

  • In ‘100’, starting consecutive zeros are 0, and ending zeros are 2. So, final sum is 2.

The maximum sum is 2.

Input

str = ‘11’

Output

0

Explanation – The string doesn’t contain any zero.

Input

str = ‘1000001’

Output

5

Explanation

  • 1000001 – Starting zeros = 0, Ending zeros = 0, Sum = 0.

  • 0000011 – Starting zeros = 5, Ending zeros = 0, Sum = 5.

  • 0000110 – Starting zeros = 4, Ending zeros = 1, Sum = 5.

  • 0001100 – Starting zeros = 3, Ending zeros = 2, Sum = 5.

  • 0011000 – Starting zeros = 2, Ending zeros = 3, Sum = 5.

  • 0110000 – Starting zeros = 1, Ending zeros = 4, Sum = 5.

  • 1100000 – Starting zeros = 0, Ending zeros = 5, Sum = 5.

The final sum is 5.

Approach 1

This is the naïve approach to solving the problem. First, we will merge the string to itself. After that, we will take a substring starting from the pth index and equal to the original string. It gives us the resultant string, which we get after making a p rotations of the binary string.

Algorithm

Step 1 – Initialize the ‘cnt0’ variable with 0 to store the count of zeros in the given string.

Step 2 – If ‘cnt0’ and ‘len’ are equal, the return value of ‘len’ as the string contains only zeros.

Step 3 – Define the string s and store alpha + alpha in that.

Step 4 – Define the ‘maxZeros’ variable to store the maximum sum of starting and ending zeros.

Step 5 – Use the loop to make total iterations equal the string length. In the loop, ‘left’ and ‘right’ variables are used to store the maximum starting consecutive and ending zeros.

Step 6 – Start traversing the string from the mth index to (m + len)th index. Use the charAt() method to access the character from the mth index, and if it is equal to ‘0’, increase the value of the ‘left’ variable by 1. Else, use the ‘break’ keyword to terminate the loop.

Step 7 – Start traversing the string from (m + len -1)th index to mth index and increase the value of the ‘right’ variable till we get zeros.

Step 8 – Do the sum of left and right. Also, update the maxZeros if the sum is greater than its value.

Step 9 – Returnt the value of the maxZeros variable containing the maximum sum of the starting and ending zeros in any string rotation.

Example

import java.util.*;

public class Main {
    static int getMaxZeros(String alpha, int len) {
        // count zeros in the string
        int cnt0 = 0;
        // Traverse the string
        for (int m = 0; m < len; ++m) {
            if (alpha.charAt(m) == '0')
                cnt0++;
        }
        // If total zeros are equal to len, return len
        if (cnt0 == len) {
            return cnt0;
        }
        // Merge string to find rotations
        String s = alpha + alpha;
        // to store the maximum sum of zeros
        int maxZeros = 0;
        // Traverse string
        for (int m = 0; m < len; ++m) {
            // to store zeros at the start and end
            int left = 0;
            int right = 0;
            // calculate starting zeros in the current rotation
            for (int n = m; n < m + len; ++n) {
                if (s.charAt(n) == '0') {
                    left++;
                } else {
                    break;
                }
            }
            // Calculate ending zeros
            for (int n = m + len - 1; n >= m; --n) {
                if (s.charAt(n) == '0') {
                    right++;
                } else {
                    break;
                }
            }
            // Get max value
            maxZeros = Math.max(left + right, maxZeros);
        }
        return maxZeros;
    }
    public static void main(String[] args) {
        String alpha = "10001";
        // string length
        int len = alpha.length();
        System.out.println("The maximum sum of start and end zeros in the rotations of the given string is - "
                + getMaxZeros(alpha, len));
    }
}

Output

The maximum sum of start and end zeros in the rotations of the given string is - 3

Time complexity – O(N^2), as strings of length N can have total N rotations.

Space complexity – O(N), as we store the merged string to get rotations using it.

Approach 2

This approach counts the total number of consecutive zeros in the given string. When we rotate the string, we can observe that the sum of consecutive zeros at the start and end remains the same.

For example, when we rotate the string ‘0000011’, we get the ‘0000110’ string which has a sum of starting and ending zeros equal to the consecutive zeros.

Algorithm

Step 1 – In the first step, count the total number of zeros in the string and return the length value if the count of zero equals the string length.

Step 2 – The variable maxZeros is used to store the maximum sum of consecutive zeros at the start and end. Furthermore, the maxConsZeros variable is used to store the count of maximum consecutive zeros.

Step 3 – Count the maximum consecutive zeros in the string by traversing the string.

Step 4 – Also, update the value of the maxZeros variable.

Step 5 – Count the total consecutive zeros at the start of the string. Also, count the consecutive zeros at the end of the string.

Step 6 – Update the maxZeros value if the sum of starting and ending consecutive zeros is greater than maxZeros, and return the updated value.

Example

import java.util.*;

public class Main {
    static int getMaxZeros(String alpha, int len) {
        // count zeros in the string
        int cnt0 = 0;
        // Traverse the string
        for (int m = 0; m < len; ++m) {
            if (alpha.charAt(m) == '0')
                cnt0++;
        }
        // If total zeros are equal to len, return len
        if (cnt0 == len) {
            return cnt0;
        }
        // to store maximum sum of zeros
        int maxZeros = 0;
        // to store max consecutive zeros
        int maxconZeros = 0;
        for (int m = 0; m < len; m++) {
            if (alpha.charAt(m) == '0')
                maxconZeros++;
            else {
                // update max consecutive zeros
                maxZeros = Math.max(maxZeros, maxconZeros);
                maxconZeros = 0;
            }
        }
        // Change max zeros if required
        maxZeros = Math.max(maxZeros, maxconZeros);
        // Calculate the sum of zeros at the start and end
        int left = 0, right = len - 1;
        maxconZeros = 0;
        // total zeros at start
        while (alpha.charAt(left) != '1' && left < len) {
            maxconZeros++;
            left++;
        }
        // total zeros at end
        while (alpha.charAt(right) != '1' && right >= 0) {
            maxconZeros++;
            right--;
        }
        // Change the maximum sum of zeros
        maxZeros = Math.max(maxZeros, maxconZeros);
        return maxZeros;
    }
    public static void main(String[] args) {
        String alpha = "10001";
        // string length
        int len = alpha.length();
        System.out.println("The maximum sum of start and end zeros in the rotations of the given string is - "
                + getMaxZeros(alpha, len));
    }
}

Output

The maximum sum of start and end zeros in the rotations of the given string is - 3

Time complexity – O(N), for traversing the given binary string.

Space complexity – O(1)

Updated on: 25-Aug-2023

60 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements