Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Geometric Algorithms
  • Basic Geometry
  • Computational Geometry
  • Slope of Line
  • Point of Intersection of Two Lines
  • Closest Pair of Points
  • Convex Hull
  • Pythagorean Quadruple
  • Polygon Triangulation
Open In App
Next Article:
Count Integral points inside a Triangle
Next article icon

Queries on count of points lie inside a circle

Last Updated : 11 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given n coordinate (x, y) of points on 2D plane and Q queries. Each query contains an integer r, the task is to count the number of points lying inside or on the circumference of the circle having radius r and centered at the origin.
Examples : 
 

Input : n = 5  Coordinates:   1 1  2 2  3 3  -1 -1  4 4    Query 1: 3  Query 2: 32    Output :  3  5  For first query radius = 3, number of points lie  inside or on the circumference are (1, 1), (-1, -1),  (2, 2). There are only 3 points lie inside or on   the circumference of the circle.  For second query radius = 32, all five points are  inside the circle. 

 

The equation for the circle centered at origin (0, 0) with radius r, x2 + y2 = r2. And condition for a point at (x1, y1) to lie inside or on the circumference, x12 + y12 <= r2.
A Naive approach can be for each query, traverse through all points and check the condition. This take O(n*Q) time complexity.
An Efficient approach is to precompute x2 + y2 for each point coordinate and store them in an array p[]. Now, sort the array p[]. Then apply binary search on the array to find last index with condition p[i] <= r2 for each query.
Below is the implementation of this approach: 
 

C++




// C++ program to find number of points lie inside or
// on the circumference of circle for Q queries.
#include <bits/stdc++.h>
using namespace std;
  
// Computing the x^2 + y^2 for each given points
// and sorting them.
void preprocess(int p[], int x[], int y[], int n)
{
    for (int i = 0; i < n; i++)
        p[i] = x[i] * x[i] + y[i] * y[i];
  
    sort(p, p + n);
}
  
// Return count of points lie inside or on circumference
// of circle using binary search on p[0..n-1]
int query(int p[], int n, int rad)
{
    int start = 0, end = n - 1;
    while ((end - start) > 1) {
        int mid = (start + end) / 2;
        double tp = sqrt(p[mid]);
  
        if (tp > (rad * 1.0))
            end = mid - 1;
        else
            start = mid;
    }
  
    double tp1 = sqrt(p[start]), tp2 = sqrt(p[end]);
  
    if (tp1 > (rad * 1.0))
        return 0;
    else if (tp2 <= (rad * 1.0))
        return end + 1;
    else
        return start + 1;
}
  
// Driven Program
int main()
{
    int x[] = { 1, 2, 3, -1, 4 };
    int y[] = { 1, 2, 3, -1, 4 };
    int n = sizeof(x) / sizeof(x[0]);
  
    // Compute distances of all points and keep
    // the distances sorted so that query can
    // work in O(logn) using Binary Search.
    int p[n];
    preprocess(p, x, y, n);
  
    // Print number of points in a circle of radius 3.
    cout << query(p, n, 3) << endl;
  
    // Print number of points in a circle of radius 32.
    cout << query(p, n, 32) << endl;
    return 0;
}
 
 

Java




// JAVA Code for Queries on count of
// points lie inside a circle
import java.util.*;
  
class GFG {
  
    // Computing the x^2 + y^2 for each given points
    // and sorting them.
    public static void preprocess(int p[], int x[],
                                  int y[], int n)
    {
        for (int i = 0; i < n; i++)
            p[i] = x[i] * x[i] + y[i] * y[i];
  
        Arrays.sort(p);
    }
  
    // Return count of points lie inside or on
    // circumference of circle using binary
    // search on p[0..n-1]
    public static int query(int p[], int n, int rad)
    {
        int start = 0, end = n - 1;
        while ((end - start) > 1) {
            int mid = (start + end) / 2;
            double tp = Math.sqrt(p[mid]);
  
            if (tp > (rad * 1.0))
                end = mid - 1;
            else
                start = mid;
        }
  
        double tp1 = Math.sqrt(p[start]);
        double tp2 = Math.sqrt(p[end]);
  
        if (tp1 > (rad * 1.0))
            return 0;
        else if (tp2 <= (rad * 1.0))
            return end + 1;
        else
            return start + 1;
    }
  
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int x[] = { 1, 2, 3, -1, 4 };
        int y[] = { 1, 2, 3, -1, 4 };
        int n = x.length;
  
        // Compute distances of all points and keep
        // the distances sorted so that query can
        // work in O(logn) using Binary Search.
        int p[] = new int[n];
        preprocess(p, x, y, n);
  
