FastPrepRandomly Select a Maximum-Value Index

Randomly Select a Maximum-Value Index

Meta logoMeta● MediumFULLTIMEONSITE INTERVIEW

Updated

Problem statement

Choose an index uniformly at random among the positions containing the largest value in nums. Equal maximum values at different positions are separate choices. Use O(1) extra space; multiple passes over the array are allowed.

For this exercise, assume the single random choice is supplied as draw. If the maximum occurs m times, draw is a zero-based rank in [0,m-1], drawn uniformly from that range. Return the index of that ranked maximum occurrence when positions are ordered from left to right. This makes each supplied draw reproducible; do not make another random call.

Return the original array index, not the maximum value or its rank. Do not reorder the array.

Function

pickMaximumIndex(nums: int[], draw: int) → int

Examples

Example 1

nums = [4,1,4,2,4]draw = 1return = 2

The maximum is 4 at indices 0, 2 and 4. Rank 1 selects index 2.

Example 2

nums = [-8,-2,-5,-2]draw = 0return = 1

The maximum is -2, not zero. Its first occurrence is index 1.

Example 3

nums = [3,3,7,2,7]draw = 1return = 4

Occurrences of the earlier maximum 3 do not count after 7 appears. Rank 1 among the final maxima selects index 4.

Example 4

nums = [9]draw = 0return = 0

The sole index is the only eligible outcome.

Constraints

  • For this exercise, assume 1 <= nums.length <= 20000 and -10^9 <= nums[i] <= 10^9.
  • 0 <= draw < m, where m is the number of maximum-value positions.
  • Use constant extra space, excluding the input array.

More Meta Onsite Interview questions

Similar questions at other companies

Meta interview experiences

All Meta interview questionsSee Meta hiring insights
Saved
class Solution {
    public int pickMaximumIndex(int[] nums, int draw) {
        // Write your code here.
    }
}
Checking account…