Given two arrays A[n] and B[m], how can I find the smallest window in A that contains all the elements of B.
I am trying to solve this problem in O(n) time but I am having problem doing it. Is there any well know algorithm or procedure for solving it.
If m > n, A cannot contain all the elements of B (and hence we have an O(1) solution).
Otherwise:
B to the sequence {0..m-1} (this is O(n) since m <= n) .C[m] to count occurences of the members of B (initialise to 0) in the current window.Create a variable z to count the the number of 0 elements of C (initialise to m).
Create variables s and e to denote the start and end of the current window
e < n:
z is nonzero, increment e and update C and z. O(1)
s and update C and z. O(1)
The while loop can be shown to have no more than 2n iterations. So the whole thing is O(n), I think.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With