Insertion and Deletion in Red-black trees

Red-black trees, aren’t they amazing? Here is how they’re commonly defined:

It’s a binary search tree, with the following additional properties:

  1. A node is either red or black.
  2. The root is black. (This rule is sometimes omitted. Since the root can always be changed from red to black, but not necessarily vice-versa, this rule has little effect on analysis.)
  3. All leaves (NIL) are black. (All leaves are same color as the root.)
  4. Both children of every red node are black.
  5. Every simple path from a given node to any of its descendant leaves contains the same number of black nodes.

Red-black trees have worst case time complexity of O(logN) for searching. (N is the number of nodes in the red-black tree). Note that binary search trees have worst case time complexity of O(N) for searching.

There are gazillion resources on internet that will tell you the definition of a red-back and what is the need for them but very few of them explain insertion and deletion operations in easy-to-follow language.
The objective of this post is to help you quickly understand how the insertion and deletion is performed on a red-black tree.

Insertion in a Red-black tree:

Mark the node as red (because red is the best we can do to avoid breaking lesser Red-Black tree laws) and insert it like we are inserting in a BST. The new red node may still break the “no continuous red nodes law”. Let new node be denoted by N, its parent by P, its grandparent by G and its uncle by U.Then we fix it via:

  1. If N is at Root, color it black and terminate.
  2. If P is Black, terminate.
  3. Check U’s color, if red, then mark P and U as black and G as red, go to G (i.e N=G) and repeat all the steps.
  4. If P is at left
    1. If N is a right child, left rotate about P.
    2. Mark P as black and G as red, then right rotate about G and terminate.
  5. If P is at right
    1. If N is a left child, right rotate about P.
    2. Mark P as black and G as red, then left rotate about G and terminate.

Deletion in a Red-black tree:

Assume that you are deleting from a binary search tree and delete the node using the conventional steps.(i.e replace the value in node to deleted by its inorder predecessor or successor), the actual problem is to delete that inorder predecessor/successor node so that the red-black properties of the tree aren’t violated). Then we go ahead and fix the tree such that it satisfies all properties of a red black tree. Let M be the effective node(inorder successor/predecessor) that need to be deleted, and Let N denotes its child node , N’s parent is denoted by P, N’s grandparent by G and its sibling by S.

  1. If N is the root node, replace it by NULL node and terminate.
  2. If M is red, replace it by N and terminate.
  3. If M is black and N is red, replace it by N, color N black and terminate.

     <–If M and N both are black follow the steps–>

  1. Replace M by N. Now forget M ever existed.
  2. If N is a left child:
    1. If S is red, reverse the color of S and P and left rotate about P. Reset S. (It’s guaranteed that new S is Black)
    2. If P, S and S’s children are all black, repaint S to red and set N=P, repeat all steps.
    3. If P is red, but S and S’s children are black, then reverse color of P and S.
    4. If only the left child of S is red, then right rotate about S and reverse color of S and its parent.
    5. If only the right child of S is red, left rotate about P, exchange the color of P and S and color S’s right child to black
  3. If N is a right child
    1. If S is red, reverse the color of S and P and right rotate about P. Reset S. (It’s guaranteed that new S is Black)
    2. If P, S and S’s children are all black, repaint S to red and set N=P, repeat all steps.
    3. If P is red, but S and S’s children are black, then reverse color of P and S.
    4. If only the right child of S is red, then left rotate about S and reverse color of S and its parent.
    5. If only the left child of S is red, right rotate about P, exchange the color of P and S and color S’s left child to black

Demo:
http://www.ece.uc.edu/~franco/C321/html/RedBlack/

References:
http://en.wikipedia.org/wiki/Red%E2%80%93black_tree
http://stackoverflow.com/questions/9469858/how-to-easily-remember-red-black-tree-insert-and-delete

Beware of this problem!

I recently came across a simple data structure problem.
You have to check if a given binary tree is binary search tree or not. This looks like a very simple problem. For each node, just check if left node of it is smaller than the node and right node of it is greater than the node(which can be implemented very easily using recursion). Well if you think so, you might have mistaken! You program will fail for following test case.

This is because 1<2<4 which fakes that this tree is BST, but if you notice 4 is on the left side of root node 3(which is the violation of a fundamental property of BST).

