DEV Community

JAYA SRI J
JAYA SRI J

Posted on • Edited on

Find Minimum and maximum in an array

Find Minimum and maximum in an array
Problem

Given an array, find:

  1. min val
  2. max val 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
            elif num > max_val:
                max_val = num
        return [min_val, max_val]
Enter fullscreen mode Exit fullscreen mode

Line-by-Line Explanation

  1. Initialize min and max min_val = arr[0] max_val = arr[0] Why?

We assume first element is both min and max
Avoids using extra comparisons or infinity values
Works for all arrays (even negative numbers)

  1. Loop through array
    for num in arr:
    Why?

    To check every element
    Needed to find smallest and largest values

  2. Check for minimum
    if num < min_val:
    min_val = num

    Why?

    If current number is smaller → update minimum
    Ensures we always keep the smallest value

  3. Check for maximum
    elif num > max_val:
    max_val = num

    Why?

    If current number is larger → update maximum
    elif avoids unnecessary check if already smaller

  4. Return result
    return [min_val, max_val]
    Why?

    Returns both values together as a list

Why This Approach is Better

  1. Single Loop (Efficient)
  1. Only one traversal
  2. Time Complexity → O(n)
  1. No Extra Space

Uses only two variables
Space Complexity is O(1)

  1. Optimized Comparison

    Uses elif that avoids extra comparison
    Reduces total operations

  2. Simple and Clean

    Easy to understand
    Works for all types of numbers

Example
arr = [3, 5, 1, 8, 2]

Output:

[1, 8]

Important Points

  1. Initialize with first element
  2. Traverse only once
  3. Update min and max dynamically
  4. Use elif for efficiency

Top comments (0)