> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/oj-practices/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/oj-practices/chapter1/binary-search/528-random-pick-with-weight.md).

# 528     Random Pick with Weight

## 528. [Random Pick with Weight](https://leetcode.com/problems/random-pick-with-weight/)

## 1. Question

Given an array`w`of positive integers, where`w[i]`describes the weight of index`i`, write a function`pickIndex` which randomly picks an index in proportion to its weight.

Note:

1. `1 <= w.length <= 10000`
2. `1 <= w[i] <= 10^5`
3. `pickIndex`will be called at most`10000`times.

**Example 1:**

```
Input: 
["Solution","pickIndex"]
[[[1]],[]]

Output: 
[null,0]
```

**Example 2:**

```
Input: 
["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
[[[1,3]],[],[],[],[],[]]

Output: 
[null,0,1,1,1,0]
```

## 2. Implementation

**(1) TreeMap**

```java
class Solution {
    TreeMap<Integer, Integer> map;
    Random rand;
    int totalWeight;
    int[] weight;

    public Solution(int[] w) {
        this.weight = w;
        map = new TreeMap();
        totalWeight = 0;
        rand = new Random();

        for (int i = 0; i < weight.length; i++) {
            totalWeight += weight[i];
            map.put(totalWeight, i);
        }
    }

    public int pickIndex() {
        int randWeight = rand.nextInt(totalWeight) + 1;
        int key = map.ceilingKey(randWeight);
        return map.get(key);
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(w);
 * int param_1 = obj.pickIndex();
 */
```

**(2) Binary Search**

```java
class Solution {
    Random rand;
    int[] weight;
    int totalWeight;

    public Solution(int[] w) {
        rand = new Random();
        this.weight = w;
        totalWeight = weight[0];

        for (int i = 1; i < weight.length; i++) {
            totalWeight += weight[i];
            weight[i] += weight[i - 1];
        }
    }

    public int pickIndex() {
        int target = rand.nextInt(totalWeight) + 1;

        int left = 0, right = weight.length - 1;

        while (left + 1 < right) {
            int mid = left + (right - left) / 2;

            if (weight[mid] < target) {
                left = mid + 1;
            }
            else {
                right = mid;
            }
        }
        return weight[left] >= target ? left : right;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(w);
 * int param_1 = obj.pickIndex();
 */
```

## 3. Time & Space Complexity

**(1) TreeMap: Time**: constructor: O(n), pickIndex: O(logn), **Space**: O(n)

**(2) Binary Tree: Time**: constructor: O(n), pickIndex: O(logn), **Space**: O(n)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://protegejj.gitbook.io/oj-practices/chapter1/binary-search/528-random-pick-with-weight.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
