🔍 Find Minimum and Maximum in an Array – Python
Hi All,
Today I solved a basic and important problem: Finding the minimum and maximum elements in an array.
📌 Problem Statement
Given an array arr[], find the minimum and maximum elements.
🔍 Examples
Example 1:
arr = [1, 4, 3, 5, 8, 6]
Output:
[1, 8]
Example 2:
arr = [12, 3, 15, 7, 9]
Output:
[3, 15]
💡 Approach
🔹 Method 1: Linear Traversal (Optimal)
- Initialize:
-
min_val= first element -
max_val= first element
-
- Traverse the array:
- Update
min_valif smaller element found - Update
max_valif larger element found
- Update
👉 Only one loop → efficient solution
💻 Python 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
if num > max_val:
max_val = num
return [min_val, max_val]
🔍 Dry Run
For:
arr = [12, 3, 15, 7, 9]
Steps:
- Start → min = 12, max = 12
- Compare 3 → min = 3
- Compare 15 → max = 15
- Remaining elements → no change
Final Output:
[3, 15]
🖥️ Sample Output
Input: [1, 4, 3, 5, 8, 6]
Output: [1, 8]
Input: [12, 3, 15, 7, 9]
Output: [3, 15]
🧠 Alternative Method
🔹 Using built-in functions
def find_min_max(arr):
return [min(arr), max(arr)]
👉 Simple and quick, but less control
⚡ Complexity Analysis
- Time Complexity: O(n) ✅
- Space Complexity: O(1) ✅
✅ Conclusion
This problem helped me understand:
- Traversing arrays efficiently
- Comparing elements
- Writing optimized solutions
🚀 This is a fundamental problem in Data Structures!
Top comments (0)