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 Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
XOR of numbers that appeared even number of times in given Range
Next article icon

Numbsubarrayer of elements less than or equal to a given number in a given

Last Updated : 27 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array ‘a[]’ and number of queries q. Each query can be represented by l, r, x. Your task is to print the number of elements less than or equal to x in the subarray represented by l to r. Examples:

Input : arr[] = {2, 3, 4, 5}             q = 2             0 3 5             0 2 2  Output : 4          1 Number of elements less than or equal to 5 in arr[0..3] is 4 (all elements)  Number of elements less than or equal to 2 in arr[0..2] is 1 (only 2)

Naive approach The naive approach for each query traverse the subarray and count the number of elements which are in the given range. 

Efficient Approach The idea is to use-Binary Index Tree. Note in the following steps x is the number according to which you have to find the elements and the subarray is represented by l, r. Step 1: Sort the array in ascending order. Step 2: Sort the queries according to x in ascending order, initialize bit array as 0. Step 3: Start from the first query and traverse the array till the value in the array is less than equal to x. For each such element update the BIT with value equal to 1 Step 4: Query the BIT array in the range l to r 

CPP




// C++ program to answer queries to count number
// of elements smaller than or equal to x.
#include<bits/stdc++.h>
using namespace std;
  
// structure to hold queries
struct Query
{
    int l, r, x, idx;
};
  
// structure to hold array
struct ArrayElement
{
    int val, idx;
};
  
// bool function to sort queries according to k
bool cmp1(Query q1, Query q2)
{
    return q1.x < q2.x;
}
  
// bool function to sort array according to its value
bool cmp2(ArrayElement x, ArrayElement y)
{
    return x.val < y.val;
}
  
// updating the bit array
void update(int bit[], int idx, int val, int n)
{
    for (; idx<=n; idx +=idx&-idx)
        bit[idx] += val;
}
  
// querying the bit array
int query(int bit[], int idx, int n)
{
    int sum = 0;
    for (; idx > 0; idx -= idx&-idx)
        sum += bit[idx];
    return sum;
}
  
void answerQueries(int n, Query queries[], int q,
                              ArrayElement arr[])
{
    // initialising bit array
    int bit[n+1];
    memset(bit, 0, sizeof(bit));
  
    // sorting the array
    sort(arr, arr+n, cmp2);
  
    // sorting queries
    sort(queries, queries+q, cmp1);
  
    // current index of array
    int curr = 0;
  
    // array to hold answer of each Query
    int ans[q];
  
    // looping through each Query
    for (int i=0; i<q; i++)
    {
        // traversing the array values till it
        // is less than equal to Query number
        while (arr[curr].val <= queries[i].x && curr<n)
        {
            // updating the bit array for the array index
            update(bit, arr[curr].idx+1, 1, n);
            curr++;
        }
  
        // Answer for each Query will be number of
        // values less than equal to x upto r minus
        // number of values less than equal to x
        // upto l-1
        ans[queries[i].idx] = query(bit, queries[i].r+1, n) -
                              query(bit, queries[i].l, n);
    }
  
    // printing answer for each Query
    for (int i=0 ; i<q; i++)
        cout << ans[i] << endl;
}
  
// driver function
int main()
{
    // size of array
    int n = 4;
  
    // initialising array value and index
    ArrayElement arr[n];
    arr[0].val = 2;
    arr[0].idx = 0;
    arr[1].val = 3;
    arr[1].idx = 1;
    arr[2].val = 4;
    arr[2].idx = 2;
    arr[3].val = 5;
    arr[3].idx = 3;
  
    // number of queries
    int q = 2;
    Query queries[q];
    queries[0].l = 0;
    queries[0].r = 2;
    queries[0].x = 2;
    queries[0].idx = 0;
    queries[1].l = 0;
    queries[1].r = 3;
    queries[1].x = 5;
    queries[1].idx = 1;
  
    answerQueries(n, queries, q, arr);
  
    return 0;
}
 
 

Java




// Java program to answer queries to count number
// of elements smaller than or equal to x.
 
import java.util.*;
 
// structure to hold queries
class Query
{
    int l, r, x, idx;
 
    public Query(int l, int r, int x, int idx) {
        this.l = l;
        this.r = r;
        this.x = x;
        this.idx = idx;
    }
}
 
// structure to hold array
class ArrayElement implements Comparable<ArrayElement>
{
    int val, idx;
 
    public ArrayElement(int val, int idx) {
        this.val = val;
        this.idx = idx;
    }
 
    // bool function to sort array according to its value
    public int compareTo(ArrayElement other) {
        return Integer.compare(this.val, other.val);
    }
}
 
