Find the Maximum and Minimum Element in an Array: Java, C, C++, JavaScript and Python
Find the minimum and maximum of an array in a single pass. Intuition, animated dry run, the 3n/2 comparison trick, and solutions in Java, C, C++, JavaScript and Python.
Finding the minimum and maximum element of an array is a classic warm-up problem. The real lesson is a pattern you will reuse everywhere: scan the array once and keep a running answer. In this post you will see how to think about it, watch it animated step by step, and get solutions in Java, C, C++, JavaScript and Python.
Problem statement#
Given an array arr of n integers (n >= 1), find the smallest and the largest element.
Input: [3, 5, 1, 8, 2]
Output: Min = 1, Max = 8
Input: [-4, -9, -2]
Output: Min = -9, Max = -2How to think about this problem#
Imagine you are reading the numbers out loud one by one and someone asks, at any moment, "what is the smallest number so far?" You do not need to remember every number. You only need to remember the best one so far and compare each new number with it.
- If the new number is smaller than the current minimum, it becomes the new minimum.
- If the new number is bigger than the current maximum, it becomes the new maximum.
- Otherwise, ignore it and move on.
Every element has to be looked at least once (the answer could be anywhere), so we can't do better than O(n). One pass is optimal.
Start min and max with the first element, not with 0. If you start max = 0 and the array is [-4, -9, -2], you will wrongly report 0 as the maximum.
Approaches#
Approach 1: Sort the array#
After sorting, arr[0] is the minimum and arr[n - 1] is the maximum. It works, but sorting costs O(n log n) and changes the array, just to read two values.
Approach 2: Single linear scan (recommended)#
- Set
min = max = arr[0]. - For every element from index 1 to
n - 1, updateminif it is smaller andmaxif it is larger. - Return
minandmax.
Approach 3: Compare in pairs (fewest comparisons)#
The simple scan makes about 2n comparisons. A smarter trick takes elements two at a time: compare the pair with each other first, then compare only the smaller one with min and only the larger one with max. That is 3 comparisons per 2 elements, about 1.5n in total. The time complexity is still O(n), but interviewers love this follow-up.
| Approach | Time | Extra space | Comparisons |
|---|---|---|---|
| Sorting | O(n log n) | O(1) to O(n) | About n log n |
| Linear scan | O(n) | O(1) | About 2n |
| Pair comparison | O(n) | O(1) | About 1.5n |
Dry run (animated)#
The linear scan on [3, 5, 1, 8, 2]. The blue box is the current minimum, the red box is the current maximum, and the pointer i shows the element being checked.
- Start:
min = max = 3. i = 1, value 5: 5 is bigger than 3, somax = 5.i = 2, value 1: 1 is smaller than 3, somin = 1.i = 3, value 8: 8 is bigger than 5, somax = 8.i = 4, value 2: not smaller than 1 and not bigger than 8, nothing changes.- Result:
min = 1,max = 8.
Code#
Java#
public class Main {
static int[] findMinMax(int[] arr) {
int min = arr[0], max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) min = arr[i];
if (arr[i] > max) max = arr[i];
}
return new int[]{min, max};
}
public static void main(String[] args) {
int[] arr = {3, 5, 1, 8, 2};
int[] result = findMinMax(arr);
System.out.println("Min: " + result[0] + ", Max: " + result[1]); // Min: 1, Max: 8
}
}C#
#include <stdio.h>
void findMinMax(int arr[], int n, int *min, int *max) {
*min = arr[0];
*max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < *min) *min = arr[i];
if (arr[i] > *max) *max = arr[i];
}
}
int main(void) {
int arr[] = {3, 5, 1, 8, 2};
int n = sizeof(arr) / sizeof(arr[0]);
int min, max;
findMinMax(arr, n, &min, &max);
printf("Min: %d, Max: %d\n", min, max); // Min: 1, Max: 8
return 0;
}C++#
#include <iostream>
#include <vector>
using namespace std;
pair<int, int> findMinMax(const vector<int>& arr) {
int mn = arr[0], mx = arr[0];
for (size_t i = 1; i < arr.size(); i++) {
mn = min(mn, arr[i]);
mx = max(mx, arr[i]);
}
return {mn, mx};
}
int main() {
vector<int> arr = {3, 5, 1, 8, 2};
auto [mn, mx] = findMinMax(arr);
cout << "Min: " << mn << ", Max: " << mx << endl; // Min: 1, Max: 8
return 0;
}JavaScript#
function findMinMax(arr) {
let min = arr[0];
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < min) min = arr[i];
if (arr[i] > max) max = arr[i];
}
return { min, max };
}
const { min, max } = findMinMax([3, 5, 1, 8, 2]);
console.log(`Min: ${min}, Max: ${max}`); // Min: 1, Max: 8Python#
def find_min_max(arr):
lo = hi = arr[0]
for x in arr[1:]:
if x < lo:
lo = x
if x > hi:
hi = x
return lo, hi
lo, hi = find_min_max([3, 5, 1, 8, 2])
print(f"Min: {lo}, Max: {hi}") # Min: 1, Max: 8Complexity analysis#
- Time: O(n). Each element is visited exactly once.
- Space: O(1). Only two variables are kept, whatever the array size.
Edge cases and common mistakes#
- All negative numbers: handled correctly because we start from
arr[0], not from 0. - Single element: the loop never runs and that element is both the min and the max.
- All elements equal: min and max are the same value, which is correct.
- Empty array: there is no answer. Check
n == 0first and return an error or a sentinel value. - Using
else ifbetween the two checks: safe here, because one value can't be both a new min and a new max after the first element. It saves a comparison when a new min is found.
In practice you can use built-ins like Math.min(...arr) in JavaScript or min(arr) and max(arr) in Python. Spreading a huge array into Math.min can overflow the call stack, so a loop is safer for very large inputs.
Key takeaways#
- Keep a running "best so far" and update it while scanning once.
- Initialise min and max with the first element, never with 0.
- One pass gives
O(n)time andO(1)space, which is optimal. - The pair comparison trick lowers comparisons from about 2n to about 1.5n, a common interview follow-up.