Problem · Array

Minimum and Maximum with Optimal Comparisons

Learn this problem
EasyInMobi logoInMobiFULLTIMEONSITE INTERVIEW

Problem statement

Given a non-empty integer array values, find both its minimum and maximum elements.

Return a two-element array [minimum, maximum].

Your algorithm should pair elements so that it uses at most ceil(3 * n / 2) - 2 element comparisons, where n = values.length. This is fewer comparisons than finding the minimum and maximum independently.

Function

findMinMax(values: int[]) → int[]

Examples

Example 1

values = [3,5,1,2,4,8]return = [1,8]

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

Example 2

values = [7]return = [7,7]

With one element, the same value is both the minimum and the maximum.

Example 3

values = [-9,-2,-11,-3]return = [-11,-2]

The minimum is -11 and the maximum is -2.

Constraints

  • 1 ≤ values.length ≤ 100,000
  • Every element of values is a signed 32-bit integer.

More InMobi problems

drafts saved locally
public int[] findMinMax(int[] values) {
  // write your code here
}
values[3,5,1,2,4,8]
expected[1,8]
checking account