Hi everyone!
I was practicing some basic array problems and came across this one, which is simple but important for building fundamentals.
Problem
We are given an array, and we need to find:
- the minimum element
- the maximum element
Example:
Input: [1, 4, 3, 5, 8, 6]
Output: [1, 8]
My Approach
At first, I thought about sorting the array and then picking the first and last elements.
But then I realized:
- Sorting takes O(n log n) time
- We can actually do it in O(n) using just one loop So I used a simple traversal method.
Logic
- Assume the first element is both min and max
- Traverse the array
- Update min and max whenever needed
Code (Python)
class Solution:
def getMinMax(self, arr):
min_val = arr[0]
max_val = arr[0]
for num in arr:
if num < min_val:
min_val = num
if num > max_val:
max_val = num
return [min_val, max_val]
Time & Space Complexity
- Time:O(n) (single loop)
- Space:O(1) (no extra space used)
What I Learned
- Not every problem needs sorting
- Always try to think of a better approach before coding
- Even simple problems help strengthen logic
Thanks for reading!
If you have a better approach or suggestion, feel free to share.
Top comments (0)