Given an array arr[], find the minimum and maximum elements. Return them as a pair: minimum first, then maximum.
Min and Max in Array
SolvedExamples:
Input: arr[] = [1, 4, 3, 5, 8, 6]
Output: [1, 8]
Explanation: The minimum and maximum elements are 1 and 8.
Input: arr[] = [12, 3, 15, 7, 9]
Output: [3, 15]
Explanation: The minimum and maximum elements are 3 and 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
Track two values while scanning once: the smallest and the largest seen so far. Initialise both with the first element.
class Solution {\n public int[] getMinMax(int[] arr) {\n int mn = arr[0], mx = arr[0];\n for (int x : arr) {\n if (x < mn) mn = x;\n if (x > mx) mx = x;\n }\n return new int[]{mn, mx};\n }\n}
Sign in to see your submissions.