Finding the minimum and maximum elements in an array is one of the most basic and important problems in programming.
It helps build a strong foundation for more advanced algorithms.
๐ Problem Statement
Given an array arr[], your task is to find:
- The minimum element
- The maximum element
๐ Examples
Example 1:
Input: [1, 4, 3, 5, 8, 6]
Output: [1, 8]
Example 2:
Input: [12, 3, 15, 7, 9]
Output: [3, 15]
๐ง Concept
We traverse the array once and keep track of:
-
min_valโ smallest value found so far -
max_valโ largest value found so far
๐ Approach: Single Traversal (Efficient)
Step-by-Step:
- Initialize:
min_val = arr[0]-
max_val = arr[0]- Traverse the array from index
1to end - For each element:
- Traverse the array from index
If element <
min_valโ updatemin_val-
If element >
max_valโ updatemax_val- Return
[min_val, max_val]
- Return
๐ป Python Code
def find_min_max(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]
# Example
print(find_min_max([1, 4, 3, 5, 8, 6]))
๐งพ Dry Run (Step-by-Step)
For:
arr = [1, 4, 3, 5, 8, 6]
| Step | Element | Min | Max |
|---|---|---|---|
| Start | 1 | 1 | 1 |
| 1 | 4 | 1 | 4 |
| 2 | 3 | 1 | 4 |
| 3 | 5 | 1 | 5 |
| 4 | 8 | 1 | 8 |
| 5 | 6 | 1 | 8 |
โก Time and Space Complexity
-
Time Complexity:
O(n)โ we traverse once -
Space Complexity:
O(1)โ no extra space used
๐ Alternative (Python Built-in)
arr = [1, 4, 3, 5, 8, 6]
print([min(arr), max(arr)])
๐งฉ Where Is This Used?
- Data analysis
- Searching algorithms
- Competitive programming
- Interview questions
๐ Conclusion
Finding the minimum and maximum in an array is a simple yet essential problem.
The optimal solution uses a single traversal, making it efficient and easy to implement.
Top comments (0)