Monthly Archives: June 2010

Find the intersection of 2 arrays

The following is an interview question used to determine if you understand pointers, even if your primary managed language doesn’t support the traditional notion of a pointer.

public static T[] FindIntersectionOfSortedArrays(T[] a, T[] b) where T : IComparable
{
    T[] answer = new T[a.length + b.length];

    int aptr = 0;
    int bptr = 0;
    int answerptr = 0;

    while (aptr < a.Length && bptr < b.Length)
    {
        if (a[aptr].Equals(b[bptr]))
        {
            answer[answerptr++] = a[aptr];
            aptr++;
            bptr++;
        }
        else if (a[aptr].CompareTo(b[bptr]) < 0)
        {
            aptr++;
        }
        else
        {
            bptr++;
        }
    }

    return answer;
}