Magicsheet logo

Count Lattice Points Inside a Circle

Medium
62.6%
Updated 6/1/2025

Count Lattice Points Inside a Circle

What is this problem about?

The "Count Lattice Points Inside a Circle" coding problem asks you to find the number of unique points (x,y)(x, y) with integer coordinates that fall inside or on the boundary of at least one of the given circles. Each circle is defined by its center (x,y)(x, y) and its radius rr.

Why is this asked in interviews?

Companies like Rubrik use this problem to test geometric logic and the ability to optimize an enumeration approach. It requires a candidate to define a bounding box for each circle and efficiently check points within that box. It also tests the use of Hash Sets to handle overlapping circles and prevent double-counting points.

Algorithmic pattern used

This is a Geometry and Enumeration problem. For each circle, you determine its "Bounding Box": from (xr)(x-r) to (x+r)(x+r) horizontally and (yr)(y-r) to (y+r)(y+r) vertically. You iterate through every integer point within this box and use the circle equation (xixc)2+(yiyc)2r2(x_i - x_c)^2 + (y_i - y_c)^2 \le r^2 to check if the point is inside. A global Hash Set stores the string or encoded representation of each valid (x,y)(x, y) point.

Example explanation

Suppose we have a circle at (2,2)(2, 2) with radius 1.

  • Bounding Box: x[1,3],y[1,3]x \in [1, 3], y \in [1, 3].
  • Possible points: (1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3).
  • Check (1,1)(1,1): (12)2+(12)2=1+1=2(1-2)^2 + (1-2)^2 = 1+1 = 2. 2>122 > 1^2, so (1,1) is OUT.
  • Check (2,2)(2,2): (22)2+(22)2=0(2-2)^2 + (2-2)^2 = 0. 0120 \le 1^2, so (2,2) is IN.
  • Check (1,2)(1,2): (12)2+(22)2=1(1-2)^2 + (2-2)^2 = 1. 1121 \le 1^2, so (1,2) is IN. Points inside are: (2,2), (1,2), (3,2), (2,1), (2,3). Total 5.

Common mistakes candidates make

A common error is using floating-point math (like sqrt) which can lead to precision issues. It's always safer to use the squared distance comparison. Another mistake is inefficiently iterating over the entire possible grid range (e.g., 0 to 200) for every circle instead of just the bounding box. Finally, failing to use a set to handle overlapping circles leads to incorrect counts.

Interview preparation tip

When dealing with "unique points" or "unique items" in a 2D space, think about how to represent a coordinate as a single key. You can use a string "x,y" or a bit-shifted long (x << 32 | y) to store points in a Hash Set efficiently.

Similar Questions