-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2013_detect_squares.html
More file actions
413 lines (348 loc) · 17.2 KB
/
Copy path2013_detect_squares.html
File metadata and controls
413 lines (348 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 2013: Detect Squares - Algorithm Visualization</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#2013</span> Detect Squares</h1>
<p>Design a data structure to add points and count axis-aligned squares that can be formed with a query point.</p>
<div class="problem-meta">
<span class="meta-tag">🔧 Design</span>
<span class="meta-tag">📊 Hash Map</span>
<span class="meta-tag">⏱️ O(n) count</span>
<span class="meta-tag">💾 O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/2013_detect_squares/2013_detect_squares.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>For counting squares with a query point:</p>
<ul>
<li><strong>Fix diagonal:</strong> Query point is one corner</li>
<li><strong>Find opposite:</strong> Look for points that could be diagonal opposite</li>
<li><strong>Check others:</strong> Need 2 more corners to complete square</li>
<li><strong>Count:</strong> Multiply counts of matching corners</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<input type="number" id="xInput" placeholder="X" style="padding: 8px; width: 60px; border-radius: 5px; border: 2px solid #ddd;" min="0" max="14">
<input type="number" id="yInput" placeholder="Y" style="padding: 8px; width: 60px; border-radius: 5px; border: 2px solid #ddd;" min="0" max="14">
<button class="btn btn-primary" onclick="addPoint()">Add Point</button>
<button class="btn" style="background: #9c27b0; color: white;" onclick="countSquares()">Count Squares</button>
<button class="btn btn-warning" onclick="reset()">Reset</button>
</div>
<div class="status-message" id="statusMessage">
Add points, then count squares with a query point
</div>
<div style="display: flex; gap: 30px; flex-wrap: wrap; margin-top: 20px;">
<div style="flex: 2; min-width: 350px;">
<svg id="gridViz" width="100%" height="400"></svg>
</div>
<div style="flex: 1; min-width: 200px;">
<h4>📊 Points Added</h4>
<div id="pointsDisplay" style="padding: 15px; background: #e3f2fd; border-radius: 12px; max-height: 150px; overflow-y: auto; margin-bottom: 15px;"></div>
<h4>🔢 Square Count</h4>
<div id="countDisplay" style="padding: 25px; background: linear-gradient(135deg, #667eea, #764ba2); border-radius: 12px; text-align: center;">
<div style="color: rgba(255,255,255,0.8); font-size: 0.9em;">Squares Found</div>
<div style="color: white; font-size: 2.5em; font-weight: bold;">0</div>
</div>
<h4 style="margin-top: 15px;">🔲 Detected Squares</h4>
<div id="squaresDisplay" style="padding: 15px; background: #f5f5f5; border-radius: 12px; max-height: 150px; overflow-y: auto;"></div>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
from collections import defaultdict
"""
LeetCode Detect Squares
Problem from LeetCode: https://leetcode.com/problems/detect-squares/
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. 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 y-axis.
Implement the DetectSquares class:
- DetectSquares() Initializes the object with an empty data structure.
- void add(int[] point) Adds a new point point = [x, y] to the data structure.
- int count(int[] point) Counts the number of ways to form axis-aligned squares with
point point = [x, y] as described above.
Example:
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]); // return 1. You can choose:
// - The first, second, and third points
detectSquares.count([14, 8]); // return 0. The query point cannot form a square with any points in the data structure.
detectSquares.add([11, 2]); // Adding duplicate points is allowed.
detectSquares.count([11, 10]); // return 2. You can choose:
// - The first, second, and third points
// - The first, third, and fourth points
Constraints:
point.length == 2
0 <= x, y <= 1000
At most 3000 calls in total will be made to add and count.
"""
class DetectSquares:
def __init__(self):
"""
Initialize the DetectSquares data structure.
Uses a defaultdict of defaultdicts to efficiently track point frequencies.
"""
self.points_count = defaultdict(lambda : defaultdict(int))
def add(self, point: List[int]) ->None:
"""
Add a point to the data structure.
Args:
point: A point [x, y] to be added
"""
x, y = point
self.points_count[x][y] += 1
def count(self, point: List[int]) ->int:
"""
Count the number of squares that can be formed with this point as one corner.
Args:
point: A query point [x, y]
Returns:
int: The number of squares that can be formed
"""
x1, y1 = point
total_squares = 0
if x1 not in self.points_count:
return 0
for y2, count_y2 in self.points_count[x1].items():
if y2 == y1:
continue
side_length = abs(y2 - y1)
total_squares += self._count_squares(x1, y1, x1 + side_length,
y2, count_y2)
total_squares += self._count_squares(x1, y1, x1 - side_length,
y2, count_y2)
return total_squares
def _count_squares(self, x1: int, y1: int, x3: int, y2: int, count_y2: int
) ->int:
"""
Helper function to count squares formed for the given coordinates.
Args:
x1, y1: Coordinates of the query point
x3: x-coordinate of the possible diagonal point
y2: y-coordinate of the second point sharing the x1 coordinate
count_y2: Count of points at (x1, y2)
Returns:
int: Number of squares that can be formed
"""
if x3 in self.points_count:
return self.points_count[x3][y1] * self.points_count[x3][y2
] * count_y2
return 0
if __name__ == '__main__':
# Example usage based on LeetCode sample
detectSquares = DetectSquares()
detectSquares.add([3, 10])
detectSquares.add([11, 2])
detectSquares.add([3, 2])
print(detectSquares.count([11, 10])) # Output: 1
print(detectSquares.count([14, 8])) # Output: 0
detectSquares.add([11, 2])
print(detectSquares.count([11, 10])) # Output: 2
</pre>
</div>
</div>
</div>
<script>
let points = {}; // (x,y) as string → count
let queryPoint = null;
let foundSquares = [];
const gridSize = 15;
const cellSize = 25;
function render() {
const svg = d3.select("#gridViz");
svg.selectAll("*").remove();
const container = svg.node().parentElement;
const width = container.clientWidth;
const height = 400;
svg.attr("viewBox", `0 0 ${width} ${height}`);
const offsetX = (width - gridSize * cellSize) / 2;
const offsetY = 20;
const g = svg.append("g").attr("transform", `translate(${offsetX}, ${offsetY})`);
// Draw grid
for (let i = 0; i <= gridSize; i++) {
g.append("line")
.attr("x1", 0).attr("y1", i * cellSize)
.attr("x2", gridSize * cellSize).attr("y2", i * cellSize)
.attr("stroke", "#eee").attr("stroke-width", 1);
g.append("line")
.attr("x1", i * cellSize).attr("y1", 0)
.attr("x2", i * cellSize).attr("y2", gridSize * cellSize)
.attr("stroke", "#eee").attr("stroke-width", 1);
// Axis labels
if (i < gridSize) {
g.append("text")
.attr("x", i * cellSize + cellSize / 2)
.attr("y", gridSize * cellSize + 15)
.attr("text-anchor", "middle")
.attr("font-size", "10px").attr("fill", "#999")
.text(i);
g.append("text")
.attr("x", -10)
.attr("y", (gridSize - 1 - i) * cellSize + cellSize / 2 + 4)
.attr("text-anchor", "middle")
.attr("font-size", "10px").attr("fill", "#999")
.text(i);
}
}
// Draw found squares
foundSquares.forEach((sq, i) => {
const color = `hsl(${(i * 60) % 360}, 70%, 80%)`;
const [x1, y1] = sq[0];
const [x2, y2] = sq[1];
g.append("rect")
.attr("x", Math.min(x1, x2) * cellSize + cellSize / 2)
.attr("y", (gridSize - 1 - Math.max(y1, y2)) * cellSize + cellSize / 2)
.attr("width", Math.abs(x2 - x1) * cellSize)
.attr("height", Math.abs(y2 - y1) * cellSize)
.attr("fill", color)
.attr("stroke", `hsl(${(i * 60) % 360}, 70%, 50%)`)
.attr("stroke-width", 2)
.attr("opacity", 0.5);
});
// Draw points
Object.entries(points).forEach(([key, count]) => {
const [x, y] = key.split(',').map(Number);
const screenX = x * cellSize + cellSize / 2;
const screenY = (gridSize - 1 - y) * cellSize + cellSize / 2;
g.append("circle")
.attr("cx", screenX).attr("cy", screenY).attr("r", 12)
.attr("fill", "#667eea")
.attr("stroke", "#5a6fd6").attr("stroke-width", 2);
if (count > 1) {
g.append("text")
.attr("x", screenX).attr("y", screenY + 4)
.attr("text-anchor", "middle")
.attr("font-size", "10px").attr("fill", "white").attr("font-weight", "bold")
.text(count);
}
});
// Draw query point
if (queryPoint) {
const screenX = queryPoint[0] * cellSize + cellSize / 2;
const screenY = (gridSize - 1 - queryPoint[1]) * cellSize + cellSize / 2;
g.append("circle")
.attr("cx", screenX).attr("cy", screenY).attr("r", 15)
.attr("fill", "#e91e63")
.attr("stroke", "#c2185b").attr("stroke-width", 3);
g.append("text")
.attr("x", screenX).attr("y", screenY + 5)
.attr("text-anchor", "middle")
.attr("font-size", "12px").attr("fill", "white").attr("font-weight", "bold")
.text("Q");
}
updatePointsDisplay();
updateSquaresDisplay();
}
function updatePointsDisplay() {
const container = document.getElementById('pointsDisplay');
const entries = Object.entries(points);
if (entries.length === 0) {
container.innerHTML = '<span style="color: #999;">(no points)</span>';
return;
}
container.innerHTML = entries.map(([key, count]) =>
`<span style="background: #667eea; color: white; padding: 4px 10px; margin: 3px; border-radius: 15px; display: inline-block;">(${key})${count > 1 ? ' ×' + count : ''}</span>`
).join(' ');
}
function updateSquaresDisplay() {
const container = document.getElementById('squaresDisplay');
if (foundSquares.length === 0) {
container.innerHTML = '<span style="color: #999;">(no squares found)</span>';
return;
}
container.innerHTML = foundSquares.map((sq, i) =>
`<div style="padding: 6px 10px; margin: 3px 0; background: hsl(${(i * 60) % 360}, 70%, 90%); border-radius: 6px; font-size: 0.85em;">
Square ${i + 1}: (${sq[0].join(',')}) ↔ (${sq[1].join(',')})${sq[2] > 1 ? ` ×${sq[2]}` : ''}
</div>`
).join('');
}
function addPoint() {
const x = parseInt(document.getElementById('xInput').value);
const y = parseInt(document.getElementById('yInput').value);
if (isNaN(x) || isNaN(y) || x < 0 || x >= gridSize || y < 0 || y >= gridSize) {
document.getElementById('statusMessage').textContent = `Please enter valid coordinates (0-${gridSize - 1})`;
return;
}
const key = `${x},${y}`;
points[key] = (points[key] || 0) + 1;
document.getElementById('statusMessage').textContent = `Added point (${x}, ${y})`;
document.getElementById('xInput').value = '';
document.getElementById('yInput').value = '';
queryPoint = null;
foundSquares = [];
render();
}
function countSquares() {
const px = parseInt(document.getElementById('xInput').value);
const py = parseInt(document.getElementById('yInput').value);
if (isNaN(px) || isNaN(py) || px < 0 || px >= gridSize || py < 0 || py >= gridSize) {
document.getElementById('statusMessage').textContent = `Please enter valid query point (0-${gridSize - 1})`;
return;
}
queryPoint = [px, py];
foundSquares = [];
let count = 0;
Object.entries(points).forEach(([key, cnt]) => {
const [x, y] = key.split(',').map(Number);
// Check if this could be diagonal opposite
if (Math.abs(px - x) !== Math.abs(py - y) || x === px) return;
// Check other two corners
const corner1 = `${px},${y}`;
const corner2 = `${x},${py}`;
if (points[corner1] && points[corner2]) {
const numSquares = cnt * points[corner1] * points[corner2];
count += numSquares;
foundSquares.push([[px, py], [x, y], numSquares]);
}
});
document.getElementById('countDisplay').querySelector('div:last-child').textContent = count;
document.getElementById('statusMessage').textContent =
count > 0
? `Found ${count} square(s) with query point (${px}, ${py})`
: `No squares found with query point (${px}, ${py})`;
render();
}
function reset() {
points = {};
queryPoint = null;
foundSquares = [];
document.getElementById('statusMessage').textContent = 'Add points, then count squares with a query point';
document.getElementById('xInput').value = '';
document.getElementById('yInput').value = '';
document.getElementById('countDisplay').querySelector('div:last-child').textContent = '0';
render();
}
reset();
window.addEventListener('resize', render);
</script>
</body>
</html>