Amazon Interview Question
SDE-2sTeam: Alexa
Country: India
Can you please tell the logic ? I think you are checking by removing each road.
I use the idea of kruskal minimum spanning tree. First I tried to build roads with type 3 as both can access. If a road form a cycle,then that can be taken as extra road which can be remove. Similary for men tried to build road with type 3 & type 1 , for women type 3 & type 2. While building for men & women the type 3 road would have been already built.
Can you explain the example? I have trouble understanding why the output would be 2.
- If you remove the 1-2 road, then no one can go from 1 to 2.
- If you remove the 2-3 road, then no one can go from 2 to 3.
- If you remove the 3-4 road, then neither women nor men can go from 3 to 4 or vice versa.
- If you remove the 5-3 road, then women can't go from 5 to 3.
- If you remove the 5-4 road, then men can't go from 5 to 4.
Unless you're allowed to change the type of roads, no road can be removed without blocking traffic.
If this problem didn't have the sexual discrimination part, I think you could solve it using a disjoint-set. For all cities to be connected, they should all exist in one set, AKA have the same 'parent' city. Therefore, for each edge (x,y), If both x and y already share a parent (in other words, if find(x)==find(y)), then the road provides a redundant connection. If they aren't connected, do union(u, v) and increase count of roads.
I'm not totally sure about this, but I think to solve the sexism part you could keep two sets. One set for male connectivity and one set for female connectivity. For two cities (x, y) to be connected, they need to satisfy find(x, y) for both male and female sets. Like before, you throw away a road if both x, y are already connected, and do union on sets that need connecting (for type 3 do both sets).
There is an additional stipulation that if your new road is type three and the previous connection was made using two roads, you can replace the two sexist roads with a type 3 road (resulting in a count--). But how do you know if the old connection was made using sexist roads? You could keep a data structure to keep track, but I think an easier way of doing it is to sort the input to handle all the type 3 roads first, then do type 1/2 roads.
At first glance I think this would work but I wouldn't be surprised if there was a problem.
Well, it's ugly and brute-force, but:
- cjudge@grandecom.net May 04, 2017