1. You are given the start time and finish time of n intervals. You have to write a a function that returns boolean value indicating if there was any overlapping interval in the set of existing intervals. (Sort and check, time complexity O(nlogn))
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Interval
{
int start, end;
Interval(): start(0), end(0) {}
Interval(int s, int e): start(s), end(e) {}
};
bool comp(const Interval &left, const Interval &right)
{
if(left.start == right.start)
return left.end < right.end;
else
return left.start < right.start;
}
bool IntervalOverlap(vector<Interval> &intervals)
{
std::sort(intervals.begin(), intervals.end(), comp);
if(intervals.size() <= 1)
return false;
for(size_t i=1; i<intervals.size(); i++)
{
if(intervals[i].start <= intervals[i-1].end)
{
return true;
}
}
return false;
}
int main()
{
Interval int1(1,2), int2(3,5), int3(6,7), int4(8,10), int5(12,16);
vector<Interval> intervals{int1, int2, int3, int4, int5};
bool result = IntervalOverlap(intervals);
cout << result << endl;
return 0;
}
2. You have 2 sparse vectors (large number of 0’s). First tell me a way to represent and store them, and then find the dot product.
(To store them, we should store the value and index of those indexes that have a non-zero value, and then finding the dot product is very straight forward).
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
vector<pair<int,int> > multiply(vector<pair<int,int> > vec1, vector<pair<int,int> > vec2)
{
vector<pair<int,int> > result;
int i=0, j=0;
while(i < vec1.size() && j<vec2.size())
{
if(vec1[i].first == vec2[j].first)
{
int val = vec1[i].second * vec2[j].second;
result.push_back(make_pair(vec1[i].first, val));
i++;
j++;
}
else if(vec1[i].first < vec2[j].first)
{
i++;
}
else
{
j++;
}
}
return result;
}
int main()
{
vector<pair<int,int> > vec1{{0,1}, {1,2}, {4,4}, {8,9}};
vector<pair<int,int> > vec2{{0,3}, {3,7}, {6,6}, {8,1}};
vector<pair<int,int> > res = multiply(vec1, vec2);
for(size_t i=0; i<res.size(); i++)
{
cout << "(" << res[i].first << "," << res[i].second << "), ";
}
cout << endl;
return 0;
}
3. You have an array of n elements, and a sum. Check if any 2 elements in the array sum to the given sum. ( Expected time complexity O(n). Use hashing)
4. Extended the previous problem to sum of 3 elements in the array summing up to the given sum.