#include<iostream>
#include<vector>
using namespace std;
vector <int> removeFirstOrder(const vector<int>& orders)
{
return vector<int>(++orders.begin() , orders.end());
}
bool isFirstComeFirstServed(const vector<int>& takeOutOrders,
const vector<int>& dineInOrders,
const vector<int>& servedOrders)
{
//base case
if(servedOrders.empty())
{
return true;
}
if(!takeOutOrders.empty() && takeOutOrders[0]==servedOrders[0])
{
return isFirstComeFirstServed(removeFirstOrder(takeOutOrders),
dineInOrders,removeFirstOrder(servedOrders));
}
else if(!dineInOrders.empty() && dineInOrders[0]==servedOrders[0])
{
return isFirstComeFirstServed(takeOutOrders, removeFirstOrder(takeOutOrders),
removeFirstOrder(servedOrders));
}
else
{
return false;
}
}
int main()
{
vector<int> takeOutOrders{17,8,4};
vector<int> dineInOrders{12,19,2};
vector<int> servedOrders{17,8,12,19,24,2};
isFirstComeFirstServed(takeOutOrders,dineInOrders,servedOrders);
return 0;
}
My doubt is that here Author of this program says that it has O(n^2) time complexity and O(n^2) space complexity.
I agree with time complexity of this program because isFirstComeFirstServed function will be called n times which is size of servedOrders Vector Right? and removeFirstOrder will be call n times in first function call of isFirstComeFirstServed and n-1 times in second function call of isFirstComeFirstServed and so on till there are no element left in servedOrder Vector Right ?
But my doubt is that how it can O(n^2) space complexity? can someone help me to visualize it ?
Each time removeFirstOrder
is called the returned vector is smaller by 1.
n-1 + n-2 + n-3 + ... + 1
From arithmetic progression rules, the sum is (n+1)*n / 2 which is order n^2.
Tail call optimization could make it O(n) space behind the scene, but it's not guaranteed be performed at all.