I would like to know the best way to approach the time complexity analysis of the following algorithm. I have come up with 2 approaches so far.
We have a std::map<int,vector<int>>
(Balanced Binary Search Tree). Each of the std::vector<int>
will be called a route.
Algorithm:
1. while(true)
2. We pick the first two routes from the map and add their key values and if ((sum of key values)>capacity)
then break else proceed to step 3.
3. Now we have two routes which we merge.
After merging (we simply append one of the routes to the other), we delete the chosen two routes and
insert the new route into the map.
The key value of the new route will be the sum of the key values of the chosen two routes.
Go to step 2.
Time Complexity Analysis:
- Approach 1
Let us consider the total number of routes to be n
. Operations like insertion and deletion in the map will cost us O(log(n))
and extraction of the first element of the map will be O(1).
When it comes to merging two routes, let us consider the average length of a route (vector<int>)
to be N
and so merging will cost us O(N)
. In the worst case, there will be (n-1)
mergings and so overall time complexity in the worst case will be O(nN)
.
- Approach 2
Let us consider the total number of routes to be n
and let us also consider k
to be the total sum of lengths (vector.size()
) of all the routes (vector<int>
). Now time complexity of operations involving map remains the same. When it comes to merging, in the worst there can be (n-1)
mergings and in total, we have k
elements in all of the routes, so overall time complexity in the worst case will be O(nk)
.
Any help will be really appreciated.