Min and Max in Array

Solved

Difficulty: Basic Accuracy: Submissions: 0 Points: 1

Given an array arr[], find its minimum and maximum elements. Return them as a pair with the minimum first.

Examples:

Input: arr[] = [1, 4, 3, 5, 8, 6]

Output: [1, 8]

Explanation: The smallest value is 1 and the largest is 8.

Input: arr[] = [12, 3, 15, 7, 9]

Output: [3, 15]

Explanation: The smallest value is 3 and the largest is 15.

Constraints:

  • 1 ≤ arr.size() ≤ 10^5
  • 1 ≤ arr[i] ≤ 10^9
Expected Complexities

Time Complexity: O(n)   Auxiliary Space: O(1)

Company Tags

NPCI

Topic Tags

ArraysBasic

Carry two values through a single scan: the smallest and the largest seen so far, both initialised with the first element. Every element is compared at most twice, so the whole thing is linear.

class Solution {
    public int[] getMinMax(int[] arr) {
        int mn = arr[0], mx = arr[0];
        for (int x : arr) {
            if (x < mn) mn = x;
            if (x > mx) mx = x;
        }
        return new int[]{mn, mx};
    }
}

Sign in to see your submissions.