Skip to content

Commit a0e6b51

Browse files
committed
Add a solution to Detect Squares
1 parent 55dab32 commit a0e6b51

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Design/DetectSquares.swift

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/detect-squares/
3+
* Primary idea: Use hashmap to track points having the same x and y and calculate all possible results
4+
*
5+
* Time Complexity: add - O(1), count - O(n)
6+
* Space Complexity: O(n)
7+
*
8+
*/
9+
10+
class DetectSquares {
11+
12+
private var xPoints = [Int: [Int: Int]]()
13+
private var yPoints = [Int: [Int: Int]]()
14+
15+
init() { }
16+
17+
func add(_ point: [Int]) {
18+
let x = point[0], y = point[1]
19+
20+
xPoints[x, default: [y: 0]][y, default: 0] += 1
21+
yPoints[y, default: [x: 0]][x, default: 0] += 1
22+
}
23+
24+
func count(_ point: [Int]) -> Int {
25+
let x = point[0], y = point[1]
26+
27+
guard let xEqualPoints = xPoints[x], let yEqualPoints = yPoints[y] else {
28+
return 0
29+
}
30+
31+
var res = 0
32+
33+
for (yEqualPointX, firstPointsCount) in yEqualPoints {
34+
if x == yEqualPointX {
35+
continue
36+
}
37+
let sideLength = abs(x - yEqualPointX)
38+
// check bottom square
39+
if let secondPointCount = xEqualPoints[y - sideLength] {
40+
if let thirdPointCount = xPoints[yEqualPointX]?[y - sideLength] {
41+
res += firstPointsCount * secondPointCount * thirdPointCount
42+
}
43+
}
44+
if let secondPointCount = xEqualPoints[y + sideLength] {
45+
if let thirdPointCount = xPoints[yEqualPointX]?[y + sideLength] {
46+
res += firstPointsCount * secondPointCount * thirdPointCount
47+
}
48+
}
49+
}
50+
51+
return res
52+
}
53+
}
54+
55+
/**
56+
* Your DetectSquares object will be instantiated and called as such:
57+
* let obj = DetectSquares()
58+
* obj.add(point)
59+
* let ret_2: Int = obj.count(point)
60+
*/

0 commit comments

Comments
 (0)