← Home

497. Random Point in Non-overlapping Rectangles

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
497

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 497. Random Point in Non-overlapping Rectangles, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • TLE
  • 2 / 35 test cases passed.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are pick.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//TLE
02//2 / 35 test cases passed.
03struct vector_hash {
04    inline std::size_t operator()(const std::vector<int> & v) const {
05        return v[0]*31+v[1];
06    }
07};
08
09class Solution {
10public:
11    unordered_set<vector<int>, vector_hash> points;
12    
13    Solution(vector<vector<int>>& rects) {
14        for(vector<int>& rect : rects){
15            int x1 = rect[0], y1 = rect[1], x2 = rect[2], y2 = rect[3];
16            
17            for(int x = x1; x <= x2; ++x){
18                for(int y = y1; y <= y2; ++y){
19                    points.insert({x, y});
20                }
21            }
22        }
23    }
24    
25    vector<int> pick() {
26        int idx = rand() % points.size();
27        auto it = points.begin();
28        advance(it, idx);
29        return *it;
30    }
31};
32
33/**
34 * Your Solution object will be instantiated and called as such:
35 * Solution* obj = new Solution(rects);
36 * vector<int> param_1 = obj->pick();
37 */
38 
39//use rand() once
40//https://leetcode.com/problems/random-point-in-non-overlapping-rectangles/discuss/155456/Java-solution-with-just-call-one-Random()-for-each-Pick()!!!666
41//https://leetcode.com/problems/random-point-in-non-overlapping-rectangles/discuss/154130/Java-Solution.-Randomly-pick-a-rectangle-then-pick-a-point-inside./235726
42//Runtime: 136 ms, faster than 55.87% of C++ online submissions for Random Point in Non-overlapping Rectangles.
43//Memory Usage: 68.6 MB, less than 31.92% of C++ online submissions for Random Point in Non-overlapping Rectangles.
44class Solution {
45public:
46    vector<vector<int>> rects;
47    //(accumulated area sum, index of rect)
48    map<int, int> accArea2idx;
49    int accArea;
50    
51    Solution(vector<vector<int>>& rects) {
52        this->rects = rects;
53        accArea = 0;
54        for(int i = 0; i < rects.size(); ++i){
55            int x1 = rects[i][0], y1 = rects[i][1], x2 = rects[i][2], y2 = rects[i][3];
56            //we know that the rects are non-overlapping
57            accArea += (x2-x1+1) * (y2-y1+1);
58            accArea2idx[accArea] = i;
59        }
60    }
61    
62    vector<int> pick() {
63        //choose a random number in the range: [1, accArea]
64        int ri = rand() % accArea + 1;
65        /*
66        important!!!
67        in C++: lower_bound: >= , upper_bound: >
68        in Java: floorKey: <=, ceilingKey: >=
69        so here we translate the Java ceilingKey into lower_bound!!!
70        */
71        auto rit = accArea2idx.lower_bound(ri);
72        //the index of rectangle
73        int ridx = rit->second;
74        //the index of point in the rectangle
75        
76        vector<int> rect = rects[ridx];
77        int x1 = rect[0], y1 = rect[1], x2 = rect[2], y2 = rect[3];
78        
79        //method 1: use rand() twice
80        // ri = rand() % ((x2-x1+1)*(y2-y1+1));
81        
82        //method 2: use rand() once
83        ri = rit->first - ri;
84        //sanity check
85        // if(ri <= 0)
86        //     cout << rit->first << ", " << ri << endl;
87        int x = x1 + ri % (x2-x1+1);
88        int y = y1 + ri / (x2-x1+1);
89        return {x, y};
90    }
91};
92
93/**
94 * Your Solution object will be instantiated and called as such:
95 * Solution* obj = new Solution(rects);
96 * vector<int> param_1 = obj->pick();
97 */

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.