public class GFG
{
    // bool function to sort queries according to k
    static boolean cmp1(Query q1, Query q2)
    {
        return q1.x < q2.x;
    }
 
    // updating the bit array
    static void update(int bit[], int idx, int val, int n)
    {
        for (; idx<=n; idx +=idx&-idx)
            bit[idx] += val;
    }
 
    // querying the bit array
    static int query(int bit[], int idx, int n)
    {
        int sum = 0;
        for (; idx > 0; idx -= idx&-idx)
            sum += bit[idx];
        return sum;
    }
 
    static void answerQueries(int n, Query queries[], int q,
                              ArrayElement arr[])
    {
        // initialising bit array
        int bit[] = new int[n+1];
        Arrays.fill(bit, 0);
 
        // sorting the array
        Arrays.sort(arr);
 
        // sorting queries
        Arrays.sort(queries, (q1, q2) -> Integer.compare(q1.x, q2.x));
 
        // current index of array
        int curr = 0;
 
        // array to hold answer of each Query
        int ans[] = new int[q];
 
        // looping through each Query
        for (int i=0; i<q; i++)
        {
            // traversing the array values till it
            // is less than equal to Query number
            while (curr < n && arr[curr].val <= queries[i].x)
            {
                // updating the bit array for the array index
                update(bit, arr[curr].idx+1, 1, n);
                curr++;
            }
 
            // Answer for each Query will be number of
            // values less than equal to x upto r minus
            // number of values less than equal to x
            // upto l-1
            ans[queries[i].idx] = query(bit, queries[i].r+1, n) -
                              query(bit, queries[i].l, n);
        }
 
        // printing answer for each Query
        for (int i=0 ; i<q; i++)
            System.out.println(ans[i]);
    }
 
    public static void main(String[] args) {
    // size of array
    int n = 4;
 
    // initializing array value and index
    ArrayElement[] arr = new ArrayElement[n];
    arr[0] = new ArrayElement(2, 0);
    arr[1] = new ArrayElement(3, 1);
    arr[2] = new ArrayElement(4, 2);
    arr[3] = new ArrayElement(5, 3);
 
    // number of queries
    int q = 2;
    Query[] queries = new Query[q];
    queries[0] = new Query(0, 2, 2, 0);
    queries[1] = new Query(0, 3, 5, 1);
 
    answerQueries(n, queries, q, arr);
    }
}
 
//this code is contributed by bhardwajji
 
 

Python3




from functools import cmp_to_key
import bisect
 
# structure to hold queries
class Query:
    def __init__(self, l, r, x, idx):
        self.l = l
        self.r = r
        self.x = x
        self.idx = idx
   
# structure to hold array
class ArrayElement:
    def __init__(self, val, idx):
        self.val = val
        self.idx = idx
   
# bool function to sort queries according to k
def cmp1(q1, q2):
    if q1.x != q2.x:
        return q1.x - q2.x
    else:
        return q1.r - q2.r
   
# bool function to sort array according to its value
def cmp2(x, y):
    if x.val != y.val:
        return x.val - y.val
    else:
        return x.idx - y.idx
   
# updating the bit array
def update(bit, idx, val, n):
    while idx <= n:
        bit[idx] += val
        idx += idx & -idx
   
# querying the bit array
def query(bit, idx, n):
    sum = 0
    while idx > 0:
        sum += bit[idx]
        idx -= idx & -idx
    return sum
   
def answerQueries(n, queries, q, arr):
    # initialising bit array
    bit = [0] * (n + 1)
   
    # sorting the array
    arr = sorted(arr, key=cmp_to_key(cmp2))
   
    # sorting queries
    queries = sorted(queries, key=cmp_to_key(cmp1))
   
    # current index of array
    curr = 0
   
    # array to hold answer of each Query
    ans = [0] * q
   
    # looping through each Query
    for i in range(q):
        # traversing the array values till it
        # is less than equal to Query number
        while curr < n and arr[curr].val <= queries[i].x:
            # updating the bit array for the array index
            update(bit, arr[curr].idx+1, 1, n)
            curr += 1
   
        # Answer for each Query will be number of
        # values less than equal to x upto r minus
        # number of values less than equal to x
        # upto l-1
        ans[queries[i].idx] = query(bit, queries[i].r+1, n) - query(bit, queries[i].l, n)
   
    # printing answer for each Query
    for i in range(q):
        print(ans[i])
   
# driver function
if __name__ == '__main__':
    # size of array
    n = 4
   
    # initialising array value and index
    arr = [ArrayElement(2, 0), ArrayElement(3, 1), ArrayElement(4, 2), ArrayElement(5, 3)]
   
    # number of queries
    q = 2
    queries = [Query(0, 2, 2, 0), Query(0, 3, 5, 1)]
   
    answerQueries(n, queries, q, arr)
 
 

