Given an array arr[], find its minimum and maximum elements. Return them as a pair with the minimum first.
Min and Max in Array
SolvedExamples:
Input: arr[] = [1, 4, 3, 5, 8, 6]
Output: [1, 8]
Explanation: The smallest value is 1 and the largest is 8.
Input: arr[] = [12, 3, 15, 7, 9]
Output: [3, 15]
Explanation: The smallest value is 3 and the largest is 15.
Constraints:
1 ≤ arr.size() ≤ 10^51 ≤ arr[i] ≤ 10^9
Expected Complexities
Time Complexity: O(n) Auxiliary Space: O(1)
Company Tags
Topic Tags
Carry two values through a single scan: the smallest and the largest seen so far, both initialised with the first element. Every element is compared at most twice, so the whole thing is linear.
class Solution {
public int[] getMinMax(int[] arr) {
int mn = arr[0], mx = arr[0];
for (int x : arr) {
if (x < mn) mn = x;
if (x > mx) mx = x;
}
return new int[]{mn, mx};
}
}
Sign in to see your submissions.