Maximum number of intersections possible for any of the N given segments
Last Updated :
23 Jul, 2025
Given an array arr[] consisting of N pairs of type {L, R}, each representing a segment on the X-axis, the task is to find the maximum number of intersections a segment has with other segments.
Examples:
Input: arr[] = {{1, 6}, {5, 5}, {2, 3}}
Output: 2
Explanation:
Below are the count of each segment that overlaps with the other segments:
- The first segment [1, 6] intersects with 2 segments [5, 5] and [2, 3].
- The second segment [5, 5] intersects with 1 segment [1, 6].
- The third segment [2, 3] intersects with 1 segment [1, 6].
Therefore, the maximum number of intersections among all the segment is 2.
Input: arr[][] = {{4, 8}, {3, 6}, {7, 11}, {9, 10}}
Output: 2
Naive Approach: The simplest approach to solve the given problem is to iterate over all segments and for each segment count the number of intersections by checking it with all other segments and then print the maximum among all the count of intersections obtained.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach 1: The above approach can also be optimized based on the following observations:
- The above approach can be optimized by traversing each segment and calculating the number of segments that do not intersect the current segment using Binary Search and from that find the number of segments that intersect with the current segment
- Suppose [L, R] is the current segment and [P, Q] is another segment then, the segment [L, R] does not intersect with segment [P, Q] if Q < L or P > R.
- Suppose X is the number of the segments not intersecting with segment [L, R] then, the count of segments that intersects segment [L, R] = (N - 1 - X).
Follow the steps below to solve the problem:
- Store all the left points of segments in an array say L[] and all the right points of the segments in the array say R[].
- Sort both the arrays L[] and R[] in ascending order.
- Initialize a variable, say count as 0 to store the count of the maximum intersection a segment has.
- Traverse the array arr[] and perform the following steps:
- Calculate the number of segments left to the current segment {arr[i][0], arr[i][1]} using lower_bound() and store it in a variable say cnt.
- Calculate the number of segments right to the current segment {arr[i][0], arr[i][1]} using upper_bound() and increment the count of cnt by it.
- Update the value of count as the maximum of count and (N - cnt - 1).
- After completing the above steps, print the value of the count as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum number
// of intersections one segment has with
// all the other given segments
int maximumIntersections(int arr[][2],
int N)
{
// Stores the resultant maximum count
int count = 0;
// Stores the starting and the
// ending points
int L[N], R[N];
for (int i = 0; i < N; i++) {
L[i] = arr[i][0];
R[i] = arr[i][1];
}
// Sort arrays points in the
// ascending order
sort(L, L + N);
sort(R, R + N);
// Traverse the array arr[]
for (int i = 0; i < N; i++) {
int l = arr[i][0];
int r = arr[i][1];
// Find the count of segments
// on left of ith segment
int x = lower_bound(R, R + N, l) - R;
// Find the count of segments
// on right of ith segment
int y = N - (upper_bound(L, L + N, r) - L);
// Find the total segments not
// intersecting with the current
// segment
int cnt = x + y;
// Store the count of segments
// that intersect with the
// ith segment
cnt = N - cnt - 1;
// Update the value of count
count = max(count, cnt);
}
// Return the resultant count
return count;
}
// Driver Code
int main()
{
int arr[][2] = { { 1, 6 }, { 5, 5 }, { 2, 3 } };
int N = sizeof(arr) / sizeof(arr[0]);
cout << maximumIntersections(arr, N);
return 0;
}
Java
// java program for the above approach
import java.util.*;
class GFG
{static int lower_bound(int[] a, int low, int high, long element)
{
while(low < high)
{
int middle = low + (high - low) / 2;
if(element > a[middle])
low = middle + 1;
else
high = middle;
}
return low;
}
static int maximumIntersections(int [][]arr,
int N)
{
// Stores the resultant maximum count
int count = 0;
// Stores the starting and the
// ending points
int[] L = new int[N];
int[] R = new int[N];
for (int i = 0; i < N; i++) {
L[i] = arr[i][0];
R[i] = arr[i][1];
}
// Sort arrays points in the
// ascending order
Arrays.sort(L);
Arrays.sort(R);
// Traverse the array arr[]
for (int i = 0; i < N; i++) {
int l = arr[i][0];
int r = arr[i][1];
// Find the count of segments
// on left of ith segment
int x = lower_bound(L, 0,N, l);
// Find the count of segments
// on right of ith segment
int y = N-lower_bound(R, 0,N, r+1);
// Find the total segments not
// intersecting with the current
// segment
int cnt = x + y;
// Store the count of segments
// that intersect with the
// ith segment
cnt = N - cnt - 1;
// Update the value of count
count = Math.max(count, cnt);
}
// Return the resultant count
return count;
}
// Driver Code
public static void main(String[] args)
{
int arr[][] = { { 1, 6 }, { 5, 5 }, { 2, 3 } };
int N = arr.length;
System.out.println(maximumIntersections(arr, N));
}
}
// This code is contributed by stream_cipher.
Python3
# Python 3 program for the above approach
from bisect import bisect_left, bisect_right
def lower_bound(a, low, high, element):
while(low < high):
middle = low + (high - low) // 2
if(element > a[middle]):
low = middle + 1
else:
high = middle
return low
# Function to find the maximum number
# of intersections one segment has with
# all the other given segments
def maximumIntersections(arr,
N):
# Stores the resultant maximum count
count = 0
# Stores the starting and the
# ending points
L = [0]*N
R = [0]*N
for i in range(N):
L[i] = arr[i][0]
R[i] = arr[i][1]
# Sort arrays points in the
# ascending order
L.sort()
R.sort()
# Traverse the array arr[]
for i in range(N):
l = arr[i][0]
r = arr[i][1]
# Find the count of segments
# on left of ith segment
x = lower_bound(L, 0, N, l)
# Find the count of segments
# on right of ith segment
y = N-lower_bound(R, 0, N, r+1)
# Find the total segments not
# intersecting with the current
# segment
cnt = x + y
# Store the count of segments
# that intersect with the
# ith segment
cnt = N - cnt - 1
# Update the value of count
count = max(count, cnt)
# Return the resultant count
return count
# Driver Code
if __name__ == "__main__":
arr = [[1, 6], [5, 5], [2, 3]]
N = len(arr)
print(maximumIntersections(arr, N))
# This code is contributed by ukasp.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
static int lower_bound(int[] a, int low,
int high, long element)
{
while(low < high)
{
int middle = low + (high - low) / 2;
if (element > a[middle])
low = middle + 1;
else
high = middle;
}
return low;
}
static int maximumIntersections(int [,]arr,
int N)
{
// Stores the resultant maximum count
int count = 0;
// Stores the starting and the
// ending points
int[] L = new int[N];
int[] R = new int[N];
for(int i = 0; i < N; i++)
{
L[i] = arr[i, 0];
R[i] = arr[i, 1];
}
// Sort arrays points in the
// ascending order
Array.Sort(L);
Array.Sort(R);
// Traverse the array arr[]
for(int i = 0; i < N; i++)
{
int l = arr[i, 0];
int r = arr[i, 1];
// Find the count of segments
// on left of ith segment
int x = lower_bound(L, 0, N, l);
// Find the count of segments
// on right of ith segment
int y = N-lower_bound(R, 0, N, r + 1);
// Find the total segments not
// intersecting with the current
// segment
int cnt = x + y;
// Store the count of segments
// that intersect with the
// ith segment
cnt = N - cnt - 1;
// Update the value of count
count = Math.Max(count, cnt);
}
// Return the resultant count
return count;
}
// Driver Code
public static void Main()
{
int [,]arr = new int[3, 2]{ { 1, 6 },
{ 5, 5 },
{ 2, 3 } };
int N = 3;
Console.Write(maximumIntersections(arr, N));
}
}
// This code is contributed by SURENDRA_GANGWAR
JavaScript
<script>
// Javascript program for the above approach
function lower_bound(a, low, high, element)
{
while(low < high)
{
let middle = low + Math.floor(
(high - low) / 2);
if (element > a[middle])
low = middle + 1;
else
high = middle;
}
return low;
}
// Function to find the maximum number
// of intersections one segment has with
// all the other given segments
function maximumLetersections(arr, N)
{
// Stores the resultant maximum count
let count = 0;
// Stores the starting and the
// ending points
let L = Array.from({length: N}, (_, i) => 0);
let R = Array.from({length: N}, (_, i) => 0);
for(let i = 0; i < N; i++)
{
L[i] = arr[i][0];
R[i] = arr[i][1];
}
// Sort arrays points in the
// ascending order
L.sort();
R.sort();
// Traverse the array arr[]
for(let i = 0; i < N; i++)
{
let l = arr[i][0];
let r = arr[i][1];
// Find the count of segments
// on left of ith segment
let x = lower_bound(L, 0, N, l);
// Find the count of segments
// on right of ith segment
let y = N-lower_bound(R, 0, N, r + 1);
// Find the total segments not
// intersecting with the current
// segment
let cnt = x + y;
// Store the count of segments
// that intersect with the
// ith segment
cnt = N - cnt - 1;
// Update the value of count
count = Math.max(count, cnt);
}
// Return the resultant count
return count;
}
// Driver Code
let arr = [ [ 1, 6 ], [ 5, 5 ], [ 2, 3 ] ];
let N = arr.length;
document.write(maximumLetersections(arr, N));
// This code is contributed by susmitakundugoaldanga
</script>
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Efficient Approach 2: Using hashmap.
Intuition: First we define a haspmap. Then traverse over the array and increment the count of L and decrement the count of (R+1) in the map( because we can draw vertical line through all the points within the range of L and R (both including) so we decrement the count of (R+1) point). At any point in time, the sum of values (total sum from start till point) in the map will give us the number of overlapping present at the point. We can then find the maximum of this sum, which will give us the maximum number of overlapping possible.
Follow the steps below to solve the problem:
- define a haspmap .
- Traverse over the array and increment the count of L and decrement the count of (R+1) int the map.
- Iterate over the map and keep track of the maximum sum seen so far. This maximum sum will give us the maximum number of the overlapping present.
- return the maximum sum.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum number
// of intersections one segment has with
// all the other given segments
int maximumIntersections(int arr[][2],
int N)
{
// Stores the resultant maximum count
int count = 0;
// create a map
map<int , int> pointCount;
// traverse the array
for(int i=0; i<N; i++){
// increment the count of L
pointCount[arr[i][0]]++;
// decrement the count of (R+1)
pointCount[arr[i][1] + 1]--;
}
// store the current sum
int currSum=0;
for( auto it : pointCount){
currSum += it.second;
// taking the max of sum
count= max(count, currSum);
}
// Return the resultant count
return count;
}
// Driver Code
int main()
{
int arr[][2] = { { 1, 6 }, { 5, 5 }, { 2, 3 } };
int N = sizeof(arr) / sizeof(arr[0]);
cout << maximumIntersections(arr, N);
return 0;
}
Java
import java.util.*;
class GFG {
// Function to find the maximum number of intersections
// one segment has with all the other given segments
public static int maximumIntersections(int[][] arr, int N) {
// Stores the resultant maximum count
int count = 0;
// Create a TreeMap
TreeMap<Integer, Integer> pointCount = new TreeMap<>();
// Traverse the array
for (int i = 0; i < N; i++) {
// Increment the count of L
pointCount.put(arr[i][0], pointCount.getOrDefault(arr[i][0], 0) + 1);
// Decrement the count of (R+1)
pointCount.put(arr[i][1] + 1, pointCount.getOrDefault(arr[i][1] + 1, 0) - 1);
}
// Store the current sum
int currSum = 0;
for (int value : pointCount.values()) {
currSum += value;
// Taking the max of sum
count = Math.max(count, currSum);
}
// Return the resultant count
return count;
}
// Driver Code
public static void main(String[] args) {
int[][] arr = {{1, 6}, {5, 5}, {2, 3}};
int N = arr.length;
System.out.println(maximumIntersections(arr, N));
}
}
Python3
def maximumIntersections(arr, N):
count = 0
pointCount = {} # Create a dictionary to store point counts
# Traverse the array of segments
for i in range(N):
# Increment the count of the left endpoint of the segment
pointCount[arr[i][0]] = pointCount.get(arr[i][0], 0) + 1
# Decrement the count of the right endpoint of the segment + 1
pointCount[arr[i][1] + 1] = pointCount.get(arr[i][1] + 1, 0) - 1
currSum = 0
# Iterate through the sorted points and their counts
for point, val in sorted(pointCount.items()):
currSum += val
count = max(count, currSum) # Update the maximum intersection count
return count
# Driver Code
if __name__ == "__main__":
arr = [[1, 6], [5, 5], [2, 3]]
N = len(arr)
result = maximumIntersections(arr, N)
print(result)
C#
using System;
using System.Collections.Generic;
class GFG
{
// Function to find the maximum number of intersections
// one segment has with all the other given segments
public static int MaximumIntersections(int[][] arr, int N)
{
// Stores the resultant maximum count
int count = 0;
// Create a SortedDictionary
SortedDictionary<int, int> pointCount = new SortedDictionary<int, int>();
// Traverse the array
for (int i = 0; i < N; i++)
{
// Increment the count of L
if (!pointCount.ContainsKey(arr[i][0]))
pointCount[arr[i][0]] = 1;
else
pointCount[arr[i][0]]++;
// Decrement the count of (R+1)
if (!pointCount.ContainsKey(arr[i][1] + 1))
pointCount[arr[i][1] + 1] = -1;
else
pointCount[arr[i][1] + 1]--;
}
// Store the current sum
int currSum = 0;
foreach (var value in pointCount.Values)
{
currSum += value;
// Taking the max of sum
count = Math.Max(count, currSum);
}
// Return the resultant count
return count;
}
// Driver Code
public static void Main(string[] args)
{
int[][] arr = { new int[] { 1, 6 }, new int[] { 5, 5 }, new int[] { 2, 3 } };
int N = arr.Length;
Console.WriteLine(MaximumIntersections(arr, N));
}
}
JavaScript
function MaximumIntersections(arr) {
// Create an array to store point counts
let pointCount = [];
// Traverse the array
for (let i = 0; i < arr.length; i++) {
// Increment the count of L
if (!pointCount[arr[i][0]]) {
pointCount[arr[i][0]] = 1;
} else {
pointCount[arr[i][0]]++;
}
// Decrement the count of (R+1)
if (!pointCount[arr[i][1] + 1]) {
pointCount[arr[i][1] + 1] = -1;
} else {
pointCount[arr[i][1] + 1]--;
}
}
// Store the current sum
let currSum = 0;
let count = 0;
for (let i = 0; i < pointCount.length; i++) {
if (pointCount[i] !== undefined) {
currSum += pointCount[i];
// Taking the max of sum
count = Math.max(count, currSum);
}
}
// Return the resultant count
return count;
}
// Driver Code
const arr = [[1, 6], [5, 5], [2, 3]];
console.log(MaximumIntersections(arr)); // Output: 2
Time Complexity: O(N*log N) ( insertion in a map takes (log N) and total N number of points)
Auxiliary Space: O(N) (size of map)
Approach 3: Sweep Line Algorithm
- This is most efficient approach that can solve the problem in O(N log N) time complexity.
Idea: Sort the segments by their left endpoint and then process them on by on using sweep line that moves from left
to right. Then maintain a set of segments that intersect with the sweep line, and update the maximum number of
intersections at each step.
Follow the steps below to solve the problem:
- read the segments from the input and store them in a vector of pair.
- Each pair represents a segment, with the first element being the left endpoint and the second element being the right endpoint.
- create two events (one for the left and one for the right endpoint).
- each event is respresnted as pair of form {x coordinates, +1 or -1}, where +1 or -1 indicates the event is left or right endpoint of the segment.
- store all the events in a single vector.
- Traverse the events : initialize a count of the segment intersecting the sweep line to 0, and initialize a variable to keep track of the maximum no. of intersections seen so far.
- loop through all the events in the sorted order, and for every event:
1. if event is a left event, then increment count.
2. if the event is right event, decrement the count.
3. update the maximum no. of intersections seen so far by taking maximum current count and maximum so far. - Return the maximum number of intersections.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Comparison function for sorting events
bool cmp(pair<int, int>& a, pair<int, int>& b)
{
return a.first < b.first;
}
// Function to find the maximum number of intersections
int maxIntersections(vector<pair<int, int> >& segments)
{
int n = segments.size();
vector<pair<int, int> > events;
for (int i = 0; i < n; i++) {
events.push_back({ segments[i].first, 1 });
events.push_back({ segments[i].second, -1 });
}
// Sort the events
sort(events.begin(), events.end(), cmp);
// Traverse the events and keep track of the maximum
// number of intersections
int ans = 0, cnt = 0;
for (int i = 0; i < 2 * n; i++) {
cnt += events[i].second;
ans = max(ans, cnt);
}
// Return the maximum number of intersections
return ans;
}
int main()
{
vector<pair<int, int> > segments
= { { 1, 6 }, { 5, 5 }, { 2, 3 } };
cout << maxIntersections(segments) << endl;
return 0;
}
Java
import java.util.*;
import java.util.AbstractMap.SimpleEntry;
// Comparison function for sorting events
class EventComparator implements Comparator<AbstractMap.SimpleEntry<Integer, Integer>> {
@Override
public int compare(AbstractMap.SimpleEntry<Integer, Integer> a, AbstractMap.SimpleEntry<Integer, Integer> b) {
return Integer.compare(a.getKey(), b.getKey());
}
}
public class MaximumIntersections {
// Function to find the maximum number of intersections
public static int maxIntersections(List<AbstractMap.SimpleEntry<Integer, Integer>> segments) {
int n = segments.size();
List<AbstractMap.SimpleEntry<Integer, Integer>> events = new ArrayList<>();
for (int i = 0; i < n; i++) {
events.add(new AbstractMap.SimpleEntry<>(segments.get(i).getKey(), 1));
events.add(new AbstractMap.SimpleEntry<>(segments.get(i).getValue(), -1));
}
// Sort the events
Collections.sort(events, new EventComparator());
// Traverse the events and keep track of the maximum
// number of intersections
int ans = 0, cnt = 0;
for (int i = 0; i < 2 * n; i++) {
cnt += events.get(i).getValue();
ans = Math.max(ans, cnt);
}
// Return the maximum number of intersections
return ans;
}
public static void main(String[] args) {
List<AbstractMap.SimpleEntry<Integer, Integer>> segments = new ArrayList<>();
segments.add(new AbstractMap.SimpleEntry<>(1, 6));
segments.add(new AbstractMap.SimpleEntry<>(5, 5));
segments.add(new AbstractMap.SimpleEntry<>(2, 3));
int maxIntersect = maxIntersections(segments);
System.out.println(maxIntersect);
}
}
Python
# Comparison function for sorting events
def cmp(a, b):
return a[0] < b[0]
# Function to find the maximum number of intersections
def maxIntersections(segments):
n = len(segments)
events = []
for i in range(n):
events.append((segments[i][0], 1))
events.append((segments[i][1], -1))
# Sort the events
events.sort(key=lambda x: x[0])
# Traverse the events and keep track of the maximum number of intersections
ans = 0
cnt = 0
for i in range(2 * n):
cnt += events[i][1]
ans = max(ans, cnt)
# Return the maximum number of intersections
return ans
segments = [(1, 6), (5, 5), (2, 3)]
print(maxIntersections(segments))
C#
using System;
using System.Collections.Generic;
// Comparison function for sorting events
class EventComparator : IComparer<KeyValuePair<int, int>>
{
public int Compare(KeyValuePair<int, int> a, KeyValuePair<int, int> b)
{
return a.Key.CompareTo(b.Key);
}
}
public class MaximumIntersections
{
// Function to find the maximum number of intersections
public static int MaxIntersections(List<KeyValuePair<int, int>> segments)
{
int n = segments.Count;
List<KeyValuePair<int, int>> events = new List<KeyValuePair<int, int>>();
for (int i = 0; i < n; i++)
{
events.Add(new KeyValuePair<int, int>(segments[i].Key, 1));
events.Add(new KeyValuePair<int, int>(segments[i].Value, -1));
}
// Sort the events
events.Sort(new EventComparator());
// Traverse the events and keep track of the maximum
// number of intersections
int ans = 0, cnt = 0;
for (int i = 0; i < 2 * n; i++)
{
cnt += events[i].Value;
ans = Math.Max(ans, cnt);
}
// Return the maximum number of intersections
return ans;
}
public static void Main(string[] args)
{
List<KeyValuePair<int, int>> segments = new List<KeyValuePair<int, int>>();
segments.Add(new KeyValuePair<int, int>(1, 6));
segments.Add(new KeyValuePair<int, int>(5, 5));
segments.Add(new KeyValuePair<int, int>(2, 3));
int maxIntersect = MaxIntersections(segments);
Console.WriteLine(maxIntersect);
}
}
JavaScript
function GFG(a, b) {
return a[0] - b[0];
}
// Function to find the maximum number of the intersections
function maxs(segments) {
const n = segments.length;
let events = [];
for (let i = 0; i < n; i++) {
events.push([segments[i][0], 1]);
events.push([segments[i][1], -1]);
}
// Sort the events
events.sort(GFG);
// Traverse the events and keep track of the maximum number of the intersections
let ans = 0, cnt = 0;
for (let i = 0; i < 2 * n; i++) {
cnt += events[i][1];
ans = Math.max(ans, cnt);
}
// Return the maximum number of the intersections
return ans;
}
// Test the function with the sample data
const segments = [[1, 6], [5, 5], [2, 3]];
console.log(maxs(segments));
Output:
2
Time Complexity: O(n log n), where n is the number of segments.
Auxiliary Space: O(n log n)
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