Finding the minimum and maximum values in an array is one of the basic problems in programming. It helps in understanding how to work with arrays and loops.
Problem Statement
Given an array "arr[]", find the smallest and largest elements in it.
Simple Approach
- Assume the first element is both minimum and maximum.
- Traverse the array from the second element.
- Compare each element:
- If it is smaller than current minimum, update minimum.
- If it is larger than current maximum, update maximum.
Java Code (GeeksforGeeks format)
import java.util.*;
class Solution {
public ArrayList 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;
}
}
Example
Input: "[5, 2, 9, 1, 7]"
Output: "1 9"
Time and Space Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Common Errors to Avoid
- Using a different class name instead of "Solution"
- Returning "int[]" instead of "ArrayList"
- Using wrong data types
Conclusion
This problem is simple but important. It helps in learning array traversal and writing efficient logic. Practicing such problems improves problem-solving skills.
Top comments (0)