Smallest and Largest
Medium
Use the least number of comparisons to get the largest and smallest number in the given integer array. Return the largest number and the smallest number.
Assumptions
The given array is not null and has length of at least 1
Examples
{2, 1, 5, 4, 3}, the largest number is 5 and smallest number is 1. return [5, 1].
Solution: pair swaps
Turn array into n / 2 pairs, swap the smaller of each pair to the left side. Once done, we now have the smaller numbers on the left, larger numbers on the right.
Iterate through both sides for smallest and largest
TC: O(2N) = O(N)
SC: O(1)
Last updated
Was this helpful?