Algorithm to determine indices i..j of array A containing all the elements of another array B

前端 未结 4 1280
野性不改
野性不改 2021-02-04 14:15

I came across this question on an interview questions thread. Here is the question:

Given two integer arrays A [1..n] and B[1..m], find the smallest<

4条回答
  •  孤街浪徒
    2021-02-04 14:41

    Here is the solution I thought of (but it's not very neat).

    I am going to illustrate it using the example in the question.

    Let A[1,2,5,11,2,6,8,24,101,17,8] and B[5,2,11,8,17]

    1. Sort B. (So B = [2,5,8,11,17]). This step takes O(log m).

    2. Allocate an array C of size A. Iterate through elements of A, binary search for it in the sorted B, if it is found enter it's "index in sorted B + 1" in C. If its not found, enter -1. After this step,

    A = [1 , 2, 5, 11, 2, 6, 8, 24, 101, 17, 8] (no changes, quoting for ease).

    C = [-1, 1, 2, 4 , 1, -1, 3, -1, -1, 5, 3]

    Time: (n log m), Space O(n).

    1. Find the smallest window in C that has all the numbers from 1 to m. For finding the window, I can think of two general directions: a. A bit oriented approach where in I set the bit corresponding to each position and finally check by some kind of ANDing. b. Create another array D of size m, go through C and when I encounter p in C, increment D[p]. Use this for finding the window.

    Please leave comments regarding the general approach as such, as well as for 3a and 3b.

提交回复
热议问题