Best way to compare two arrays when there are infinite processors?

This is a problem that I encountered in an interview. There are two sorted arrays A and B. Check if there is every element in array A in array B. Suppose there are infinite CPU cores. The interviewer suggested that the algorithms should run in O (1). I just came up with an O (log (n)) solution. Any ideas?

PS My solution O (log (n)) is to assign one element to one core of the central processor, each processor uses a binary search to check if an element exists in array B. I remember that the interviewer could suggest that a binary search could be optimized for O (1), given infinite processors. But I'm not so sure about that. Just in case.

+4
source share
4 answers

The following is the OP (1) PRAM algorithm in the Common CRCW model, that is, you can only write in parallel if the same value is written equally. Say the original array A has n elements, and B has size m.

found = new bool[n]
parallel for i in 0..n-1:
  found[i] = false
  parallel for j in 0..m-1: 
    if A[i] == B[j]:
      found[i] = true

result = true
parallel for i in 0..n-1:
  if !found[i]:
    result = false

print result ? "Yes": "No"

Of course, I'm not quite sure how practical the model is. In fact, you probably don't have concurrent entries. In an exclusive CREW model, you can calculate the AND and OR aggregates in O (log log n), and I think there is a corresponding lower bound as well.

Perhaps it would be nice to ask your interviewer about the specifics of the parallel model that interests him.

+2
source

​​ A B. ​​ . . A B ( ), A, B.

. , a1000 b1 b2, , .

+2

A , B b ( , ).

total ((a * b) + 1) core: A B. , b A, * b. Last +1 , .

, . , true, else false. A [0], . , B A [0]. A [0] B [0] , A [0] B [1] , OR . , test(), , :

public static bool test (int aElement, int bElement)
{
    return aElement == bElement;
}

A [1], A [2].. A [a-1] .

, :

(test(A[0], B[0]) || test(A[0], B[1])...) && (test(A[1], B[0]) || test(A[1], B[1])... )

, Main() :

public void Main (string[] args)
{
    //Read A and B arrays and create the next line dynamically
    var allPresent = (test(A[0], B[0]) || test(A[0], B[1]) ||... test(A[0], B[b-1]))
                  && (test(A[1], B[0]) || test(A[1], B[1]) ||... test(A[1], B[b-1]))
                  .
                  .
                  .
                  && (test(A[a-1], B[0]) || test(A[a-1], B[1]) ||... test(A[a-1], B[b-1]))
    Console.WriteLine("All Elements {0}", (allPresent ? "Found" : "Not Found"));
}

test(A[k], B[l]) , O (1) .

+1

., , O (1), , , Ω (MN) , .

( M = N), N , "" , Θ (N).

, , Ω (M + N) . , Ω (MN).

0

Source: https://habr.com/ru/post/1610149/


All Articles