Amazon Interview Question for Software Engineer / Developers


Country: United States
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
3
of 3 vote

Use queue to traverse level by level and stack to hold all elemnts in reverse order.

@Override
	public String toString(){
		
		StringBuilder strRepr = new StringBuilder();
		strRepr.append("[");
		
		Deque<Node<T>> workingQueue = new ArrayDeque<>();
		workingQueue.add( root );		
		
		Deque<Node<T>> resStack = new ArrayDeque<>();
		
		while( ! workingQueue.isEmpty() ){
			Node<T> node = workingQueue.pollFirst();
			
			resStack.push( node );
			
			if( node.hasChildren() ){				
				 List<Node<T>> children = new ArrayList<>( node.getChildren() );
				 Collections.reverse( children );				
				 workingQueue.addAll( children );
			}
		}
		
		while( true ){
			
			strRepr.append( resStack.pop() );
			
			if( resStack.isEmpty() ){
				break;
			}
			
			strRepr.append( "," );
		}
		
		strRepr.append("]");
		
		return strRepr.toString();
	}

- m@}{ June 08, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Hey, thanks a ton for this. Trying to go thru the logic, but a little difficult to undersatnd without comments for someone new to collections. Could you plese comment on the time complexity of this and Could you please port it to the following function and interface so that i can test it.
Thanks a ton!
method name: void displayBFSReverse (Node head);

Where Node implements the interface:

interface Node {

public String getNodeData ();

public List<Node> getChildren ();

}

- chaos June 08, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Starting to sound a little like homework...

(Honestly, in all fairness, if you're new to collections, this problem is probably not the first problem you should be attempting.)

- Anonymous June 09, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Its an interview question and I wanted a working code so that I can build on what I know, at times there is a syntax issue which takes up a lot of time rather than the logic and I wanted to avoid that and hence the request to fit it in the implementation..... thanks a ton :)

- chaos June 10, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Use a set to hold the nodes , starting from root node for each level obtain the list of nodes and add them to stack or queue . Push the queue or stack to the set defined initially ,

After traversing all the levels , retrieve elements from the set starting from the last element and print them

- kk June 08, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Add the queue and stack alternatively for every level to the set

- kk June 08, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote
public void printReverse(Node head)//C# {{{{ ArrayList arrL = new ArralyList(); List<Node> newList = new List<Node>(); newList.add(head); while(newList.Count!=0) {{{{ List<Node> lastList = newList; newList= new List<Node>(); arrL.add(lastList); foreach(Node nd in lastList) {{{{ newList.AddRange(nd.getChildClass().Cast<Node>()); }}}}//end of foreach }}}}//end of while lastList for(int i=arrL.Count-1;i=0;i--) {{{{ printList(arrL[i]); }}}}//end of for arrL }}}}//end of function public void printList(List<Node> lst) {{{{ ///print it. }}}} - Frank June 08, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void displayTree_BreadthFirst(Node root) {
        Queue<Node> queue = new LinkedList<Node>();
        Stack<Node> stack = new Stack<Node>();
        queue.add(root);
        stack.push(root);
        while (!queue.isEmpty()) {
            Node node = queue.poll();
            System.out.printf("%3d", node.element);
            if (node.left != null) {
                queue.add(node.left);
                stack.push(node.left);
            }
            if (node.right != null) {
                queue.add(node.right);
                stack.push(node.right);
            }
        }
        System.out.println();
        while (!stack.isEmpty()) {
            System.out.printf("%3d", stack.pop().element);
        }
    }

Output
=====
Regular = 1 2 3 4 5 6 7
Reverse = 7 6 5 4 3 2 1

Was the question asked to use constant space OR can a queue be used OR can a queue and stack be used ?? Was there any limitation on available space?

- Singleton June 09, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Its a written question. The question says that one needs to reverse the tree in BFS.
The Tree Structure is

34
                            /         |        \
                          3          56        12
                    /         \                  |
                 89            7               22
                                                 |
                                                78
reverse in BFS and return should return

78 22 7 89 12 56 3 34

Comment on the time complexity of the problem and

