DEV Community

Sruthika Ramachandran
Sruthika Ramachandran

Posted on

Find Minimum and Maximum in an Array

Introduction

Arrays are fundamental data structures used to store multiple elements.
One of the most common operations is finding the minimum (smallest) and maximum (largest) values in an array.

This problem is simple but very important for building logical thinking and is frequently asked in coding interviews.

Problem Statement

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

  • The minimum element
  • The maximum element

Return both values.

Examples

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

Explanation:
Minimum = 1, Maximum = 8

Example 2:
Input: [12, 3, 15, 7, 9]
Output: [3, 15]

Explanation:
Minimum = 3, Maximum = 15

Intuition

To find the minimum and maximum:

  • Traverse the array once
  • Keep track of: Smallest value seen so far Largest value seen so far

Approach

1.Initialize:
min_val = arr[0]
max_val = arr[0]
2.Traverse the array:
If element < min_val → update min_val
If element > max_val → update max_val
3.Return both values

Code (Python)

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

Step-by-Step Explanation

For array:
[1, 4, 3, 5, 8, 6]

Start →min = 1, max = 1
Compare 4 → max = 4
Compare 3 → no change
Compare 5 → max = 5
Compare 8 → max = 8
Compare 6 → no change

Final → min = 1, max = 8

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

Constraints

  • 1 ≤ array size ≤ 10⁵
  • 1 ≤ arr[i] ≤ 10⁹

Conclusion

Finding the minimum and maximum elements in an array is a basic yet essential problem.
It helps in understanding traversal and comparison logic, which are widely used in many real-world applications and coding interviews.

Top comments (0)