DEV Community

Christina Sharon S
Christina Sharon S

Posted on • Edited on

Finding Minimum and Maximum Elements in an Array

Introduction

In many programming problems, we often need to identify the smallest and largest elements in a dataset. This is a fundamental operation that helps in analysis, optimization and decision-making.

Here we will learn how to find the minimum and maximum elements in an array using simple and efficient approaches.

Problem Statement

Given an array arr[], your task is to find:

  • The minimum element
  • The maximum element

Example

Input:

arr = [1, 4, 3, 5, 8, 6]
Enter fullscreen mode Exit fullscreen mode

Output:

[1, 8]
Enter fullscreen mode Exit fullscreen mode

Explanation:
The smallest element is 1 and the largest element is 8.

Approach 1: Simple Traversal

The most basic way is to:

  1. Assume the first element is both minimum and maximum
  2. Traverse the array
  3. Update values when a smaller or larger element is found

Python Implementation

def find_min_max(arr):
    # Assume first element is min and max
    minimum = arr[0]
    maximum = arr[0]

    # Traverse the array
    for num in arr:
        if num < minimum:
            minimum = num
        elif num > maximum:
            maximum = num

    return [minimum, maximum]

# Example usage
arr = [1, 4, 3, 5, 8, 6]
print(find_min_max(arr))
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Explanation
For:

[1, 4, 3, 5, 8, 6]
Enter fullscreen mode Exit fullscreen mode
  • Start with min = 1, max = 1
  • Compare with 4 then max = 4
  • Compare with 3 so no change
  • Compare with 5 then max = 5
  • Compare with 8 then max = 8
  • Compare with 6 then no change

Final result: [1, 8]

Approach 2: Using Built-in Functions

Python provides built-in functions:

arr = [1, 4, 3, 5, 8, 6]

minimum = min(arr)
maximum = max(arr)

print([minimum, maximum])
Enter fullscreen mode Exit fullscreen mode

Key Points

  • Only one traversal is enough to find both minimum and maximum
  • Efficient and works for large arrays
  • Built-in functions make the code shorter and cleaner

Conclusion

Finding the minimum and maximum elements in an array is a simple yet important operation. Understanding this helps build a strong foundation for more complex algorithms and data processing tasks.

This problem is commonly asked in coding interviews and is a good starting point for beginners.

Top comments (0)