Pergunta de entrevista da empresa Goldman Sachs

Find the second largest number in the array.

Respostas da entrevista

Sigiloso

17 de jan. de 2018

Transversing twice is not quadratic , careful there is someone here saying it is

1

Sigiloso

5 de dez. de 2017

#Python3 >>lst=[8,7,1,2,3,4,5] >>sorted(lst)[-2] out[2]: 7

Sigiloso

25 de set. de 2017

A Better Solution is to traverse the array twice. In the first traversal find the maximum element. In the second traversal find the greatest element less than the element obtained in first traversal. The time complexity of this solution is O(n). A more Efficient Solution can be to find the second largest element in a single traversal. Below is the complete algorithm for doing this: 1) Initialize two variables first and second to INT_MIN as, first = second = INT_MIN 2) Start traversing the array, a) If the current element in array say arr[i] is greater than first. Then update first and second as, second = first first = arr[i] b) If the current element is in between first and second, then update second to store the value of current variable as second = arr[i] 3) Return the value stored in second.

Sigiloso

15 de nov. de 2017

Disagree. Traversing a list twice isn't O(n), it's O(n*2), but I think sorting and returning second to last element is better. Or traverse it once and keep a last variable for the last largest, current for the current largest once the list is done, return last.