Monte Carlo Pi Estimation

Easy · Coding & Algorithms · Frontend Engineer · Technical Screen

Problem Statement

Given a list pts of 2D coordinates sampled from the unit square [0, 1] x [0, 1], implement approx(pts: List[List[float]]) -> float to estimate pi from geometric area ratios.

Every item in pts is a two-element numeric list [x, y] satisfying 0 <= x <= 1 and 0 <= y <= 1. Consider the origin-centered quarter disk of radius 1 inside this square: a coordinate [x, y] counts as inside the quarter disk whenever x * x + y * y <= 1 (points sitting right on the circular boundary x * x + y * y == 1 are included).

Because the unit square has area 1 while the quarter disk has area pi / 4, the proportion of points in pts that fall inside the quarter disk approximates pi / 4. Multiply that proportion by 4 and return the resulting floating-point estimate of pi.

Examples

Example 1

Input:  pts = [[0.2, 0.3], [0.5, 0.5], [1.0, 0.0], [0.8, 0.7], [0.9, 0.6]]
Output: 2.4

Walk-through: Computing x * x + y * y gives 0.13, 0.50, 1.00, 1.13, and 1.17. The first three satisfy <= 1 (including [1.0, 0.0] on the boundary), so 3 out of 5 points qualify and 4 * (3 / 5) = 2.4.

Example 2

Input:  pts = [[0.0, 0.0], [0.25, 0.25], [0.4, 0.7], [0.6, 0.8], [0.7, 0.5], [0.1, 0.9], [0.5, 0.8], [0.9, 0.9]]
Output: 3.5

Walk-through: Seven of the eight coordinates satisfy x * x + y * y <= 1 ([0.6, 0.8] lies directly on the arc since 0.36 + 0.64 = 1.0, while [0.9, 0.9] gives 1.62 > 1), producing 4 * (7 / 8) = 3.5.

Example 3

Input:  pts = [[0.3, 0.4], [1.0, 1.0]]
Output: 2.0

Walk-through: [0.3, 0.4] lies inside (0.25 <= 1) and [1.0, 1.0] lies outside (2.0 > 1), giving 4 * (1 / 2) = 2.0.

Constraints

  • pts is never None and always contains at least 1 coordinate pair.
  • Every element in pts has length 2 with numeric coordinates 0 <= x <= 1 and 0 <= y <= 1.
  • Return the exact floating-point result without rounding, in O(len(pts)) time and O(1) extra space.

