Problem Statement
Given an array arr[], the task is to find:
The minimum element in the array
The maximum element in the array
Return both values in a list as:
[min, max]
Example 1
Input:
arr[] = [1, 4, 3, 5, 8, 6]
Output:
[1, 8]
Explanation:
Minimum element is 1
Maximum element is 8
Example 2
Input:
arr[] = [12, 3, 15, 7, 9]
Output:
[3, 15]
Explanation:
Minimum element is 3
Maximum element is 15
Constraints
1 ≤ arr.size() ≤ 10^5
1 ≤ arr[i] ≤ 10^9
Logical Approach
To solve this problem:
Assume the first element is both minimum and maximum.
Traverse the array from index 1 to end.
For each element:
If it is smaller than current minimum → update minimum
If it is greater than current maximum → update maximum
Return both values.
This approach ensures we check each element only once.
Time Complexity: O(n)
Space Complexity: O(1)
SOLUTION:
class Solution:
def getMinMax(self, arr):
minimum = arr[0]
maximum = arr[0]
for i in range(1, len(arr)):
if arr[i] < minimum:
minimum = arr[i]
if arr[i] > maximum:
maximum = arr[i]
return [minimum, maximum]
Explanation of the Code
minimum = arr[0]
We assume the first element is the smallest initially.
maximum = arr[0]
We assume the first element is the largest initially.
Loop starts from index 1 because index 0 is already considered.
Inside loop:
If current element is smaller than minimum, update it.
If current element is greater than maximum, update it.
Finally, return both values as a list.
Top comments (0)