Home > Software engineering >  How to count the number of subarrays within a bigger array using recursion
How to count the number of subarrays within a bigger array using recursion

Time:03-10

How can you get a subarray from a bigger array recursively, and without using copyOfRange?

For example if int[] a = {1,2,1,3,1,2,1,1,2}, and int[] b = {1,2}, the correct answer is 3. This is the only recursive call I have, but I'm not sure what to do beyond this. I know the base case should be if(a.length < b.length), but I don't understand how to count the occurrences. The function returns return numSubstring(a,b,low, mid-1) numSubstring(a,b, mid 1,high);

CodePudding user response:

public static int countSubs(int [] data, int [] sub) {
    int cnt = 0;
    if (data.length < sub.length) {
        return cnt;
    }
    boolean found = true;
    for (int i = 0; i < sub.length; i  ) {
        if (data[i] != sub[i]) {
            found = false;
            break;
        }
    }
    if (found) {
        cnt  ;
    }
    
    cnt  = countSubs(Arrays.copyOfRange(data, 1, data.length), sub);
    return cnt;
}
  • Related