D18 Answer


int isDuplicate( int x[][NUMCOLS], int nrows )
{
  int r,  c;  /* row and column of element to search for */
  int ri, ci; /* sweep thru the array looking for target */
  int target; /* check that this element is unique */

  for ( r=0; r<nrows; r++ )
    for ( c=0; c<NUMCOLS; c++ )
    {
      target = x[r][c];

      /* look for target in the rest of the current row */
      for ( ci=c+1; ci<NUMCOLS; ci++ )
        if ( target == x[r][ci] )
          return 1;

      /* look for target in the remaining rows */
      for ( ri=r+1; ri<nrows; ri++ )
        for ( ci=0; ci<NUMCOLS; ci++ )
          if ( target == x[ri][ci] )
            return 1;
    }
  return 0;
}

Comments: When checking if there is a duplicate of the element at x[row][col] it is only necessary to look through the elements that follow that element in raster order. This is because if there were a duplicate of x[row][col] in the elements that preceed it, that element would already have been checked (and found to be duplicated.)

The best-case behavior of this code is O(1), when two duplicate elements lie at the start of the array. The worst-case behavior is O(n2), when there are no duplicate elements. The average case behavior depends on how likely duplicates are in the array.

Note that the function cannot return the actual duplicated value, since that value might be zero. You might wish to augment the function by adding two pointers to the parameter list which point at variables in the caller for the row and column of the duplicated element.