KatInterview

Players Whose Leaderboard Position Is Forced

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsgraphtopological-sorttransitive-closure

Last updated

Find every player comparable to all others in a consistent win/loss DAG, using transitive reachability in both directions, ideally with bitsets.

A tournament has n players, numbered 1 through n. Only some games have been played. Each result is a pair [winner, loser] in the list results, meaning winner finished strictly above loser.

Rankings are transitive. If a is above b and b is above c, then a is above c. Those are the only inferences you may make. Two players you cannot compare through a chain of results may be in either order in some valid final ordering.

A player's final position is forced when every valid complete ordering consistent with the results puts that player in the same place. This happens exactly when, for every other player x, you can infer that the player is above x or that x is above the player (through a direct result or a chain of results).

The results are guaranteed to be consistent, so they contain no cycles.

Return the labels of all players whose position is forced, as a list sorted in ascending order.

Special cases:

  • If n = 1, the only player is trivially forced, so the answer is [1].
  • If there are no results and n > 1, nobody is forced, so the answer is [].
  • A player with no connection to the others cannot be forced when n > 1.

Constraints

  • 1 <= n <= 500
  • 0 <= len(results) <= 10^4
  • Each entry is [winner, loser] with 1 <= winner, loser <= n and winner != loser.
  • All pairs in results are distinct.
  • The results contain no cyclic contradictions.
  • Return the player labels in increasing order.

Examples

Example 1

Input: forced_position_players(5, [[4, 3], [4, 2], [3, 2], [1, 2], [2, 5]])

Output: [2, 5]

Example 2

Input: forced_position_players(3, [[1, 2], [2, 3]])

Output: [1, 2, 3]

Hints

Hint 1

Treat each result as a directed edge winner -> loser. A player is known to be above another exactly when a directed path leads from one to the other.

Hint 2

A player's position is forced exactly when the number of players it can reach plus the number of players that can reach it equals n - 1. In a DAG these two groups never overlap.

Hint 3

Compute reachability with one bitmask per player, processing nodes in topological order. Do a forward pass for 'who can reach me' and a reverse pass for 'who I can reach', so you avoid an O(n^3) closure.