Counting Triangles in a Rectangular space using BIT
Last Updated :
23 Jul, 2025
Pre-requisite: BIT(Binary Indexed Tree or Fenwick Tree), 2D BIT
Given a 2D plane, respond to Q queries, each of the following type:
- Insert x y - Insert a point (x, y) coordinate.
- Triangle x1 y1 x2 y2 - Print the number of triangles that can be formed, by joining the points inside the rectangle, described by two points (x1, y1) and (x2, y2), (x1, y1) is the lower-left corner while (x2, y2) is the upper right corner. We will represent it as {(x1, y1), (x2, y2)}.(Include the triangles with zero areas also in your answer)
Example:

In the red rectangle there are 6 points inserted,
when each of them is joined with a line with every
other point, in all 20 triangles will be formed.
Let's say we somehow have a mechanism to find the number of points inside a given rectangle, let the number of points be 'm' in an instance.
The number of triangles that can be formed with it are mC3 (every 3 points when joined will make a triangle); if we had to count only degenerate triangles, we would have to subtract the number of triangles with zero areas or formed from points on the same line.
Now we sneak into the mechanism to find the number of points in a rectangle; let's assume we have a mechanism to find the number of points inside a rectangle.
Then number of points inside the rectangle
{(x1, y1), (x2, y2)} are,
P(x2, y2) -
P(x1 - 1, y2) -
P(x2, y1 - 1) +
P(x1 - 1, y1 - 1)
Where,
P(x, y) is number of triangles in rectangle
from (1, 1) to (x, y), i.e., {(1, 1), (x, y)}
Now once we find a way to find P(x, y), we are done.
If all the insert queries were made first, then all the triangle queries, it would have been an easy job, we could maintain a 2D table to store the points and table[x][y] would contain the total number of points in the rectangle {(1, 1), (x, y)}.
It can be created using the following DP:
table[x][y] = table[x][y - 1] + table[x - 1][y] - table[x - 1][y - 1]
Or we can use a 2D BIT to insert a point and evaluate P(x, y). For visualization of a 2D BIT, refer Top Coder. The image shows a 16 * 8 2D BIT, and the state after an insertion at (5, 3), the blue nodes are the onces that are updated.
The horizontal BITs correspond to 3, and store 1 at index 3, 1 at index 4, and 1 at index 8; while the vertical representation corresponds to which horizontal BITs will receive that update, the ones that correspond to 5, so 5th BIT from the bottom gets an update, 6th BIT, then 8th BIT, and then 16th BIT.
Let's consider update in a 1D BIT
update(BIT, x)
while ( x < maxn )
BIT[x] += val
x += x & -x
Update for 2D BIT goes like:
update2DBIT(x, y)
// update BIT at index x (from bottom, in the image)
while ( x < maxn )
update(BIT[x], y)
x += x & -x
C++
// A C++ program implementing the above queries
#include<bits/stdc++.h>
#define maxn 2005
using namespace std;
// 2D Binary Indexed Tree. Note: global variable
// will have initially all elements zero
int bit[maxn][maxn];
// function to add a point at (x, y)
void update(int x, int y)
{
int y1;
while (x < maxn)
{
// x is the xth BIT that will be updated
// while y is the indices where an update
// will be made in xth BIT
y1 = y;
while ( y1 < maxn )
{
bit[x][y1]++;
y1 += ( y1 & -y1 );
}
// next BIT that should be updated
x += x & -x;
}
}
// Function to return number of points in the
// rectangle (1, 1), (x, y)
int query(int x, int y)
{
int res = 0, y1;
while (x > 0)
{
// xth BIT's yth node must be added to the result
y1 = y;
while (y1 > 0)
{
res += bit[x][y1];
y1 -= y1 & -y1;
}
// next BIT that will contribute to the result
x -= x & -x;
}
return res;
}
// (x1, y1) is the lower left and (x2, y2) is the
// upper right corner of the rectangle
int pointsInRectangle(int x1, int y1, int x2, int y2)
{
// Returns number of points in the rectangle
// (x1, y1), (x2, y2) as described in text above
return query(x2, y2) - query(x1 - 1, y2) -
query(x2, y1 - 1) + query(x1 - 1, y1 - 1);
}
// Returns count of triangles with n points, i.e.,
// it returns nC3
int findTriangles(int n)
{
// returns pts choose 3
return (n * (n - 1) * (n - 2)) / 6;
}
//driver code
int main()
{
//inserting points
update(2, 2);
update(3, 5);
update(4, 2);
update(4, 5);
update(5, 4);
cout << "No. of triangles in the rectangle (1, 1)"
" (6, 6) are: "
<< findTriangles(pointsInRectangle(1, 1, 6, 6));
update(3, 3);
cout << "\nNo. of triangles in the rectangle (1, 1)"
" (6, 6) are: "
<< findTriangles( pointsInRectangle(1, 1, 6, 6));
return 0;
}
Java
// Java program implementing the above queries
import java.util.*;
class GFG
{
static int maxn = 2005;
// 2D Binary Indexed Tree. Note: global variable
// will have initially all elements zero
static int [][]bit = new int[maxn][maxn];
// function to add a point at (x, y)
static void update(int x, int y)
{
int y1;
while (x < maxn)
{
// x is the xth BIT that will be updated
// while y is the indices where an update
// will be made in xth BIT
y1 = y;
while ( y1 < maxn )
{
bit[x][y1]++;
y1 += (y1 & -y1);
}
// next BIT that should be updated
x += x & -x;
}
}
// Function to return number of points in the
// rectangle (1, 1), (x, y)
static int query(int x, int y)
{
int res = 0, y1;
while (x > 0)
{
// xth BIT's yth node
// must be added to the result
y1 = y;
while (y1 > 0)
{
res += bit[x][y1];
y1 -= y1 & -y1;
}
// next BIT that will contribute to the result
x -= x & -x;
}
return res;
}
// (x1, y1) is the lower left and (x2, y2) is the
// upper right corner of the rectangle
static int pointsInRectangle(int x1, int y1,
int x2, int y2)
{
// Returns number of points in the rectangle
// (x1, y1), (x2, y2) as described in text above
return query(x2, y2) - query(x1 - 1, y2) -
query(x2, y1 - 1) +
query(x1 - 1, y1 - 1);
}
// Returns count of triangles with n points, i.e.,
// it returns nC3
static int findTriangles(int n)
{
// returns pts choose 3
return (n * (n - 1) * (n - 2)) / 6;
}
// Driver Code
public static void main(String[] args)
{
// inserting points
update(2, 2);
update(3, 5);
update(4, 2);
update(4, 5);
update(5, 4);
System.out.print("No. of triangles in the " +
"rectangle (1, 1) (6, 6) are: " +
findTriangles(pointsInRectangle(1, 1, 6, 6)));
update(3, 3);
System.out.print("\nNo. of triangles in the " +
"rectangle (1, 1) (6, 6) are: " +
findTriangles( pointsInRectangle(1, 1, 6, 6)));
}
}
// This code is contributed by Rajput-Ji
Python3
# A Python3 program implementing
# the above queries
maxn = 2005
# 2D Binary Indexed Tree.
# Note: global variable
# will have initially all
# elements zero
bit = [[0 for j in range(maxn)]
for i in range(maxn)]
# function to add a point
# at(x, y)
def update(x, y):
y1 = 0
while (x < maxn):
# x is the xth BIT that will
# be updated while y is the
# indices where an update
# will be made in xth BIT
y1 = y
while (y1 < maxn):
bit[x][y1] += 1
y1 += (y1 & -y1)
# next BIT that should
# be updated
x += x & -x
# Function to return number of
# points in the rectangle(1, 1),
# (x, y)
def query(x, y):
res = 0
y1 = 0
while (x > 0):
# xth BIT's yth node must
# be added to the result
y1 = y
while (y1 > 0):
res += bit[x][y1]
y1 -= y1 & -y1
# next BIT that will contribute
# to the result
x -= x & -x
return res
# (x1, y1) is the lower left
# and (x2, y2) is the upper
# right corner of the rectangle
def pointsInRectangle(x1, y1,
x2, y2):
# Returns number of points
# in the rectangle (x1, y1),
# (x2, y2) as described in
# text above
return (query(x2, y2) - query(x1 - 1, y2) -
query(x2, y1 - 1) + query(x1 - 1, y1 - 1))
# Returns count of triangles with
# n points, i.e., it returns nC3
def findTriangles(n):
# returns pts choose 3
return ((n * (n - 1) *
(n - 2)) // 6)
# Driver code
if __name__ == "__main__":
# inserting points
update(2, 2)
update(3, 5)
update(4, 2)
update(4, 5)
update(5, 4)
print("No. of triangles in the " +
"rectangle (1, 1) (6, 6) are: ",
findTriangles(pointsInRectangle(1, 1,
6, 6)))
update(3, 3)
print("No. of triangles in the rectangle " +
"(1, 1) (6, 6) are:", findTriangles(
pointsInRectangle(1, 1, 6, 6)))
# This code is contributed by Rutvik_56
C#
// C# program implementing the above queries
using System;
class GFG
{
static int maxn = 2005;
// 2D Binary Indexed Tree. Note: global variable
// will have initially all elements zero
static int [,]bit = new int[maxn, maxn];
// function to add a point at (x, y)
static void update(int x, int y)
{
int y1;
while (x < maxn)
{
// x is the xth BIT that will be updated
// while y is the indices where an update
// will be made in xth BIT
y1 = y;
while (y1 < maxn)
{
bit[x, y1]++;
y1 += (y1 & -y1);
}
// next BIT that should be updated
x += x & -x;
}
}
// Function to return number of points in the
// rectangle (1, 1), (x, y)
static int query(int x, int y)
{
int res = 0, y1;
while (x > 0)
{
// xth BIT's yth node
// must be added to the result
y1 = y;
while (y1 > 0)
{
res += bit[x, y1];
y1 -= y1 & -y1;
}
// next BIT that will
// contribute to the result
x -= x & -x;
}
return res;
}
// (x1, y1) is the lower left and (x2, y2) is the
// upper right corner of the rectangle
static int pointsInRectangle(int x1, int y1,
int x2, int y2)
{
// Returns number of points in the rectangle
// (x1, y1), (x2, y2) as described in text above
return query(x2, y2) - query(x1 - 1, y2) -
query(x2, y1 - 1) +
query(x1 - 1, y1 - 1);
}
// Returns count of triangles with n points, i.e.,
// it returns nC3
static int findTriangles(int n)
{
// returns pts choose 3
return (n * (n - 1) * (n - 2)) / 6;
}
// Driver Code
public static void Main(String[] args)
{
// inserting points
update(2, 2);
update(3, 5);
update(4, 2);
update(4, 5);
update(5, 4);
Console.Write("No. of triangles in the " +
"rectangle (1, 1) (6, 6) are: " +
findTriangles(pointsInRectangle(1, 1, 6, 6)));
update(3, 3);
Console.Write("\nNo. of triangles in the " +
"rectangle (1, 1) (6, 6) are: " +
findTriangles( pointsInRectangle(1, 1, 6, 6)));
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// JavaScript program implementing the above queries
var maxn = 2005;
// 2D Binary Indexed Tree. Note: global variable
// will have initially all elements zero
var bit = Array(maxn).fill().map(()=>Array(maxn).fill(0));
// function to add a point at (x, y)
function update(x , y) {
var y1;
while (x < maxn) {
// x is the xth BIT that will be updated
// while y is the indices where an update
// will be made in xth BIT
y1 = y;
while (y1 < maxn) {
bit[x][y1]++;
y1 += (y1 & -y1);
}
// next BIT that should be updated
x += x & -x;
}
}
// Function to return number of points in the
// rectangle (1, 1), (x, y)
function query(x , y) {
var res = 0, y1;
while (x > 0) {
// xth BIT's yth node
// must be added to the result
y1 = y;
while (y1 > 0) {
res += bit[x][y1];
y1 -= y1 & -y1;
}
// next BIT that will contribute to the result
x -= x & -x;
}
return res;
}
// (x1, y1) is the lower left and (x2, y2) is the
// upper right corner of the rectangle
function pointsInRectangle(x1 , y1 , x2 , y2) {
// Returns number of points in the rectangle
// (x1, y1), (x2, y2) as described in text above
return query(x2, y2) - query(x1 - 1, y2) -
query(x2, y1 - 1) + query(x1 - 1, y1 - 1);
}
// Returns count of triangles with n points, i.e.,
// it returns nC3
function findTriangles(n) {
// returns pts choose 3
return (n * (n - 1) * (n - 2)) / 6;
}
// Driver Code
// inserting points
update(2, 2);
update(3, 5);
update(4, 2);
update(4, 5);
update(5, 4);
document.write("No. of triangles in the " +
"rectangle (1, 1) (6, 6) are: "
+ findTriangles(pointsInRectangle(1, 1, 6, 6)));
update(3, 3);
document.write("<br/>No. of triangles in the " +
"rectangle (1, 1) (6, 6) are: "
+ findTriangles(pointsInRectangle(1, 1, 6, 6)));
// This code contributed by gauravrajput1
</script>
Output:
No of triangles in the rectangle (1, 1) (6, 6) are: 10
No of triangles in the rectangle (1, 1) (6, 6) are: 20
Time Complexity: For each query of either type: O(log(x) * log(y)) Or infact: O( number of ones in binary representation of x * number of ones in a binary representation of y )
Total time complexity: O(Q * log(maxX) * log(maxY))
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem