Interview Set

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值