Math Fundamentals18 sections · 814 units
Open in Course

Pick Index - Implementation

The code

Here's the complete solution:


class Solution
    nums := stored array

    function __init__(nums)
        this.nums := nums

    function pick(target)
        result := -1
        count := 0
        for i from 0 to length of nums - 1
            if nums[i] = target then
                count := count + 1
                // Replace with probability 1/count
                if random() < 1/count then
                    result := i
        return result

Time: O(n)O(n) per pick (single scan), Space: O(1)O(1) additional space (just storing the array). The reservoir sampling ensures each matching index has equal selection probability.