Thursday, July 2, 2015

Codingexercise:
Given a linked list say
LL = 1-2-3-4 and the position k = 2, swap the nodes k and n-k such that the output now becomes:
1-3-2-4

Node Swap(Node left, Node right, Node prevleft, Node prevright, Node root)
{
  Assert(left != NULL  && right != NULL)
  // prevleft left leftnext prevright right nextright
  // prevleft right leftnext prevright left nextleft
  if (left == right) return root;
  Node leftnext  = left.next;
  Node rightnext  = right.next;
  left.next = rightnext;
  if(prevright && prevright != left) { Prevright.next  = left; }
  // if (prevright && prevright == left) {left.next = rightnext;}
  if (leftnext != right) right.next= leftnext;
  else {right.next = left;}
  if(prevleft) { Prevleft.next = right;}
  else return right;
  return root;
}

Node SwapKth(Node root, int K);
{
 int len = 0;
 Node cur = root;
 while(cur){
     len = len + 1;
     cur = cur.next;
 }
 Node left = root;
 Node Prevleft  = root;
 Node right = root;
 Node Prevright = root;
 if (K < 0) return root;
 if (K  > len) return root;
 for (int i = 0; i < K-1; i++){
     Prevleft = left;
     left = left->next;
     }  
 for (int i = 0; i <  len-K; i++){
     Prevright = right;
     right = right->next;
 }
 if (K > len - K)
 {
 temp = left;
 left = right;
 right = temp;
 temp=prevleft;
 prevleft = prevright;
 prevright = temp;
 }
 if (left && right)
   return Swap(left,right, prevleft, prevright, root);
 return root;  
}
Test cases:
Empty Set
NULL 1
1 NULL
1 2 ( checks in the swap function)
1 2 K = 0
1 2 K = 1
1 2 K = 2
1234 K = 2
Prevleft left right PrevRight
1          2    3    2
1          2    2    1
1          2    5    4  len = 6 K = 2
3          4    1    NULL  len = 4 K = 4
NULL       1    4    3

This was an actual interview question. How do you improve high availability  and low latency. My answer was you improve HA with fault tolerance and at least one fail over server. For low latency, you don't do anything as an application programmer. You delegate it to Web accelerators and data deduplicators. If the application was talking to another instance of itself, then it could make its protocol less chatty.

No comments:

Post a Comment