Detect Squares — LeetCode 2013 Python Solution

MediumDesignArrayHash TableCounting
Problem
#2013
Pattern
Hash Map
Reading time
5 min

The problem

You are given a stream of points on the X-Y plane. Design an algorithm that: Adds new points from the stream into a data structure.

Example

Input
["DetectSquares", "add", "add", "add", "count", "count", "add", "count"]
Output
[null, null, null, null, 1, 0, null, 2]
Explanation
DetectSquares detectSquares = new DetectSquares();

Python solution

Python
class DetectSquares:
    def __init__(self):
        self.cnt = defaultdict(Counter)

    def add(self, point: List[int]) -> None:
        x, y = point
        self.cnt[x][y] += 1

    def count(self, point: List[int]) -> int:
        x1, y1 = point
        if x1 not in self.cnt:
            return 0
        ans = 0
        for x2 in self.cnt.keys():
            if x2 != x1:
                d = x2 - x1
                ans += self.cnt[x2][y1] * self.cnt[x1][y1 + d] * self.cnt[x2][y1 + d]
                ans += self.cnt[x2][y1] * self.cnt[x1][y1 - d] * self.cnt[x2][y1 - d]
        return ans


# Your DetectSquares object will be instantiated and called as such:
# obj = DetectSquares()
# obj.add(point)
# param_2 = obj.count(point)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2013. Detect Squares is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

On a study list

This problem is on NeetCode 150.

Frequently asked questions

How hard is LeetCode 2013. Detect Squares?
LeetCode 2013. Detect Squares is rated Medium on LeetCode.
What is the time complexity of LeetCode 2013. Detect Squares?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2013. Detect Squares?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2013. Detect Squares cover?
LeetCode 2013. Detect Squares is tagged Design, Array, Hash Table and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview