Problem Statement
Given an array arr[], the task is to find the minimum and maximum elements present in the array.
Examples
Input: arr = [1, 4, 3, 5, 8, 6]
Output: [1, 8]
Input: arr = [12, 3, 15, 7, 9]
Output: [3, 15]
Objective
• Identify the smallest element
• Identify the largest element
• Return both values as output
Approach 1: Using Loop (Manual Method)
This approach involves:
• Initializing two variables:
o minimum → first element
o maximum → first element
• Iterating through the array
• Updating values when a smaller or larger element is found
Algorithm
- Start with the first element as both min and max
- Traverse the array
- For each element: o If it is smaller than current min → update min o If it is larger than current max → update max
- Return both values ________________________________________ Python Code arr = [1, 4, 3, 5, 8, 6]
minimum = arr[0]
maximum = arr[0]
for i in arr:
if i < minimum:
minimum = i
if i > maximum:
maximum = i
print("Minimum:", minimum)
print("Maximum:", maximum)
________________________________________Step-by-Step Execution
For arr = [1, 4, 3, 5, 8, 6]
Element Min Max
1 1 1
4 1 4
3 1 4
5 1 5
8 1 8
6 1 8
Final Output:
Minimum = 1
Maximum = 8
Approach 2: Using Built-in Functions
Python provides simple functions to directly get the result.
Python Code
arr = [1, 4, 3, 5, 8, 6]
print("Minimum:", min(arr))
print("Maximum:", max(arr))
Why Use Built-in Functions?
• Cleaner code
• Less chance of error
• Faster to write
• Optimized internally
________________________________________Time and Space Complexity
Approach Time Complexity Space Complexity
Manual Loop O(n) O(1)
Built-in Method O(n) O(1)
Edge Cases to Consider
• Array with only one element → min and max are same
• All elements are equal
• Very large arrays
Final Thoughts
Finding the minimum and maximum in an array is a basic but important operation in programming.
It helps in:
• Data analysis
• Optimization problems
• Searching and sorting algorithms
Using a loop gives better understanding, while built-in functions make coding faster and cleaner.
Top comments (0)