#2013

Detect Squares

Medium
ArrayHash TableDesignCountingData StreamHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

In the optimal solution, we maintain a frequency map of points to quickly access how many points exist at specific coordinates. This allows us to count potential squares efficiently without checking every combination.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a HashMap to store the frequency of each point.
  2. 2Step 2: For each query point, find points with the same y-coordinate and calculate the potential coordinates for the other two corners of the square.
  3. 3Step 3: Use the frequency map to count how many of these potential points exist and calculate the total combinations.
solution.py18 lines
1from collections import defaultdict
2
3class DetectSquares:
4    def __init__(self):
5        self.point_count = defaultdict(int)
6
7    def add(self, point):
8        self.point_count[tuple(point)] += 1
9
10    def count(self, point):
11        count = 0
12        xq, yq = point
13        for (x, y), freq in self.point_count.items():
14            if y == yq:
15                side_length = abs(x - xq)
16                count += freq * self.point_count[(x, yq + side_length)] * self.point_count[(xq, yq + side_length)]
17                count += freq * self.point_count[(x, yq - side_length)] * self.point_count[(xq, yq - side_length)]
18        return count

Complexity note: This complexity is linear because we only traverse the points once to build the frequency map and then check potential squares in constant time for each point.

  • 1Using a frequency map allows for quick access to point counts, making the solution efficient.
  • 2Identifying points with the same y-coordinate is crucial for forming squares.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.