Skip to main content

Sales Path

MediumPremium

The car manufacturer Honda holds their distribution system in the form of a tree (not necessarily binary). The root is the company itself, and every node in the tree represents a car distributor that receives cars from the parent node and ships them to its children nodes. The leaf nodes are car dealerships that sell cars direct to consumers. In addition, every node holds an integer that is the cost of shipping a car to it.

Take for example the tree below:

sales_path.png

A path from Honda’s factory to a car dealership, which is a path from the root to a leaf in the tree, is called a Sales Path. The cost of a Sales Path is the sum of the costs for every node in the path. For example, in the tree above one Sales Path is 0→3→0→10, and its cost is 13 (0+3+0+10).

Honda wishes to find the minimal Sales Path cost in its distribution tree. Given a node rootNode, write a function getCheapestCost that calculates the minimal Sales Path cost in the tree.

Implement your function in the most efficient manner and analyze its time and space complexities.

For example:

Given the rootNode of the tree in diagram above

Your function would return:

7 since it’s the minimal Sales Path cost (there are actually two Sales Paths in the tree whose cost is 7: 0→6→1 and 0→3→2→1→1)

Give it a try using the code editor!

Stuck? Make sure you fully understand what's being asked. Can you find the minimum sales path(s) in the above example?

Practice by diagramming an example tree and finding all the possible paths there. The tree in the question is abstract, but if it helps to concretize the problem, you can assume that the function initially gets a tree node, and that every node has a field holding the cost, and an array holding its children nodes.

Try dividing the paths per child of the root node.

What would happen if you input the function of the children of the root node? Given that, go back and look for the connection between the function's value on the root, and on every child node. What's the runtime and space requirements for your answer? If not O(N) for both, you can do better.

What's the runtime and space requirements for your answer? If not O(N) for both, you can do better!