— courtesy http://www.geeksforgeeks.org/archives/3042

Finally Graduated…

31st May 2011
I was waiting for this day for the past many years, but really can’t believe that it has finally come.
Today I finished all the exams of my 8th semester at DCE, Now only the final result is awaited, and getting the degree is just a formality. But anyway I am out of the college now. Throughout the 4 years I regretted my stay at DCE. but at the end I bagged a good enough placement(at US ;)) and met great people. you can’t expect more from a college which is governed by Delhi government and winning a seat in election is far more important than imparting education.

A Fun day at DCE

Taming the WUBI Grub daemon

If you are not an advanced unix user and you have installed ubuntu via the WUBI installer. Then you might face this problem sometimes.

How I define this problem:
When I started my computer and chose ubuntu from the boot-menu I got a black-screen with nothing but Grub>
When I put the live CD and tried to mount the root disk of my Ubuntu, it failed with input/output error (apparently due to FS errors in the root disk) .

Solution:

  1. Go to windows and go inside your wubi installation files and locate root.disk
  2. Try to copy this file to some other drive(Note that this is a huge file)
  3. If the copying is successful, it means that there are no file system errors in your root drive and you can easily retrieve your data using a live CD and you might like to retry this (If your CD drive doesn’t work you can create a bootable USB also, which works same as CD or even better)
  4. If the copying fails with some weird error code, it means that you have file system errors on this drive(common in old hard drives), Lets fix them!
    • Start windows
    • Run CMD as admin
    • Enter chkdsk and press enter, wait for the output
    • Enter chkdsk volume: /f , where volume is the disk label of the drive in which ubuntu is installed. For me it was D. /f means fix it. Wait for the output to come.(This might take a lot time)
    • If all the above steps completed successfully, it means that you have successfully fixed the fs errors in the drive. So reboot the system and try to access ubuntu from the boot menu. It should work, If it doesn’t  then try to mount the root disk manually using this

How to use Yahoo! term extraction service with PHP

Yahoo provides a term extraction web service by which you can extract important keyphrases from a given text.The service is accessible via Yahoo Boss.You will need a Yahoo! BOSS Application ID to use it. It’s free of cost, so get it 🙂

Then you can use the PHP cURL  function to post the variables to the specified URL and return the result to a variable($xml here). The function I used if pasted below:

PHP Function:

function getKeyphrases($texttoprocess){
// cURL must be installed for this to work
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ‘http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction&#8217;);       curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, ‘appid=PASTE YOUR YAHOO BOSS APP ID HERE&context=’ . urlencode($texttoprocess) );
$xml = curl_exec($ch) or die(‘error’);
curl_close($ch);
return $xml
}

The sample working code with HTML GUI could be downloaded from here.(Don’t forget to add your App ID in yahoo.php file)

Multiplying 2 huge numbers

Multiplying 2 huge numbers is a very common problem in programming competitions and interviews.I am attaching my code for this problem.

My algorithm:

1.Input the 2 numbers in a string say S1,S2

2.Consider one of the 2 number say S2 as a collection of many single digit numbers eg if s2=”3243″ then it is a collection of ‘3’,’2′,’4′ and ‘3’

3.Multiply each such digit with S1, taking care of the carry

Follow this link for the c++ implementation which handles upto 1000 digit long unsigned numbers.The code is well commented.If you come across any bugs in it,please let me know by post it here!

My code is not perfect, of course there is a scope of improvement.

My first Job, yahooooooooooooooooooo!