C#




// C# program to answer queries to count number
// of elements smaller than or equal to x.
using System;
using System.Linq;
 
// structure to hold queries
class Query
{
    public int l, r, x, idx;
 
    public Query(int l, int r, int x, int idx) {
        this.l = l;
        this.r = r;
        this.x = x;
        this.idx = idx;
    }
}
 
// structure to hold array
class ArrayElement : IComparable<ArrayElement>
{
    public int val, idx;
     
    public ArrayElement(int val, int idx) {
        this.val = val;
        this.idx = idx;
    }
 
    // bool function to sort array according to its value
    public int CompareTo(ArrayElement other) {
        return this.val.CompareTo(other.val);
    }
}
 
public class GFG
{
    // bool function to sort queries according to k
    static bool cmp1(Query q1, Query q2)
    {
        return q1.x < q2.x;
    }
    // updating the bit array
    static void update(int[] bit, int idx, int val, int n)
    {
        for (; idx <= n; idx += idx & -idx)
            bit[idx] += val;
    }
 
    // querying the bit array
    static int query(int[] bit, int idx, int n)
    {
        int sum = 0;
        for (; idx > 0; idx -= idx & -idx)
            sum += bit[idx];
        return sum;
    }
 
    static void answerQueries(int n, Query[] queries, int q, ArrayElement[] arr)
    {
        // initialising bit array
        int[] bit = new int[n + 1];
        Array.Fill(bit, 0);
     
        // sorting the array
        Array.Sort(arr);
     
        // sorting queries
        Array.Sort(queries, (q1, q2) => q1.x.CompareTo(q2.x));
 
        // current index of array
        int curr = 0;
 
        // array to hold answer of each Query
        int[] ans = new int[q];
 
        // looping through each Query
        for (int i = 0; i < q; i++)
        {
            // traversing the array values till it
            // is less than equal to Query number
            while (curr < n && arr[curr].val <= queries[i].x)
            {
                // updating the bit array for the array index
                update(bit, arr[curr].idx + 1, 1, n);
                curr++;
            }
 
            // Answer for each Query will be number of
            // values less than equal to x upto r minus
            // number of values less than equal to x
            // upto l-1
            ans[queries[i].idx] = query(bit, queries[i].r + 1, n) -
                            query(bit, queries[i].l, n);
        }
 
        // printing answer for each Query
        for (int i = 0; i < q; i++)
            Console.WriteLine(ans[i]);
    }
 
    public static void Main(string[] args)
    {
        // size of array
        int n = 4;
     
        // initializing array value and index
        ArrayElement[] arr = new ArrayElement[n];
        arr[0] = new ArrayElement(2, 0);
        arr[1] = new ArrayElement(3, 1);
        arr[2] = new ArrayElement(4, 2);
        arr[3] = new ArrayElement(5, 3);
 
        // number of queries
        int q = 2;
        Query[] queries = new Query[q];
        queries[0] = new Query(0, 2, 2, 0);
        queries[1] = new Query(0, 3, 5, 1);
 
        answerQueries(n, queries, q, arr);
    }
}
// This code is contributed by prasad264
 
 

Javascript




// JavaScript program to answer queries to count number
// of elements smaller than or equal to x.
 
// structure to hold queries
class Query {
constructor(l, r, x, idx) {
this.l = l;
this.r = r;
this.x = x;
this.idx = idx;
}
}
 
// structure to hold array
class ArrayElement {
constructor(val, idx) {
this.val = val;
this.idx = idx;
}
 
// function to compare array elements
static compare(a, b) {
return a.val - b.val;
}
}
 
function answerQueries(n, queries, q, arr) {
// initialising bit array
let bit = new Array(n + 1).fill(0);
 
// sorting the array
arr.sort(ArrayElement.compare);
 
// sorting queries
queries.sort((q1, q2) => q1.x - q2.x);
 
// current index of array
let curr = 0;
 
// array to hold answer of each Query
let ans = new Array(q).fill(0);
 
// looping through each Query
for (let i = 0; i < q; i++) {
// traversing the array values till it
// is less than equal to Query number
while (curr < n && arr[curr].val <= queries[i].x) {
// updating the bit array for the array index
update(bit, arr[curr].idx + 1, 1, n);
curr++;
}
 
 
// Answer for each Query will be number of
// values less than equal to x upto r minus
// number of values less than equal to x
// upto l-1
ans[queries[i].idx] =
  query(bit, queries[i].r + 1, n) - query(bit, queries[i].l, n);
}
 
// printing answer for each Query
for (let i = 0; i < q; i++) {
console.log(ans[i]);
}
}
 
