Forem

Samantha Vincent
Samantha Vincent

Posted on

Find the Maximum and Minimum Element in the Array

Problem

You’re given an array of integers and need to find the minimum and maximum elements.


Strategy

At first, it feels like sorting the array will help.

But we don’t really need to sort just to find min and max.

So I kept it simple:

For each number, I check—

  • Is it smaller than the current minimum?
  • Is it bigger than the current maximum?

And update accordingly.


Code

class Solution:
    def getMinMax(self, arr):
        minimum = arr[0]
        maximum = arr[0]

        for num in arr:
            if num < minimum:
                minimum = num
            if num > maximum:
                maximum = num

        return [minimum, maximum]
Enter fullscreen mode Exit fullscreen mode

Key Lines Explained

if num < minimum:
Update the minimum when we find a smaller number.


if num > maximum:
Update the maximum when we find a bigger number.


Why This Works

We just keep track of two things while looping:

  • Smallest number so far
  • Largest number so far

No need to rearrange anything.


Complexity

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


Final Note

This problem is very straightforward.

Instead of doing extra work like sorting, just compare and update as you go.

Top comments (0)