FastPrepRandom Pick Index with Recorded Draws

Random Pick Index with Recorded Draws

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

Simulate one call to Random Pick Index for target in nums using recorded random draws.

Visit target occurrences from left to right. For the c-th occurrence, draws[c - 1] is an integer from 0 through c - 1. Replace the currently selected index with this occurrence's index exactly when that recorded draw is 0.

Return the final selected index.

Function

pickIndex(nums: int[], target: int, draws: int[]) → int

Examples

Example 1

nums = [1,2,3,3,3]target = 3draws = [0,1,0]return = 4

Index 2 is selected first, index 3 is skipped, and the final zero draw replaces the choice with index 4.

Example 2

nums = [5]target = 5draws = [0]return = 0

The sole occurrence must be selected.

Example 3

nums = [2,2,2,2]target = 2draws = [0,0,2,1]return = 1

The second occurrence replaces the first; later nonzero draws keep index 1.

Constraints

  • 1 <= nums.length <= 200000.
  • -10^9 <= nums[i], target <= 10^9.
  • target appears at least once.
  • draws.length equals the number of target occurrences.
  • For the zero-based draw index j, 0 <= draws[j] <= j.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int pickIndex(int[] nums, int target, int[] draws) {
    // Write your code here.
}
nums[1,2,3,3,3]
target3
draws[0,1,0]
expected4
Checking account…