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 ]
Difficulty
and has an acceptance rate of about 43% (100k+ submissions).
Typical patterns to solve this problem:
- Geometry
- Math
- Randomized
- Rejection Sampling
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 470: Implement Rand10() Using Rand7()
- problem 497: Random Point in Non-overlapping Rectangles
Solved On The Same Day
- problem 680: Valid Palindrome II
- problem 497: Random Point in Non-overlapping Rectangles
- problem 519: Random Flip Matrix
- problem 581: Shortest Unsorted Continuous Subarray
- problem 659: Split Array into Consecutive Subsequences
- problem 738: Monotone Increasing Digits
- problem 743: Network Delay Time
- problem 769: Max Chunks To Make Sorted
- problem 985: Sum of Even Numbers After Queries
- problem 1048: Longest String Chain
- problem 1094: Car Pooling
- problem 1324: Print Words Vertically
- problem 1680: Concatenation of Consecutive Binary Numbers
- problem 1823: Find the Winner of the Circular Game
- problem 1860: Incremental Memory Leak
- problem 1922: Count Good Numbers
- problem 2487: Remove Nodes From Linked List
- problem 381: Insert Delete GetRandom O(1) - Duplicates allowed
- problem 517: Super Washing Machines
- problem 632: Smallest Range Covering Elements from K Lists
Extra
- 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