
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 ] 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 ar
Continue reading on Dev.to Python
Opens in a new tab



