DEV Community

Sri Mahalakshmi
Sri Mahalakshmi

Posted on

Finding Minimum and Maximum in an Array Using Linear Search in Python

Problem Explanation

Given an array arr[], the task is to find the minimum and maximum elements in the array.

Example:

  • Input: arr = [1, 4, 3, 5, 8, 6]
    Output: [1, 8]

  • Input: arr = [12, 3, 15, 7, 9]
    Output: [3, 15]


Method Used: Linear Search

We traverse the array once and keep track of:

  • The smallest value (minimum)
  • The largest value (maximum)

Why This Method?

  • Time complexity is O(n) (only one traversal)
  • Space complexity is O(1) (no extra space used)
  • Simple and efficient for this problem

Python 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

Code Explanation (Line by Line)

  • class Solution:
    Defines the class as required by the platform.

  • def getMinMax(self, arr):
    Function to find minimum and maximum values.

  • minimum = arr[0]
    Initialize minimum with the first element.

  • maximum = arr[0]
    Initialize maximum with the first element.

  • for num in arr:
    Loop through each element in the array.

  • if num < minimum:
    Check if current element is smaller than minimum.

  • minimum = num
    Update minimum value.

  • if num > maximum:
    Check if current element is greater than maximum.

  • maximum = num
    Update maximum value.

  • return [minimum, maximum]
    Return both values as a list.


Output

Input:

[1, 4, 3, 5, 8, 6]
Enter fullscreen mode Exit fullscreen mode

Output:

[1, 8]
Enter fullscreen mode Exit fullscreen mode

Key Takeaway

A single traversal using Linear Search is enough to efficiently find both minimum and maximum values in an array.


Top comments (0)