Tuesday, May 31, 2016

This is a continuation of the series of coding exercises from previous posts to see a sample of the interview questions being asked.

#codingexercise
1. An Array of buildings is facing the sun. The heights of the buildings is given in an array, Find out which all buildings will see the sunset.
List<int > SeeSunsetBuildings(List<int> heights)
{
var ret = new List<int>();
if (heights.Count == 0) return ret;
int min = heights[0];
for (int i =1; i < heights.Count; i++)
{
if (heights[i] > min)
    ret.Add(heights[i])
}
return ret;
}
2. Print all nodes at a distance k from a given node
void printKDistanceDown(Node root, int k)
{
if (root == null || k < 0) return;
if (k == 0)
   Console.Write(root.data);
printKDistanceDown(root.left, k-1);
printKDistanceDown(root.right, k-1);
}

// returns distance of root from target
int PrintKDistanceNode(Node root, Node target, int k)
{
if (root == null) return -1;
if (root == target){printKDistanceDown(root, k); return 0;}
int dl = printKDistanceNode(root.left, target, k);
if (dl != -1)
{
   if (dl + 1 == k)
       Console.Write(root.data);
   else
       printKDistanceDown(root.right, k -dl-2);
   return 1 + dl;
}
int dr = printKDistanceDown(root.right, target, k);
if (dr != -1)
{
      if (dr +1 ==k)
         Console.Write(root.data);
      else
          printKDistanceDown(root.left, k-dr-2);
      return 1+dr;
}
return -1;
}

3. Count the decoding for a given digit string. Let say ‘A’ -> 1, B -> 2 and so on
 Eg : Input: digits[] = “123”
Output: 3  //”ABC”, “ LC” ,  “AW”

bool GetCode(string digits, ref stringbuilder candidate, ref int count)
{
if (digits.length == 0) { Console.Write(candidate.toString()); count += 1; return true; }
for (int i =0; i < 2 && i<=digits.length; i++)
{
  int code = int(digits.Substring(0,i+1);
  if (code >=1 && code <=26){
         candidate.add(lookup(code));
        if ( GetCode(digits.GetRange(i+1,digits.length-i-1), ref candidate,  ref count))
         return true;
}
return false;
}

Find the maximum sum root to leaf in a tree
Void getLeafMax ( node root, int sum,  ref int max)
{
If (root == null) return;
Sum += root.data;
If (root.left == null && root.right == null)
{
If sum > max
    sum = max;
}
Getleafmax (root.left, sum, max);
Getleafmax (root.right, sum, max);

No comments:

Post a Comment