Amazon Interview Question


Country: United States
Interview Type: In-Person




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

first find the max sum in tree and then search for path for max sum in the tree.
below c++ function will give you the result.
global variable: vector <int> v, int s=0 and int sum=0;

void maxSum(node * root) {
	if( root == NULL) 
		return;	
	sum += root->data;
	maxSum( root->left);
	maxSum( root->right);
	if( root->left == NULL && root->right == NULL) 
		if( s < sum ) s = sum;	
	sum -= root->data;
}
void hasPathSum( node * root, int sum) {
	if( root == NULL) return ;
	else {
		int subSum = sum - root->data;
		v.push_back( root->data);
		if( subSum == 0 && root->left == NULL && root->right ==NULL)
			for( int i=0; i<v.size(); i++) cout<<v[i]<<"->";
		hasPathSum(root->left, subSum);
		hasPathSum(root->right, subSum);
		v.pop_back();
	}
}

- Ratn October 14, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Can you Please explain how would you reach the code line
maxSum( root->right);

- REAMS.AL October 17, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@REAMS.AL it's just normal tree traversal. just like we do in preOrder / inOrder Traversal. sum(variable) keep adding the root data as we move to left node until reaches the leaf node. When we reach to left most node, sum(variable) will have the sum of all left node value (included root value) and then move to right to explore other possibility. The moment it reaches to leaf node, if s < sum then update s(variable) and decreament the sum by current root->data.

- Ratn October 18, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

I have a solution but the run time is horrible (n^3 I think, correct me if wrong), I thought of a couple ways to optimize but they are complicated. If anybody knows something with better run time please post.

int findMax(Node * root)
{
    if (!root) return 0;
    return root->value + std::max(findMax(root->left), findMax(root->right));
}


void printMaximalPath(Node * root)
{
     std::cout << root->value << std::endl;
     int maxLeft = findMax(root->left);
     int maxRight = findMax(root->right);
     if (maxLeft < maxRight)
          printPath(root->right);
     else if (maxRight < maxLeft)
          printPath(root->left);
     else
          return; //Leaf node reached
}

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

A solution using DFS or BFS has the run time O(V+E) for worst case.

- marcelovox2 October 13, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

yeah here's my updated solution that is order (n + n). The maximum paths are stored in the node itself, could just as easily be stored in another data structure.

long findMax(node * root)
{
    callCount++;
//
    if (!root) return 0;
	
	long maxLValue = 0;
	if (root->maxLeft != -1)
	{
		maxLValue = root->maxLeft;
	}
	else
	{
		root->maxLeft = findMax(root->left);
		maxLValue = root->maxLeft;
	}
	
	long maxRValue = 0;
	if (root->maxRight != -1)
	{
		maxRValue = root->maxRight;
	}
	else
	{
		root->maxRight = findMax(root->right);
		maxRValue = root->maxRight;
	}
	
    return ((long) root->data) + std::max(maxLValue, maxRValue);
}

void printMaximalPath(node * root) //this is an order N algoritm as well
{
    std::cout << root->data << std::endl;
    long maxLeft = findMax(root->left); //order N call first time, 0(1) for all other calls
    long maxRight = findMax(root->right);
    if (maxLeft < maxRight)
        printMaximalPath(root->right);
    else if (maxRight < maxLeft)
        printMaximalPath(root->left);
    else
        return; //Leaf node reached
}

- Anonymous October 14, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

int global_max=0;
ArrayList<TreeNode> global_max_path=null;

void findMaxPath (TreeNode t, int sum, ArrayList<TreeNode> path)
{
	if(t == null)
	{
		if(sum > global_max)
		{
			global_max=sum;
			global_max_path = path;
		}
	}
	else
	{
		 ArrayList<TreeNode> left_path = new ArrayList<TreeNode>(path);
		 findMaxPath(t.left,sum+t.data,path.add(t));
		 
		 ArrayList<TreeNode> right_path = new ArrayList<TreeNode>(path);
		 findMaxPath(t.right,sum+t.data,path.add(t));	
	}

}

findMaxPath(t,0,new ArrayList<TreeNode>());

- DeathEater October 26, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

does it mean the sum of values on the path is maximum or path to the node with max value

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

sum of the values on the path is maximum

- freeninza October 13, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Binary tree we cant assume it is sort(BST), in that case I'd use a DFS(depth-first search), visiting all paths from the root. You can keep in a separeted structure the max sum found and the nodes visited.... You can even considering using a max priority queue to support it.

- marcelovox2 October 13, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

What is the definition of a path..start at root and ends at leaf? or start at root and ends at leaf or non-leaf node? or start at leaf and ends at leaf with/without root as an intermediate node? or start at non-leaf and end at non-leaf? or any combo?

- Abhishek October 13, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def dfsMax(bt, n="root", path=[], maxPath=[],  maxData=None):
    #Init
    if n=="root":
        n=bt.root
    if maxData==None:
        maxData=n.data
    if n==None:
        return maxPath

    path.append(n)

    #Update Max Path    
    if n.data >maxData:
        maxPath = list(path)
        
    maxPathL=dfsMax(bt, n.left, path, maxPath, maxData)
    maxPathR=dfsMax(bt, n.right, path, maxPath, maxData)
    
    path.pop(-1)
          
    if len(maxPathL)==0:
        return maxPathR
    if len(maxPathR)==0:
        return maxPathL

    if (maxPathL[-1].data>maxPathR[-1].data):
        return maxPathL
    else:
        return maxPathR

- Will October 21, 2012 | 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