MIN AND MAX OF THE ARRAY

 

Finding Minimum and Maximum in an Array 

Introduction

Finding the minimum and maximum elements in an array is a basic yet important problem in programming. It helps in understanding array traversal and comparison techniques.

Problem Statement

Given an array arr[], find:

  • The minimum element

  • The maximum element

Example

Input:

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

Output:

[1, 8]

Solution Code

class Solution:
    def getMinMax(self, 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)

Approach Used: Linear Traversal

Idea

We traverse the array once and keep track of:

  • The smallest value seen so far = min_val

  • The largest value seen so far = max_val

How It Works

  1. Initialize:

    • min_val = arr[0]

    • max_val = arr[0]

  2. Loop through each element:

    • If current element < min_val = update min_val

    • If current element > max_val = update max_val

  3. Return both values at the end

Why This Approach Was Chosen

  • Efficient: Only one pass through the array

  • Simple and easy to understand

  • No extra space required

Alternative Approach

return (min(arr), max(arr))

Why not preferred here?

  • Uses built-in functions (less control over logic)

  • In some problems/interviews, manual implementation is expected

Time and Space Complexity

  • Time Complexity: O(n)

  • Space Complexity: O(1)

Important Observation

  • We initialize with the first element to avoid unnecessary comparisons

  • Only one traversal is enough to find both minimum and maximum

Conclusion

The linear traversal approach is an efficient and simple way to find the minimum and maximum elements in an array. While Python provides built-in functions, implementing the logic manually helps in better understanding and is often required in coding interviews.

Comments

Popular posts from this blog

THE DELIVERY MAN

EC2 LAUNCHING

SORT A LINKED LIST USING MERGE SORT