Amazon Interview Question
Software EngineersCountry: United States
Interview Type: In-Person
#include <list>
#include <unordered_set>
struct Node {
int ID = 0; // >= 0
int parentID = -1; // no parent
};
// Create a hash set to store traversing nodes.
// Insert node[i] into the set once node[i] has its parent in the set.
// If parent of node[i] is not found in the set, then the list is not given in preorder.
bool IsInPreorder(const std::list<Node> &list) {
if (list.empty())
return true;
if (list.size() == 1)
return list.front().parentID == -1;
std::unordered_set<decltype(Node::parentID)> parents;
parents.insert(list.front().ID);
auto i = list.begin();
for (++i; i != list.end(); ++i) {
if (parents.find(i->parentID) == parents.end())
return false;
parents.insert(i->ID);
}
return true;
}
def isPreOrder(nodelist):
"""
:type nodelist: List[Node]
:rtype: bool
"""
# Node = namedtuple('Node', ['parentid', 'nodeid'])
# Each node is written as parentid:nodeid
# Examples are written in this form:
# [parentid1:nodeid1, parentid2:nodeid2, parentid3:nodeid3, ...]
if nodelist[0].parentid == 0:
return False
parent_to_check = nodelist[0].parentid
for count in range(1, len(nodelist)):
if nodelist[count].nodeid == parent_to_check:
if nodelist[count + 1].parentid == parent_to_check:
return False
else:
return True
Sorry my earlier answer did not cotain explanations. This is the improved answer.
def isPreOrder(nodelist):
"""
:type nodelist: List[Node]
:rtype: bool
"""
# This example accounts for the fact when the tree is not a binary tree
# Node = namedtuple('Node', ['parentid', 'nodeid'])
# Each node is written as parentid:nodeid
# Examples are written in this form:
# [parentid1:nodeid1, parentid2:nodeid2, parentid3:nodeid3, ...]
# Solution
# (a) Scan the nodelist from left to right.
# (b) If the parent id of the first node is null or 0, then it is a postorder. Reject and
# declare that it is postorder.
# (c) If the parent id is not null or 0, then store the parent id as p.
# (d) Scan the nodelist till the id of the current node being scanned matches p.
# (e) Check the following node. If the node's parent id matches p, then reject and declare
# that it is inorder. Otherwise, declare that it is preorder
if nodelist[0].parentid == 0:
return False
parent_to_check = nodelist[0].parentid
for count in range(1, len(nodelist)):
if nodelist[count].nodeid == parent_to_check:
if nodelist[count + 1].parentid == parent_to_check:
return False
else:
return True
In preorder, parent node is visited before child node. The solution is to traverse the list left to right. Maintain the stack of traversed nodes, if a current node.parent is not equal to stack.peek(), pop the stack until found or stack is empty. If found. add current node. if stack is empty, meaning the current node.parent haven't visited, return false.
Below is the code snippet:
public boolean isPreorderedList(List<Tree.Node<Integer>> inList) {
Stack<String> parents = new Stack<String>();
for (Tree.Node<Integer> aNode : inList) {
// Add root node
if (aNode.getParentId() == null) {
parents.push(aNode.id());
continue;
}
while (!parents.isEmpty()) {
if (aNode.getParentId().equals(parents.peek())) {
parents.push(aNode.id());
break;
}
else {
parents.pop();
}
}
if (parents.isEmpty()) {
return false;
}
}
return true;
}
import java.io.*;
import java.util.*;
class MyCode {
static class Node {
public int nodeId;
public int parentId;
Node(int a, int b){
this.nodeId = a;
this.parentId = b;
}
}
public static boolean isPreOrdered(ArrayList<Node> tree) {
Stack<Integer> checker = new Stack<>();
// first node should be root node
if(tree.get(0).parentId != 0)
return false;
// adding root in stack
checker.add(tree.get(0).nodeId);
for (int i=1; i<6; i++){
Node node = tree.get(i);
// check if parent node exist in stack
if (checker.search(node.parentId) != -1){
Node temp = tree.stream().filter(t -> node.parentId == t.nodeId).findAny().orElse(null);
if (temp != null){
checker.add(node.nodeId);
}
else {
while(checker.peek() != node.parentId)
checker.pop();
}
}
else
return false;
System.out.println(node.nodeId);
}
return true;
}
public static void main (String[] args) {
ArrayList<Node> myList = new ArrayList<>();
myList.add(new Node(1,0));
myList.add(new Node(6,5));
myList.add(new Node(2,1));
myList.add(new Node(3,1));
myList.add(new Node(4,3));
myList.add(new Node(5,3));
// check if pre-ordered
boolean answer = isPreOrdered(myList);
System.out.println(answer);
}
}
Looking for interview experience sharing and coaching?
Visit AONECODE.COM for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates of FB, LinkedIn, Amazon, Google & Uber etc.)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn, MS and other top-tier companies after weeks of training.
Email us aonecoding@gmail.com with any questions. Thanks!
- aonecoding January 06, 2018