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
ptsis neverNoneand always contains at least1coordinate pair.- Every element in
ptshas length2with numeric coordinates0 <= x <= 1and0 <= y <= 1. - Return the exact floating-point result without rounding, in
O(len(pts))time andO(1)extra space.
Step-by-step walkthrough
Understand the goal and inputs
We are given
pts, a non-empty list of 2D coordinates[x, y]inside the unit square (0 <= x <= 1and0 <= y <= 1). Our job is not to generate new random points — instead, we use the exact points provided inpts, check what fraction of them fall inside (or on) the quarter circle of radius1centered at(0, 0), and scale that fraction into an estimate ofpi.Because
ptsalways has at least one point, we never have to worry about dividing by zero.Connect area ratios to pi
Why does counting points in a square tell us anything about
pi? Picture the1 x 1unit square in the first quadrant (x >= 0, y >= 0) with a circle of radiusr = 1centered 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 = 1Let's trace the algebra one step at a time:
- A full circle of radius
r = 1has areapi * r * r = pi. - Only the top-right quarter of that circle lies inside
0 <= x <= 1and0 <= y <= 1, so the shaded region has areapi / 4. - The entire
1 x 1unit square has area1 * 1 = 1. - 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- Multiply both sides by
4to isolatepi:
pi ≈ 4 * (inside_count / total_points)- A full circle of radius
Check whether a point is inside without square roots
By the Pythagorean theorem, the straight-line distance from
(0, 0)to(x, y)issqrt(x * x + y * y). A point lies within radius1when:sqrt(x * x + y * y) <= 1Because distances are never negative, squaring both sides preserves the exact inequality (
1 * 1 = 1):x * x + y * y <= 1Skipping
math.sqrtmakes 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](since0.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 chop3.2down to3).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_fractionTrace 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.4Notice how using
<instead of<=would drop[1.0, 0.0], returning1.6instead of2.4.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 theNpoints 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 largeptsis.
Edge cases
- Single point (
len(pts) == 1): Returns4.0if the lone point satisfiesx * x + y * y <= 1, or0.0if 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]gives0 <= 1(inside), whereas[1.0, 1.0]gives2 > 1(outside). - Duplicate points: Each occurrence in
ptsrepresents an independent sample and is counted separately. - Repeating decimals:
1point inside out of3returns4.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 <= 1literally without adding an arbitrary tolerance like1 + 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: Returninginside_count / len(pts)givespi / 4instead ofpi. - Writing
< 1instead of<= 1: Excludes exact boundary points on the circle of radius1. - Using integer division (
//): Truncates4 * 3 // 5to2instead of2.4. - Centering the circle at
(0.5, 0.5)with radius0.5: An inscribed full circle also coverspi / 4of the unit square in theory, but it disagrees with the problem's rulex * 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 acrossNindependent yes/no trials). The standard error (typical random fluctuation of the estimate around the true valuepi) of4 * inside_count / Nis4 * sqrt(p * (1 - p) / N) ≈ 1.64 / sqrt(N). Becausesqrt(N)grows slowly, gaining one extra decimal digit of accuracy (10xsmaller error) requires100xmore random points — making Monte Carlo great for high-dimensional integrals, though deterministic series are vastly faster for computing digits ofpi. - If you generated the random coordinates inside the function instead of receiving an array, how could you keep memory usage O(1)? Sample
xandyindependently from a uniform random number generator on[0, 1)(such as Python'srandom.random()or JavaScript'sMath.random()) inside a loop and incrementinside_counton the fly without ever storing a list of[x, y]pairs. That keeps memory strictlyO(1)even forN = 100,000,000samples. - 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 summinginside_countandtotal_pointsacross batches.
Follow-up questions
- How rapidly does the estimation error shrink as you increase the sample count N?
- If you generated the random coordinates inside the function instead of receiving an array, how could you keep memory usage O(1)?
- How would you compute 50 million samples in a web application without blocking UI rendering?
Similar questions
- Multi-Track Audio Stream Mixer
- CSS Channel Color Function
- CSS Color Functions for Alpha Transparency
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses