In an interview, I was asked a coding question. The question was —

“Count the no. of subarrays having the equal count of 5, 6 and 7.

Input --> 7 5 6 7

Output --> 2

Explanation -> 7 5 6 and 5 6 7.”

I was able to come up with O(n2) approach but the optimal solution is O(n). Please explain the optimal approach.

Hint:

This solution is for 2 elements…and it is testing for 0 difference. How can we implement for 3 numbers? Please help…

That’s why I wrote hint, the complete idea is to just store it as a pair(one for 5 and 6, other for 6 and 7).

ok…let me try