<p>You are given an array of points in the <strong>X-Y</strong> plane <code>points</code> where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>

<p>Return <em>the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes</em>. If there is not any such rectangle, return <code>0</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/08/03/rec1.JPG" style="width: 500px; height: 447px;" />
<pre>
<strong>Input:</strong> points = [[1,1],[1,3],[3,1],[3,3],[2,2]]
<strong>Output:</strong> 4
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/08/03/rec2.JPG" style="width: 500px; height: 477px;" />
<pre>
<strong>Input:</strong> points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]
<strong>Output:</strong> 2
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= points.length &lt;= 500</code></li>
	<li><code>points[i].length == 2</code></li>
	<li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 4 * 10<sup>4</sup></code></li>
	<li>All the given points are <strong>unique</strong>.</li>
</ul>

class Solution {
public:

    vector<int> intersectionOfYs(set<int> y1, set<int> y2) {
        auto i = y1.begin(), j = y2.begin();
        vector<int> res;
        while(i != y1.end() && j != y2.end()) {
            if (*i < *j) {
                i++;
            } else if (*i > *j) {
                j++;
            } else {
                res.push_back(*i);
                i++;
                j++;
            }
        }

        return res; 
    }

    int minAreaRect(vector<vector<int>>& points) {
        unordered_map<int, set<int>> XY;

        for (auto p : points) {
            XY[p[0]].insert(p[1]);
        }

        // remove x co-ord with less than 2 y co-ordinates.
        auto it = XY.begin();
        while(it != XY.end()) {
            auto temp = it;
            it++;
            if (temp->second.size() < 2) XY.erase(temp);
        }

        int minArea = INT_MAX;
        // for each x co-ord , match with every other x co-ord and get a list of intersecting y co-ordinates
        // calculate the area for these and keep track of min.
        for (auto i = XY.begin(); i != XY.end(); i++) {
            for(auto j = next(i); j != XY.end(); j++) {
                vector<int> Ys = intersectionOfYs(i->second, j->second);

                // Ys are sorted
                for (int k =1; k < Ys.size(); k++) {
                    minArea = min(minArea, abs(i->first - j->first)*(Ys[k]-Ys[k-1]));
                }
            }
        }

        return minArea == INT_MAX? 0 : minArea;
    }
};
168003