tinycodinglm / cp /cp-10035.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
2.51 kB
{"type": "session", "harness": "opencode", "id": "cp-10035", "name": "LeetCode 0528: Random Pick With Weight"}
{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}
{"type": "message", "message": {"role": "user", "content": "Problem: Random Pick with Weight (Difficulty: Medium)\nTags: Array, Math, Binary Search, Prefix Sum, Randomized\n\nYou are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index.\nYou need to implement the function pickIndex(), which randomly picks an index in the range [0, w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w).\n\nExample 1:\nInput\n[\"Solution\",\"pickIndex\"]\n[[[1]],[]]\nOutput\n[null,0]\n\nExplanation\nSolution solution = new Solution([1]);\nsolution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.\n\nExample 2:\nInput\n[\"Solution\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\"]\n[[[1,3]],[],[],[],[],[]]\nOutput\n[null,1,1,1,1,0]\n\nExplanation\nSolution solution = new Solution([1, 3]);\nsolution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.\n\nSince this is a randomization problem, multiple answers are allowed.\nAll of the following outputs can be considered correct:\n[null,1,1,1,1,0]\n[null,1,1,1,1,1]\n[null,1,1,1,0,0]\n[null,1,1,1,0,1]\n[null,1,0,1,0,0]\n......\nand so on.\n\nConstraints:\n- 1 <= w.length <= 10^4\n- 1 <= w[i] <= 10^5\n- pickIndex will be called at most 104 times."}}
{"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(n)\n# pickIndex: O(logn)\n# Space: O(n)\n\nimport random\nimport bisect\n\n\nclass Solution(object):\n\n def __init__(self, w):\n \"\"\"\n :type w: List[int]\n \"\"\"\n self.__prefix_sum = list(w)\n for i in range(1, len(w)):\n self.__prefix_sum[i] += self.__prefix_sum[i-1]\n\n def pickIndex(self):\n \"\"\"\n :rtype: int\n \"\"\"\n target = random.randint(0, self.__prefix_sum[-1]-1)\n return bisect.bisect_right(self.__prefix_sum, target)\n\n\n\n"}}