Recently did my phone screen for London location. Below two questions were asked-
I solved the second question with O(N) space which can be done in O(1). I realised it after solving the problem. Hence got rejected. :(
Adding my solution for reference:
public Node LCA(Node a, Node b) {
Set<Integer> nodes = new HashSet<>();
while (a != null) {
nodes.add(a.val);
a = a.parent;
}
while (b != null) {
if (nodes.contains(b.val)) return b;
b = b.parent;
}
return b;
}