Your method is super interesting. I think the theme of this question was to use topological sort O(V+E), but you've solved it using custom sort function O(nlogn). Nice use of the custom sort option (and the set it to 1 whenever the ordering is False). In terms of the sorting efficiency though not sure it would be efficient as it would have many 'equal' comparisons (harder to divide and conquer?)