You are on page 1of 3

 

Interview Camp 

 
Technique: Record and Move On 

Level: Medium 

Given a BST that can contain duplicate elements, find the first occurrence of a number N. 
 
Questions to Clarify: 
Q. If there is a duplicate element, will it be on the left or right side of an equal element? 
A. It can be on either side. 
 
Q. By first occurrence, you mean a node that would come first in an inorder traversal? 
A. Yes, that is correct. 

Solution: 
We use the ​Record and Move On​ technique. This is very similar to the ​Record and Move On​ technique we 
used in Binary Search. 
 
The idea is that when we do a binary search, we are moving closer to our target element. If we find a 
node equal to the target, we record it in a variable. We then continue our search on the left, because if 
there is another equal node that came earlier, it will be on the left. 
 
After we're done with our search, the variable will have the earliest occurrence of the target. 
 
Follow Up Question​: What if you wanted the last occurrence of target? 

Pseudocode: 
current = root
result = null
while current != null
if current > target
go left
else if current < target
go right
else
result = current
go left

Test Cases: 
Edge Cases: empty tree 
Base Cases: single node tree 
Regular Cases: target not in tree, target occurs once, multiple times 

Time Complexity:​ O(h) 

Space Complexity:​ O(1) 


 

 
 
© ​2017 Interview Camp (interviewcamp.io) 
 
Interview Camp 

public static Node findFirstOccurence(Node root, int target) {


Node current = root;
Node result = null;
while (current != null) {
if (current.getValue() > target) {
current = current.getLeft();
} else if (current.getValue() < target) {
current = current.getRight();
} else {
result = current;
current = current.getLeft();
}
}
return result;
}

/*
* Helper code. Implement only if the interviewer wants you to.
*/
public class Node {
Node left;
Node right;
int value;

public Node() {
super();
}

public Node getLeft() {


return left;
}

public void setLeft(Node left) {


this.left = left;
}

public Node getRight() {


return right;
}

public void setRight(Node right) {


this.right = right;
}

public int getValue() {


return value;
}

 
 
© ​2017 Interview Camp (interviewcamp.io) 
 
Interview Camp 

public void setValue(int value) {


this.value = value;
}
}
 

 
 
© ​2017 Interview Camp (interviewcamp.io) 

You might also like