DEV Community

Abinaya Dhanraj
Abinaya Dhanraj

Posted on

FINDING MINIMUM AND MAXIMUM IN AN ARRAY

Problem Statement

Given an array of integers, the task is to find the smallest (minimum) and largest (maximum) elements in the array.


Approach

Instead of sorting the array (which takes extra time), we can solve this problem in a single traversal.

Here’s the idea:

  • Assume the first element of the array is both the minimum and maximum.
  • Traverse through the rest of the array.
  • For each element:

    • If it is smaller than the current minimum → update the minimum.
    • If it is larger than the current maximum → update the maximum.
  • Finally, return both values.

This way, we only loop through the array once — making the solution efficient.


Code Implementation

python
class Solution:
def getMinMax(self, 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]
Enter fullscreen mode Exit fullscreen mode

Example

Input:

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

Output:

[1, 8]

Here, 1 is the smallest element and 8 is the largest.


Time Complexity

  • O(n) → We traverse the array only once.

Space Complexity

  • O(1) → No extra space is used.

Why this approach is better?

  • No need to sort the array (which would take O(n log n))
  • Simple and easy to understand
  • Efficient for large datasets

Bonus Tip

Python also provides built-in functions:

python
min(arr), max(arr)

But in coding platforms and interviews, writing the logic manually helps demonstrate your understanding.


Conclusion

This problem might look simple, but it’s a great way to practice looping, condition checking, and optimization thinking. Mastering such basics makes solving complex problems much easier later on.

Top comments (0)