tinycodinglm / cp /cp-10006.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
2.85 kB
opencode trace
System You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

User

Problem: Random Point in Non-overlapping Rectangles (Difficulty: Medium)
Tags: Array, Math, Binary Search, Reservoir Sampling, Prefix Sum, Ordered Set, Randomized

You 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.
Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned.
Note that an integer point is a point that has integer coordinates.
Implement the Solution class:

Example 1:
Input
["Solution", "pick", "pick", "pick", "pick", "pick"]
[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]
Output
[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]

Explanation
Solution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);
solution.pick(); // return [1, -2]
solution.pick(); // return [1, -1]
solution.pick(); // return [-1, -2]
solution.pick(); // return [-2, -2]
solution.pick(); // return [0, 0]

Constraints:

  • 1 <= rects.length <= 100
  • rects[i].length == 4
  • -10^9 <= ai < xi <= 10^9
  • -10^9 <= bi < yi <= 10^9
  • xi - ai <= 2000
  • yi - bi <= 2000
  • All the rectangles do not overlap.
  • At most 104 calls will be made to pick.
Assistant

Time: ctor: O(n)

pick: O(logn)

Space: O(n)

import random
import bisect

class Solution(object):

markdown
def __init__(self, rects):
    """
    :type rects: List[List[int]]
    """
    self.__rects = list(rects)
    self.__prefix_sum = map(lambda x : (x[2]-x[0]+1)*(x[3]-x[1]+1), rects)
    for i in range(1, len(self.__prefix_sum)):
        self.__prefix_sum[i] += self.__prefix_sum[i-1]

def pick(self):
    """
    :rtype: List[int]
    """
    target = random.randint(0, self.__prefix_sum[-1]-1)
    left = bisect.bisect_right(self.__prefix_sum, target)
    rect = self.__rects[left]
    width, height = rect[2]-rect[0]+1, rect[3]-rect[1]+1
    base = self.__prefix_sum[left]-width*height
    return [rect[0]+(target-base)%width, rect[1]+(target-base)//width]