Find Minimum and maximum in an array
Find Minimum and maximum in an array 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 max_val: max_val = num return [min_val, max_val] Line-by-Line Explanation Initialize min and max min_val = arr[0] max_val
JAYA SRI J
Original Source
Dev.to
https://dev.to/jaya_srij_c37a6ea796335c/find-minimum-and-maximum-in-an-array-4i7lFind 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
Found this useful? Share it!
Read the Full Story
Continue reading on Dev.to
Related Stories
Majority Element
about 2 hours ago
Building a SQL Tokenizer and Formatter From Scratch โ Supporting 6 Dialects
about 2 hours ago
Markdown Knowledge Graph for Humans and Agents
about 2 hours ago

Moving Beyond Disk: How Redis Supercharges Your App Performance
about 2 hours ago