Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about function design

Tags:

c++

I just had an interview question about how I design a simple function - find the second largest number in an Int Array.

int findSecondLargest(int * arr, int len){
    int second = 0;
    ...

    return second;
}

However, I was asked the following questions about how I deal with the issues.

  1. If the len is less than 2(I think we can return a special value, like 0, or MinInt.)
  2. But, if the second largest is 0. (Since in this case, I can not differentiate between an error and a normal return value. so I might throw an exception)
  3. If the array is {1,1,1}(Since 1 is the largest number, not an second largest. so I might throw an exception)

I really felt confused. I think it is not possible to deal with all situations. We usually have to document the usage of our function, instead of throw exception.

Hope some advice. Thanks

//The function body is written by myself. I really like the design supposed by Donotalo and PigBen

like image 944
Gin Avatar asked Dec 10 '22 11:12

Gin


2 Answers

Following the standard library model, when searching a sequence, we don't return the value we are looking for, we return an iterator to the value(a pointer in this case). If we don't find the value, we return an iterator to one past the last element, the signature would look like this:

// end is not the last element, it is one past the last element
int * findSecondLargest(int * begin, int * end);
like image 178
Benjamin Lindley Avatar answered Dec 21 '22 08:12

Benjamin Lindley


Is the function body given by the interviewer? If not, I'd write a function that returns the index of the second largest item in the array. If no second largest item is found (like your error cases), my function would return len to indicate that second largest item is not found.

like image 21
Donotalo Avatar answered Dec 21 '22 07:12

Donotalo