Count Lattice Points Inside a Circle — LeetCode 2249 Python Solution

MediumGeometryArrayHash TableMathEnumeration
Problem
#2249
Reading time
3 min

The problem

Given a 2D integer array circles where circles[i] = [xi, yi, ri] represents the center (xi, yi) and radius ri of the ith circle drawn on a grid, return the number of lattice points that are present inside at least one circle. Note: A lattice point is a point with integer coordinates.

Example

Input
circles = [[2,2,1]]
Output
5
Explanation
The figure above shows the given circle.

Python solution

Python
class Solution:
    def countLatticePoints(self, circles: List[List[int]]) -> int:
        ans = 0
        mx = max(x + r for x, _, r in circles)
        my = max(y + r for _, y, r in circles)
        for i in range(mx + 1):
            for j in range(my + 1):
                for x, y, r in circles:
                    dx, dy = i - x, j - y
                    if dx * dx + dy * dy <= r * r:
                        ans += 1
                        break
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2249. Count Lattice Points Inside a Circle is filed here because LeetCode tags it Math and Geometry, which is the vocabulary this hub collects.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2249. Count Lattice Points Inside a Circle?
LeetCode 2249. Count Lattice Points Inside a Circle is rated Medium on LeetCode.
What is the time complexity of LeetCode 2249. Count Lattice Points Inside a Circle?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2249. Count Lattice Points Inside a Circle?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2249. Count Lattice Points Inside a Circle cover?
LeetCode 2249. Count Lattice Points Inside a Circle is tagged Geometry, Array, Hash Table, Math and Enumeration on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview