My Thought Process (Java DSA)
When I saw this problem on GeeksforGeeks, it looked very straightforward. But instead of rushing into coding, I tried to think about the most efficient way to solve it.
Problem Statement
We are given an array of integers arr[].
The task is to find the minimum and maximum elements in the array.
Initial Thinking
Let’s take an example:
arr = [1, 4, 3, 5, 8, 6]
From this:
- Minimum = 1
- Maximum = 8
At first, one idea was to sort the array and pick the first and last elements.
But sorting takes extra time, which is unnecessary for this problem.
Key Observation
We don’t need to rearrange the array.
We just need to scan through it once and keep track of:
- The smallest value seen so far
- The largest value seen so far
my Way Approach
- Assume the first element is both
minandmax - Traverse the array from index
1 - For every element:
- If it is smaller than
min, updatemin - If it is larger than
max, updatemax
how it Runs
arr = [12, 3, 15, 7, 9]
Start:
min = 12, max = 12
i = 1 → 3 → min = 3
i = 2 → 15 → max = 15
i = 3 → 7 → no change
i = 4 → 9 → no change
Final Output → [3, 15]
Code in (Java)
import java.util.*;
class Solution {
public ArrayList<Integer> getMinMax(int[] arr) {
int min = arr[0];
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}
ArrayList<Integer> result = new ArrayList<>();
result.add(min);
result.add(max);
return result;
}
}
why This Works
- We are checking each element exactly once
- We continuously update min and max
- No unnecessary operations like sorting
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
This is optimal because:
- Only one traversal is used
- No extra memory is required
Final Thought
This problem is a basic example of array traversal with tracking variables.
It teaches an important lesson:
Instead of doing extra work like sorting, always think if a single pass solution is possible.
Top comments (0)