Find Minimum and maximum in an array
Problem
Given an array, find:
- min val
- max val Code
class Solution:
def getMinMax(self, arr):
min_val = arr[0]
max_val = arr[0]
for num in arr:
if num < min_val:
min_val = num
elif num > max_val:
max_val = num
return [min_val, max_val]
Line-by-Line Explanation
- Initialize min and max
min_val = arr[0] max_val = arr[0]Why?
We assume first element is both min and max
Avoids using extra comparisons or infinity values
Works for all arrays (even negative numbers)
-
Loop through array
for num in arr:
Why?To check every element
Needed to find smallest and largest values -
Check for minimum
if num < min_val:
min_val = num
Why?If current number is smaller → update minimum
Ensures we always keep the smallest value -
Check for maximum
elif num > max_val:
max_val = num
Why?If current number is larger → update maximum
elif avoids unnecessary check if already smaller -
Return result
return [min_val, max_val]
Why?Returns both values together as a list
Why This Approach is Better
- Single Loop (Efficient)
- Only one traversal
- Time Complexity → O(n)
- No Extra Space
Uses only two variables
Space Complexity → O(1)
-
Optimized Comparison
Uses elif → avoids extra comparison
Reduces total operations -
Simple and Clean
Easy to understand
Works for all types of numbers
Example
arr = [3, 5, 1, 8, 2]
Output:
[1, 8]
Important Points
- Initialize with first element
- Traverse only once
- Update min and max dynamically
- Use elif for efficiency
Top comments (0)