I have an array contains 10 integer values. Now I want to find out the second highest number.I should not use any java API. This question was asked by one interviewer to me. He wants the logic.And his requirement is, I should not traverse through the the entire elements. Is there any way where we can achieve the result without traversing? Travesing means going through all the elements in the array. I thought for long time.Finally I gave up. If any one can explain, it would be nice. And also I asked about Sorting. He does not want the array to be sorted.
One of the most simple solutions can be sorting the array in ascending order and then finding the second element which is not equal to the largest element from the sorted array. So, in this way, we can find second largest element in array.
Approach: Take two variables; let's call them first and second and mark them as -∞. Iterate through the array and for each element (let's call it current), Compare it with the first and if first is less, assign the first value to second and assign current to first.
apply(null, arr), // get the max of the array maxi = arr. indexOf(max); arr[maxi] = -Infinity; // replace max in the array with -infinity var secondMax = Math. max. apply(null, arr); // get the new max arr[maxi] = max; return secondMax; };
No, it's completely impossible. If you don't look at all the data, you can't possibly know the second highest value.
You don't have to sort all the data, of course, which may be what your interviewer meant - but you do need to look at every element at least once. Every element has the possibility of changing the result, so needs to be examined.
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