Interview Question for Software Engineer / Developers


Country: United States




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

I think it's not correct as in your case it seems like every path in the tree should start in the root of the tree. I guess print_path_with_sum is the first function to be called, and it start counting the sum from this place. But what if the sum starts later let's say having a following binary tree (you didn't mention it's binary search tree so will keep it just as binary tree) and you look for sum 5?

root:                   1
level 1:         2           8
level 2:   4         3

Obviously the sum is there but looks like 2, 3, and doesn't start from the root. The solution to this problem is described in Cracking Coding Review book AFAIR.

- joe kidd August 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

joe kidd, thanks for your response. Apparently you missed that fact that the main function (print_path_with_sum) calls the inner function (search_to_bottom) for EVERY node in the tree. So it will find other paths than those starting at the root.

I know the solution from the Cracking the Coding Interview book, I just wanted to present my approach and get some opinions.

Running on some sample data, it seems that my function visits fewer nodes than the book's solution. But they are probably equal in the worst case.

- ks4394 August 20, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Ah yeah, sorry it was arround 2 am when I took a look at this: then it's absolutely correct :) The problem now is that you make some extra work analysing the same node several times instead of just once. But the correctness of solution is preserved.

- joe kidd August 20, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

your answer is correct~

- fword August 22, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Store all the values from the tree in an array in an inorder traversal form. Of course it wont give us a sorted array as it is not a binary search tree but then in the array just apply the sum of subsets algorithm to generate all the possible paths in the array. Now two scenarios arise:
a. If in the path the root node of the tree is included then just subtract the root node from the sum and then check for the remaining sum subset in the array.
b. If in the path root node is not to be included then just apply the sos algorithm and you will get all the paths that lead us to a given sum

- vgeek August 20, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void checkPath(Node<T> cur, int actualSum, int expectedSum, Deque<T> path ){
		
		if( cur == null || actualSum > expectedSum ){
			return;
		}
		
		actualSum += (Integer)cur.value;
		path.push( cur.value );
		
		if( actualSum == expectedSum && cur.isLeaf() ){
			System.out.println( path );
			path.pop();
		}
		else {				
			checkPath(cur.left, actualSum, expectedSum, path);
			checkPath(cur.right, actualSum, expectedSum, path);
			
			path.pop();
		}
		
	}

- m@}{ August 21, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Using depth first search on the tree, create a hashtable with all the paths and there corresponding sum, then iterate through the hashtable to get the sum. To save the iteration of hashtable, we can instantly print the result

Hashtable ht = new Hashtable();
        int MySum = 0;
        List<MyNode> MyPath = new List<MyNode>();

        private ArrayList GetAllPathWithSum(int sum)
        {
            ArrayList result = new ArrayList();
            MyNode node = tree.root;

            GetMyHash(node);

            var e = ht.GetEnumerator();

            while (e.MoveNext())
            {
                int CurrentKey = Convert.ToInt32(e.Value);
                if (CurrentKey == sum)
                    result.Add(e.Key);

            }

            return result;
        }

        private void GetMyHash(MyNode node)
        {
            if (node != null)
            {
                MySum += node.Value;
                MyPath.Add(node);

                ht.Add(MyPath.ToArray(),MySum );

                GetMyHash(node.Left);
                GetMyHash(node.Right);

                int iLastNodeIndex = MyPath.Count - 1;
                MySum -= MyPath[iLastNodeIndex].Value;
                MyPath.RemoveAt(iLastNodeIndex);
            }
            
        }

- Pooja Singh August 27, 2013 | 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