Skip to main content

Find minimum and maximum element in an array

Problem​

Given an array A of size N of integers. Your task is to find the minimum and maximum elements in the array.

Note: Return an array that contains 2 elements the first one will be a minimum element and the second will be a maximum of an array.

Examples:​

Example 1:

Input:
N = 6
A[] = {3, 2, 1, 56, 10000, 167}
Output: 1 10000
Explanation: minimum and maximum elements of array are 1 and 10000.

Example 2:

Input:
N = 5
A[] = {1, 345, 234, 21, 56789}
Output: 1 56789
Explanation: minimum and maximum element of array are 1 and 56789.

Your task:​

You don't need to read input or print anything. Your task is to complete the function getMinMax() which takes the array A[] and its size N as inputs and returns the minimum and maximum element of the array.

  • Expected Time Complexity: O(N)O(N)
  • Expected Auxiliary Space: O(1)O(1)

Constraints:​

  • 1<=N<=1051 <= N <= 10^5
  • 1<=Ai<=10121 <= A_i <=10^{12}

Solution​

Python​

def getMinMax( a, n):
if n == 0:
return None
min_value = float('inf')
max_value = float('-inf')
for num in a:
if num < min_value:
min_value = num
if num > max_value:
max_value = num
minmax = [min_value, max_value]
return minmax

Java​

static Pair getMinMax(long a[], long n) {
if (n == 0) {
return null;
}
long min_value = Long.MAX_VALUE;
long max_value = Long.MIN_VALUE;
for (long num : a) {
if (num < min_value) {
min_value = num;
}
if (num > max_value) {
max_value = num;
}
}
return new Pair(min_value, max_value);
}

C++​

public:
pair<long long, long long> getMinMax(long long a[], int n) {
if (n == 0) {
return {0, 0};
}
long long min_value = LLONG_MAX;
long long max_value = LLONG_MIN;
for (int i = 0; i < n; ++i) {
if (a[i] < min_value) {
min_value = a[i];
}
if (a[i] > max_value) {
max_value = a[i];
}
}
return {min_value, max_value};
}
};

C​

struct pair getMinMax(long long int arr[], long long int n) {
struct pair minmax;
int i;
if (n == 1) {
minmax.max = arr[0];
minmax.min = arr[0];
return minmax;
}
if (arr[0] > arr[1]) {
minmax.max = arr[0];
minmax.min = arr[1];
}
else {
minmax.max = arr[1];
minmax.min = arr[0];
}

for (i = 2; i<n; i++) {
if (arr[i] > minmax.max)
minmax.max = arr[i];
else if (arr[i] < minmax.min)
minmax.min = arr[i];
}
return minmax;
}
  • Time Complexity: O(N)O(N)
  • Auxiliary Space: O(1)O(1)