Detect Squares
Detailed guide and Python implementation for the 'Detect Squares' problem.
1. Concept Overview
The 'Detect Squares' problem is a key challenge in the Math & Geometry section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Detect Squares.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Detect Squares carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
Problem Statement
You are given a stream of points on the X-Y plane. Design a data structure that:
- Adds new points from the stream. Duplicate points are allowed and should be treated as different points.
- Given a query point, counts the number of ways to choose three points from the data structure such that the three points and the query point form an axis-aligned square with positive area.
An axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and the y-axis.
Implement a function detectSquares(operations: list, arguments: list) -> list where operations are 'DetectSquares', 'add', or 'count', and arguments are the corresponding parameters. Returns a list of results (None for constructor and add).
- •point.length == 2
- •0 <= x, y <= 1000
- •At most 3000 calls in total will be made to add and count
Examples
["DetectSquares","add","add","add","count","count","add","count"], [[],[3,10],[11,2],[3,2],[11,10],[14,8],[11,2],[11,10]]
[None,None,None,None,1,0,None,2]
After adding (3,10), (11,2), (3,2): count(11,10) finds 1 square with corners (3,10),(11,10),(11,2),(3,2). count(14,8) finds 0. After adding another (11,2): count(11,10) finds 2 squares (using each copy of (11,2)).
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Interview Insights & Variations
Complexity Analysis Breakdown
Why Time: Directly evaluates all possibilities.
Why Space: Uses standard local memory.
Why Time: Optimized paths reduce total operations.
Why Space: May trade memory for speed.
Optimized Solution Python Code
Optimized Solution Python Code
from collections import defaultdict
class DetectSquaresOpt:
def __init__(self):
self.ptsCount = defaultdict(int)
self.pts = []
def add(self, point: list[int]) -> None:
self.ptsCount[tuple(point)] += 1
self.pts.append(point)
def count(self, point: list[int]) -> int:
res = 0
px, py = point
for x, y in self.pts:
if abs(px - x) == abs(py - y) and px != x and py != y:
res += self.ptsCount[(x, py)] * self.ptsCount[(px, y)]
return resBrute Force Code (Spoiler Guarded)
Brute Force Code (Spoiler Guarded)
class DetectSquaresBrute:
def __init__(self):
self.points = []
def add(self, point: list[int]) -> None:
self.points.append(point)
def count(self, point: list[int]) -> int:
res = 0
px, py = point
for x, y in self.points:
if abs(px - x) == abs(py - y) and px != x and py != y:
c1 = self.points.count([x, py])
c2 = self.points.count([px, y])
res += c1 * c2
return resAlgorithm Pattern Checklist
When dealing with Math & Geometry data patterns.
Core Prerequisites
Revision Key Notes
Common Mistakes & Pitfalls
Related Questions
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.