Find the point where maximum intervals overlap
Last Updated :
23 Jul, 2025
Consider a big party where a log register for guest's entry and exit times is maintained. Find the time at which there are maximum guests in the party. Given the Entry(Entry[]) and Exit (Exit[]
) times of individuals at a place.
Note: Entries in the register are not in sorted order.
Examples:
Input: Entry[] = [1, 2, 9, 5, 5]
Exit[] = [4, 5, 12, 9, 12]
Output: 3 5
Explanation:
Time Event Type Total Guests Present
------------------------------------------------
1 Entry 1
2 Entry 2
4 Exit 1
5 Entry 2
5 Entry 3 // Max Guests
5 Exit 2
9 Exit 1
10 Entry 2
12 Exit 1
12 Exit 0
The maximum number of guests present at any time is 3, occurring at time 5.
Input: Entry[] = [3, 0, 5, 8, 6]
Exit[] = [7, 6, 9, 10, 8]
Output: 3 6
Explanation: Maximum guests are 3 at time 6
Input: Entry[] = [2, 3, 5, 7, 8]
Exit[] = [4, 6, 8, 9, 10]
Output: 2 5
Explanation: Maximum guests are 2 at time 5
[Naive Approach] - Using Nested for loop - O((max-min+1)*n) Time and O(max-min+1) Space
Find the minimum and maximum times from the guest entry and exit times, then iterate through this range to count the number of guests present at each time. The maximum count gives the peak number of guests.
C++
// Program to find maximum guest at any time in a party
#include <bits/stdc++.h>
using namespace std;
vector<int> findMaxGuests(vector<int> &Entry, vector<int> &Exit)
{
int n = Entry.size();
int mini_time = INT_MAX, max_time = INT_MIN;
// find the minimum time of the guests
for (int i = 0; i < n; i++)
{
mini_time = min(mini_time, Entry[i]);
}
// find the maximum time of the guests
for (int i = 0; i < n; i++)
{
max_time = max(max_time, Exit[i]);
}
// ith index store the count of the guest
// at time (mini_time + i)
vector<int> count(max_time - mini_time + 1, 0);
// traverse over the array
for (int i = 0; i < n; i++)
{
for (int j = Entry[i]; j <= Exit[i]; j++)
{
// increase the count of the guest at the
// time they are present
count[j - mini_time]++;
}
}
// find the maximum guests number at any time and store it
int time = -1, max_guests = INT_MIN;
for (int i = mini_time; i <= max_time; i++)
{
if (max_guests < count[i - mini_time])
{
max_guests = count[i - mini_time];
time = i;
}
}
return {max_guests, time};
}
// Driver program to test above function
int main()
{
vector<int> Entry = {1, 2, 10, 5, 5};
vector<int> Exit = {4, 5, 12, 9, 12};
int n = Entry.size();
vector<int> ans = findMaxGuests(Entry, Exit);
cout << ans[0] << " " << ans[1];
return 0;
}
Java
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
class GfG {
public static int[] findMaxGuests(int[] Entry,
int[] Exit)
{
// Finding maximum Entrying time
int n = Entry.length;
int maxa = Arrays.stream(Entry).max().getAsInt();
// Finding maximum Exiting time
int maxb = Arrays.stream(Exit).max().getAsInt();
int maxc = Math.max(maxa, maxb);
int[] x = new int[maxc + 2];
Arrays.fill(x, 0);
int cur = 0, idx = 0;
// Creating an auxiliary array
for (int i = 0; i < n; i++) {
// Lazy addition
for (int j = Entry[i]; j <= Exit[i]; j++) {
x[j]++;
}
}
int maxy = Integer.MIN_VALUE;
// Lazily Calculating value at index i
for (int i = 0; i <= maxc; i++) {
cur = x[i];
if (maxy < cur) {
maxy = cur;
idx = i;
}
}
return new int[] { maxy, idx };
}
// Driver code
public static void main(String[] args)
{
int[] Entry = new int[] { 1, 2, 10, 5, 5 };
int[] Exit = new int[] { 4, 5, 12, 9, 12 };
int[] ans = findMaxGuests(Entry, Exit);
System.out.println(ans[0] + " " + ans[1]);
}
}
Python
def findMaxGuests(Entry, Exit):
mini_time = min(Entry)
max_time = max(Exit)
n = len(Entry)
count = [0] * (max_time - mini_time + 1)
for i in range(n):
for j in range(Entry[i], Exit[i] + 1):
count[j - mini_time] += 1
max_guests = max(count)
time = mini_time + count.index(max_guests)
return [max_guests, time]
# Driver code
Entry = [1, 2, 10, 5, 5]
Exit = [4, 5, 12, 9, 12]
ans = findMaxGuests(Entry, Exit)
print(ans[0], " ", ans[1])
C#
using System;
class GfG {
static int[] findMaxGuests(int[] Entry, int[] Exit)
{
int mini_time = int.MaxValue, max_time
= int.MinValue;
int n = Entry.Length;
for (int i = 0; i < n; i++) {
mini_time = Math.Min(mini_time, Entry[i]);
max_time = Math.Max(max_time, Exit[i]);
}
int[] count = new int[max_time - mini_time + 1];
for (int i = 0; i < n; i++) {
for (int j = Entry[i]; j <= Exit[i]; j++) {
count[j - mini_time]++;
}
}
int time = -1, max_guests = int.MinValue;
for (int i = mini_time; i <= max_time; i++) {
if (max_guests < count[i - mini_time]) {
max_guests = count[i - mini_time];
time = i;
}
}
return new int[] { max_guests, time };
}
public static void Main()
{
int[] Entry = { 1, 2, 10, 5, 5 };
int[] Exit = { 4, 5, 12, 9, 12 };
int[] ans = findMaxGuests(Entry, Exit);
Console.WriteLine(ans[0] + " " + ans[1]);
}
}
JavaScript
function findMaxGuests(Entry, Exit)
{
let mini_time = Math.min(...Entry);
let max_time = Math.max(...Exit);
let n = Entry.length;
let count = new Array(max_time - mini_time + 1).fill(0);
for (let i = 0; i < n; i++) {
for (let j = Entry[i]; j <= Exit[i]; j++) {
count[j - mini_time]++;
}
}
let time = -1, max_guests = -Infinity;
for (let i = mini_time; i <= max_time; i++) {
if (max_guests < count[i - mini_time]) {
max_guests = count[i - mini_time];
time = i;
}
}
return [ max_guests, time ];
}
// Driver Code
let Entry = [ 1, 2, 10, 5, 5 ];
let Exit = [ 4, 5, 12, 9, 12 ];
let ans = findMaxGuests(Entry, Exit);
console.log(ans[0], " ", ans[1]);
Time Complexity: O((max-min+1)*n) where n is the length of the array of guests
Auxiliary Space: O(max-min+1) where min is the minimum time at which any guests enter and max is the maximum time at which any guests exit.
[Better Approach] - Using Sorting - O(n * logn) Time and O(1) Space
Sort the entry and exit times, then use two pointers to track guests arriving and leaving. Maintain a count of guests present at any time and update the maximum count whenever needed.
C++
// Program to find maximum guest at any time in a party
#include <bits/stdc++.h>
using namespace std;
vector<int> findMaxGuests(vector<int> &Entry, vector<int> &Exit)
{
int n = Entry.size();
// Sort arrival and Exit arrays
sort(Entry.begin(), Entry.end());
sort(Exit.begin(), Exit.end());
// guests_in indicates number of guests at a time
int guests_in = 1, max_guests = 1, time = Entry[0];
int i = 1, j = 0;
// Similar to merge in merge sort to process
// all events in sorted order
while (i < n && j < n)
{
// If next event in sorted order is arrival,
// increment count of guests
if (Entry[i] <= Exit[j])
{
guests_in++;
// Update max_guests if needed
if (guests_in > max_guests)
{
max_guests = guests_in;
time = Entry[i];
}
i++; // increment index of arrival array
}
else // If event is Exit, decrement count
{ // of guests.
guests_in--;
j++;
}
}
return {max_guests, time};
}
// Driver program to test above function
int main()
{
vector<int> Entry = {1, 2, 10, 5, 5};
vector<int> Exit = {4, 5, 12, 9, 12};
vector<int> ans = findMaxGuests(Entry, Exit);
cout << ans[0] << " " << ans[1];
return 0;
}
Java
import java.util.*;
class GFG {
static int[] findMaxGuests(int[] Entry, int[] Exit)
{
int n = Entry.length;
// Sort arrival and Exit arrays
Arrays.sort(Entry);
Arrays.sort(Exit);
int guests_in = 1, max_guests = 1, time = Entry[0];
int i = 1, j = 0;
// Merge-like processing for sorted events
while (i < n && j < n) {
if (Entry[i] <= Exit[j]) {
guests_in++;
// Update max_guests if needed
if (guests_in > max_guests) {
max_guests = guests_in;
time = Entry[i];
}
i++;
}
else {
guests_in--;
j++;
}
}
return new int[] { max_guests, time };
}
// Driver program to test the function
public static void main(String[] args)
{
int[] Entry = { 1, 2, 10, 5, 5 };
int[] Exit = { 4, 5, 12, 9, 12 };
int[] ans = findMaxGuests(Entry, Exit);
System.out.println(ans[0] + " " + ans[1]);
}
}
Python
def findMaxGuests(Entry, Exit):
# Sort arrival and Exit arrays
Entry.sort()
Exit.sort()
n = len(Entry)
# guests_in indicates number of
# guests at a time
guests_in = 1
max_guests = 1
time = Entry[0]
i = 1
j = 0
# Similar to merge in merge sort to
# process all events in sorted order
while (i < n and j < n):
# If next event in sorted order is
# arrival, increment count of guests
if (Entry[i] <= Exit[j]):
guests_in = guests_in + 1
# Update max_guests if needed
if (guests_in > max_guests):
max_guests = guests_in
time = Entry[i]
# increment index of arrival array
i = i + 1
else:
guests_in = guests_in - 1
j = j + 1
return [max_guests, time]
# Driver Code
Entry = [1, 2, 10, 5, 5]
Exit = [4, 5, 12, 9, 12]
n = len(Entry)
ans = findMaxGuests(Entry, Exit)
print(ans[0], " ", ans[1])
C#
using System;
class GfG {
static int[] findMaxGuests(int[] Entry, int[] Exit)
{
int n = Entry.Length;
// Sort arrival and Exit arrays
Array.Sort(Entry);
Array.Sort(Exit);
// guests_in indicates number
// of guests at a time
int guests_in = 1, max_guests = 1, time = Entry[0];
int i = 1, j = 0;
while (i < n && j < n) {
if (Entry[i] <= Exit[j]) {
guests_in++;
// Update max_guests if needed
if (guests_in > max_guests) {
max_guests = guests_in;
time = Entry[i];
}
// increment index of arrival array
i++;
}
// If event is Exit, decrement
// count of guests.
else {
guests_in--;
j++;
}
}
return new int[] { max_guests, time };
}
// Driver Code
public static void Main()
{
int[] Entry = { 1, 2, 10, 5, 5 };
int[] Exit = { 4, 5, 12, 9, 12 };
int n = Entry.Length;
int[] ans = findMaxGuests(Entry, Exit);
Console.WriteLine(ans[0] + " " + ans[1]);
}
}
JavaScript
function findMaxGuests(Entry, Exit)
{
// Sort arrival and Exit arrays
let n = Entry.length;
Entry.sort((a, b) => a - b);
Exit.sort((a, b) => a - b);
let guests_in = 1, max_guests = 1, time = Entry[0];
let i = 1, j = 0;
// Process all events in sorted order
while (i < n && j < n) {
// If the next event is an arrival, increment guest
// count
if (Entry[i] <= Exit[j]) {
guests_in++;
// Update max_guests if needed
if (guests_in > max_guests) {
max_guests = guests_in;
time = Entry[i];
}
i++; // Move to the next arrival
}
else {
// If it's an Exit, decrement the guest count
guests_in--;
j++; // Move to the next Exit
}
}
return [ max_guests, time ];
}
// Sample Input
let Entry = [ 1, 2, 10, 5, 5 ];
let Exit = [ 4, 5, 12, 9, 12 ];
// Function Call
let ans = findMaxGuests(Entry, Exit);
console.log(ans[0], " ", ans[1]);
[Expected Approach] - Using Difference Array - O(n) Time and O(max-min+1) Space
Use a difference array to record guest entries and exits, then compute a running sum to track the number of guests at any time, updating the maximum count accordingly.
C++
#include <bits/stdc++.h>
using namespace std;
vector<int> findMaxGuests(vector<int> &Entry, vector<int> &Exit)
{
int n = Entry.size();
// Finding maximum Entrying time O(n)
int maxa = *max_element(Entry.begin(), Entry.end());
// Finding maximum Exiting time O(n)
int maxb = *max_element(Exit.begin(), Exit.end());
int maxc = max(maxa, maxb);
int x[maxc + 2];
memset(x, 0, sizeof x);
int cur = 0, idx;
// Creating and auxiliary array O(n)
for (int i = 0; i < n; i++)
{
// Lazy addition
++x[Entry[i]];
--x[Exit[i] + 1];
}
int maxy = INT_MIN;
// Lazily Calculating value at index i O(n)
for (int i = 0; i <= maxc; i++)
{
cur += x[i];
if (maxy < cur)
{
maxy = cur;
idx = i;
}
}
return {maxy, idx};
}
// Driver code
int main()
{
vector<int> Entry = {1, 2, 10, 5, 5}, Exit = {4, 5, 12, 9, 12};
vector<int> ans = findMaxGuests(Entry, Exit);
cout << ans[0] << " " << ans[1];
return 0;
}
Java
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
class GFG {
static int[] findMaxGuests(int[] Entry, int[] Exit)
{
// Finding maximum Entrying time
int n = Entry.length;
int maxa = Arrays.stream(Entry).max().getAsInt();
// Finding maximum Exiting time
int maxb = Arrays.stream(Exit).max().getAsInt();
int maxc = Math.max(maxa, maxb);
int[] x = new int[maxc + 2];
Arrays.fill(x, 0);
int cur = 0, idx = 0;
// Creating an auxiliary array
for (int i = 0; i < n; i++) {
// Lazy addition
++x[Entry[i]];
--x[Exit[i] + 1];
}
int maxy = Integer.MIN_VALUE;
// Lazily Calculating value at index i
for (int i = 0; i <= maxc; i++) {
cur += x[i];
if (maxy < cur) {
maxy = cur;
idx = i;
}
}
return new int[] { maxy, idx };
}
// Driver code
public static void main(String[] args)
{
int[] Entry = new int[] { 1, 2, 10, 5, 5 };
int[] Exit = new int[] { 4, 5, 12, 9, 12 };
int[] ans = findMaxGuests(Entry, Exit);
System.out.println(ans[0] + " " + ans[1]);
}
}
Python
import sys
def findMaxGuests(Entry, Exit):
n = len(Entry)
maxa = max(Entry)
maxb = max(Exit)
maxc = max(maxa, maxb)
x = (maxc + 2) * [0]
cur = 0
idx = 0
for i in range(0, n):
x[Entry[i]] += 1
x[Exit[i] + 1] -= 1
maxy = -1
# Lazily Calculating value at index i
for i in range(0, maxc + 1):
cur += x[i]
if maxy < cur:
maxy = cur
idx = i
return [maxy, idx]
if __name__ == "__main__":
Entry = [1, 2, 10, 5, 5]
Exit = [4, 5, 12, 9, 12]
ans = findMaxGuests(Entry, Exit)
print(ans[0], " ", ans[1])
C#
using System;
using System.Linq;
class GfG {
static int[] findMaxGuests(int[] Entry, int[] Exit)
{
int n = Entry.Length;
// Finding maximum Entrying time
int maxa = Entry.Max();
// Finding maximum Exiting time
int maxb = Exit.Max();
int maxc = Math.Max(maxa, maxb);
int[] x = new int[maxc + 2];
int cur = 0, idx = 0;
// Creating an auxiliary array
for (int i = 0; i < n; i++) {
// Lazy addition
++x[Entry[i]];
--x[Exit[i] + 1];
}
int maxy = int.MinValue;
// Lazily Calculating value at index i
for (int i = 0; i <= maxc; i++) {
cur += x[i];
if (maxy < cur) {
maxy = cur;
idx = i;
}
}
return new int[] { maxy, idx };
}
// Driver code
public static void Main()
{
int[] Entry = new int[] { 1, 2, 10, 5, 5 };
int[] Exit = new int[] { 4, 5, 12, 9, 12 };
int[] ans = findMaxGuests(Entry, Exit);
Console.WriteLine(ans[0] + " " + ans[1]);
}
}
JavaScript
// Javascript implementation of above approach
function findMaxGuests(Entry, Exit)
{
let n = Entry.length;
// Finding maximum Entrying time
let maxa = 0;
for (let i = 0; i < Entry.length; i++) {
maxa = Math.max(maxa, Entry[i]);
}
// Finding maximum Exiting time
let maxb = 0;
for (let i = 0; i < Exit.length; i++) {
maxb = Math.max(maxb, Exit[i]);
}
let maxc = Math.max(maxa, maxb);
let x = new Array(maxc + 2);
x.fill(0);
let cur = 0, idx = 0;
// Creating an auxiliary array
for (let i = 0; i < n; i++) {
// Lazy addition
++x[Entry[i]];
--x[Exit[i] + 1];
}
let maxy = Number.MIN_VALUE;
// Lazily Calculating value at index i
for (let i = 0; i <= maxc; i++) {
cur += x[i];
if (maxy < cur) {
maxy = cur;
idx = i;
}
}
return [ maxy, idx ]
}
let Entry = [ 1, 2, 10, 5, 5 ];
let Exit = [ 4, 5, 12, 9, 12 ];
let ans = findMaxGuests(Entry, Exit);
console.log(ans[0], " ", ans[1]);
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