r/csinterviewproblems • u/suresh9058 • Jan 09 '21
Best Solution to find the Second Largest Element in the Array
https://www.youtube.com/watch?v=FtDBwAKy3aI
5
Upvotes
r/csinterviewproblems • u/suresh9058 • Jan 09 '21
2
u/zhay Jan 09 '21
Or just use a heap and never let its size go beyond 2.
1
u/[deleted] Feb 08 '21
I believe I have a better way to solve this in O(n) time. The solution you've given appears to be 2*O(n) time, since we have to traverse our array twice-- once behind the scenes when we call Math.min and once for going through our array.
Would it not be better to just say something like this:
for(let i =0; i<arr.length;i++){ if(arr[i]>fLarNum){ secLarNum = fLarNum fLarNum = arr[i] }else if(arr[i]<fLarNum && secLarNum === undefined){ secLarNum = arr[i] } else if (arr[i]>fLarNum && arr[i]>secLarNum){ secLarNum = arr[i] } }
Now we only have to traverse the array once rather than twice. Not a big deal when we're dealing with arrays that are only a few elements long, but if we assumed that this was going to be applied to an array that is thousands of elements long, it could make a huge difference in terms of time.
If we wanted to run this in as few lines as possible, we could do it a little more concisely with
arr.sort((a,b)=>a-b)[1]to sort the array by numeric value from greatest to least (I may have it backwards-- maybe I want b-a, but you get the idea)
Alternatively, if we're going to use Math, why not just use
We just remove the largest element, then spit out the largest one. Slightly larger time complexity, as we're now traversing the array 3 times, but significantly quicker to read.