What is the runtime of my algorithm?

岁酱吖の 提交于 2019-12-11 02:47:25

问题


I'm writing an algorithm that will first take a config file of various endpoints and their associated method like the following:

/guest guestEndpoint
/guest/lists listEndpoint
/guest/friends guestFriendsEndpoint
/guest/X/friends guetFriendsEndpoint
/guest/X/friends/X guestFriendsEndpoint
/X/guest guestEndpoint
/X/lists listEndpoint
/options optionsEndpoint

X here represents a wildcard, so any string would match with this. The algorithm would take this as input and build a tree with each node representing one token between the /'s. Each leaf would be a valid endpoint.

Then when the user passes in something like guest/abc/friends it would traverse the tree starting from the root, then look for a guest node attached to the root, if it exists go to node guest, if guest here guest would have a wildcard node, so if abc did not match with any of guest's nodes but there was a wildcard node present it would go to the wildcard. Then it would look from wildcard to see if it had a friends node, if so go there. Then if friendsis a leaf node it would return the corresponding method.

Does this algorithm makes sense? I'm wondering what the runtime of the lookup would be. I'm thinking it would be O(n) where n is the number of tokens in the param that was passed in.

Here is an image of the graph I would build based on the input above. Each diamond represents an endpoint method.

Thanks for any help!


回答1:


Worst look up time will be O(E+N) where E is number if edges and N is number of nodes. Becuase We don't know how many nodes are there at each level. So by your algorithm you find first node in desired sequence by doing level search as you don't have any parameter to check for to going through desired path. (I know number of nodes are going to reduce each time I go down by one level but by how many is uncertain in this case) It's Not even n-array.

Wild card won't help in reducing time complexity of worst case and will be uncertain to know the best case of a tree. Wild card checking takes constant time and it won't count in run time.

Now algorithm looks bit confusing what will you do when you have two options

1) you have natural matched node 2) you have wild card node.

On same level , where you will go? Assume you we go in direction first you encountered. But what if It is not the actual path you get to know at last node so you backtrack it . To avoid that you will keep mark of number of available paths at each level by BFS and do the search. So Worst Case time complexity would be O(E+N) provided you have handled all the cases.



来源:https://stackoverflow.com/questions/45258067/what-is-the-runtime-of-my-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!