π§ Find Minimum and Maximum in an Array
β Problem Statement
Given an array arr
, find the minimum and maximum elements.
This is a fundamental problem to understand array traversal, comparisons, and optimization techniques.
π§© Example
Input: arr = [3, 7, 1, 9, 2]
Output: Min = 1, Max = 9
π Approach 1: Brute Force (O(n) time, O(1) space)
What: Traverse the array once, updating min and max values sequentially.
Why: Simple and intuitive.
How: Initialize min_val
and max_val
with the first element, then check each element in the array.
π Python Code
def find_min_max(arr):
if not arr:
return None, None
min_val = max_val = arr[0]
for num in arr:
if num < min_val:
min_val = num
if num > max_val:
max_val = num
return min_val, max_val
# Example
arr = [3, 7, 1, 9, 2]
print(find_min_max(arr)) # Output: (1, 9)
π§ͺ JavaScript Code
function findMinMax(arr) {
let min = arr[0],
max = arr[0];
for (let num of arr) {
if (num < min) min = num;
if (num > max) max = num;
}
return { min, max };
}
// Example
const arr = [3, 7, 1, 9, 2];
console.log(findMinMax(arr)); // Output: { min: 1, max: 9 }
Execution Trace / Step-by-Step
arr = [3, 7, 1, 9, 2]
Step 1: min=3, max=3
Step 2: num=7 β max=7
Step 3: num=1 β min=1
Step 4: num=9 β max=9
Step 5: num=2 β no change
Final β min=1, max=9
π Breaking It Down for Understanding
- Single Pass Traversal: Check each element once β O(n) time.
- Space Efficient: Only two variables used β O(1) space.
- Mental Model: Imagine holding a βcurrent minβ and βcurrent maxβ while walking through the array β update when a new extreme is found.
- Pattern Recognition: Many array problems involve tracking extremes, counts, or sums, and this pattern is reusable.
π Summary
Approach | Time Complexity | Space Complexity | Notes |
---|---|---|---|
Single Pass | O(n) | O(1) | Simple, clear, efficient, optimal |
Tip: Whenever you need minimum, maximum, or running stats in an array, a single-pass comparison is usually the most elegant solution.