Find Smallest and Largest Element in an Array
Four C++ approaches to find the min and max in an array: iterative scan, STL, recursive, and sort-based. With code, complexity analysis, and placement interview tips.
Every placement test that screens for C++ knowledge includes at least one array-traversal problem, and finding the minimum and maximum values in a single pass is the canonical example.
The question is well-scoped, deterministic, and reveals three things at once: whether the student writes a correct loop, whether they state complexity without being prompted, and whether they know when a simpler or faster approach applies. Four C++ approaches cover the full range of what an interviewer can ask here.
The Problem and Its Variants
Given a non-empty array of integers, identify both the minimum and maximum values.
- Input:
arr = {7, 2, 9, 4, 1, 5} - Expected output:
- Smallest element: 1
- Largest element: 9
Three edge cases worth verifying before coding:
- Single element:
arr = {5}— both the minimum and maximum are 5. The algorithm below handles this correctly because the loop body never executes whenn = 1. - All identical:
arr = {3, 3, 3}— the minimum and maximum are both 3. No update fires;smallandlargestay equal toarr[0]. - Negative integers:
arr = {-4, -1, -7, 0}— the algorithm works without modification. Comparisons are value-based, and negative values satisfy the same less-than and greater-than conditions.
Interviewers at product-tier companies sometimes follow up with modified variants: find the second minimum, find both min and max in fewer comparisons than a naive double scan, or find the minimum in a rotated sorted array. Understanding the base case makes all three variants easier to approach systematically.
Approach 1: Single-Pass Linear Scan
This is the expected solution in nearly every placement context. One loop, two candidate variables, two comparisons per element.
Algorithm
- Initialise
small = arr[0]andlarge = arr[0]. - Walk the array from index 1 to
n-1.- If
arr[i] > large, updatelarge = arr[i]. - If
arr[i] < small, updatesmall = arr[i].
- If
- Print
smallandlarge.
C++ Code
#include <iostream>
using namespace std;
void findMinMax(int arr[], int n) {
int small = arr[0], large = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > large) large = arr[i];
if (arr[i] < small) small = arr[i];
}
cout << "Smallest: " << small << "\n";
cout << "Largest: " << large << "\n";
}
int main() {
int arr[] = {7, 2, 9, 4, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
findMinMax(arr, n);
return 0;
}
Trace Through the Example
Tracing arr = {7, 2, 9, 4, 1, 5} step by step:
- Start:
small = 7,large = 7 - i=1, val=2: 2 < 7, so
small = 2 - i=2, val=9: 9 > 7, so
large = 9 - i=3, val=4: no update
- i=4, val=1: 1 < 2, so
small = 1 - i=5, val=5: no update
- Result: smallest = 1, largest = 9
Complexity
- Time: O(n) — one pass through the array.
- Space: O(1) — two variables, independent of input size.
This is the approach to state first in any interview. Its space advantage over the recursive method is the key differentiator when an interviewer asks you to compare.
Approach 2: STL min_element and max_element
The <algorithm> header provides std::min_element and std::max_element, each running a linear scan. For a single call that returns both values in one pass, std::minmax_element (C++11 and later) is more concise.
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arr[] = {7, 2, 9, 4, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
auto result = minmax_element(arr, arr + n);
cout << "Smallest: " << *result.first << "\n";
cout << "Largest: " << *result.second << "\n";
return 0;
}
minmax_element returns a pair of iterators: .first points to the minimum, .second to the maximum. Dereference with * to read the values. If the range is empty, both pointers are invalid and dereferencing is undefined behaviour; always confirm n > 0 before calling.
Complexity
- Time: O(n) — identical to the manual loop.
- Space: O(1) — iterator storage only.
This approach signals STL familiarity. The manual loop is equally correct. Use whichever is clearer in the context of the surrounding code.
Approach 3: Recursive Traversal
Recursion replaces the loop counter with a call-stack depth. The logic mirrors the iterative scan, but each element gets its own stack frame instead of sharing one loop body. Use this approach only when the problem explicitly requires recursion.
Algorithm
- Accept the array, the current index, the array size
n, and references tosmallandlarge. - Base case: if
index == n, return. - Compare
arr[index]with the currentsmallandlarge; update if needed. - Recurse with
index + 1.
C++ Code
#include <iostream>
using namespace std;
void findMinMaxRecursive(int arr[], int index, int n, int &small, int &large) {
if (index == n) return;
if (arr[index] > large) large = arr[index];
if (arr[index] < small) small = arr[index];
findMinMaxRecursive(arr, index + 1, n, small, large);
}
int main() {
int arr[] = {7, 2, 9, 4, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int small = arr[0], large = arr[0];
findMinMaxRecursive(arr, 1, n, small, large);
cout << "Smallest: " << small << "\n";
cout << "Largest: " << large << "\n";
return 0;
}
Complexity
- Time: O(n) — visits every element exactly once.
- Space: O(n) — the call depth equals the number of elements, so n stack frames are active simultaneously at peak depth.
State the O(n) space cost explicitly in an interview. Compilers may optimise tail recursion in some build configurations, but this is not guaranteed and should not be cited as a mitigation without qualification.
Approach 4: Sort and Read the Endpoints
Sort the array in ascending order. The first element is the minimum; the last is the maximum.
C++ Code
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arr[] = {7, 2, 9, 4, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n);
cout << "Smallest: " << arr[0] << "\n";
cout << "Largest: " << arr[n - 1] << "\n";
return 0;
}
Complexity
- Time: O(n log n) — sorting dominates.
- Space: O(1) —
std::sortis in-place.
One practical consequence: std::sort modifies the original array. If the rest of the program needs the original order preserved, copy the array before sorting, or use Approach 1 instead. The time complexity is strictly worse than the linear scan for this specific task.
The only situation where sorting is sensible here is when the rest of the function needs the array in sorted order anyway. Reading the endpoints then costs nothing extra.
Complexity Comparison
| Approach | Time | Space | Modifies Array | Best Used When |
|---|---|---|---|---|
| Linear scan | O(n) | O(1) | No | Default choice for standalone min/max |
| STL min/max_element | O(n) | O(1) | No | Preferred for readability in production code |
| Recursive traversal | O(n) | O(n) | No | Problem explicitly requires recursion |
| Sort and endpoints | O(n log n) | O(1) | Yes | Sorting already needed for other operations |
The linear scan and STL approach are equivalent in complexity. The recursive approach and sorting are generally the wrong default for this specific task. An interviewer who asks you to compare them is checking whether you can articulate the cost, not just write the code.
Where This Problem Appears in Placement Tests
Array min/max appears in three distinct question formats in Indian placement tests:
- Straightforward coding question: write a function that returns both the minimum and maximum of a given integer array. The common mistake here is initialising
smalltoINT_MAXandlargetoINT_MINfrom<climits>— technically correct, but initialising toarr[0]is cleaner and avoids an unnecessary include. - Modified variant: find the second minimum or second maximum, or track both the first and second minimum in a single pass. This extends the same loop with two candidate variables per extreme instead of one.
- Complexity reasoning question: given a sorted array of n elements, what is the most efficient approach to find both the minimum and maximum? The answer is O(1) — read the first and last elements directly. This distinction between sorted and unsorted input separates candidates who have internalised complexity reasoning from those who have only memorised code.
The AMCAT Automata module and InfyTQ’s campus recruitment track include array-traversal questions as part of their standard C++ problem bank. For the full list of array and linked-list patterns likely to appear across these tests, see data structures interview questions.
The single-pass O(n) pattern from Approach 1 (initialise a candidate value at index 0, walk once, update on each comparison) appears in tasks beyond competitive programming. Scoring and ranking pipelines in AI systems use the same loop structure: iterate over candidate outputs, compare against a current best, update when a stronger match is found. TinkerLLM at ₹299 builds that connection through exercises that start from problems like this one and progress toward LLM evaluation and ranking tasks.
For another traversal-based problem in the same pattern, see string palindrome check.
Primary sources
Frequently asked questions
Can I find both min and max in a single pass?
Yes. The iterative approach initialises both small and large to arr[0], then updates each in the same loop. One pass, at most 2(n-1) comparisons in the worst case.
What does std::min_element return on an empty range?
It returns the end iterator. Dereferencing it is undefined behaviour. Always verify the array is non-empty before calling min_element or max_element.
Why does the recursive approach use O(n) space?
Each recursive call adds a stack frame. For an array of n elements, the call depth reaches n, so n frames are live simultaneously. The iterative approach uses two fixed variables regardless of input size.
Does sorting the array modify the original?
Yes. std::sort is in-place and overwrites the element order. If you need to preserve the original, copy the array before sorting, or use the iterative scan instead.
What if all elements in the array are the same?
Both small and large will equal that single value. No comparison triggers an update, which is the correct result: when all values match, the minimum and maximum are identical.
Is there an approach faster than O(n) for finding min and max in an unsorted array?
No. Any correct algorithm must inspect every element at least once, giving a lower bound of O(n). For a sorted array the endpoints give both values in O(1), with no traversal needed.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)