Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does anybody know how to count the number of subarrays within a bigger array using recursion?

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…

return numSubstring(a,b,low, mid-1) + numSubstring(a,b, mid+1,high);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading