MediumNo. 2249

Count Lattice Points Inside a Circle — LeetCode 2249 Python Solution

Topics
Geometry, Array, Hash Table, Math, Enumeration
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0149Max Points on a LineHard
0391Perfect RectangleHard
0939Minimum Area RectangleMedium
0963Minimum Area Rectangle IIMedium
0268Missing NumberEasy
0380Insert Delete GetRandom O(1)Medium

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.

Free to download. Check it runs on your machine, then pick a plan.