-1

Given an two sorted arrays X and Y, both of size n. Determine if there is an element x of X and an element y of Y such that x = 3y. The algorithm needs to run in linear time in the worst case. At the moment, the algorithm runs in O(n^2). I am unsure how to leverage the fact that the algorithm is sorted to have a scenario where the worst case would have O(n). I am aware of the fact that a binary search has O(log n).

public static void main (String [] args)
{
    int[] listX = {1,2,3,4};
    int[] listY = {1,2,3,8};

    for(int x = 0; x<listX.length; x++)
        for(int y = 0; y<listY.length; y++)
        {
            if(listX[X] == (3*listY[y]))
            {
                System.out.println("TRUE");
                break;
            }

        }
}
Raphael
  • 73,212
  • 30
  • 182
  • 400
user
  • 129
  • 5

1 Answers1

3

If we imagine that every element of Y is multiplied by 3 in-place in a first step, the problem then becomes equivalent to finding whether there is a common element in the resulting list and X. The required algorithm is similar to the algorithm for merging two sorted lists into a single sorted list, which has a well-known solution in linear time.

The pseudo-code for the solution of O(n) is:

for (x=0, y=0; x < listX.length && y < listY.length; ) {
  if (listX[X] == (3*listY[y])) {
    print TRUE;
    break;
  } 
  if (listX[X] < (3*listY[y])) {
    x++
  } else {
    y++
  }
}
dormouse
  • 31
  • 2