NumPy: Counting a Subarray

Data Wrangling

Difficulty: 2 | Problem written by bilaldadanlar

Educational Resource: https://cs231n.github.io/python-numpy-tutorial/

Problem reported in interviews at


Write a function that counts how many times the second array pattern (pattern) exists in the first array (arr) and returns the number of occurrences.

Bonus points if you do not use a for loop or list comprehension.

Sample Input:
<class 'numpy.ndarray'>
arr: [0 1 1 1 2 2 2 1 1 3 3 3]
<class 'numpy.ndarray'>
pattern: [1 1]

Expected Output:
<class 'int'>

This is a premium problem, to view more details of this problem please sign up for MLPro Premium. MLPro premium offers access to actual machine learning and data science interview questions and coding challenges commonly asked at tech companies all over the world

MLPro Premium also allows you to access all our high quality MCQs which are not available on the free tier.

Not able to solve a problem? MLPro premium brings you access to solutions for all problems available on MLPro

Get access to Premium only exclusive educational content available to only Premium users.

Have an issue, the MLPro support team is available 24X7 to Premium users.

This is a premium feature.
To access this and other such features, click on upgrade below.

Log in to post a comment

Jump to comment-93
ariel • 7¬†months ago


Probably my solution is not well optimized but atleast i've make it work. Feel free to give advice. TIA

matched = 0
    for x in range(len(arr) - (len(pattern) - 1)):
        match = np.array([arr[x+i] for i in range(len(pattern))])
        comparison = match == pattern
        if comparison.all():
            matched += 1



Input Test Case

Please enter only one test case at a time
numpy has been already imported as np (import numpy as np)