# Employee Free Time in C++

C++Server Side ProgrammingProgramming

Suppose we have given a list of schedules of employees; this represents the working time for each employee. Now suppose each employee has a list of non-overlapping Intervals, these intervals are sorted. We have to find the list of finite intervals representing the common, positive-length free time for all employees, and that will also be in sorted order. We are representing Intervals in the form [x, y], For example, schedule .start = 1, schedule.end = 2.

So, if the input is like schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]], then one of the output will be [[3,4]].

To solve this, we will follow these steps −

• Define one 2D array v

• for initialize i := 0, when i < size of schedule, update (increase i by 1), do

• for initialize j := 0, when j < size of schedule[i], update (increase j by 1), do

• insert schedule[i, j] at the end of v

• sort the array v

• Define one 2D array ret

• Define an array temp := v

• for initialize i := 0, when i < size of v, update (increase i by 1), do −

• if temp < v[i, 1], then −

• insert {temp, v[i, 0]} at the end of ret

• temp := v[i]

• Otherwise

• temp := (if temp < v[i, 1], then v[i], otherwise temp)

• return ret

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class Solution {
public:
static bool cmp(vector<int> a, vector<int> b){
return a < b;
}
vector<vector<int>> employeeFreeTime(vector<vector<vector<int>>> schedule) {
vector<vector<int>> v;
for (int i = 0; i < schedule.size(); i++) {
for (int j = 0; j < schedule[i].size(); j++) {
v.push_back(schedule[i][j]);
}
}
sort(v.begin(), v.end(), cmp);
vector<vector<int>> ret;
vector<int> temp = v;
for (int i = 0; i < v.size(); i++) {
if (temp < v[i]) {
ret.push_back({temp, v[i]});
temp = v[i];
} else {
temp = temp < v[i] ? v[i] : temp;
}
}
return ret;
}
};
main(){
Solution ob;
vector<vector<vector<int>>> v = {{{1,2},{5,6}},{{1,3}},{{4,10}}};
print_vector(ob.employeeFreeTime(v));
}

## Input

{{{1,2},{5,6}},{{1,3}},{{4,10}}}

## Output

[[2, 1, ],[2, 1, ],[3, 4, ],[10, 5, ],]