DEV Community

Navin S
Navin S

Posted on

๐Ÿ” Find Minimum and Maximum in an Array

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

Example 2:

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

๐Ÿง  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:

  1. Initialize:
  • min_val = arr[0]
  • max_val = arr[0]

    1. Traverse the array from index 1 to end
    2. For each element:
  • If element < min_val โ†’ update min_val

  • If element > max_val โ†’ update max_val

    1. Return [min_val, max_val]

๐Ÿ’ป 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]))
Enter fullscreen mode Exit fullscreen mode

๐Ÿงพ Dry Run (Step-by-Step)

For:

arr = [1, 4, 3, 5, 8, 6]
Enter fullscreen mode Exit fullscreen mode
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)])
Enter fullscreen mode Exit fullscreen mode

๐Ÿงฉ 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)