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.
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
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With