I was able to get this problem accepted in C++ using a simple approach: read the input, record the parent of each node, then for each query, generate the path from each node to the root, reverse both paths, and look for the rightmost position at which both paths have the same node.

I have not been able to get accepted in Java. I think it might have to do with the input method. I use BufferedReader and to read lines that contain multiple integers, I call readLine(), then split(" "), and then Integer.parseInt() for each resulting element. But I see that other people have gotten this problem accepted in Java. Any tips?

  • created

    Apr '24
  • last reply

    Apr '24
  • 1

    reply

  • 341

    views

  • 2

    users

  • 2

    links

Wikipedia describes that approach as brute force. Have you tried one of the more efficient algorithms, such as those described here8?