Exercise IV

Consider the following program

public boolean hasCommonElement (int[] a, int[] b) {
  for (int i = 0; i < a.length; i++) {
    for (int j = 0; j < b.length; j++) {
      if (a[i] == b[i]) {
        return true;
      }
    }
  }

  return false; 
}

Exercise What is the asymptotic running time of the code above for checking for a common element, as a function of the array lengths $n$?

A) $O(n^2)$
B) $O(n!)$
C) $O(n)$

Solution

The answer is $O(n^2)$. The code again does a constant number of operations for each loop iteration (that is, for each choice of the indices i and j). However, for each of the $n$ iterations of the outer for loop, the code performs $n$ iterations of the inner for loop. This gives $n \times n = n^2$ iterations in all.