Problem Statement
Given an array arr[], the task is to find the minimum and maximum elements in the array.
Example
Input:
[1, 4, 3, 5, 8, 6]
Output:
[1, 8]
Explanation:
The smallest element in the array is 1, and the largest element is 8.
Approach : 1
To solve this problem efficiently:
Assume the first element is both minimum and maximum
Traverse through the array
Compare each element
If smaller, update minimum
If larger, update maximum
Python Implementation
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]
*Approach :2 *
class Solution:
def getMinMax(self, arr):
return [min(arr), max(arr)]
Time and Space Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Conclusion
Finding the minimum and maximum in an array is a fundamental programming problem. It helps in understanding array traversal and comparison logic, which are widely used in real-world applications.
This problem builds a strong foundation for problem-solving and is commonly asked in coding interviews and assessments.
Top comments (0)