Make the intervals non-overlapping by assigning them to two different processors
Last Updated :
17 Mar, 2023
Given a list of intervals interval[] where each interval contains two integers L and R, the task is to assign intervals to two different processors such that there are no overlapping intervals for each processor. To assign the interval[i] to the first processor, print "F" and to assign it to the second processor, print "S".
Note: If there is no possible solution print -1.
Examples:
Input: interval[] = {{360, 480}, {420, 540}, {600, 660}}
Output: S, F, S
Explanation:
The intervals assigned to processors are -
Intervals of First Processor {{420, 540}}
Intervals of Second Processor {{360, 480}, {600, 660}}
As there are no overlapping intervals for each processor, it will be a valid solution.Input: interval[] = {{99, 150}, {1, 100}, {100, 301}, {2, 5}, {150, 250}}
Output: S, F, F, S, S
Explanation:
The intervals assigned to processors are -
Intervals of First Processor {{1, 100}, {100, 301}}
Intervals of Second Processor {{99, 150}, {2, 5}, {150, 250}}
As there are no overlapping intervals for each processor, it will be a valid solution.
Approach: The idea is to use Greedy algorithm to assign the intervals to the processor.
If the highest end time of the processor is less than or equal to start time of an interval, then this interval can be assigned to the processor. Otherwise, check for the another processor. If any interval cannot be assigned to any processor then there is no possible solution.
Below is the illustration of the steps of the approach:
- As in the current problem we have to print according to the order of the intervals. So to save the order of intervals, pair the intervals with their index.
- Sort the intervals by their start time. i.e. L.
- Iterate over the intervals and assign the intervals to the processors as follows:
if (interval[i][0] >= firstProcessorEndTime)
answer[interval[i]] = "F"
firstProcessorEndTime =
max(firstProcessorEndTime, interval[i][0])
else if (interval[i][0] >= secondProcessorEndTime)
answer[interval[i]] = "S"
secondProcessorEndTime =
max(secondProcessorEndTime, interval[i][0])
else
print(-1)
Below is the implementation of the above approach:
C++
// C++ implementation for intervals
// scheduling to two processors such
// that there are no overlapping intervals
#include <bits/stdc++.h>
using namespace std;
// Function to assign the intervals
// to two different processors
void assignIntervals(vector<vector<int> > interval, int n)
{
// Loop to pair the interval
// with their indices
for (int i = 0; i < n; i++)
interval[i].push_back(i);
// sorting the interval by
// their start times
sort(interval.begin(), interval.end());
int firstEndTime = -1;
int secondEndTime = -1;
char find = ' ';
bool flag = false;
// Loop to iterate over the
// intervals with their start time
for (int i = 0; i < n; i++) {
if (interval[i][0] >= firstEndTime) {
firstEndTime = interval[i][1];
interval[i].push_back('S');
}
else if (interval[i][0] >= secondEndTime) {
secondEndTime = interval[i][1];
interval[i].push_back('F');
}
else {
flag = true;
break;
}
}
// Condition to check if there
// is a possible solution
if (flag)
cout << (-1);
else {
vector<char> form(n, ' ');
for (int i = 0; i < n; i++) {
int indi = interval[i][2];
form[indi] = interval[i][3];
}
// form = ''.join(form)
for (int i = 0; i < form.size(); i++)
cout << form[i] << ",";
}
}
// Driver Code
int main()
{
vector<vector<int> > intervals
= { { 360, 480 }, { 420, 540 }, { 600, 660 } };
// Function Call
assignIntervals(intervals, intervals.size());
return 0;
}
Java
// Java program for the above approach
import java.util.*;
public class Main {
public static void main(String[] args) {
// Intervals to be scheduled
int[][] intervals = {
{ 360, 480 },
{ 420, 540 },
{ 600, 660 }
};
// Function Call
assignIntervals(intervals, intervals.length);
}
// Function to assign the intervals
// to two different processors
public static void assignIntervals(int[][] interval, int n) {
// Loop to pair the interval
// with their indices
for (int i = 0; i < n; i++) {
interval[i] = Arrays.copyOf(interval[i], interval[i].length + 1);
interval[i][interval[i].length - 1] = i;
}
// Sorting the interval by their start times
Arrays.sort(interval, Comparator.comparingInt(a -> a[0]));
int firstEndTime = -1;
int secondEndTime = -1;
boolean flag = false;
// Loop to iterate over the
// intervals with their start time
for (int i = 0; i < n; i++) {
if (interval[i][0] >= firstEndTime) {
firstEndTime = interval[i][1];
interval[i] = Arrays.copyOf(interval[i], interval[i].length + 1);
interval[i][interval[i].length - 1] = 'S';
} else if (interval[i][0] >= secondEndTime) {
secondEndTime = interval[i][1];
interval[i] = Arrays.copyOf(interval[i], interval[i].length + 1);
interval[i][interval[i].length - 1] = 'F';
} else {
flag = true;
break;
}
}
// Condition to check if there
// is a possible solution
if (flag) {
System.out.println("-1");
} else {
List<Character> form = new ArrayList<>(Collections.nCopies(n, ' '));
for (int i = 0; i < n; i++) {
int indi = interval[i][2];
form.set(indi, (char) interval[i][3]);
}
// Print the result
String output = form.toString();
System.out.println(output);
}
}
}
// This code is contributed by Prince Kumar
Python3
# Python implementation for intervals
# scheduling to two processors such
# that there are no overlapping intervals
# Function to assign the intervals
# to two different processors
def assignIntervals(interval, n):
# Loop to pair the interval
# with their indices
for i in range(n):
interval[i].append(i)
# sorting the interval by
# their startb times
interval.sort(key = lambda x: x[0])
firstEndTime = -1
secondEndTime = -1
find = ''
flag = False
# Loop to iterate over the
# intervals with their start time
for i in range(n):
if interval[i][0] >= firstEndTime:
firstEndTime = interval[i][1]
interval[i].append('S')
elif interval[i][0] >= secondEndTime:
secondEndTime = interval[i][1]
interval[i].append('F')
else:
flag = True
break
# Condition to check if there
# is a possible solution
if flag:
print(-1)
else:
form = ['']*n
for i in range(n):
indi = interval[i][2]
form[indi] = interval[i][3]
# form = ''.join(form)
print(form, ", ")
# Driver Code
if __name__ == "__main__":
intervals = [[360, 480], [420, 540], [600, 660]]
# Function Call
assignIntervals(intervals, len(intervals))
C#
using System;
using System.Collections.Generic;
using System.Linq;
class MainClass {
public static void Main(string[] args) {
// intervals to be scheduled
int[][] intervals = {
new int[] {360, 480},
new int[] {420, 540},
new int[] {600, 660}
};
// Function Call
AssignIntervals(intervals, intervals.Length);
}
// Function to assign the intervals
// to two different processors
public static void AssignIntervals(int[][] interval, int n) {
// Loop to pair the interval
// with their indices
for (int i = 0; i < n; i++) {
interval[i] = interval[i].Concat(new int[] {i}).ToArray();
}
// sorting the interval by
// their start times
interval = interval.OrderBy(x => x[0]).ToArray();
int firstEndTime = -1;
int secondEndTime = -1;
bool flag = false;
// Loop to iterate over the
// intervals with their start time
for (int i = 0; i < n; i++) {
if (interval[i][0] >= firstEndTime) {
firstEndTime = interval[i][1];
interval[i] = interval[i].Concat(new int[] {'S'}).ToArray();
} else if (interval[i][0] >= secondEndTime) {
secondEndTime = interval[i][1];
interval[i] = interval[i].Concat(new int[] {'F'}).ToArray();
} else {
flag = true;
break;
}
}
// Condition to check if there
// is a possible solution
if (flag) {
Console.WriteLine("-1");
} else {
List<char> form = new List<char>(new char[n]);
for (int i = 0; i < n; i++) {
int indi = interval[i][2];
form[indi] = (char)interval[i][3];
}
string output = string.Join( ",", form);
Console.WriteLine("["+output+"]");
}
}
}
JavaScript
// JavaScript implementation for intervals
// scheduling to two processors such
// that there are no overlapping intervals
// Function to assign the intervals
// to two different processors
function assignIntervals(interval, n) {
// Loop to pair the interval
// with their indices
for (let i = 0; i < n; i++) {
interval[i].push(i);
}
// sorting the interval by
// their startb times
interval.sort((a, b) => a[0] - b[0]);
let firstEndTime = -1;
let secondEndTime = -1;
let find = '';
let flag = false;
// Loop to iterate over the
// intervals with their start time
for (let i = 0; i < n; i++) {
if (interval[i][0] >= firstEndTime) {
firstEndTime = interval[i][1];
interval[i].push('S');
} else if (interval[i][0] >= secondEndTime) {
secondEndTime = interval[i][1];
interval[i].push('F');
} else {
flag = true;
break;
}
}
// Condition to check if there
// is a possible solution
if (flag) {
console.log(-1);
} else {
let form = Array(n).fill('');
for (let i = 0; i < n; i++) {
let indi = interval[i][2];
form[indi] = interval[i][3];
}
// form = form.join('');
console.log(form, ", ");
}
}
// Driver Code
let intervals = [[360, 480], [420, 540], [600, 660]];
// Function Call
assignIntervals(intervals, intervals.length);
// This code is contributed by phasing17.
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
Similar Reads
Make given segments non-overlapping by assigning directions
Given an array arr[][] consisting of N segments of the form {L, R, V} where, [L, R] denotes a segment with velocity V in any direction, the task is to check if it is possible to assign directions as left or right to all the segments such that they do not intersect after a long period of time. Exampl
14 min read
Count of available non-overlapping intervals to be inserted to make interval [0, R]
Given an integer R which signifies the range [0, R] and two arrays start[] and end[] of size N which signifies the starting and ending intervals in the range [0, R]. The task is to count the number of available non-overlapping intervals which need to be inserted in the arrays such that on merging th
13 min read
Check if given intervals can be made non-overlapping by adding/subtracting some X
Given an array arr[] containing N intervals, the task is to check that if the intervals can be added or subtracted by X after which there are no overlapping intervals. Here X be any real number. Examples: Input: arr[] = {[1, 3], [2, 4], [4, 5], [5, 6]} Output: YES Explanation: We can add X = 1000 in
9 min read
Minimum removals required to make any interval equal to the union of the given Set
Given a set S of size N (1 ? N ? 1e5) consisting of intervals, the task is to find the minimum intervals required to be removed from the set such that any one of the remaining intervals becomes equal to the union of this set. Examples: Input: S = {[1, 3], [4, 12], [5, 8], [13, 20]}Output: 2Explanati
7 min read
Maximum sum of at most two non-overlapping intervals in a list of Intervals | Interval Scheduling Problem
Given an array interval of length N, where each element represents three values, i.e. {startTime, endTime, value}. The task is to find the maximum sum of values of at most two non-overlapping intervals. Example: Input: interval[] = [[1, 3, 2], [4, 5, 2], [2, 4, 3]]Output: 4Explanation: Select interv
7 min read
Find a pair of overlapping intervals from a given Set
Given a 2D array arr[][] with each row of the form {l, r}, the task is to find a pair (i, j) such that the ith interval lies within the jth interval. If multiple solutions exist, then print anyone of them. Otherwise, print -1. Examples: Input: N = 5, arr[][] = { { 1, 5 }, { 2, 10 }, { 3, 10}, {2, 2}
11 min read
Non-overlapping intervals in an array
Given a 2d array arr[][] of time intervals, where each interval is of the form [start, end]. The task is to determine all intervals from the given array that do not overlap with any other interval in the set. If no such interval exists, return an empty list.Examples: Input: arr[] = [[1, 3], [2, 4],
4 min read
Find least non-overlapping number from a given set of intervals
Given an array interval of pairs of integers representing the starting and ending points of the interval of size N. The task is to find the smallest non-negative integer which is a non-overlapping number from the given set of intervals. Input constraints: 1 ⤠N ⤠10^{5}0 ⤠interval[i] ⤠10^{9} Examp
15+ min read
Find index of closest non-overlapping interval to right of each of given N intervals
Given an array arr[] of N intervals, the task is to calculate the index of the closest interval to the right of each of the given N intervals that do not overlap with the current interval. Examples: Input: arr[] = {{3, 4}, {2, 3}, {1, 2}}Output: -1 0 1Explanation: For the interval arr[0], there exis
7 min read
Find the point where maximum intervals overlap
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: En
14 min read