#2249
Count Lattice Points Inside a Circle
MediumArrayHash TableMathGeometryEnumerationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n * r²) | O(n * r) |
| Space | O(n * r²) | O(n * r) |
💡
Intuition
Time O(n * r)Space O(n * r)
Instead of checking every point in the bounding box, we can directly calculate the number of lattice points that lie within the circle using geometry. This reduces unnecessary checks and improves efficiency.
⚙️
Algorithm
5 steps- 1Step 1: For each circle, calculate the bounding box as before.
- 2Step 2: For each integer x-coordinate in the bounding box, calculate the maximum y-coordinate that lies within the circle using the circle equation.
- 3Step 3: Count the integer y-coordinates from the minimum to the maximum for each valid x-coordinate.
- 4Step 4: Use a set to store unique lattice points to ensure no duplicates.
- 5Step 5: Return the size of the set as the result.
solution.py9 lines
1def countLatticePoints(circles):
2 points = set()
3 for x, y, r in circles:
4 for i in range(x - r, x + r + 1):
5 max_y = y + int((r ** 2 - (i - x) ** 2) ** 0.5)
6 min_y = y - int((r ** 2 - (i - x) ** 2) ** 0.5)
7 for j in range(min_y, max_y + 1):
8 points.add((i, j))
9 return len(points)ℹ
Complexity note: This approach is more efficient because we only calculate the valid y-coordinates for each x-coordinate, reducing the number of checks significantly compared to the brute-force method.
- 1Understanding the geometry of circles helps in reducing unnecessary checks.
- 2Using sets ensures unique counting of lattice points.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.