A social app processes m friend-link requests over n users (numbered 1 through n), in the given order. A request joining users u and v is called redundant if, at the moment it is processed, u and v are already in the same friend circle — that is, they are already connected directly or through a chain of earlier links (a request that links a user to themselves is also redundant). A non-redundant request adds a new link; a redundant request changes nothing.
Count how many of the m requests are redundant.
n and m.m lines: two integers u and v (1-indexed), the request to link u and v, in processing order.A single integer: the number of redundant requests.
Example 1
Input
4 4 1 2 2 3 3 1 3 4
Expected
1
Explanation
The first two links join {1,2,3}. The third link (3-1) is redundant because 3 and 1 are already connected. The fourth link (3-4) is new. So 1 request is redundant.
Example 2
Input
3 2 1 2 2 3
Expected
0
Explanation
Both links connect previously separate users, so none are redundant.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →