@SimonW Thanks. Unfortunately, it does not work if the inputs are:
x = torch.LongTensor([1,5,3,4])
y = torch.LongTensor([5,3,4,1])

The correct output is tensor([1, 2, 3, 0]), but your method outputs tensor([3, 2, 0, 1]).