The code need to fit the following method and interface.

method name: void displayBFSReverse (Node head);

Where Node implements the interface:

interface Node {

public String getNodeData ();

public List<Node> getChildren ();

}

- chaos June 10, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

And yes, as mentioned earlier, its not a binary tree. Its a n-ary tree so there can be more than two children for a node. So we cannot assume left and right nodes.

Can you please help me with a n-ary solution??

- chaos June 11, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

as previous commenter said, really depends on the space constraints. below code in c++.

int ReverseBFS(Node* root) {
  vector<Node*> nodes;
  int i=0;
  nodes.push_back(root);
  while (i < nodes.size()) {
     for (int j=0;j<nodes[i]->children.size();j++) {
        nodes.push_back(nodes[i]->children[j]);
     }
     i++;
  }
  for (int i=nodes.size()-1;i>=0;i--) {
     cout << nodes[i]->value << " ";
  }
  cout << endl;
  return 0;
}

if there'll be back, forward or cross edges, need to maintain a separate visited array.

- balajinix June 10, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.algorithms;

import java.util.ArrayList;
import java.util.List;

public class BFS {
private static List<String> list = new ArrayList<String>();
public static void main(String[] args){
BFSNode rootNode = new BFSNode("1");
List<BFSNode> childrenNodeListFirst = new ArrayList<BFSNode>();
childrenNodeListFirst.add(new BFSNode("2"));
childrenNodeListFirst.add(new BFSNode("3"));
childrenNodeListFirst.add(new BFSNode("4"));
rootNode.childrenNodeList = childrenNodeListFirst;

BFSNode childNode = childrenNodeListFirst.get(0);
List<BFSNode> childrenNodeListSecond = new ArrayList<BFSNode>();
childrenNodeListSecond.add(new BFSNode("5"));
childrenNodeListSecond.add(new BFSNode("6"));
childNode.childrenNodeList = childrenNodeListSecond;

childNode = childrenNodeListFirst.get(2);

List<BFSNode> childrenNodeListFourth = new ArrayList<BFSNode>();
childrenNodeListFourth.add(new BFSNode("7"));
childrenNodeListFourth.add(new BFSNode("8"));
childNode.childrenNodeList = childrenNodeListFourth;

childNode = childrenNodeListSecond.get(0);
List<BFSNode> childrenNodeListFifth = new ArrayList<BFSNode>();
childrenNodeListFifth.add(new BFSNode("9"));
childrenNodeListFifth.add(new BFSNode("10"));
childNode.childrenNodeList = childrenNodeListFifth;

childNode = childrenNodeListFourth.get(0);
List<BFSNode> childrenNodeListSeventh = new ArrayList<BFSNode>();
childrenNodeListSeventh.add(new BFSNode("11"));
childrenNodeListSeventh.add(new BFSNode("12"));
childNode.childrenNodeList = childrenNodeListSeventh;

List<BFSNode> queue = new ArrayList<BFSNode>();
queue.add(rootNode);
BFSTraverse(queue);

for(int i=list.size()-1;i>=0;i--){
System.out.println("Node : "+list.get(i));
}
}

public static void BFSTraverse(List<BFSNode> queue){
while(!queue.isEmpty()){
BFSNode node = dequeue(queue);
list.add(node.nodeName);
//System.out.println("Node : "+node.nodeName);
if(node.childrenNodeList!=null){
enqueue(node.childrenNodeList,queue);
}
BFSTraverse(queue);
}
}

public static void enqueue(List<BFSNode> childNodeList,List<BFSNode> queue){
for(int i=0;i<childNodeList.size();i++){
queue.add(childNodeList.get(i));
}
}

public static BFSNode dequeue(List<BFSNode> queue){
BFSNode node = queue.get(0);
queue.remove(0);
return node;
}
}


class BFSNode{
List<BFSNode> childrenNodeList;
String nodeName;

public BFSNode(String nodeName){
this.nodeName = nodeName;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
}

- entityvsentityv2 June 13, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Could you please add a few comments and a general explanation for the same.

Thanks!

- chaos June 13, 2012 | Flag


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