27th october 2010(yesterday), the most remarkable day if my whole life, I got my first Job and guess the recruiter….well its Yahooooooooooooooo! I am loving it. 🙂
I woke up a bit earlier yesterday, got ready and reached TnP sharp at 9 am, shockingly the Pre Placement talk started at its scheduled time(which is generally rare). It was a great talk, we really got to know how big the brand Yahoo is and how cool the environment at Yahoo is. PPT continued for alomost 1 hr then we all were moved to auditorium for the written test. I was pretty much nervous, as my performance in the past written tests doesn’t worth mentioning.
WRitten test consisted of 25 MCQs with 5 options in each question, there were questions from topics like multithreading, Processes,Algorithms complexity, data structures, Counting etc. The paper was entirely based upon the fundamentals. If you have done fundamentals well, you’ll clear it. 20 people were shortlisted for the coding round.
COding round, We were given the problem of implementing the unix utility ‘grep’ I didn’t really do good in that round but still I was through 🙂
Overall 7/20 could clear the coding round.
FIrst interview, This interview went quite well, my interviewer was from DCE itself, so I got the benefit I guess, He was basically checking my fundamentals, he asked me to improve the best case performance of bubble sort, then a good discussion on quick sort,  one quick puzzle, a lengthy discussion on my GSoC project and some fundas of web development(dcetech.com)
SEcond interview, This interview was a disaster, My interviewer was the most senior member of the Yahoo team and threw a lot of good questions, I didn’t actually answered them very well, but still I was through 🙂 .They really liked me 🙂
Only 3 people were called for the 3rd interview, It was basically based on though processing, He asked me problem which is under active research and I has a good discussion with my interviewer, It was really fun.Again I was asked about the GSoC project(the work I did for Mozilla) and then my language preferences.
Next was the HR interview, It was just a really casual talk and I enjoyed it thoroughly.
Finally we all were asked to wait for sometime.
Then HR came and announced the result, My heart was throbbing and mind full of contradictory thoughts……. yes,yes I was jumping after I heard the result, I finally made it.
and best part is that the profile I am being offered is Software Engineer(Engineering Production) which is entirely development(no QA 😛 )
Congrats to my fellow Yahoo selectees Akhil and Mukesh! Hope to have a nice time at Yahoo!!
Tomorrow(29th October) is my birthday and I could have never imagined a better gift 🙂

Algorithm to remove duplicates from a sorted array

int unique(int *array, int number)   //sorted array
{
int k = 0;
for (int i = 1; i < n; i++) {
if (a[k] != a[i]) {              //comparing the first 2 unequal numbers
a[k+1] = a[i];                 //shifting to the left if distinct
k++;
}
}
return (k+1);             //return the last index of new array i.e. the number of distinct elements
}

Algo to find duplicates in an array having elements in the range [1,n]

Algorithm 1

input[n]  //input array of size n, containing n  numbers

int output[n]; // Supporting array for our algo, initialized to 0
for(int i=0;i<n;i++)
output[input[i]]++;  //using elements of input array as index to create the o/p array

for(int i=0;i<n;i++)
{
if(output[i]==0)  // If the ith element is zero, it means i wasn’t present in input array

cout<<i; // display i
}

Algorithm 2 << My favourite 🙂

traverse the list for i= 1st to n+2 elements
{
check for sign of A[abs(A[i])] ;
if positive then
   make it negative by   A[abs(A[i])]=-A[abs(A[i])];
else  // i.e., A[abs(A[i])] is negative
   this   element (ith element of list) is a repetition
}

Reversing a singly linked list : Useful methods

Hi,
Yesterday I was thinking of different ways to reverse a linked list.Here are the best ones I worked on:

Assume the following structure definition:
struct llist
{
int data;
llist *next;
};

3 Pointer method(with decomposition):
llist * reverselist_3p(llist * start)
{
llist * current = start;     //Pointer 1: To store the current node
llist * nexttocurrent = NULL;  //Pointer 2: To store the node next to current
llist * temp = NULL;            //Pointer 3: To temporarily store node just detached from the main list, so that we can assign it to the ‘current’ in the next iteration
while(current!=NULL)
{
nexttocurrent = current->next;

current->next = temp;
temp = current;

current = nexttocurrent;
}
return temp;
}

3 Pointer method(without decomposition):
llist * reverselist_2p(llist * start)
{
llist * back = NULL;     //Pointer 1: To store the back node
llist * middle = start;            //Pointer 2: Middle node
llist * front = middle->next;        //Pointer 3: Front node
while(front!=NULL)
{
middle->next = back;
back = middle;
middle = front;
front = front->next;
}
middle->next=back;
return middle;
}

2-3 Pointer method (A beautiful Recursion) : # My favorite 🙂 🙂
llist * reverselist_re(llist * start)
{
if(start==NULL)
return NULL;
llist * first = start;
llist * rest = first->next;
if(rest==NULL)
return first;

start=reverselist_re(rest);  //you may argue that start is the 3rd pointer

first->next->next = first;
first->next = NULL;

return start;
}

If you like this post, please post you valuable comments.