Problem
Given an array arr[], the task is to find the minimum and maximum elements in the array.
Output
Example 1
Output: [1, 8]
Example 2
Output: [3, 15]
My Approach
To solve this problem, I used a single traversal method.
I assume the first element is both the minimum and maximum.
Then I iterate through the array:
If an element is smaller than the current minimum, I update the minimum
If an element is greater than the current maximum, I update the maximum
I continue this process until the end of the array.
This works because every element is compared only once.
This approach is efficient because:
It requires only one traversal
It uses constant extra space
Code
def find_min_max(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]
Top comments (0)