Question:

Given a jumbled collection of segments, each of which is represented as a Pair(startPoint, endPoint), this function sorts the segments to make a continuous path.

A few assumptions you can make:

Each particular segment goes in one direction only, i.e.: if you see (1, 2), you will not see (2, 1).

Each starting point only have one way to the end point, i.e.: if you see (6, 5), you will not see (6, 10), (6, 3), etc.

For example, if you've passed a list containing the following int arrays:

[(4, 5), (9, 4), (5, 1), (11, 9)]

Then your implementation should sort it such:

[(11, 9), (9, 4), (4, 5), (5, 1)]

@param segments collection of segments, each represented by a Pair(startPoint, endPoint).

@return The sorted segments such that they form a continuous path.

@throws Exception if there is no way to create one continuous path from

all the segments passed into this function. Feel free to change the Exception type as you think appropriate.

I thought about use hashmap or topological sort but I don't know how to finish it. And I have checked the Chegg before unfortunately the answer is not completed.

Can someone show me how to solve this problem in Python? Thank you.