- Sort and return last index time complexity: nlog(n), space: O(1) for quick sort,
- O(n), traverse through an array and keep max pointer
Second Largest Element in an array
- Sort and return last index
- time complexity: nlog(n) for sorting + O(N) traverse for 0 to n-2
- space: O(1) for quick sort
- O(n), traverse through an array and keep max pointer
- then traverse again and find the second largest. i.e largest
- if(a[i] < largest) and a[i]>sLargest
- Total time is 2 O(N)
-
if(a.length<2)
return -1;
largest = a[0], sLArgest = Math.INT_MIN;
for(int i=1;i<n;i++){
if(a[i]>largest){
sLArgest = largest;
largest = a[i];
}
if(a[i] < largest && a[i]>sLargest){
sLArgest = a[i];
}
}
return sLargest;
Space: O(N)