Min and Max in Array

Solved

Difficulty: Basic Accuracy: Submissions: 0 Points: 1

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

Examples:

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

Output: [1, 8]

Explanation: The minimum and maximum elements are 1 and 8.

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

Output: [3, 15]

Explanation: The minimum and maximum elements are 3 and 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

Track two values while scanning once: the smallest and the largest seen so far. Initialise both with the first element.

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

Sign in to see your submissions.