stringalgorithmsearchtime-complexitysubsequence

Find occurrences of subsequence in a binary string (non-necessarily-contiguous)


Given a binary string with 0 and 1. I want to know number of occurrences of subsequences 01 and 10 in the given input String. Subsequences are not necessarily contiguous.

For example:

input : "10101"
"01" subsequences: 3, with indices (1,2), (1,4), (3,4)
"10" subsequences: 3, with indices (0,1), (0,3), (2,3)

Result = 3 + 3 = 6

My idea is to use nested loops to find the occurrence of 01 in input string, and do again with another nested loops to get for 10

Here is my code:

public static int solve(String s) {
    int n = s.length();
    // count occurrences of "01" in s
    int count1 = 0;
    int index = s.indexOf('0');
    if(index != -1) {
        for(int i=index; i<n; i++) {
            char c = s.charAt(i);
            if(c != '0') continue;
            for(int j=i+1; j<n; j++) {
                char d = s.charAt(j);
                if(d == '1')  count1++;
            }
        }
    }
    // count occurrences of "10" in s
    int count2 = 0;
    index = s.indexOf('1');
    if(index != -1) {
        for(int i=index; i<n; i++) {
            char c = s.charAt(i);
            if(c != '1') continue;
            for(int j=i+1; j<n; j++) {
                char d = s.charAt(j);
                if(d == '0')  count2++;
            }
        }
    }
    return count1 + count2; 
}   

How to do this in optimal way by reducing time complexity.


Solution

  • I'm posting the first solution that comes to mind, it's very simple and clean, I don't take into account 2 different counters but with a small modification you can do it. This example strictly applies to your case, if you wanted to change the binary strings to be checked, this solution would no longer be suitable.

        String word = "10101";
        int result = 0, count0 = 0, count1 = 0;
    
        for(int i = 0; i < word.length(); i++) {
            if (word.charAt(i) == '0') {
                count0++;
                result += count1;
            }
            else {
                count1++;
                result += count0;
            }
    
        }
        System.out.println("Count: " + result);