Two autonomous delivery drones, A and B, each fly a fixed, ordered route of checkpoints from their own warehouse to a shared drop site. Every checkpoint on either route is identified by a distinct positive integer ID. It sometimes happens that, from some point onward, drone A's remaining checkpoints and drone B's remaining checkpoints are exactly the same sequence of IDs in the same order, all the way to the drop site -- that is, the two routes merge onto a common trailing path. Given both complete routes, find the ID of the very first checkpoint at which the two routes merge, or determine that they never merge.
The first line contains two integers n and m (1 <= n, m <= 20000) -- the number of checkpoints on drone A's route and on drone B's route. The second line contains n space-separated integers (1 <= id <= 10^9): drone A's checkpoint IDs, in the order it visits them. The third line contains m space-separated integers (1 <= id <= 10^9): drone B's checkpoint IDs, in the order it visits them. It is guaranteed that either (a) the two routes share no checkpoint at all, or (b) there exists an integer k >= 1 such that the last k IDs of A's route are, in order, identical to the last k IDs of B's route -- and that in either case, no checkpoint ID outside of that shared trailing path ever repeats anywhere in the combined input.
Print a single integer: the ID of the first checkpoint of the shared trailing path (i.e. drone A's route's ID at position n-k), or -1 if the two routes never merge.
Example 1
Input
5 4 2 7 11 4 1 9 11 4 1
Expected
11
Explanation
Drone A's route ends in the tail [11, 4, 1], and drone B's route (after its own lone prefix checkpoint 9) ends in that exact same tail. The routes therefore merge starting at checkpoint 11, the first ID of the shared tail.
Example 2
Input
3 3 1 2 3 4 5 6
Expected
-1
Explanation
None of drone A's checkpoints (1, 2, 3) appear anywhere on drone B's route (4, 5, 6), so the two routes never merge and the answer is -1.
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 →