My Thinking and Approach
Introduction
In this problem, I was given an array of integers and asked to find the minimum and maximum elements in the array.
This is a basic problem but important for understanding array traversal.
Problem Statement
Given an array of integers
arr-
Find:
- Minimum element
- Maximum element
Return both values
My Initial Thought
At first, I considered:
- Sorting the array
- Taking the first element as minimum
- Taking the last element as maximum
But sorting takes more time and is not necessary.
Key Observation
Instead of sorting:
- I can traverse the array once
- Keep track of minimum and maximum values
Optimized Approach
I decided to:
- Initialize min and max with first element
- Traverse the array
- Update values when needed
Logic:
- If current element < min → update min
- If current element > max → update max
My Approach (Step-by-Step)
- Initialize:
- min_val = arr[0]
-
max_val = arr[0]
- Traverse the array from index 1
- For each element:
If element < min_val → update min_val
-
If element > max_val → update max_val
- Return both values
Code (Python)
Below is the implementation clearly separated inside a code block:
```python id="p5j0ps"
def findMinMax(arr):
min_val = arr[0]
max_val = arr[0]
for i in range(1, len(arr)):
if arr[i] < min_val:
min_val = arr[i]
if arr[i] > max_val:
max_val = arr[i]
return [min_val, max_val]
---
## Example Walkthrough
### Input:
```text id="htc0zt"
arr = [1, 4, 3, 5, 8, 6]
Steps:
- Start with min = 1, max = 1
- Compare with 4 → max = 4
- Compare with 3 → no change
- Compare with 5 → max = 5
- Compare with 8 → max = 8
- Compare with 6 → no change
Output:
```text id="x4jsm3"
[1, 8]
---
## Complexity Analysis
| Type | Complexity |
| ---------------- | ---------- |
| Time Complexity | O(n) |
| Space Complexity | O(1) |
---
## Key Takeaways
* No need to sort the array
* Single traversal is enough
* Efficient use of variables improves performance
---
## Conclusion
This problem helped me understand how to find minimum and maximum values efficiently using a single traversal.
It is a basic but important concept in array manipulation.
---
Top comments (0)