1.MIN AND MAX IN AN ARRAY
Problem
Given an array, find:
The smallest element (min)
The largest element (max)
Id="ex1"
Input: [3, 5, 1, 8, 2]
Output: [1, 8]
Approach Used: Linear Scan
Instead of sorting (which is slower),
we:
Traverse the array once
Keep updating min and max
Step-by-step explanation
Step 1: Initialize values
Python id="s1"
min_val = arr[0]
max_val = arr[0]
--> Assume first element is both min and max initially
Step 2: Traverse the array
Python id="s2"
for i in range(1, len(arr)):
Step 3: Compare and update
Python id="s3"
if arr[i] < min_val:
min_val = arr[i]
if arr[i] > max_val:
max_val = arr[i]
--> Each element is checked:
Smaller → update min
Larger → update max
CODE:
`class Solution:
def getMinMax(self, arr):
min_val = arr[0]
max_val = arr[0]
for i in range(1, len(arr)):
if arr[i] < min_val:
min_val = arr[i]
if arr[i] > max_val:
max_val = arr[i]
return [min_val, max_val]`
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Conclusion
This linear scan approach is the most efficient way to find min and max in an array. It avoids unnecessary sorting and works in a single pass.
Top comments (0)