        // Print number of points in a circle of
        // radius 3.
        System.out.println(query(p, n, 3));
  
        // Print number of points in a circle of
        // radius 32.
        System.out.println(query(p, n, 32));
    }
}
// This code is contributed by Arnav Kr. Mandal.
 
 

Python 3




# Python 3 program to find number of 
# points lie inside or on the circumference 
# of circle for Q queries.
import math
  
# Computing the x^2 + y^2 for each 
# given points and sorting them.
def preprocess(p, x, y, n):
    for i in range(n):
        p[i] = x[i] * x[i] + y[i] * y[i]
  
    p.sort()
  
# Return count of points lie inside 
# or on circumference of circle using
# binary search on p[0..n-1]
def query(p, n, rad):
  
    start = 0
    end = n - 1
    while ((end - start) > 1):
        mid = (start + end) // 2
        tp = math.sqrt(p[mid])
  
        if (tp > (rad * 1.0)):
            end = mid - 1
        else:
            start = mid
  
    tp1 = math.sqrt(p[start])
    tp2 = math.sqrt(p[end])
  
    if (tp1 > (rad * 1.0)):
        return 0
    else if (tp2 <= (rad * 1.0)):
        return end + 1
    else:
        return start + 1
  
# Driver Code
if __name__ == "__main__":
      
    x = [ 1, 2, 3, -1, 4 ]
    y = [ 1, 2, 3, -1, 4 ]
    n = len(x)
  
    # Compute distances of all points and keep
    # the distances sorted so that query can
    # work in O(logn) using Binary Search.
    p = [0] * n
    preprocess(p, x, y, n)
  
    # Print number of points in a 
    # circle of radius 3.
    print(query(p, n, 3))
  
    # Print number of points in a 
    # circle of radius 32.
    print(query(p, n, 32))
  
# This code is contributed by ita_c
 
 

C#




// C# Code for Queries on count of
// points lie inside a circle
using System;
  
class GFG {
  
    // Computing the x^2 + y^2 for each 
    // given points and sorting them.
    public static void preprocess(int[] p, int[] x,
                                    int[] y, int n)
    {
        for (int i = 0; i < n; i++)
            p[i] = x[i] * x[i] + y[i] * y[i];
  
        Array.Sort(p);
    }
  
    // Return count of points lie inside or on
    // circumference of circle using binary
    // search on p[0..n-1]
    public static int query(int[] p, int n, int rad)
    {
        int start = 0, end = n - 1;
        while ((end - start) > 1) {
            int mid = (start + end) / 2;
            double tp = Math.Sqrt(p[mid]);
  
            if (tp > (rad * 1.0))
                end = mid - 1;
            else
                start = mid;
        }
  
        double tp1 = Math.Sqrt(p[start]);
        double tp2 = Math.Sqrt(p[end]);
  
        if (tp1 > (rad * 1.0))
            return 0;
        else if (tp2 <= (rad * 1.0))
            return end + 1;
        else
            return start + 1;
    }
  
    /* Driver program to test above function */
    public static void Main()
    {
        int[] x = { 1, 2, 3, -1, 4 };
        int[] y = { 1, 2, 3, -1, 4 };
        int n = x.Length;
  
        // Compute distances of all points and keep
        // the distances sorted so that query can
        // work in O(logn) using Binary Search.
        int[] p = new int[n];
        preprocess(p, x, y, n);
  
        // Print number of points in a circle of
        // radius 3.
        Console.WriteLine(query(p, n, 3));
  
        // Print number of points in a circle of
        // radius 32.
        Console.WriteLine(query(p, n, 32));
    }
}
  
// This code is contributed by vt_m.
 
 

Javascript




<script>
  
// Javascript Code for Queries on count of
// points lie inside a circle
      
    // Computing the x^2 + y^2 for each given points
    // and sorting them.
    function preprocess(p,x,y,n)
    {
        for (let i = 0; i < n; i++)
            p[i] = x[i] * x[i] + y[i] * y[i];
          
        p.sort(function(a,b){return a-b;});
          
    }
      
    // Return count of points lie inside or on
    // circumference of circle using binary
    // search on p[0..n-1]
    function query(p,n,rad)
    {
        let start = 0, end = n - 1;
        while ((end - start) > 1) {
            let mid = Math.floor((start + end) / 2);
            let tp = Math.sqrt(p[mid]);
    
            if (tp > (rad * 1.0))
                end = mid - 1;
            else
                start = mid;
        }
    
        let tp1 = Math.sqrt(p[start]);
        let tp2 = Math.sqrt(p[end]);
    
        if (tp1 > (rad * 1.0))
            return 0;
        else if (tp2 <= (rad * 1.0))
            return end + 1;
        else
            return start + 1;
    }
      
    /* Driver program to test above function */
    let x=[1, 2, 3, -1, 4 ];
    let y=[1, 2, 3, -1, 4];
    let n = x.length;
      
    // Compute distances of all points and keep
    // the distances sorted so that query can
    // work in O(logn) using Binary Search.
    let p=new Array(n);
    for(let i=0;i<n;i++)
    {
        p[i]=0;
    }
    preprocess(p, x, y, n);
  
    // Print number of points in a circle of
    // radius 3.
    document.write(query(p, n, 3)+"<br>");
  
    // Print number of points in a circle of
    // radius 32.
    document.write(query(p, n, 32)+"<br>");
      
    // This code is contributed by rag2127
      
