← Back to libraryQuestion 81 of 273
⌨️Java CodingBeginner

Find the Largest and Smallest in an Array

📌 Definition:

Return the maximum and minimum values of an integer array in a single pass.

📖 Detailed Explanation:

Initialize both min and max to the first element, then scan the rest, updating each as needed. One pass is O(n) and beats sorting. Handle empty arrays explicitly.

💻 Solutions:
public static int[] minMax(int[] a) {
    int min = a[0], max = a[0];
    for (int x : a) { if (x < min) min = x; if (x > max) max = x; }
    return new int[]{min, max};
}
function minMax(a) {
  let min = a[0], max = a[0];
  for (const x of a) { if (x < min) min = x; if (x > max) max = x; }
  return { min, max };
}
def min_max(a):
    return min(a), max(a)
🔑 Key Points:
  • Initialize min and max to the first element
  • One pass — O(n), no sorting
  • Handle empty input
  • Track both simultaneously
🌍 Real-World Example:

Finding extremes in one pass is how you report the fastest/slowest measurement from a stream without sorting everything.

🎯 Scenario-Based Interview Question:

A candidate initializes max to 0. Why does that fail for an all-negative array?