Skip to main content
1 of 2

Algorithm to match / link complementary pairs

I'm working on a problem where I have a large number of pairs

e.g

1 -> 2

4 -> 3

2 -> 8

..

And a "match" would be considered 1 -> 2 and 2 -> 8 to make 1 -> 2 -> 8, as "1 -> 2" ends with 2 and "2 -> 8" starts with 2.

Given a large set of pairs, i'd like to create the longest possible chain. I know I could brute force it, but I'm wondering if there is a better way