Ctrl K

Friendships Despite Feuds

Hard
A community has people members numbered 0 to people - 1; at first nobody is friends with anyone. The list feuds holds pairs [x, y]: these two are feuding and must never end up in the same circle, neither directly nor through a chain of friends. Friend requests requests[j] = [u, v] are processed in order. A request is accepted if afterwards no feuding pair is connected by a chain of friendships; then u and v become friends. Otherwise it is rejected and changes nothing. If u and v are already in the same circle, the request is simply accepted. Return a list of True/False values, one per request.
Example 1
people=4, feuds=[[0, 3]], requests=[[0, 1], [2, 3], [1, 2], [1, 0]] → [True, True, False, True]

0 and 1 become friends, then 2 and 3. Request 1–2 would link 0 and 3 through friends, so it is rejected. Request 1–0 is accepted since they are already friends.

Example 2
people=3, feuds=[], requests=[[0, 1], [1, 2]] → [True, True]

There are no feuds, so every request is accepted.

Example 3
people=5, feuds=[[1, 4], [0, 2]], requests=[[0, 4], [3, 1], [3, 4], [2, 3]] → [True, True, False, True]
Constraints
  • 2 ≤ people ≤ 1000
  • 0 ≤ len(feuds) ≤ 1000
  • 1 ≤ len(requests) ≤ 1000
  • Each pair holds two different numbers from 0 to people - 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsThe Extra Link in a Rooted Tree HardPartners Side by Side HardWhich Machine to Cure HardWhich Machine to Unplug HardWater for the Whole Village Hard
loading Python…
Input
people=4, feuds=[[0, 3]], requests=[[0, 1], [2, 3], [1, 2], [1, 0]]
Expected
[True, True, False, True]

Run checks the first 3 tests in your browser. Submit checks all 75 tests on the server, hidden ones included.