LeetCode 478: Generate Random Point in a Circle Solution

Master LeetCode problem 478 (Generate Random Point in a Circle), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

478. Generate Random Point in a Circle

Problem Explanation

Explanation

To generate a random point within a circle, we can use the polar coordinates system. We first generate a random angle within the range [0, 2π) and a random distance within the radius. Then we convert these polar coordinates to Cartesian coordinates to get the random point inside the circle.

  1. Generate a random angle theta between 0 and 2π.
  2. Generate a random distance r between 0 and the radius.
  3. Calculate the Cartesian coordinates using the formula:
    x = x_center + r * cos(theta)
    y = y_center + r * sin(theta)
    

The probability of a random point landing inside the circle is proportional to the area of the circle, ensuring uniform distribution.

  • Time complexity: O(1) for each call to randPoint.
  • Space complexity: O(1).

Solution Code

class Solution {
    double radius, x_center, y_center;

    public Solution(double radius, double x_center, double y_center) {
        this.radius = radius;
        this.x_center = x_center;
        this.y_center = y_center;
    }

    public double[] randPoint() {
        double r = radius * Math.sqrt(Math.random());
        double theta = Math.random() * 2 * Math.PI;
        double x = x_center + r * Math.cos(theta);
        double y = y_center + r * Math.sin(theta);
        return new double[]{x, y};
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 478 (Generate Random Point in a Circle)?

This page provides optimized solutions for LeetCode problem 478 (Generate Random Point in a Circle) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 478 (Generate Random Point in a Circle)?

The time complexity for LeetCode 478 (Generate Random Point in a Circle) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 478 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 478 in Java, C++, or Python.

Back to LeetCode Solutions