javastringbinary

Largest alternating subsequence of 1s and 0s in a string


Find largest alternating 1s and 0s sub-sequence in a String containing only 1s and 0s. Also find the starting index for the largest sub-sequence.

Example:

For 1101011, the longest alternating sub-sequence length is 5, from index 1 to 5.

I tried doing it by comparing consecutive elements and if they are not equal, comparing current length to max size:

int findSubArray(int arr[], int n) 
{
    int sum = 0;
    int maxsize = -1, startindex = 0;
    int endindex = 0;

    int j = 0;
    for (int i = 0; i < n - 1; i++)  {
        if (arr[i] != arr[i+1] && maxsize < i - j + 1) {
            maxsize = i - j + 1;
            startindex = j;
        } else {
            j = i;
        }
    }

    endindex = startindex+maxsize-1;
    if (maxsize == -1)
        System.out.println("No such subarray");
    else
        System.out.println(startindex+" to "+endindex);

    return maxsize;
}

Testing the method:

int [] ia = {1, 1, 0, 1, 0, 1, 1};
findSubArray (ia, 7);

Returns: 5 and prints 0 to 4

The problem is that although it prints correct length, which is 5, the indexes are incorrect. Correct Output should be 1 to 5.

To rectify this, if I do j = i + 1, then the whole matching goes for a toss and I get the indexes as 0 to 0.

What is the mistake in the above code? Also, any pseudo code for an alternative approach would help.


Solution

  • You were correct in changing j = i; to j = i + 1;, but it wasn't enough.

    What you are missing is that the current alternating series begins at j and ends at i+1, not i.

    In addition, there is a problem in the logic of your condition. Your else clause should be reached only when the current alternating sequence ends (i.e. arr[i] == arr[i+1]) but it is also reached when the current sequence is not longer than the max sequence.

    Therefore the condition should be broken into two conditions:

    if (arr[i] != arr[i+1]) {
        if (maxsize < i + 1 - j + 1) {
            maxsize = i + 1 - j + 1;
            startindex = j;       
        }
    } else {
        j = i + 1;
    }