</script>
 
 

Output: 

3  5

Time Complexity: O(n log n) for preprocessing and O(Q Log n) for Q queries.
Auxiliary Space: O(n) it is using extra space for array p

 



Next Article
Count Integral points inside a Triangle

A

Aarti_Rathi and Anuj Chauhan
Improve
Article Tags :
  • DSA
  • Geometric
  • Binary Search
Practice Tags :
  • Binary Search
  • Geometric

Similar Reads

  • Count points from an array that lies inside a semi-circle
    Given two pairs (X, Y), (P, Q) and R the coordinate of the center of semi-circle, coordinate of the intersection of semicircle and diameter of the semicircle and, the radius of the semicircle, and an array arr[] of dimension N*2 consisting of the coordinates of few points, the task is to find the nu
    7 min read
  • Non-crossing lines to connect points in a circle
    Consider a circle with n points on circumference of it where n is even. Count number of ways we can connect these points such that no two connecting lines to cross each other and every point is connected with exactly one other point. Any point can be connected with any other point. Consider a circle
    10 min read
  • Find if a point lies inside a Circle
    Given a circle (coordinates of centre and radius) and a point (coordinate), find if the point lies inside or on the circle, or not. Examples : Input: x = 4, y = 4 // Given Point circle_x = 1, circle_y = 1, rad = 6; // Circle Output: Inside Input: x = 3, y = 3 // Given Point circle_x = 0, circle_y =
    5 min read
  • Count Integral points inside a Triangle
    Given three non-collinear integral points in XY plane, find the number of integral points inside the triangle formed by the three points. (A point in XY plane is said to be integral/lattice point if both its co-ordinates are integral). Example: Input: p = (0, 0), q = (0, 5) and r = (5,0) Output: 6Ex
    8 min read
  • Count the number of circles at edges
    Given a line. At each level, that line can be divided into either two new lines or end up with a circle at its edge. An array X[] of size N is given to you, in which each X[i] denotes the number of circles at the ith level for (1? i ? N). Then you must determine whether X[] meets the above condition
    6 min read
  • Count of integral coordinates that lies inside a Square
    Given lower left and upper right coordinates (x1, y1) and (x2, y2) of a square, the task is to count the number of integral coordinates that lies strictly inside the square.Examples: Input: x1 = 1, y1 = 1, x2 = 5, x3 = 5 Output: 9 Explanation: Below is the square for the given coordinates: Input: x1
    4 min read
  • Find if a point lies inside, outside or on the circumcircle of three points A, B, C
    Given four non-collinear points A, B, C, and P. The task is to find whether point P lies inside, outside or on the circumcircle formed by points A, B, and C.Examples Input: A = {2, 8}, B = {2, 1}, C = {4, 5}, P = {2, 4}; Output: Point (2, 4) is inside the circumcircle. Input: A = {2, 8}, B = {2, 1},
    15+ min read
  • Count distinct points visited on the number line
    Given a person who is at position current_pos and a binary string path which is the moves the person took, if path[i] = '0' then the person moved one step left, and if path[i] = '1' then the person moved one step to the right. The task is to find the count of distinct positions the person visited. E
    9 min read
  • Count ways to divide circle using N non-intersecting chords
    Given a number N, find the number of ways you can draw N chords in a circle with 2*N points such that no 2 chords intersect. Two ways are different if there exists a chord which is present in one way and not in other.Examples: Input : N = 2 Output : 2 Explanation: If points are numbered 1 to 4 in cl
    5 min read
  • Find N random points within a Circle
    Given four integers N, R, X, and Y such that it represents a circle of radius R with [X, Y] as coordinates of the center. The task is to find N random points inside or on the circle. Examples: Input: R = 12, X = 3, Y = 3, N = 5 Output: (7.05, -3.36) (5.21, -7.49) (7.53, 0.19) (-2.37, 12.05) (1.45, 1
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences