DEV Community

Manoj Kumar
Manoj Kumar

Posted on

Find Minimum and Maximum in an Array – Python

🔍 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]
Enter fullscreen mode Exit fullscreen mode

Output:

[1, 8]
Enter fullscreen mode Exit fullscreen mode

Example 2:

arr = [12, 3, 15, 7, 9]
Enter fullscreen mode Exit fullscreen mode

Output:

[3, 15]
Enter fullscreen mode Exit fullscreen mode

💡 Approach

🔹 Method 1: Linear Traversal (Optimal)

  • Initialize:
    • min_val = first element
    • max_val = first element
  • Traverse the array:
    • Update min_val if smaller element found
    • Update max_val if larger element found

👉 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]
Enter fullscreen mode Exit fullscreen mode

🔍 Dry Run

For:

arr = [12, 3, 15, 7, 9]
Enter fullscreen mode Exit fullscreen mode

Steps:

  • Start → min = 12, max = 12
  • Compare 3 → min = 3
  • Compare 15 → max = 15
  • Remaining elements → no change

Final Output:

[3, 15]
Enter fullscreen mode Exit fullscreen mode

🖥️ Sample Output

Input: [1, 4, 3, 5, 8, 6]
Output: [1, 8]

Input: [12, 3, 15, 7, 9]
Output: [3, 15]
Enter fullscreen mode Exit fullscreen mode

🧠 Alternative Method

🔹 Using built-in functions

def find_min_max(arr):
    return [min(arr), max(arr)]
Enter fullscreen mode Exit fullscreen mode

👉 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)