Amazon Interview Question for Software Engineers


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
2
of 4 vote

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!

class Node:
    def __init__(self, ID, parent):
        self.ID = ID
        self.parentID = parent
        self.left = None
        self.right = None

#function to identify if given is preorder
'''
Create a stack to store nodes in the current path when traversing.
Push node[i] into stack once node[i] is verified to be valid (valid only when parent of node[i] is in stack. 
In preorder a parent must show up earlier than its child)
Whenever stack top is not the parent of node[i], pop until parent of node[i] is at stack top. Push node[i].
If all nodes popped but parent of node[i] still not found, then node[i] is not in preorder sequence.
'''
def isPreorder(nodes):
    if not nodes:
        return True
    
    st = [nodes[0].ID]
    i = 1
    while i < len(nodes):
        if not st:
            return False
        if st[-1] is nodes[i].parentID:
            st.append(nodes[i].ID)
            i += 1
        else:
            st.pop()
    return True

- aonecoding January 06, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#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;
}

- S.M. January 07, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

- Okusanya.Damilola January 11, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

- Okusanya.Damilola January 11, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
	}

- Nick N. January 31, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);
	}
}

- Sahiba October 31, 2019 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More