15% off all plans & roadmaps Use code
See plansDetect Squares
- LeetCode 2013
- Medium
- Design Patterns
- Design (General/Specific)
Updated
TL;DR: Store every added point in a list and a frequency map. For a query, treat each stored point as the diagonal corner, then multiply the counts of the two forced corners.
Problem
You receive a stream of points on the X-Y plane. Build a data structure that supports two operations:
- Add a point from the stream. Duplicate points are allowed, and each copy counts as a separate point.
- Count how many ways you can pick three stored points that, together with a given query point, form an axis-aligned square with positive area.
An axis-aligned square has four equal sides, and every side is parallel to the x-axis or the y-axis.
Implement the DetectSquares class:
DetectSquares()creates an empty data structure.void add(int[] point)adds the point[x, y]to the structure.int count(int[] point)returns the number of ways to form axis-aligned squares using the query point[x, y], as described above.
Example 1
Input: ["DetectSquares", "add", "add", "add", "count", "count", "add", "count"] [[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]] Output: [null, null, null, null, 1, 0, null, 2] Explanation: DetectSquares detectSquares = new DetectSquares(); detectSquares.add([3, 10]); detectSquares.add([11, 2]); detectSquares.add([3, 2]); detectSquares.count([11, 10]); // returns 1: the first, second and third points detectSquares.count([14, 8]); // returns 0: no square is possible detectSquares.add([11, 2]); // duplicates are allowed detectSquares.count([11, 10]); // returns 2: points 1, 2, 3 or points 1, 3, 4
Constraints
point.length == 20 <= x, y <= 1000- At most
3000calls in total are made toaddandcount.
Constraints that matter
- At most 3000 calls in total, so up to about 3000 stored points. A count that checks every triple does around 4.5 * 10^9 steps, which is far too slow.
- A count that touches each stored point once costs about 3000 steps. Even 3000 such calls cost under 10^7 steps in total, which is fine.
- Coordinates are between 0 and 1000, so a point packs into one integer key as x * 1001 + y. Keys never collide.
- Duplicates are separate points, so you must store counts rather than a set. Two copies of a corner double the number of squares.
- One count result is at most 1000 * 1000 * 1000 = 10^9 in the worst case, which fits in a 32-bit int.
Hints
Hint 1
This is a design problem with a hash map inside.
Hint 2
Keep every added point in a list.
Solution
Intuition
This is a design problem with a hash map inside. The hard part is count, because the statement says to choose three points. That wording hides a shortcut: in an axis-aligned square, two opposite corners fix the other two.
Picture a pegboard where each hole holds a count of how many points were placed there. The hash map is that pegboard, and each stored point is a peg you test against the query: you find the two holes that would complete the square with it and multiply the peg counts in those holes.
Take the query (qx, qy) and a stored point (px, py) as diagonal corners. They form a square only if |qx - px| == |qy - py| and the side is not zero. Then the remaining corners must be (qx, py) and (px, qy). You do not search for them. You look them up.
So the problem turns from "find three unknown points" into "pick one diagonal point and read two counts". A frequency map gives each count in O(1). The number of squares for that diagonal point is count(qx, py) * count(px, qy), because any copy of one corner pairs with any copy of the other.
Duplicates need one more thought. If you loop over a list that holds every added point, each copy of the diagonal point is visited on its own. That gives the diagonal multiplicity for free, and you never multiply by it explicitly.
Worked example
Input: commands = ["DetectSquares", "count"], params = [[], [[5, 5]]] Output: [null, 0] Explanation: The structure is empty when count([5, 5]) runs, so no three stored points exist and the answer is 0. The dry runs below also replay the add and count calls from the problem statement, so you can see a non-zero answer.
Approach 1: Brute force over triples
Keep every added point in a list. For a query, try every group of three stored points and test whether the four points form an axis-aligned square.
The test is the only subtle part. Pick one of the three points as the diagonal partner of the query, check the side rule, and see whether the other two points are exactly the two forced corners.
Steps
- Store each added point in a list.
- In
count, loop over every index triple i < j < k. - For each triple, try each of the three points as the diagonal partner of the query.
- The partner
(dx, dy)must satisfydx != qxand|dx - qx| == |dy - qy|. - The other two points must be
(qx, dy)and(dx, qy)in either order. - Add 1 to the answer for every triple that passes, then return the total.
Dry run
On the page example the list is empty, so there are no triples and count([5, 5]) returns 0.
On the statement's first count the list holds (3, 10), (11, 2), (3, 2) and the query is (11, 10). There is one triple. Trying (3, 2) as the partner gives dx = 3, |3 - 11| = 8 and |2 - 10| = 8, so the side rule holds.
The forced corners are (11, 2) and (3, 10), and the other two points are exactly those. The answer is 1.
Complexity
| Time | O(n^3) per count, O(1) per add |
|---|---|
| Space | O(n) |
Here n is the number of points added so far. count visits n * (n - 1) * (n - 2) / 6 triples and each test is constant work, which is O(n^3). With n near 3000 that is about 4.5 * 10^9 tests for one call. The list stores one entry per added point, so space is O(n).
PythonTested in our runner
from typing import List, Optional
class DetectSquares:
def __init__(self):
self.points = []
def add(self, point: List[int]) -> None:
self.points.append((point[0], point[1]))
def count(self, point: List[int]) -> int:
qx, qy = point
n = len(self.points)
res = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
trio = (self.points[i], self.points[j], self.points[k])
if self._is_square(qx, qy, trio):
res += 1
return res
def _is_square(self, qx, qy, trio):
for d in range(3):
dx, dy = trio[d]
o1 = trio[(d + 1) % 3]
o2 = trio[(d + 2) % 3]
if dx != qx and abs(dx - qx) == abs(dy - qy):
a = (qx, dy)
b = (dx, qy)
if (o1 == a and o2 == b) or (o1 == b and o2 == a):
return True
return False
JavaTested in our runner
import java.util.*;
class DetectSquares {
private List<int[]> points;
public DetectSquares() {
points = new ArrayList<>();
}
public void add(int[] point) {
points.add(new int[]{point[0], point[1]});
}
public int count(int[] point) {
int qx = point[0], qy = point[1];
int n = points.size();
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
int[][] trio = {points.get(i), points.get(j), points.get(k)};
if (isSquare(qx, qy, trio)) res++;
}
}
}
return res;
}
private boolean same(int[] p, int x, int y) {
return p[0] == x && p[1] == y;
}
private boolean isSquare(int qx, int qy, int[][] trio) {
for (int d = 0; d < 3; d++) {
int dx = trio[d][0], dy = trio[d][1];
int[] o1 = trio[(d + 1) % 3];
int[] o2 = trio[(d + 2) % 3];
if (dx != qx && Math.abs(dx - qx) == Math.abs(dy - qy)) {
if ((same(o1, qx, dy) && same(o2, dx, qy)) || (same(o1, dx, qy) && same(o2, qx, dy))) {
return true;
}
}
}
return false;
}
}
C++Tested in our runner
using namespace std;
class DetectSquares {
vector<pair<int, int>> points;
bool isSquare(int qx, int qy, const pair<int, int> trio[3]) {
for (int d = 0; d < 3; d++) {
int dx = trio[d].first, dy = trio[d].second;
pair<int, int> o1 = trio[(d + 1) % 3];
pair<int, int> o2 = trio[(d + 2) % 3];
if (dx != qx && abs(dx - qx) == abs(dy - qy)) {
pair<int, int> a = {qx, dy};
pair<int, int> b = {dx, qy};
if ((o1 == a && o2 == b) || (o1 == b && o2 == a)) return true;
}
}
return false;
}
public:
DetectSquares() {
}
void add(vector<int>& point) {
points.push_back({point[0], point[1]});
}
int count(vector<int>& point) {
int qx = point[0], qy = point[1];
int n = points.size();
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
pair<int, int> trio[3] = {points[i], points[j], points[k]};
if (isSquare(qx, qy, trio)) res++;
}
}
}
return res;
}
};
JavaScriptTested in our runner
var DetectSquares = function() {
this.points = [];
};
/**
* @param {number[]} point
* @return {void}
*/
DetectSquares.prototype.add = function(point) {
this.points.push([point[0], point[1]]);
};
/**
* @param {number[]} point
* @return {number}
*/
DetectSquares.prototype.count = function(point) {
const qx = point[0], qy = point[1];
const pts = this.points;
const n = pts.length;
const same = (p, x, y) => p[0] === x && p[1] === y;
let res = 0;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
for (let k = j + 1; k < n; k++) {
const trio = [pts[i], pts[j], pts[k]];
for (let d = 0; d < 3; d++) {
const dx = trio[d][0], dy = trio[d][1];
const o1 = trio[(d + 1) % 3];
const o2 = trio[(d + 2) % 3];
if (dx !== qx && Math.abs(dx - qx) === Math.abs(dy - qy)) {
if ((same(o1, qx, dy) && same(o2, dx, qy)) || (same(o1, dx, qy) && same(o2, qx, dy))) {
res++;
break;
}
}
}
}
}
}
return res;
};
GoTested in our runner
type DetectSquares struct {
points [][2]int
}
func Constructor() DetectSquares {
return DetectSquares{}
}
func absInt(x int) int {
if x < 0 {
return -x
}
return x
}
func isSquare(qx, qy int, t [3][2]int) bool {
for d := 0; d < 3; d++ {
dx, dy := t[d][0], t[d][1]
o1 := t[(d+1)%3]
o2 := t[(d+2)%3]
if dx != qx && absInt(dx-qx) == absInt(dy-qy) {
a := [2]int{qx, dy}
b := [2]int{dx, qy}
if (o1 == a && o2 == b) || (o1 == b && o2 == a) {
return true
}
}
}
return false
}
func (this *DetectSquares) add(point []int) {
this.points = append(this.points, [2]int{point[0], point[1]})
}
func (this *DetectSquares) count(point []int) int {
qx, qy := point[0], point[1]
n := len(this.points)
res := 0
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
for k := j + 1; k < n; k++ {
t := [3][2]int{this.points[i], this.points[j], this.points[k]}
if isSquare(qx, qy, t) {
res++
}
}
}
}
return res
}
C#Tested in our runner
public class DetectSquares {
private List<int[]> points;
public DetectSquares() {
points = new List<int[]>();
}
public void add(int[] point) {
points.Add(new int[] { point[0], point[1] });
}
public int count(int[] point) {
int qx = point[0], qy = point[1];
int n = points.Count;
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
int[][] trio = { points[i], points[j], points[k] };
if (IsSquare(qx, qy, trio)) res++;
}
}
}
return res;
}
private bool Same(int[] p, int x, int y) {
return p[0] == x && p[1] == y;
}
private bool IsSquare(int qx, int qy, int[][] trio) {
for (int d = 0; d < 3; d++) {
int dx = trio[d][0], dy = trio[d][1];
int[] o1 = trio[(d + 1) % 3];
int[] o2 = trio[(d + 2) % 3];
if (dx != qx && Math.Abs(dx - qx) == Math.Abs(dy - qy)) {
if ((Same(o1, qx, dy) && Same(o2, dx, qy)) || (Same(o1, dx, qy) && Same(o2, qx, dy))) {
return true;
}
}
}
return false;
}
}

