{"type": "session", "harness": "opencode", "id": "cp-10006", "name": "LeetCode 0497: Random Point In Non Overlapping Rectangles"} {"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 Point in Non-overlapping Rectangles (Difficulty: Medium)\nTags: Array, Math, Binary Search, Reservoir Sampling, Prefix Sum, Ordered Set, Randomized\n\nYou are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [ai, bi, xi, yi] indicates that (ai, bi) is the bottom-left corner point of the ith rectangle and (xi, yi) is the top-right corner point of the ith rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle.\nAny integer point inside the space covered by one of the given rectangles should be equally likely to be returned.\nNote that an integer point is a point that has integer coordinates.\nImplement the Solution class:\n\nExample 1:\nInput\n[\"Solution\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\"]\n[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]\nOutput\n[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]\n\nExplanation\nSolution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);\nsolution.pick(); // return [1, -2]\nsolution.pick(); // return [1, -1]\nsolution.pick(); // return [-1, -2]\nsolution.pick(); // return [-2, -2]\nsolution.pick(); // return [0, 0]\n\nConstraints:\n- 1 <= rects.length <= 100\n- rects[i].length == 4\n- -10^9 <= ai < xi <= 10^9\n- -10^9 <= bi < yi <= 10^9\n- xi - ai <= 2000\n- yi - bi <= 2000\n- All the rectangles do not overlap.\n- At most 104 calls will be made to pick."}} {"type": "message", "message": {"role": "assistant", "content": "# Time: ctor: O(n)\n# pick: O(logn)\n# Space: O(n)\n\nimport random\nimport bisect\n\n\nclass Solution(object):\n\n def __init__(self, rects):\n \"\"\"\n :type rects: List[List[int]]\n \"\"\"\n self.__rects = list(rects)\n self.__prefix_sum = map(lambda x : (x[2]-x[0]+1)*(x[3]-x[1]+1), rects)\n for i in range(1, len(self.__prefix_sum)):\n self.__prefix_sum[i] += self.__prefix_sum[i-1]\n\n def pick(self):\n \"\"\"\n :rtype: List[int]\n \"\"\"\n target = random.randint(0, self.__prefix_sum[-1]-1)\n left = bisect.bisect_right(self.__prefix_sum, target)\n rect = self.__rects[left]\n width, height = rect[2]-rect[0]+1, rect[3]-rect[1]+1\n base = self.__prefix_sum[left]-width*height\n return [rect[0]+(target-base)%width, rect[1]+(target-base)//width]\n\n\n\n"}}