Detect Squares

Detect Squares – Medium Level Problem

You are given a stream of 2D points with x-y coordinates, and you can perform the following operations:

  • Add – Add new points to a data structure. Duplicate points are allowed and treated independently.
  • Query – For a given query point, count how many ways you can select three additional points from the data structure to form a square. The square must have sides parallel to the x-axis and y-axis, and all sides must be of equal length (no diagonal squares).
Detect Squares Question

Examples related to Detect Squares Problem

Example 1:

Detect Squares Problem

Constraints:

  • point.length == 2
  • 0 <= x, y <= 1000

Methods to Solve Detect Squares Problem

There are mainly 2 approaches to Detect Squares Problem:

  1. Hash Map I
  2. Hash Map II

1. Hash Map I

Use a hash map to store the frequency of each point added. To detect squares, iterate over all possible diagonal points for the query point, and calculate the frequencies of the other two required points to form a square.

  • Time complexity: O(1) for add(), O(n) for count()
  • Space complexity: O(n)

Code:

2. Hash Map II

Enhance the basic hash map approach by organizing points based on their x-coordinates. For each query point, find potential matching y-coordinates, then use stored frequencies to count valid squares more efficiently.

  • Time complexity: O(1) for add(), O(n) for count()
  • Space complexity: O(n)

Code:

More Articles