Solution pattern
Design (General/Specific)
Part of Design Patterns
Approach 2: Hash map plus diagonal scanOptimalDesign (General/Specific)
What's slow: the brute force searches for three unknown points, so it pays for every triple. Almost all of those triples fail the first side check.
The insight that fixes it: one stored point plus the query already decides the whole square. Scan the stored points once. For each point that sits on a valid diagonal from the query, read the counts of the two forced corners from a frequency map and multiply them.
Keep two structures. A list holds every added point, so duplicate copies of a diagonal point are each visited. A map from point to count answers corner lookups in O(1).
Why it is correct. Every square that has the query as one corner has exactly one opposite corner, so it is found by exactly one stored point. Once that diagonal point is fixed, the other two corners are forced, so no square is missed or counted twice. Each copy of a stored point is its own list entry, so duplicate copies multiply correctly. Points that fail the side-length check cannot be opposite corners of any square with the query, so skipping them loses nothing.
Steps
- Create an empty list
pointsand an empty mapcountsfrom point to frequency. - In
add, append the point to the list and increase its count in the map by 1. - In
count, read(qx, qy)and setans = 0. - For each
(px, py)in the list, skip it unless|px - qx| == |py - qy|andpx != qx. - Look up
counts[(qx, py)]andcounts[(px, qy)], treating a missing key as 0. - Add the product of those two counts to
ans. - Return
ansafter the scan.
Dry run
Trace the page example first. count([5, 5]) runs on an empty list. The loop body never runs, so the answer is 0 and the output is [null, 0].
Now replay the statement's calls to see a non-zero result. Counts are keyed by (x, y).
| Step | Action | List of points | Counts or work | Result |
|---|---|---|---|---|
| 1 | add (3, 10) | (3,10) | counts[(3,10)] = 1 | null |
| 2 | add (11, 2) | (3,10), (11,2) | counts[(11,2)] = 1 | null |
| 3 | add (3, 2) | (3,10), (11,2), (3,2) | counts[(3,2)] = 1 | null |
| 4 | count (11, 10), point (3,10) | same | dx = 8, dy = 0, not equal, skip | ans = 0 |
| 5 | point (11,2) | same | dx = 0, skip | ans = 0 |
| 6 | point (3,2) | same | dx = 8, dy = 8. Corners (11,2) and (3,10) have counts 1 and 1 | ans = 1 |
| 7 | count (14, 8) | same | (3,10): dx 11, dy 2. (11,2): dx 3, dy 6. (3,2): dx 11, dy 6. None match | 0 |
| 8 | add (11, 2) | (3,10), (11,2), (3,2), (11,2) | counts[(11,2)] = 2 | null |
| 9 | count (11, 10) | same | (3,10) skip, both (11,2) skip because dx = 0. (3,2) gives counts[(11,2)] * counts[(3,10)] = 2 * 1 | 2 |
The outputs for steps 4, 7 and 9 are 1, 0 and 2, matching the statement.
Complexity
| Time | O(1) per add, O(n) per count |
|---|---|
| Space | O(n) |
Here n is the number of points added so far. add does one append and one map update, so it is O(1) on average. count makes one pass over the list, and each iteration does an absolute value check and two map lookups, so it is O(n). The list and the map each hold at most n entries, so space is O(n). With at most 3000 calls the whole run stays under about 10^7 steps.
PythonTested in our runner
from typing import List, Optional
from collections import defaultdict
class DetectSquares:
def __init__(self):
self.counts = defaultdict(int) # (x, y) -> how many copies
self.points = [] # every added point, duplicates included
def add(self, point: List[int]) -> None:
x, y = point
self.counts[(x, y)] += 1
self.points.append((x, y))
def count(self, point: List[int]) -> int:
qx, qy = point
ans = 0
for px, py in self.points:
# (px, py) must be a diagonal corner with positive side
if px == qx or abs(px - qx) != abs(py - qy):
continue
# forced corners: (qx, py) and (px, qy)
ans += self.counts.get((qx, py), 0) * self.counts.get((px, qy), 0)
return ans
JavaTested in our runner
import java.util.*;
class DetectSquares {
private Map<Integer, Integer> counts;
private List<int[]> points;
public DetectSquares() {
counts = new HashMap<>();
points = new ArrayList<>();
}
public void add(int[] point) {
int key = point[0] * 1001 + point[1];
counts.merge(key, 1, Integer::sum);
points.add(new int[]{point[0], point[1]});
}
public int count(int[] point) {
int qx = point[0], qy = point[1];
int ans = 0;
for (int[] p : points) {
int px = p[0], py = p[1];
if (px == qx || Math.abs(px - qx) != Math.abs(py - qy)) continue;
// forced corners: (qx, py) and (px, qy)
int a = counts.getOrDefault(qx * 1001 + py, 0);
int b = counts.getOrDefault(px * 1001 + qy, 0);
ans += a * b;
}
return ans;
}
}
C++Tested in our runner
using namespace std;
class DetectSquares {
unordered_map<int, int> cnt;
vector<pair<int, int>> pts;
public:
DetectSquares() {
}
void add(vector<int>& point) {
cnt[point[0] * 1001 + point[1]]++;
pts.push_back({point[0], point[1]});
}
int count(vector<int>& point) {
int qx = point[0], qy = point[1];
int ans = 0;
for (auto& p : pts) {
int px = p.first, py = p.second;
if (px == qx || abs(px - qx) != abs(py - qy)) continue;
auto a = cnt.find(qx * 1001 + py);
auto b = cnt.find(px * 1001 + qy);
if (a == cnt.end() || b == cnt.end()) continue;
ans += a->second * b->second;
}
return ans;
}
};
JavaScriptTested in our runner
var DetectSquares = function() {
this.counts = new Map();
this.points = [];
};
/**
* @param {number[]} point
* @return {void}
*/
DetectSquares.prototype.add = function(point) {
const key = point[0] * 1001 + point[1];
this.counts.set(key, (this.counts.get(key) || 0) + 1);
this.points.push([point[0], point[1]]);
};
/**
* @param {number[]} point
* @return {number}
*/
DetectSquares.prototype.count = function(point) {
const qx = point[0], qy = point[1];
let ans = 0;
for (const [px, py] of this.points) {
if (px === qx || Math.abs(px - qx) !== Math.abs(py - qy)) continue;
const a = this.counts.get(qx * 1001 + py) || 0;
const b = this.counts.get(px * 1001 + qy) || 0;
ans += a * b;
}
return ans;
};
GoTested in our runner
type DetectSquares struct {
counts map[int]int
points [][2]int
}
func Constructor() DetectSquares {
return DetectSquares{counts: map[int]int{}}
}
func absInt(x int) int {
if x < 0 {
return -x
}
return x
}
func (this *DetectSquares) add(point []int) {
this.counts[point[0]*1001+point[1]]++
this.points = append(this.points, [2]int{point[0], point[1]})
}
func (this *DetectSquares) count(point []int) int {
qx, qy := point[0], point[1]
ans := 0
for _, p := range this.points {
px, py := p[0], p[1]
if px == qx || absInt(px-qx) != absInt(py-qy) {
continue
}
// a missing key reads as 0 in Go maps
ans += this.counts[qx*1001+py] * this.counts[px*1001+qy]
}
return ans
}
C#Tested in our runner
public class DetectSquares {
private Dictionary<int, int> counts;
private List<int[]> points;
public DetectSquares() {
counts = new Dictionary<int, int>();
points = new List<int[]>();
}
public void add(int[] point) {
int key = point[0] * 1001 + point[1];
counts.TryGetValue(key, out int c);
counts[key] = c + 1;
points.Add(new int[] { point[0], point[1] });
}
public int count(int[] point) {
int qx = point[0], qy = point[1];
int ans = 0;
foreach (int[] p in points) {
int px = p[0], py = p[1];
if (px == qx || Math.Abs(px - qx) != Math.Abs(py - qy)) continue;
counts.TryGetValue(qx * 1001 + py, out int a);
counts.TryGetValue(px * 1001 + qy, out int b);
ans += a * b;
}
return ans;
}
}
Common mistakes
- Using a set or a map without a list, such as
if (x, y) not in seenbefore adding. Duplicates are separate points, so keep a frequency map for the corners and a list (or a count multiplier) for the diagonal point. - Dropping the
px == qxcheck. A stored point with the same x and y as the query gives|dx| == |dy| == 0, which counts a zero-area square. Skip any point withpx == qx. - Comparing
qx - px == qy - pywithout absolute values. That only finds squares in one direction. Useabs(qx - px) == abs(qy - py)so squares above, below, left and right all count. - Multiplying by the diagonal point's own count, as in
counts[(px, py)] * counts[(qx, py)] * counts[(px, qy)]while also looping over the list with duplicates. Each copy is already visited separately, so this counts the copies twice. Multiply only the two corner counts. - Counting rectangles by checking only that corners exist, without the
|dx| == |dy|test. A rectangle with unequal sides is not a square. Test the side equality first. - Looking up a missing key and getting an error or inserting an entry, such as
counts[(qx, py)]on a plain Python dict. Use.get(key, 0), or adefaultdictthat you do not mind growing. In Java and C#, use the default-value form of the lookup.
Edge cases
counton an empty structure returns 0. This is the page example.- The query equals a stored point, such as query (5, 5) with (5, 5) stored. The side is zero, so skip it. The answer stays 0.
- Two copies of one corner and one copy of the other, with the diagonal point present once. The answer is 2 * 1 = 2.
- The diagonal point is stored twice and each corner once. The answer is 2, because the list visits both copies.
- Points that share only x or only y with the query, such as (3, 10) against query (11, 10). They fail
|dx| == |dy|or havedx = 0, so they add nothing. - Coordinates at the limits, such as query (0, 0) with points (1000, 1000), (0, 1000) and (1000, 0). The answer is 1, and the key
x * 1001 + ystays unique.
Follow-ups interviewers ask
- Can you make count faster than a scan over all stored points?
- Yes. Group counts by x, so
cols[x]maps y to a frequency. For a query, loop over the y values incols[qx], which are the points directly above and below the query. For each y with sided = y - qyandd != 0, check the columnqx + dand the columnqx - d. Multiply the three counts. The work is bounded by the distinct y values in one column, at most 1001, instead of the number of added points. - What if coordinates were huge and a 2D array was impossible?
- Use a hash map keyed by the pair or by a packed integer. Packing needs a multiplier larger than the maximum coordinate, and 64-bit integers if the product could overflow. The approach and the complexity do not change. Only memory per entry changes.
- What if squares could be rotated, not just axis-aligned?
- Two diagonal corners no longer fix the others by a simple swap. For a diagonal pair you compute the other two corners with the midpoint and a 90 degree rotation, and they must land on integer points. You can then look them up in the same frequency map. The scan stays O(n) per count, but you need care with integer midpoints and a doubled-coordinate trick to avoid fractions.
Detect Squares FAQ
What is the time complexity of Detect Squares?
add is O(1) on average. count is O(n), where n is the number of points added so far, because it scans the list once and does two O(1) lookups per point. The brute force over triples is O(n^3) per count.
Why use a hash map for Detect Squares?
After you pick a diagonal point, the other two corners are fixed, so you only need to know how many copies of each exist. A hash map from point to count answers that in O(1). Without it you would scan the list again for every corner.
Why do the two corner counts multiply?
Any copy of the first corner can pair with any copy of the second corner. With a copies of one and b copies of the other, there are a * b distinct choices of three points for that diagonal point.
Can Detect Squares be solved in O(1) extra space?
No. The structure must remember every added point, and duplicates change the answer, so you need at least a count per distinct point. A fixed 1001 by 1001 array is constant in n but still uses about a million integers. The list of points is the part that grows with n.
How do I solve LeetCode 2013 in Python?
Use a defaultdict(int) for point counts and a list of points. In count, loop over the list, skip points where px == qx or the absolute differences differ, and add the product of the two corner counts. Use .get(key, 0) for the lookups so the map does not grow during a query.
Why must the query point be treated differently from stored points?
The query is never stored, so a call to count does not change the structure. Only the three other corners come from stored points. The query only supplies the fixed corner from which you test each diagonal.
Asked at
See which companies ask this — Pro
Related problems
- LRU Cache · same technique: Design (General/Specific)
- Min Stack · same technique: Design (General/Specific)
- Time Based Key-Value Store · same technique: Design (General/Specific)
- Encode and Decode Strings · same technique: Design (General/Specific)
- Design Circular Queue · same technique: Design (General/Specific)
- Find Median from Data Stream · next harder, same pattern
- Implement Trie (Prefix Tree) · same pattern: Design Patterns
- Design Add and Search Words Data Structure · same pattern: Design Patterns
- Extra Characters in a String · same pattern: Design Patterns
- Design Hit Counter · same pattern: Design Patterns