Lamentis's blog

By Lamentis, history, 21 month(s) ago, In English

This question came in the recent summer internship drive on my campus but I could not solve it

Q)Array contains only 0 and 1. You are given two integers X and Y. Count how many subarrays have (count of 0) to (count of 1) equal to X: Y.

1<=N<=1e5 1<=X,Y<=1e5

Please help. Thanks

  • Vote: I like it
  • +2
  • Vote: I do not like it

»
21 month(s) ago, # |
Rev. 2   Vote: I like it -16 Vote: I do not like it

edit: I thought it was two pointers, turns out it wasnt facepalm

»
21 month(s) ago, # |
  Vote: I like it +28 Vote: I do not like it

change all 0s to y, and all 1s to -x. Make a prefix sum array of this.

subarray i,j, with i>0 fulfills the condition if and only if pre[j]=pre[i-1]

For i=0, pre[j] needs to be 0

count how many times each prefix appears and do some math

»
21 month(s) ago, # |
  Vote: I like it 0 Vote: I do not like it

If the string contains only 0s and 1s, then you could have just googled and found this . I think that string contained 0,1 and 2 because I was also asked the same in Intuit OA. You can find the answer for 0,1,2 here in Kallaseldor's comment