Amazon Interview Question
Software EngineersCountry: United States
Interview Type: In-Person
Solution in java, memory is constant and time is linear (amortized)
public class Solution {
// Node class
private class Node {
int ID;
Node parent;
}
public boolean isPreOrder(List<Node> nodes) {
// Assume that empty list represents correct tree
if (nodes.size() == 0) {
return true;
}
Node prev = nodes.get(0);
// Root has no parent otherwise not pre-order
if (prev.parent != null) {
return false;
}
for (int i = 1; i < nodes.size(); i++) {
Node current = nodes.get(i);
// There is only one root node
if (current.parent == null) {
return false;
}
// Find parent in current list of actively exploring
while (prev != null && current.parent.ID != prev.ID) {
prev = prev.parent;
}
// It means that we have not visited such element or we visited but we already marked subtree as done
if (prev == null) {
return false;
}
// Explore current's subtree
prev = current;
}
}
return true;
}
I think the keep it simple, stupid works better here.
1. Construct a graph from the list ( it is a type of adj list anyways )
2. Check if the graph is a tree first.
2.1 In that case, there must be no cycle
2.2 and one clear node with null parent.
3. Do a pre-order traversal on that "tree" and check at any point if there is any discrepancy
from the already given traversal.
Looking for interview experience sharing and mentors?
- acoding167 May 07, 2019Visit A++ Coding Bootcamp at aonecode.com.
Taught by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greed and other advanced algo problems),
and mock interviews.
Our students got offers from Google, Uber, Facebook, Amazon and other top companies after a few weeks of training.
Welcome to email us with any questions. Thanks for reading.