Skip navigation

The old well-known(?) puzzle

Suppose we have two sorted arrays: A and B of size n.
We would like to know if there is such a pair of indexes (i,j) that A[i] + B[j] = C.
C is a given number.
What’s the best worst-case time complexity (Big Oh) of the algorithm to solve the problem?

8 Comments

  1. Nikolay
    Posted August 13, 2008 at 4:47 am | Permalink

    Hm. At first sight it is O(n*log(n)). But probably I’m wrong and there is O(n) solution.

  2. Posted August 13, 2008 at 4:58 am | Permalink

    Nikolay: Yes, that’s the first solution that comes to mind:
    for i in A:
    search(C – A[i]) in B

    But… ;)

  3. Posted August 13, 2008 at 9:12 am | Permalink

    it looks like you have to pass each array only once, but at the same time and in different directions.
    so Nikolay was right, there is a O(n) solution :)

    p.s. i wonder if html tags work here invisible text

  4. Posted August 13, 2008 at 9:13 am | Permalink

    nope, html tags don’t work here :)

  5. Posted August 13, 2008 at 9:23 am | Permalink

    Aram: You’re right. There is O(n) solution :)

  6. Posted August 13, 2008 at 9:54 am | Permalink

    There is an obvious O(n) solution if you have infinite memory and numbers are integers :)

  7. Posted August 13, 2008 at 10:08 am | Permalink

    Damn!!! Arrays are sorted!!!!
    That is really obvious then!!!

  8. Posted August 13, 2008 at 12:21 pm | Permalink

    Actually, the merge sort algorithm exploits the same idea. Its ‘merge’ part takes an input of several sorted arrays and must choose, on which of them to step forward.

    In this puzzle the tricky part is to process one of the arrays in the reversed order.

    Here’s the puzzle from the same domain: “You have three sorted arrays and required to find a triplet of elements from each array having the minimum distance between them. Distance is calculated as max(|a[i] – b[j]|, |a[i] – c[k]|, |b[j] – c[k]|). The algorithm must have linear time complexity and constant space complexity”.


Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*