// bool function to sort queries according to k
function cmp1(q1, q2) {
return q1.x < q2.x;
}
 
// updating the bit array
function update(bit, idx, val, n) {
for (; idx <= n; idx += idx & -idx) bit[idx] += val;
}
 
// querying the bit array
function query(bit, idx, n) {
let sum = 0;
for (; idx > 0; idx -= idx & -idx) sum += bit[idx];
return sum;
}
 
// size of array
let n = 4;
 
// initializing array value and index
let arr = [
new ArrayElement(2, 0),
new ArrayElement(3, 1),
new ArrayElement(4, 2),
new ArrayElement(5, 3),
];
 
// number of queries
let q = 2;
let queries = [
new Query(0, 2, 2, 0),
new Query(0, 3, 5, 1),
];
 
answerQueries(n, queries, q, arr);
 
 

Output:

1 4

Time Complexity: O((n+q)*log(n))

Auxiliary Space: O(n+q)



Next Article
XOR of numbers that appeared even number of times in given Range

A

Ayush Jha
Improve
Article Tags :
  • Advanced Data Structure
  • DSA
  • array-range-queries
  • Binary Indexed Tree
Practice Tags :
  • Advanced Data Structure

Similar Reads

  • Number of elements less than or equal to a given number in a given subarray | Set 2 (Including Updates)
    Given an array 'a[]' and number of queries q there will be two type of queries Query 0 update(i, v) : Two integers i and v which means set a[i] = vQuery 1 count(l, r, k): We need to print number of integers less than equal to k in the subarray l to r. Given a[i], v <= 10000 Examples : Input : arr
    12 min read
  • Number of elements less than or equal to a number in a subarray : MO's Algorithm
    Given an array arr of size N and Q queries of the form L, R and X, the task is to print the number of elements less than or equal to X in the subarray represented by L to R. Prerequisites: MO's Algorithm, Sqrt Decomposition Examples: Input: arr[] = {2, 3, 4, 5} Q = {{0, 3, 5}, {0, 2, 2}} Output: 4 1
    15+ min read
  • Number of ways to select K small even number from left of each element in given Array
    Given an array, arr[] consisting of N distinct integers and a positive integer K, the task is to find the number of ways to select K elements from the left side of the every ith position such that the elements are even and less than arr[i]. Examples: Input: arr[] = {4, 2, 12, 33}, K = 2Output: 0 0 1
    8 min read
  • Count elements less than or equal to a given value in a sorted rotated array
    Given a sorted array of n distinct integers rotated at some point. Given a value x. The problem is to count all the elements in the array which are less than or equal to x. Examples: Input : arr[] = {4, 5, 8, 1, 3}, x = 6 Output : 4 Input : arr[] = {6, 10, 12, 15, 2, 4, 5}, x = 14 Output : 6 Naive A
    15 min read
  • XOR of numbers that appeared even number of times in given Range
    Given an array of numbers of size N and Q queries. Each query or a range can be represented by L (LeftIndex) and R(RightIndex). Find the XOR-sum of the numbers that appeared even number of times in the given range. Prerequisite : Queries for number of distinct numbers in given range. | Segment Tree
    15+ min read
  • Minimum number of elements to add to make median equals x
    A median in an array with the length of n is an element which occupies position number (n+1)/2 after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the n
    11 min read
  • Count of numbers in given Array greater than next K elements
    Given an array arr[] of integers of size N, the task is to count the number of elements whose value is greater than all the K elements to its immediate right. If there are less than K numbers to the right of the ith element, then the value of all of them must be lesser than that of the ith person. E
    13 min read
  • Find elements larger than half of the elements in an array
    Given an array of n elements, the task is to find the elements that are greater than half of elements in an array. In case of odd elements, we need to print elements larger than floor(n/2) elements where n is total number of elements in array. Examples : Input : arr[] = {1, 6, 3, 4}Output : 4 6Input
    8 min read
  • Queries to count array elements greater than or equal to a given number with updates
    Given two arrays arr[] and query[] of sizes N and Q respectively and an integer M, the task for each query, is to count the number of array elements that are greater than or equal to query[i] and decrease all such numbers by M and perform the rest of the queries on the updated array. Examples: Input
    15+ min read
  • Find a number K such that Array contains at least K numbers greater than or equal to K
    Given an array arr[] of non-negative integers of size N, the task is to find an integer H such that at least K integers in the array are greater or equal to K.Examples: Input: arr[] = [3, 0, 6, 1, 5] Output: 3 Explanation: There are 3 number greater than or equal to 3 in the array i.e. 3, 6 and 5.In
    4 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