Step-by-step walkthrough

  1. Understand the goal and inputs

    We are given pts, a non-empty list of 2D coordinates [x, y] inside the unit square (0 <= x <= 1 and 0 <= y <= 1). Our job is not to generate new random points — instead, we use the exact points provided in pts, check what fraction of them fall inside (or on) the quarter circle of radius 1 centered at (0, 0), and scale that fraction into an estimate of pi.

    Because pts always has at least one point, we never have to worry about dividing by zero.

  2. Connect area ratios to pi

    Why does counting points in a square tell us anything about pi? Picture the 1 x 1 unit square in the first quadrant (x >= 0, y >= 0) with a circle of radius r = 1 centered at (0, 0):

    y = 1 +---------._        Unit square area     = 1 * 1 = 1
          | inside    '-.     Full circle area     = pi * 1^2 = pi
          |   x^2+y^2<=1 \    Quarter-circle area  = pi / 4
          |               \
    y = 0 +----------------+  outside: corners near (1, 1) have x^2 + y^2 > 1
        x = 0            x = 1
    

    Let's trace the algebra one step at a time:

    1. A full circle of radius r = 1 has area pi * r * r = pi.
    2. Only the top-right quarter of that circle lies inside 0 <= x <= 1 and 0 <= y <= 1, so the shaded region has area pi / 4.
    3. The entire 1 x 1 unit square has area 1 * 1 = 1.
    4. When points are spread evenly across the unit square, the fraction landing inside the quarter circle matches the ratio of the two areas:
    inside_count / total_points  ≈  (pi / 4) / 1  =  pi / 4
    
    1. Multiply both sides by 4 to isolate pi:
    pi  ≈  4 * (inside_count / total_points)
    
  3. Check whether a point is inside without square roots

    By the Pythagorean theorem, the straight-line distance from (0, 0) to (x, y) is sqrt(x * x + y * y). A point lies within radius 1 when:

    sqrt(x * x + y * y) <= 1
    

    Because distances are never negative, squaring both sides preserves the exact inequality (1 * 1 = 1):

    x * x + y * y <= 1
    

    Skipping math.sqrt makes the loop faster and avoids extra floating-point rounding. Pay special attention to <= rather than <: points sitting right on the circular arc — such as [1, 0], [0, 1], or [0.6, 0.8] (since 0.36 + 0.64 = 1.0) — must count as inside. Also make sure to use / (true floating-point division in Python) rather than // (integer division, which would chop 3.2 down to 3).

    def approx(pts: List[List[float]]) -> float:
        # inside_count: number of input points [x, y] that lie inside or on the unit quarter circle.
        inside_count = 0
    
        for x, y in pts:
            # A point's distance from (0, 0) is sqrt(x^2 + y^2). Comparing squared distance <= 1^2
            # avoids a square root, and <= includes points lying directly on the circle arc.
            squared_distance = x * x + y * y
            if squared_distance <= 1:
                inside_count += 1
    
        # The quarter circle of radius 1 has area pi / 4 inside the 1 x 1 unit square (area 1),
        # so inside_fraction approximates pi / 4; multiplying by 4.0 recovers pi.
        total_points = len(pts)
        inside_fraction = inside_count / total_points
        return 4.0 * inside_fraction
    
  4. Trace Example 1 step by step

    Let's walk through pts = [[0.2, 0.3], [0.5, 0.5], [1.0, 0.0], [0.8, 0.7], [0.9, 0.6]]:

    Point        x*x + y*y              <= 1?    inside_count
    ---------------------------------------------------------
    [0.2, 0.3]   0.04 + 0.09 = 0.13     Yes      1
    [0.5, 0.5]   0.25 + 0.25 = 0.50     Yes      2
    [1.0, 0.0]   1.00 + 0.00 = 1.00     Yes      3   (on the boundary!)
    [0.8, 0.7]   0.64 + 0.49 = 1.13     No       3
    [0.9, 0.6]   0.81 + 0.36 = 1.17     No       3
    
    total_points    = 5
    inside_fraction = 3 / 5 = 0.6
    estimate        = 4.0 * 0.6 = 2.4
    

    Notice how using < instead of <= would drop [1.0, 0.0], returning 1.6 instead of 2.4.

  5. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def approx(pts: List[List[float]]) -> float:
        # inside_count: number of input points [x, y] that lie inside or on the unit quarter circle.
        inside_count = 0
    
        for x, y in pts:
            # A point's distance from (0, 0) is sqrt(x^2 + y^2). Comparing squared distance <= 1^2
            # avoids a square root, and <= includes points lying directly on the circle arc.
            squared_distance = x * x + y * y
            if squared_distance <= 1:
                inside_count += 1
    
        # The quarter circle of radius 1 has area pi / 4 inside the 1 x 1 unit square (area 1),
        # so inside_fraction approximates pi / 4; multiplying by 4.0 recovers pi.
        total_points = len(pts)
        inside_fraction = inside_count / total_points
        return 4.0 * inside_fraction
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine taping a 1 m × 1 m square sheet of paper to a wall, drawing a quarter-circle arc of radius 1 m centered at the bottom-left corner (0, 0), and throwing blindfolded darts that land evenly across the square. Because the whole square has area 1 and the quarter circle has area pi / 4, roughly pi / 4 (about 78.5%) of the darts land inside the arc. Multiplying that hit fraction by 4 turns the dart count directly into an estimate of pi! Approximating an exact number by measuring random samples like this is called Monte Carlo estimation (using repeated random sampling to estimate numerical quantities).

Why do hasty implementations go wrong? Returning the raw fraction inside_count / len(pts) estimates pi / 4 ≈ 0.785 instead of pi ≈ 3.1416. Using strict < 1 instead of <= 1 rejects points sitting directly on the circle arc (such as [1.0, 0.0] in Example 1 or [0.6, 0.8] in Example 2), and using integer division // truncates fractional results like 2.4 down to 2.

Here is a quick trace on Example 1 (pts = [[0.2, 0.3], [0.5, 0.5], [1.0, 0.0], [0.8, 0.7], [0.9, 0.6]]):

[0.2, 0.3] -> 0.04 + 0.09 = 0.13 <= 1  (inside)
[0.5, 0.5] -> 0.25 + 0.25 = 0.50 <= 1  (inside)
[1.0, 0.0] -> 1.00 + 0.00 = 1.00 <= 1  (inside, on boundary)
[0.8, 0.7] -> 0.64 + 0.49 = 1.13 >  1  (outside)
[0.9, 0.6] -> 0.81 + 0.36 = 1.17 >  1  (outside)

3 out of 5 points inside -> 4.0 * (3 / 5) = 2.4

Complexity

Let N be len(pts), the number of points in the input list.

  • Time: O(N), because we loop through the N points once and perform two multiplications, one addition, and one comparison (O(1) work) per point, followed by one final division and multiplication.
  • Space: O(1) extra, because we only keep scalar variables (inside_count, squared_distance, total_points, inside_fraction) regardless of how large pts is.

Edge cases

  • Single point (len(pts) == 1): Returns 4.0 if the lone point satisfies x * x + y * y <= 1, or 0.0 if it lies outside.
  • Points right on the arc ([1.0, 0.0], [0.0, 1.0], [0.6, 0.8]): Count as inside because the boundary check uses <= 1.
  • Opposite corners of the square: [0.0, 0.0] gives 0 <= 1 (inside), whereas [1.0, 1.0] gives 2 > 1 (outside).
  • Duplicate points: Each occurrence in pts represents an independent sample and is counted separately.
  • Repeating decimals: 1 point inside out of 3 returns 4.0 / 3 (1.333333...) without rounding to an integer.
  • Floating-point rounding right on the circle: Binary floating-point arithmetic rounds intermediate products, so evaluate x * x + y * y <= 1 literally without adding an arbitrary tolerance like 1 + 1e-9 — that way our check agrees with any judge evaluating the exact rule in the problem statement.

Common mistakes

  • Forgetting to multiply by 4: Returning inside_count / len(pts) gives pi / 4 instead of pi.
  • Writing < 1 instead of <= 1: Excludes exact boundary points on the circle of radius 1.
  • Using integer division (//): Truncates 4 * 3 // 5 to 2 instead of 2.4.
  • Centering the circle at (0.5, 0.5) with radius 0.5: An inscribed full circle also covers pi / 4 of the unit square in theory, but it disagrees with the problem's rule x * x + y * y <= 1 (for example, (0, 0) would be outside!).

Follow-up questions

  • How rapidly does the estimation error shrink as you increase the sample count N? Each uniformly random point lands inside the quarter circle with probability p = pi / 4, so the count inside follows a binomial distribution (the distribution of the number of successes across N independent yes/no trials). The standard error (typical random fluctuation of the estimate around the true value pi) of 4 * inside_count / N is 4 * sqrt(p * (1 - p) / N) ≈ 1.64 / sqrt(N). Because sqrt(N) grows slowly, gaining one extra decimal digit of accuracy (10x smaller error) requires 100x more random points — making Monte Carlo great for high-dimensional integrals, though deterministic series are vastly faster for computing digits of pi.
  • If you generated the random coordinates inside the function instead of receiving an array, how could you keep memory usage O(1)? Sample x and y independently from a uniform random number generator on [0, 1) (such as Python's random.random() or JavaScript's Math.random()) inside a loop and increment inside_count on the fly without ever storing a list of [x, y] pairs. That keeps memory strictly O(1) even for N = 100,000,000 samples.
  • How would you compute 50 million samples in a web application without blocking UI rendering? Running 50 million loop iterations synchronously on the browser's main UI thread blocks clicks, scrolling, and animations until the loop finishes. Instead, offload the loop to a Web Worker (a background browser thread that runs JavaScript off the main UI thread) — or split the work into small chunks of 100,000 points scheduled across frames with requestAnimationFrame — and combine partial results simply by summing inside_count and total_points across batches.

Follow-up questions

Similar questions

More Toma interview questions

All 4 Toma questions →