Problem 478

Abstract / Summary

Generate a random point uniformly inside a circle with given radius and center coordinates.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0478.py

class Solution:
    def __init__(self, radius: float, x_center: float, y_center: float):
        self.r = radius
        self.x = x_center
        self.y = y_center

    def randPoint(self) -> List[float]:
        dx = uniform(-self.r, +self.r)
        dy = uniform(-self.r, +self.r)
        while dx*dx + dy*dy > self.r*self.r:
            dx = uniform(-self.r, +self.r)
            dy = uniform(-self.r, +self.r)
        return [ self.x + dx, self.y + dy ]
13 lines | 472 bytes | submitted September 23, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 43% (100k+ submissions).

Typical patterns to solve this problem:
  • Geometry
  • Math
  • Randomized
  • Rejection Sampling
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class encapsulates the data needed to describe a circle-its radius and the coordinates of its center-and offers a method randPoint that returns a uniformly distributed random point inside that circle. The implementation follows a classic rejection-sampling strategy: it first picks a candidate point from the square that bounds the circle and then discards it if it falls outside the circular region. This approach guarantees that every point inside the circle has an equal probability of being selected.

Construction of the Circle

The constructor stores the three geometric parameters as instance attributes. By assigning them to short names (self.r, self.x, self.y) the later code can access them quickly without repeated attribute lookups.

class Solution:
    def __init__(self, radius: float, x_center: float, y_center: float):
        self.r = radius
        self.x = x_center
        self.y = y_center

Generating a Candidate Point

Inside randPoint the algorithm draws two independent uniform random numbers, dx and dy, each ranging from -r to +r. These offsets represent a point relative to the circle’s center, positioned somewhere inside the axis-aligned square that encloses the circle.

dx = uniform(-self.r, +self.r)
dy = uniform(-self.r, +self.r)

Rejection Loop

The core of the method is a while loop that checks whether the candidate lies within the circle. The condition dx*dx + dy*dy > self.r*self.r computes the squared distance from the origin of the offset coordinate system and compares it to the squared radius. If the candidate falls outside, new offsets are drawn and the test repeats. The loop terminates as soon as a point satisfies the circular inequality, ensuring that the returned point is always inside the circle.

while dx*dx + dy*dy > self.r*self.r:
    dx = uniform(-self.r, +self.r)
    dy = uniform(-self.r, +self.r)

Returning the Absolute Coordinates

Once a valid offset is found, the method translates it back to the original coordinate system by adding the stored center coordinates. The result is returned as a two-element list containing the x and y values of the random point.

return [ self.x + dx, self.y + dy ]

Edge Cases Handled

The implementation gracefully handles several boundary conditions without additional code. When the radius is zero, the uniform calls always produce 0, the rejection condition evaluates to 0 > 0 (false), and the method returns the exact center point. Points that lie precisely on the circle’s perimeter satisfy dx*dx + dy*dy == self.r*self.r; because the loop condition uses a strict greater-than comparison, such points are accepted, preserving uniformity up to the boundary. Floating-point rounding errors that could otherwise cause an infinite loop are mitigated by the same strict inequality, allowing points that are infinitesimally outside due to rounding to be rejected and regenerated.

Performance Optimizations

The code leverages a few subtle choices that improve execution speed. Storing the radius and center values in short attribute names reduces attribute-lookup overhead inside the tight loop. The distance check uses multiplication (dx*dx) rather than a function call like pow, avoiding the extra function-call cost. By generating both coordinates in a single iteration of the loop, the algorithm minimizes the number of calls to the random number generator. The rejection-sampling method itself is efficient for circles because the area of the bounding square is only four times the area of the circle, leading to an average acceptance rate of π/4 (about 78 %). Consequently, most iterations exit after the first candidate, keeping the expected number of random draws low.

Overall, the class provides a concise and effective means of sampling uniformly from a circle, handling edge conditions naturally and employing straightforward optimizations that keep the runtime overhead minimal.

written by openai gpt

ELI5 - Simplified Explanation

Imagine there is a big circle drawn on a piece of paper. This code acts like a helper who wants to pick a random spot anywhere inside that circle.

First, it remembers where the middle of the circle is and how wide the circle reaches from the center. These are the three pieces of information stored at the very beginning.

When the time comes to find a spot, the helper starts by imagining a square box around the whole circle. It picks a random point somewhere inside that box.

Sometimes, because the circle is round and the box has corners, that random point might land outside the circle. To fix this, the code checks if the chosen spot is too far from the middle. If the spot is outside, it simply picks a new one over and over again until it finds one that is safely inside the circle.

Once it finds a good spot, it takes the distance from the middle and adds it to the center of the circle on the map so the final location is exactly where it needs to be.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.85 | σ = 1.73

Complexity Analysis

Time: constant
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca Python
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
halfrost Go
JoshCrozier JS
Krazune C++
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
wisdompeak C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca Python
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
halfrost Go
JoshCrozier JavaScript
Krazune C++
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
wisdompeak C++
YuriSpiridonov Python
27 links | 18 authors | 8 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

21 solutions   September 23, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality