1

I came across this problem - input - I am given two sorted arrays a1 and a2. I need to find the elements that are not present in the second array.

I have two approaches

1) Hashtable - O(m+n)
[use when second array is small]

2) Binary Search - O(m*logn)
[use when second array is huge]

Are there any other approaches with better time complexities?

Thank You

Fox
  • 9,384
  • 13
  • 42
  • 63
  • 6
    If the arrays are already sorted, you can simply iterate them in parallel in O(n+m). This should be faster than the hashtable approach. – nwellnhof Feb 24 '13 at 23:49
  • Using two pointers? But using that method I can only get the common elements between the two sets. I will have to iterate through the first array again to subtract the common elements. – Fox Feb 24 '13 at 23:55
  • 1
    Yes, using two pointers and making sure you process the elements from both arrays in increasing order. This way you can also find the elements from a1 that are not in a2. But I'm too lazy to show some example code ;) – nwellnhof Feb 25 '13 at 00:05

1 Answers1

1

Just iterate them in parallel.

Here's a JavaScript example:

var a1 = [1, 2, 3, 4, 5, 6, 7, 9];
var a2 = [0, 2, 4, 5, 8];

findNotPresent(a1, a2); // [1, 3, 6, 7, 9]


function findNotPresent(first, second) {
    var first_len = first.length;
    var first_index = 0;

    var second_len = second.length;
    var second_index = 0;

    var result = [];

    while (first_index < first_len && second_index < second_len) {
        if (first[first_index] < second[second_index]) {
            result.push(first[first_index]);
            ++first_index;
        }
        else if (first[first_index] > second[second_index]) {
            ++second_index;
        }
        else {
            ++first_index;
            ++second_index;
        }
    }

    while (first_index < first_len) {
        result.push(first[first_index++]);
    }

    return result;
}

I believe it will take O(max(N, M)).

sigod
  • 3,514
  • 2
  • 21
  • 44
  • This example is not correct. Try it with `a2 = [0, 2, 4, 5]` and it won't return any results. – nwellnhof Feb 25 '13 at 00:24
  • You need to increment the a2_index counter too ... you did not consider the other case where a2[index]>a1[index] – Fox Feb 25 '13 at 00:47