<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-8242511539054593745</id><updated>2025-07-15T05:40:51.035-07:00</updated><category term="Algorithms"/><category term="HTML5"/><category term="JavaScript"/><category term="Concurrency"/><category term="Java"/><category term="Oracle"/><category term="Regular Expression"/><category term="SQLPLUS"/><title type='text'>Code Samurai</title><subtitle type='html'>A Practice Ground for Programmers</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default?start-index=26&amp;max-results=25&amp;redirect=false'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>53</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-3448353709994609673</id><published>2011-08-18T13:34:00.000-07:00</published><updated>2011-09-24T16:40:41.241-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Difference Between Sums of Odd and Even Levels in Binary Trees</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; calculate the difference between the sum of nodes at even level and sum of nodes at odd level. &lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; recursion is the easiest way to solve this problem. At each non-null node of the tree, we have three things to do. 1) Find the difference between the node&#39;s left child with it&#39;s children by calling the function recursively on the node&#39;s left child. 2) Do the same thing for the node&#39;s right child. 3) Find the difference between the current node and the sum of it&#39;s left and right child. Here is the implementation in JavaScript: &lt;/p&gt;

&lt;p style=&quot;font-size: 18px&quot;&gt;
&lt;pre class=&quot;brush: js&quot;&gt;
function diffBetween(pRootNode)
{
   if (pRootNode === null || pRootNode === undefined) 
      return 0;

   var lvalue = diffBetween(pRootNode.pLChild);
   var rvalue = diffBetween(pRootNode.pRChild);

   var result = pRootNode.nData - (lvalue + rvalue);
   return result;
}
&lt;/pre&gt;
&lt;/p&gt;

&lt;p&gt;

&lt;b&gt;Explanation:&lt;/b&gt; the method takes in the root node of the binary tree that users want to compute the difference. Here are the steps:
&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Line 3 and 2, check for invalid input. This step acts as the case stopper for our recursion.&lt;/li&gt;
&lt;li&gt;Line 6: find the difference between the left child and its children.&lt;/li&gt;
&lt;li&gt;Line 7: find the difference between the right child and its children.&lt;/li&gt;
&lt;li&gt;Line 9: find the difference between the current node and its children.&lt;/li&gt;
&lt;li&gt;Line 10: finally returns the result.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you have any comment, please post. Also if there is any part that is not clear, please also let me know :)&lt;/p&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
SyntaxHighlighter.all()
&lt;/script&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/3448353709994609673/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/08/difference-between-sums-of-odd-and-even.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/3448353709994609673'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/3448353709994609673'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/08/difference-between-sums-of-odd-and-even.html' title='Difference Between Sums of Odd and Even Levels in Binary Trees'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-7806999543806658833</id><published>2011-07-29T22:46:00.000-07:00</published><updated>2011-07-29T22:46:59.963-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>How to Reverse a String</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; given a string, reverse it. You can destroy the original string or return a new string that is the reverse of the original string. For example, if input is &quot;abcde&quot;, output will be &quot;edcba&quot;.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt;  this is a simple problem. We just need to traverse the input string from last character to the first character. As we traversing the input string, we add its characters to the output string. At the end of the traversal, we have an output string that is the reverse of the original. Here is the code in JavaScript: &lt;/p&gt;

&lt;pre class=&quot;brush: js&quot;&gt;
function sReverseStr(pInputStr)
{
   if (pInputStr === null || pInputStr === undefined)
      return;

   var pResultStr = &quot;&quot;;
   
   for (var i = pInputStr.length - 1; i &gt; -1; i--)
   {
      pResultStr += pInputStr.charAt(i);
   }

   return pResultStr;
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Code Explanation:&lt;/b&gt; the code is straight forward. Here is the breakdown:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
First, we check for invalid input. Nothing new here.
&lt;/li&gt;
&lt;li&gt;
Next, we allocate a new string named &lt;b&gt;pResultStr&lt;/b&gt;. 
&lt;/li&gt;
&lt;li&gt;
The for loop goes through each character in the input one by one from the end to the beginning. Then we add each of those character to the new string.
&lt;/li&gt;

&lt;li&gt;When the for loop finishes, &lt;b&gt;pResultStr&lt;/b&gt; is now the reverse of the input. We simply return it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That&#39;s all for this post. Thanks for reading :)&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/7806999543806658833/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/07/how-to-reverse-string.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/7806999543806658833'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/7806999543806658833'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/07/how-to-reverse-string.html' title='How to Reverse a String'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-5039309532176645800</id><published>2011-07-08T10:16:00.000-07:00</published><updated>2011-07-12T09:57:12.425-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Minimum Distance Between Two Elements in an Array</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; given an array and two elements, find the minimum distance between the elements in the array. The array may have duplicates. For example, if the array is (2, 1, 3, 4, 0, 2, 5) and the two elements are 4 and 5, then the min distance is 3 because 4 is at index 3 and 5 is at index 6.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; this problem can be solved using two index trackers. The idea is to loop through the array and keep track of the indices of elements that have the same values with the inputs. At the same time, calculate the distance between those two indices and keep the smallest distance.&lt;/p&gt;

&lt;p&gt;This solution works great because it doesn&#39;t compare all possible distances of inputs when there are duplicates in the array. A naive solution would be computing all different distances between elements that have the same values with the inputs and then return the smallest distance. Here is the implementation in JavaScript: &lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
function nMinDistanceBetweenTwoElements (nInputArray, nNum1, nNum2)
{
   if (nInputArray.length &lt;= 0)
   {
      document.write(&quot;Empty Array!&quot;);
      return -1;
   }

   var nPos1 = nPos2 = nDis = nInputArray.length;

   for (var i = 0; i &lt; nInputArray.length; i++)
   {
      if (nInputArray[i] == nNum1)
         nPos1 = i;
      else if (nInputArray[i] == nNum2)
         nPos2 = i;

      if (nPos1 &lt; nInputArray.length &amp;&amp; nPos2 &lt; nInputArray.length)
      {
         if (nDis &gt; Math.abs(nPos1 - nPos2))
            nDis = Math.abs(nPos1 - nPos2);
      }
   }

   return nDis == nInputArray.length ? -1 : nDis;
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Code explanation:&lt;/b&gt; the method accepts three parameters. &lt;b&gt;nInputArray&lt;/b&gt; is an array of integers. &lt;b&gt;nNum1&lt;/b&gt; and &lt;b&gt;nNum2&lt;/b&gt; are the two numbers that we must find the minimum distance between them. Here are the steps in the method:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First, we check for the length of the array. If the client passes in an empty or invalid array, we return -1 and an error message.&lt;/li&gt;

&lt;li&gt;Next, we declare three variables. &lt;b&gt;nPos1&lt;/b&gt; and &lt;b&gt;nPos2&lt;/b&gt; keep track of the indices of the first number &lt;b&gt;nNum1&lt;/b&gt; and the second number &lt;b&gt;nNum2&lt;/b&gt; respectively. &lt;b&gt;nDis&lt;/b&gt; keeps track of the minimum distance between the two numbers. We also initialize all of these variables to the input array&#39;s length because there is a chance that the input array doesn&#39;t contain both of the input numbers whose distance we must find. In other words, if the input array doesn&#39;t contain any of the two input numbers, &lt;b&gt;nDis&lt;/b&gt; will equal the array&#39;s length at the end of the method. Moreover, we must also initialize nDis to a large number that is not obtainable by any pair of numbers in the array because we are trying to find the minimum distance. If we initialize nDis to 0, it&#39;s more complicated to use nDis to keep track of the minimum distance. nDis = 0 is already the smallest possible distance between any two elements in an array.&lt;/li&gt;

&lt;li&gt;The for loop will go through the entire input array ,&lt;b&gt;nInputArray&lt;/b&gt; once. At each iteration, we do the following:
 
&lt;ul style=&quot;font-size: 16px&quot;&gt;

&lt;li&gt;If the current element, nInputArray[i], equals to the first input number, nNum1, then assign nPos1 to that element&#39;s index, i. On the other hand, if the current element&#39;s value equals nNum2, then assign nPos2 to that element&#39;s index. Otherwise, we do nothing.&lt;/li&gt;

&lt;li&gt;Next, we check if both of the index trackers&#39; values have changed. If the values of nPos1 and nPos2 are less than the input array&#39;s length, it means that nNum1 and nNum2 exist in the input array. Again, we are guarding against the possibility that nNum1 or nNum2 is not in the input array.&lt;/li&gt;

&lt;li&gt;If nPos1 and nPos2 are less than their initial values, then both nNum1 and nNum2 are present in nInputArray. Thus, we need to find out whether the new distance between nNum1 and nNum2 is less than the current minimum distance, nDis. If the new distance is less than nDis, we change nDis to the new distance. Note that we use the absolute value of the difference between nPos1 and nPos2 to figure out the distance. The reason are that nPos2 may be smaller than nPos1 and that we don&#39;t care about the numbers&#39; order.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;After the for loop, we check to see whether nDis is different from its initial value which is the input array&#39;s length. If nDis equals its initial value, input numbers are not present in the input array. We return -1 as an error indicator. However, if nDis is different from its initial value, both input numbers must be in the input array. Therefore, we return nDis as the minimum distance between those two numbers.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I hope the code and the explanation are clear. However, if you have any question, please let me know by emailing or commenting. Thanks for reading :)&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/5039309532176645800/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/07/minimun-distance-between-two-elements.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/5039309532176645800'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/5039309532176645800'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/07/minimun-distance-between-two-elements.html' title='Minimum Distance Between Two Elements in an Array'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-7203245487654712025</id><published>2011-07-01T09:10:00.000-07:00</published><updated>2011-07-01T09:10:47.498-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Convert Binary Tree to Double Linked List in Zig-Zag Order</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; given a binary tree, write an algorithm to convert the tree into a double-linked list. The list must be as if the tree is traversed in zig-zag and level order.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; let&#39;s first understand what the objective is. By zig-zag level order, the question means that we need to traverse the tree in level order, a.k.a breadth first, such that the next level is traversed in the oposite direction to the current level. For example, take a look at this tree: &lt;/p&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjmvAqAhfOirH65CwKPC73N3lWNTPZFuGfIzAy055q3UmZ1JX_Yh4EncYXQEDZWMLcZEXBHk9p8B2vauWziJcGvbTwD4MDtR-iJRHCy2hKhVTMcsSKeWo58rP78BJIgzj4CMVBJHVLp_GcL/s1600/binaryTree.png&quot; imageanchor=&quot;1&quot; style=&quot;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;177&quot; width=&quot;243&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjmvAqAhfOirH65CwKPC73N3lWNTPZFuGfIzAy055q3UmZ1JX_Yh4EncYXQEDZWMLcZEXBHk9p8B2vauWziJcGvbTwD4MDtR-iJRHCy2hKhVTMcsSKeWo58rP78BJIgzj4CMVBJHVLp_GcL/s400/binaryTree.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;A zig-zag level-order traversal creates the list 1, 2, 3, 5, 4. It doesn&#39;t matter which direction the root is printed because there is only one node. However, since the second level is printed left to right, 2 then 3, the third level is printed from right to left, 5 then 4.&lt;/p&gt;

&lt;p&gt;Now we understand the question, let&#39;s figure out how to solve this problem. Well, the only tricky part is to traverse the tree in zig-zag order. The other part, adding nodes to a linked list, is easy.&lt;/p&gt;

&lt;p&gt;To solve this problem, we need two stacks. One stack stores nodes of levels that traversed from left to right. The other stores nodes of levels that traversed from right to left. The idea is to add the children of each node of the same level into a different stack than their parent. Thus, all children of the same level are in the same stack, separating one level from another. These children nodes are also pushed in the stack in the same direction with each other but opposite direction with their parents, so they can be traversed in the opposite direction to their parents. Moreover, as we traverse the tree, we add each node into a double linked list. Here is the implementation in C++:&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
struct Node* bt2ZigZagDoubleLinkedList(struct Node* root)
{
  if (root == NULL)
    return NULL;

  struct Node* head = root;
  struct Node* listIT = NULL;
  struct Node* prevNode = NULL;
  
  stack&lt;struct Node*&gt; left2RightStack;
  stack&lt;struct Node*&gt; right2LeftStack;

  left2RightStack.push(root);
  
  while (!left2RightStack.empty())
  {
    //add nodes from left to right to the list
    while (!left2RightStack.empty())
    {
      //set previous node
      prevNode = listIT;
    
      //pop a node in left2RightStack and add it to list
      listIT = left2RightStack.top(); 
      left2RightStack.pop();

      //add child nodes of the newly node in right to left direction
      if (listIT-&gt;left != NULL)
        right2LeftStack.push(listIT-&gt;left);
      
      if (listIT-&gt;right != NULL)
        right2LeftStack.push(listIT-&gt;right);

      //set left pointer of current node to the node in front of it
      listIT-&gt;left = prevNode; 

      //the previous node points to the current node in list
      if (prevNode != NULL)
        prevNode-&gt;right = listIT;
    }

    //add nodes from right to left to the list
    while (!right2LeftStack.empty())
    {
      prevNode = listIT;
      
      listIT = right2LeftStack.top();

      right2LeftStack.pop();

      if(listIT-&gt;right != NULL)
        left2RightStack.push(listIT-&gt;right);
        
      if(listIT-&gt;left != NULL)
        left2RightStack.push(listIT-&gt;left);

      listIT-&gt;left = prevNode;

      if (prevNode != NULL)
        prevNode-&gt;right = listIT;
    }
  }

  //connect linked the end node of list to NULL and the node in front of it
  listIT-&gt;right = NULL;
  listIT-&gt;left = prevNode;
  
  return head;
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Code explanation:&lt;/b&gt; the method accepts the tree&#39;s root node as its parameter and return the head node to the double linked list.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First two lines check for null node, empty tree. If the tree is empty, we return an empty linked list.&lt;/li&gt;

&lt;li&gt;The next three lines declare three pointers to tree nodes. &lt;b&gt;head&lt;/b&gt; points to the head node of the linked list. We initialize it to the root node because the root node will be the first node in the list. &lt;b&gt;listIT&lt;/b&gt; will be the iterator to traverse the tree. &lt;b&gt;prevNode&lt;/b&gt; points to the last node visited by listIT. We need it to construct the double linked list since we must point the previous node to the current node and the current node back to previous node.&lt;/li&gt;

&lt;li&gt;We also create two stacks that contain pointers to tree nodes. &lt;b&gt;left2RightStack&lt;/b&gt; contains nodes in left to right order while &lt;b&gt;right2LeftStack&lt;/b&gt; contains nodes in right to left order.&lt;/li&gt;

&lt;li&gt;We then initialize &lt;b&gt;left2RightStack&lt;/b&gt; by pushing the root node inside it.&lt;/li&gt;

&lt;li&gt;There are three different while loops. The first while loop makes sure that we visit all nodes in the tree and add them into our double linked list. The two inner while loops make sure that we add the nodes level by level and in opposite directions. We do the following in the first inner while loop:

&lt;ul style=&quot;font-size:16px&quot;&gt;

&lt;li&gt;First, we pop a node off the &lt;b&gt;left2RightStack&lt;/b&gt; and assign it to &lt;b&gt;listIT&lt;/b&gt;.&lt;/li&gt;

&lt;li&gt;Then, we add listIT&#39;s left child into the &lt;b&gt;right2LeftStack&lt;/b&gt; before adding listIT&#39;s right child into the same stack. This guarantees that when we pop those children off the &lt;b&gt;right2LeftStack&lt;/b&gt; they will be poped in the opposite order to their parent.&lt;/li&gt;

&lt;li&gt;After that, we add listIT into the linked list. Pointing its left pointer to the node before it, prevNode&lt;/li&gt;

&lt;li&gt;Finally, we point the right pointer of the prevNode to listIT. Remember we&#39;re making a double linked list, that&#39;s why we need to point the node in front of listIT,  which is prevNode, to listIT.&lt;/li&gt;

&lt;li&gt;The while loop runs until there is no nodes left in &lt;b&gt;left2RightStack&lt;/b&gt;.
&lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;After the first inner loop traverses a level from left to right, the second inner while loop traverses the next level from right to left. The process is similar to that of left-to-right traversal. The only difference is that we add right children to the stack before left children.&lt;/li&gt;

&lt;li&gt;Once all nodes have been added into the double linked list, we&#39;ll connect the end node of the list to the node before it and to a null node as the node after it.&lt;/li&gt;

&lt;li&gt;Lastly, we return &lt;b&gt;head&lt;/b&gt;. In the beginning, we have already assigned &lt;b&gt;head&lt;/b&gt; to the root node which is the first node of the list, so &lt;b&gt;head&lt;/b&gt; is point at the first node in the list.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That&#39;s all for this problem. If you find any mistake or have better solution, please feel free to let me know. Thanks for reading :)&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/7203245487654712025/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/07/convert-binary-tree-to-double-linked.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/7203245487654712025'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/7203245487654712025'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/07/convert-binary-tree-to-double-linked.html' title='Convert Binary Tree to Double Linked List in Zig-Zag Order'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjmvAqAhfOirH65CwKPC73N3lWNTPZFuGfIzAy055q3UmZ1JX_Yh4EncYXQEDZWMLcZEXBHk9p8B2vauWziJcGvbTwD4MDtR-iJRHCy2hKhVTMcsSKeWo58rP78BJIgzj4CMVBJHVLp_GcL/s72-c/binaryTree.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-499667101916570754</id><published>2011-06-28T09:33:00.000-07:00</published><updated>2011-06-28T09:33:05.454-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Check If an Integer&#39;s Bit Representation Is a Palindrome</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; how can you determine if a positive integer is a palindrome. For example, 5 is a palindrome because 5 = 101. Also, 9 is a palindrome because 9 = 1001.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; an integer is palindrome when its bit representation is the same reading from left to right or from right to left. Thus, in order to know if it is a palindrome or not, we just have to check if the number&#39;s value is still the same when we read the number&#39;s bits backward (right to left). For example, 5 is 101 and when we read its bits from right to left, which is 101, the result is still 5. However, 4 is 100 and when read backward it becomes 001 which is 1, so 4 is not a palindrome.
&lt;/p&gt; 

&lt;p&gt;&lt;b&gt;Pseudocode:&lt;/b&gt; here is the pseudocode for the algorithm:&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
integer nResultNum = 0
integer nInputNumCopy = nInputNum

while nInputNumCopy &gt; 0
  nResultNum = nResult &lt;&lt; 1;
  if nInputNumCopy &amp; 1 == 1
    nResultNum = nResultNum | 1;
  nResultNumCopy = nResultNumCopy &gt;&gt; 1;
end while

if nResultNumCopy == nInputNum 
  return true

return false
&lt;/pre&gt;

&lt;p&gt;Here is the implementation of the pseudocode using JavaScript:&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
function bIsIntPalindrome(nInputNum)
{
   if (nInputNum === &#39;undefined&#39; || nInputNum === null || nInputNum &lt; 0)
      return false;

   var nInputNumCopy = nInputNum;
   var nResultNum = 0;

   while (nInputNumCopy &gt; 0)
   {
      nResultNum &lt;&lt;= 1;

      if (nInputNumCopy &amp; 1)
      {
         nResultNum |=1;
      }

      nInputNumCopy &gt;&gt;= 1;
   }

   if (nInputNum == nResultNum)
      return true;

   return false;
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation:&lt;/b&gt; the general plan is to generate a number whose bit representation is the reverse of that of the input number. After that, we check to see if the two numbers equal. If they do, the input number is palindrome as explained above:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Check for invalid inputs.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;nResultNum&lt;/b&gt; is the number whose bit representation is the reverse of the input number. &lt;b&gt;nInputNumCopy&lt;/b&gt; is the copy of the input number. Since we&#39;ll destroy the value in the process, we must make copy of it so that we can compare the result to the original input later on.&lt;/li&gt;
&lt;li&gt;The while loop runs until nInputNumCopy is 0, meaning that we have copied all of its bits. In other words, this loop copies the bits from nInputNumCopy to nResultNum from right to left. At each iteration:
  &lt;ul style=&quot;font-size: 16px&quot;&gt;
    &lt;li&gt;First, shift nResultNum&#39;s bits to the left by 1&lt;/li&gt;
    &lt;li&gt;Second, check if the current right most bit in nInputNumCopy is 1 by using &amp; operator. If the right most bit is 1, turn the right most bit of nResultNum to 1 using | operator.&lt;/li&gt;
    &lt;li&gt;Third, shift all bits of nInputNumCopy to the right by 1.
  &lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;When finishing copying the bits from right to left, we check for equality between &lt;b&gt;nInputNum&lt;/b&gt; (the original input value) and nResultNum (containing the same number of bits but in reverse order). If the two equal, then input number is palindrome, otherwise not.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;b&gt;Example:&lt;/b&gt; let&#39;s check to see if 5 is a palindrome. At the start of while loop, variables&#39; values are nResultNum = 0 and nInputNumCopy = 5 (101). Entering the while loop:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First iteration, nResultNum &lt;&lt;= 1 still equals 0 because 000 &lt;&lt; 1 = 0. nInputNumCopy &amp; 1 = 1 because 101 &amp; 001 = 001, so nResultNum |= 1 = 000 | 1 = 001. Then, nInputNumCopy &gt;&gt;= 1 = 2 because 101 &gt;&gt; 1 = 010 which is 2. Because nInputNumCopy &gt; 0, loop continues.&lt;/li&gt;
&lt;li&gt;Second iteration, nResultNum &lt;&lt;= 1 makes nResultNum = 010 because 001 &lt;&lt; 1 = 010. Since nInputNumCopy &amp; 1 = 0 (010 &amp; 001 = 000), nothing added to nResultNum in this iteration. nInputNumCopy &gt;&gt;= 1 = 001 = 1. Since nInputNumCopy is still greater than 0, the loop continues.&lt;/li&gt;
&lt;li&gt;Third iteration, (nResultNum &lt;&lt;= 1) = (010 &lt;&lt; 1) = 100. (nInputNumCopy &amp; 1) = 001 &amp; 001 = 001, so a 1 bit is added to nResultNum such that (nResultNum |= 1) = (100 | 1) = 101. Shift nInputNumCopy to right by 1, making nInputNumCopy = 000. Since nInputNumCopy is now 0, the loop ends.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;After the while loop, nResultNum = 101 which is 5. Thus, nResultNum equals nInputNum. The method returns true. 5 is a palindrome. We&#39;re done.&lt;/p&gt;

&lt;p&gt;I hope the explanation was clear. If you have any question, please feel free to ask by emailing or posting in the comment section. Until next time!&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/499667101916570754/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/06/check-if-integers-bit-representation-is.html#comment-form' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/499667101916570754'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/499667101916570754'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/06/check-if-integers-bit-representation-is.html' title='Check If an Integer&#39;s Bit Representation Is a Palindrome'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-6922354289698418776</id><published>2011-06-25T11:00:00.000-07:00</published><updated>2011-06-25T11:00:55.297-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Search for Intersection Between Two Sorted Arrays of Integers</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; there are two sorted arrays of integers such as array(1, 3, 6, 9, 10) and array(-2, 0, 4, 6, 12). Search for the intersection between these arrays. The intersection is 6 at index 2 and index 3 in the example arrays.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; a naive solution would be to compare each element in the first array to each element in the second array, resulting in an O(N * M) algorithm where N and M are the numbers of elements in first and second array respectively. A better solution is using binary search for each element in the first array in the second array. That is an O(N LogM) algorithm. However, we can even do better using two array iterators at a time. Take a look at the pseudocode below:&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
it1, it2
while it1 &lt; size1 and it2 &lt; size2
  if (array1[it1] == array2[it2])
    print(it1 and it2)
    return
  else if (array1[it1] &gt; array2[it2])
    it2++
  else
    it1++
&lt;/pre&gt;

&lt;p&gt;We simply move the iterators, one for each array, whenever an element of one array is less that the element of the other array. We do this until we either find the common element (intersection) or we reach the end of any array. This works because both arrays are sorted in the ascending order. Thus, we don&#39;t have to compare each and every element to all other elements to know where the intersection is. Here is the implementation of the pseudocode in JavaScript :)&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
function vIntersectionInSortedArrays(cIntArray1, cIntArray2)
{
   if (cIntArray1 === null || cIntArray1 === undefined 
      || cIntArray2 === null || cIntArray2 === undefined)
   {
      document.write(&quot;Empty arrays!&quot;); 
      return;
   }

   var nArray1It = 0;
   var nArray2It = 0;
   
   while (nArray1It &lt; cIntArray1.length 
         &amp;&amp; nArray2It &lt; cIntArray2.length)
   {
      if (cIntArray1[nArray1It] == cIntArray2[nArray2It])
      {
         document.write(&quot;Intersect at index&quot; + nArray1It 
                        + &quot; and &quot; + nArray2It);
         return;
      }
      else if (cIntArray1[nArray1It] &gt; cIntArray2[nArray2It])
         nArray2It++;
      else
         nArray1It++;
   }

   document.write(&quot;No intersection!&quot;);
}
&lt;/pre&gt;

&lt;p&gt;I know it&#39;s unusual to use JavaScript but a break from C++ and Java is nice. As we expect, this algorithm is more efficient. In the worst case, it takes only O(M + N) time to return the answer!&lt;/p&gt;

&lt;p&gt;As always, thanks for following and if you have any suggestion, please don&#39;t hesitate to let me know in the comment section.&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/6922354289698418776/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/06/search-for-intersection-between-two.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/6922354289698418776'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/6922354289698418776'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/06/search-for-intersection-between-two.html' title='Search for Intersection Between Two Sorted Arrays of Integers'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-307649395049849614</id><published>2011-06-23T10:13:00.000-07:00</published><updated>2011-06-23T10:13:37.778-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Convert integers to roman numbers</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; write an algorithm to convert an integer into roman number. For example, 1 -&gt; I, 2 -&gt; II, or 4 -&gt; IV.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; in order to solve this problem, we must know the rules of writing roman numerals. For example, I is 1 and V is 5 but IV is not 6 but 4 (5 -1). Moreover, there is no 0 number in roman numeral system. Here is the &lt;a href=&quot;http://en.wikipedia.org/wiki/Roman_numeral&quot;&gt;link to an article&lt;/a&gt; about roman numerals if you are unfamiliar with the system.&lt;/p&gt;

&lt;p&gt;As you may notice, the roman numeral system consists of several fundamental and unique numbers. They are used in conjunction with rules to create other numbers. Therefore, we just have to cache the unique numbers and apply the rules in order to generate any roman number we want. Let&#39;s take a look at the implementation below in C++&lt;/p&gt;

&lt;pre class = &quot;example&quot;&gt;
#include&amp;lt;iostream&gt;
#include&amp;lt;map&gt;
#include&amp;lt;string&gt;
using namespace std;

string int2RomanNum(int intVal)
{
   if (intVal &lt;= 0)
   {
      cout &lt;&lt; &quot;Roman numbers don&#39;t support 0 or negative! Return NULL&quot; &lt;&lt; endl;
      return &quot;&quot;; 
   }

   //build hash table of unique values 
   map&lt;int, string&gt; valueMap;

   valueMap[1] = &quot;I&quot;;
   valueMap[4] = &quot;IV&quot;;
   valueMap[5] = &quot;V&quot;;
   valueMap[9] = &quot;IX&quot;;
   valueMap[10] = &quot;X&quot;;
   valueMap[40] = &quot;XL&quot;;
   valueMap[50] = &quot;L&quot;;
   valueMap[90] = &quot;XC&quot;;
   valueMap[100] = &quot;C&quot;;
   valueMap[400] = &quot;CD&quot;;
   valueMap[500] = &quot;D&quot;;
   valueMap[900] = &quot;CM&quot;;
   valueMap[1000] = &quot;M&quot;;

   //the roman value
   string romanResult = &quot;&quot;;

   //traverse the list in reverse order 
   map&lt;int, string&gt;::reverse_iterator it;
   
   for (it = valueMap.rbegin(); it != valueMap.rend(); it++)
   {
      //if current number is greater than current key in list
      //add the value corresponded with key to result
      //then subtract the equivalent int value from current number
      while (intVal &gt;= it-&gt;first)
      {
         romanResult = romanResult + it-&gt;second;
         intVal = intVal - it-&gt;first;
      }
   }

   return romanResult;
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation:&lt;/b&gt; our method accepts an integer as parameter and return a string that contains the roman number equivalent to that integer.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First we check the parameter to see if it is equal or less than 0. Because there is no 0 or negative roman numbers, we return an empty string after printing out the warning.&lt;/li&gt;

&lt;li&gt;
Next, we build a hash table of unique roman numbers which are then combined to create other numbers.
&lt;/li&gt;

&lt;li&gt;
The heart of this method consists of two loops. The &quot;for&quot; loop runs through the hash table from bottom to top (largest number to smallest number). At each number in the hash table, we run the &quot;while&quot; loop to construct the roman number. This while loop will run until the integer is less than the current number in the hash table. And for every iteration in the while loop we add the current roman number to the returned string. For example, if our integer is 35, at the 10 or X position in the hash table, the while loop will kick in and add XXX into our string. And then the for loop continues at the 5 or V position, letting the while loop add V into our string.
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;b&gt;Example:&lt;/b&gt; let&#39;s say we want to convert the integer 430 into its equivalent roman number. Here is how the method runs: &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First &quot;for&quot; loop&#39;s iteration, &lt;b&gt;intVal&lt;/b&gt; = 430 and &lt;b&gt;it-&gt;first&lt;/b&gt; = 1000. No while loop because intVal is less than it-&gt;first.&lt;/li&gt;

&lt;li&gt;Second iteration, intVal = 430 and it-&gt;first = 900. No while loop.&lt;/li&gt;

&lt;li&gt;Third iteration, intVal = 430 and it-&gt;first = 500. No while loop.&lt;/li&gt;

&lt;li&gt;Fourth iteration, intVal = 430 and it-&gt;first = 400. Enter while loop: &lt;b&gt;romanResult&lt;/b&gt; = CD and intVal = 30. Because intVal is less than it-&gt;first after the first &quot;while&quot; iteration, the while loop exits.&lt;/li&gt;

&lt;li&gt;Fifth iteration, intVal = 30 and it-&gt;first = 100. No while loop.&lt;/li&gt;

&lt;li&gt;Sixth iteration, intVal = 30 and it-&gt;first = 90. No while loop.&lt;/li&gt;

&lt;li&gt;Seventh iteration, intVal = 30 and it-&gt;first = 50. No while loop.&lt;/li&gt;

&lt;li&gt;Ninth iteration, intVal = 30 and it-&gt;first = 40. No while loop.&lt;/li&gt;

&lt;li&gt;Tenth iteration, intVal = 30 and it-&gt;first = 10. Enter while loop: 1) intVal = 20 and romanResult = CDX, 2) intVal = 10 and romanResult = CDXX, and 3) intVal = 0 and romanResult = CDXXX. The while loop exits after that because intVal is less than it-&gt;first.&lt;/li&gt;

&lt;li&gt;Nothing happens in the last four iterations because intVal is 0. Thus, the final result is romanResult = CDXXX&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Thank you for reading and until next time :)&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/307649395049849614/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/06/convert-integers-to-roman-numbers.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/307649395049849614'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/307649395049849614'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/06/convert-integers-to-roman-numbers.html' title='Convert integers to roman numbers'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-8208125908623307718</id><published>2011-06-02T22:45:00.000-07:00</published><updated>2011-06-02T22:45:35.978-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Least-Square Linear Regression of Data Using C++</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; implement the least-square method to determine the linear function that best fits the data. This method also needs to find the coefficient of determination (R^2) and standard error of estimation (E). Input to this method is a collection of data points (x, y) and the collection&#39;s size, a.k.a. number of data points.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; the answer is straight forward. We basically just have to apply the statistics formulas for finding the least-square linear function to the data. If you are not familiar with the formulas and where they come from here is &lt;a href=&quot;http://en.wikipedia.org/wiki/Linear_regression&quot;&gt;the link&lt;/a&gt; for you. Now, let&#39;s take a look at the implementation below:&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
#include&amp;lt;iostream&gt;
#include&amp;lt;cmath&gt;
using namespace std;

struct Point
{
   double x;
   double y;
};

void leastSqrRegression(struct Point* xyCollection, int dataSize)
{
   if (xyCollection == NULL || dataSize == 0)
   {
      printf(&quot;Empty data set!\n&quot;);
      return;
   }

   double SUMx = 0;     //sum of x values
   double SUMy = 0;     //sum of y values
   double SUMxy = 0;    //sum of x * y
   double SUMxx = 0;    //sum of x^2
   double SUMres = 0;   //sum of squared residue
   double res = 0;      //residue squared
   double slope = 0;    //slope of regression line
   double y_intercept = 0; //y intercept of regression line
   double SUM_Yres = 0; //sum of squared of the discrepancies
   double AVGy = 0;     //mean of y
   double AVGx = 0;     //mean of x
   double Yres = 0;     //squared of the discrepancies
   double Rsqr = 0;     //coefficient of determination

   //calculate various sums 
   for (int i = 0; i &lt; dataSize; i++)
   {
      //sum of x
      SUMx = SUMx + (xyCollection + i)-&gt;x;
      //sum of y
      SUMy = SUMy + (xyCollection + i)-&gt;y;
      //sum of squared x*y
      SUMxy = SUMxy + (xyCollection + i)-&gt;x * (xyCollection + i)-&gt;y;
      //sum of squared x
      SUMxx = SUMxx + (xyCollection + i)-&gt;x * (xyCollection + i)-&gt;x;
   }

   //calculate the means of x and y
   AVGy = SUMy / dataSize;
   AVGx = SUMx / dataSize;

   //slope or a1
   slope = (dataSize * SUMxy - SUMx * SUMy) / (dataSize * SUMxx - SUMx*SUMx);

   //y itercept or a0
   y_intercept = AVGy - slope * AVGx;
   
   printf(&quot;x mean(AVGx) = %0.5E\n&quot;, AVGx);
   printf(&quot;y mean(AVGy) = %0.5E\n&quot;, AVGy);

   printf (&quot;\n&quot;);
   printf (&quot;The linear equation that best fits the given data:\n&quot;);
   printf (&quot;       y = %2.8lfx + %2.8f\n&quot;, slope, y_intercept);
   printf (&quot;------------------------------------------------------------\n&quot;);
   printf (&quot;   Original (x,y)   (y_i - y_avg)^2     (y_i - a_o - a_1*x_i)^2\n&quot;);
   printf (&quot;------------------------------------------------------------\n&quot;);

   //calculate squared residues, their sum etc.
   for (int i = 0; i &lt; dataSize; i++) 
   {
      //current (y_i - a0 - a1 * x_i)^2
      Yres = pow(((xyCollection + i)-&gt;y - y_intercept - (slope * (xyCollection + i)-&gt;x)), 2);

      //sum of (y_i - a0 - a1 * x_i)^2
      SUM_Yres += Yres;

      //current residue squared (y_i - AVGy)^2
      res = pow((xyCollection + i)-&gt;y - AVGy, 2);

      //sum of squared residues
      SUMres += res;
      
      printf (&quot;   (%0.2f %0.2f)      %0.5E         %0.5E\n&quot;, 
       (xyCollection + i)-&gt;x, (xyCollection + i)-&gt;y, res, Yres);
   }

   //calculate r^2 coefficient of determination
   Rsqr = (SUMres - SUM_Yres) / SUMres;
   
   printf(&quot;--------------------------------------------------\n&quot;);
   printf(&quot;Sum of (y_i - y_avg)^2 = %0.5E\t\n&quot;, SUMres);
   printf(&quot;Sum of (y_i - a_o - a_1*x_i)^2 = %0.5E\t\n&quot;, SUM_Yres);
   printf(&quot;Standard deviation(St) = %0.5E\n&quot;, sqrt(SUMres / (dataSize - 1)));
   printf(&quot;Standard error of the estimate(Sr) = %0.5E\t\n&quot;, sqrt(SUM_Yres / (dataSize-2)));
   printf(&quot;Coefficent of determination(r^2) = %0.5E\t\n&quot;, (SUMres - SUM_Yres)/SUMres);
   printf(&quot;Correlation coefficient(r) = %0.5E\t\n&quot;, sqrt(Rsqr));

}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation:&lt;/b&gt; assuming that each data point is structured similar to our &lt;b&gt;Point&lt;/b&gt; struct, then our method takes an array of Points and the array&#39;s size as its parameters.&lt;/p&gt;

&lt;p&gt;To advance any further, we must first find these sums:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;SUMx&lt;/b&gt;: the sum of all x values of the points&lt;/li&gt;
&lt;li&gt;&lt;b&gt;SUMy&lt;/b&gt;: the sum of all y values of the points&lt;/li&gt;
&lt;li&gt;&lt;b&gt;SUMxx&lt;/b&gt;: the sum of the square of x values, meaning that we square x values individually and add them togethers&lt;/li&gt;
&lt;li&gt;&lt;b&gt;SUMxy&lt;/b&gt;: for each point we multiply its x value with its y value, then add all the results together to find this sum.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The first for loop is used to calculate those sums simultaneously.&lt;/p&gt;

&lt;p&gt;After that, we calculate the means of x and y values which equal sum of x values divided by the number of points and sum of y values divided by the number of points respectively.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;slope&lt;/b&gt; and &lt;b&gt;y_intercept&lt;/b&gt; of the best-fit function can then be determined using the means and the sums we found. Thus, the linear function is y = slope*x + y_intercept.&lt;/p&gt;

&lt;p&gt;Finally, to calculate the coefficient of determination and standard error of estimation, we need to find the sum of squared standard deviation (&lt;b&gt;SUM_Yres&lt;/b&gt;) of each point from the best-fit linear function and sum of the squared residues (&lt;b&gt;SUMres&lt;/b&gt;). That&#39;s what the second for loop does.&lt;/p&gt;

&lt;p&gt;Once, we know sum of squared residues and sum of squared standard deviation, we just apply formulas to find the coefficient and the standard error.&lt;/p&gt;

&lt;p&gt;As you can see, the challenge is not writing the code to compute the least-square regression but being able to understand the logic behind that. Why slope, y_intercept, coefficient of determination and standard error of estimation are calculated that way? Where do the formulas come from? Etc..&lt;/p&gt;

&lt;p&gt;Answering those questions is beyond the scope of this post, so I leave it to you. I actually took statistics in order to understand the concepts and translate the formulas into code :)&lt;/p&gt;

&lt;p&gt;As always, any comment or suggestion is welcome! Bye for now. &lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/8208125908623307718/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/06/least-square-linear-regression-of-data.html#comment-form' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/8208125908623307718'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/8208125908623307718'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/06/least-square-linear-regression-of-data.html' title='Least-Square Linear Regression of Data Using C++'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>7</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-7408941722937094443</id><published>2011-05-08T19:08:00.000-07:00</published><updated>2011-05-08T23:38:08.414-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Find Local Maximum of a Function Using Bisection Method</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; implement the bisection method to find a function&#39;s local maximum.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; bisection is one of the root-finding methods that are used to find real roots of a continuous function. More information about the method and mathematical analysis can be found &lt;a href=&quot;http://en.wikipedia.org/wiki/Bisection_method&quot;&gt;here&lt;/a&gt;. For this question, we&#39;ll modify the bisection method to find the local maximum of a function instead of its roots.&lt;/p&gt;

&lt;p&gt;The maximum of a function is a point where the value of the function is max. Thus, the local maximum is the maximum of a specified interval of the function. It is local because outside of the specified interval, we can&#39;t prove that it is the maximum of the function. Here is the code in C:&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
double bisect(double x_lower, double x_upper, double epsilon, double (*dx)(double), int maxIteration)
{
   double result = 0.0; //the root
   double f_result = 0.0; //value of f(x)
   int iteration = 0;

   while (fabs(x_upper - x_lower) &gt; epsilon &amp;&amp; iteration &lt; maxIteration)
   {
      iteration++;

      //compute the new root
      result = (x_upper + x_lower) / 2;

      //derivative of the new root
      f_result = dx(result);
      
      //see if derivative has changed sign
      if (dx(x_lower) * f_result &lt; 0)
         x_upper = result;
      else if (dx(x_upper) * f_result &lt; 0)
         x_lower = result;
      else
      {
         return result;
      }
   }
   printf(&quot;No root found, returning -1 ! \n&quot;);
   return -1;
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation:&lt;/b&gt; our function accepts five arguments and return the maximum if it finds one. 

&lt;ol&gt;
&lt;li&gt;The first two arguments, &lt;b&gt;x_lower&lt;/b&gt; and &lt;b&gt;x_upper&lt;/b&gt;, are the lower and upper bound of the interval whose maximum is our interest.&lt;/li&gt;

&lt;li&gt;The third argument, &lt;b&gt;epsilon&lt;/b&gt; is the accuracy or the acceptable range of error that the answer must meet. Why do we have this? Because in real life, it is extremely difficult to find the exact solution. Some reasons include the limit on computer&#39;s ability to store floating point numbers and round off error. Moreover, most real world applications only need the answer to be precise enough instead of being exact. That&#39;s why we accept the concept of tolerable error. To keep the error to minimum, I suggest passing in &lt;b&gt;machine epsilon&lt;/b&gt; as the acceptable error. Machine epsilon is the smallest difference between two numbers that the computer, on which the program is run, can produce. Thus, if the error is less than machine epsilon, then the answer is the most precise that particular computer can produce.&lt;/li&gt;
&lt;li&gt;The fourth argument, &lt;b&gt;*dx&lt;/b&gt;, is the pointer to the function&#39;s first derivative.&lt;/li&gt;
&lt;li&gt;the last argument, &lt;b&gt;maxIteration&lt;/b&gt;, is the max number of times that we want our program to run. If the bisection method doesn&#39;t converge (it does in some cases), then our program will run forever. The maxIteration is there to prevent that case. After a certain number of calculations and the method has not returned the result, we better find another way to solve the problem right? :)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The basis to find the local maximum is that the derivative of lower and upper bounds have opposite signs (positive vs. negative). Furthermore, after passing through the maximum the derivative changes sign. Therefore, we can run the function until the derivative changes sign. It means that when neither dx(x_upper) * dx(x) &lt; 0 nor dx(x_lower) * dx(x) &lt; 0, then x is the value in interval (x_lower, x_upper) where f(x) is max.&lt;/p&gt;

&lt;p&gt;Mathematically, the local maximum is the point where the derivative is 0 (dx = 0). Think about slope of a graph. However, since we are dealing with computer and floating point numbers, it&#39;s not a good idea to use equality comparison as the way to find maximum. That&#39;s why we exploit the fact that the derivative changes sign after passing through the maximum.&lt;/p&gt;

&lt;p&gt;Thanks for reading and until next time.&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/7408941722937094443/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/05/solve-function-optimization-problem.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/7408941722937094443'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/7408941722937094443'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/05/solve-function-optimization-problem.html' title='Find Local Maximum of a Function Using Bisection Method'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-6762682998608440049</id><published>2011-05-03T20:29:00.000-07:00</published><updated>2011-05-03T20:29:33.296-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Determine the Height of Binary Trees</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; given a root of a binary tree, write an algorithm to find the tree&#39;s height.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; the height of a binary tree is the length of the path from the root to the deepest leaf node of the tree. For example, the following tree has height of 3: &lt;/p&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixzO_9S-qNU0dEH2qdzJJt6TxX64zntpFy9uRZ0yQkyJ5PFl8S4dOk_NzePJZej4YC65q0qwbub0IK_zzfmkjaW9BosxTERWHUbjUy4EVwlzre6NxlBkFXDaGQOlC8-7yg-RNEe-8yPFtz/s1600/binaryTree.png&quot; imageanchor=&quot;1&quot; style=&quot;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;177&quot; width=&quot;243&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixzO_9S-qNU0dEH2qdzJJt6TxX64zntpFy9uRZ0yQkyJ5PFl8S4dOk_NzePJZej4YC65q0qwbub0IK_zzfmkjaW9BosxTERWHUbjUy4EVwlzre6NxlBkFXDaGQOlC8-7yg-RNEe-8yPFtz/s400/binaryTree.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;To find the height, we need to count the number of nodes on the path from root to the deepest leaf. This can be done recursively. Here is the code in C++:&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
//basic tree node definition
struct Node
{
  int data;
  struct Node* left;
  struct Node* right;
};

int getBinaryTreeHeight(struct Node* root)
{
   if (root == NULL)
      return 0;

   int leftHeight = getBinaryTreeHeight(root-&gt;left);
   int rightHeight = getBinaryTreeHeight(root-&gt;right);

   return 1 + (leftHeight &lt;= rightHeight ? rightHeight : leftHeight);
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation:&lt;/b&gt; assuming that we have a tree node structure just like that in the example code, our method takes in a pointer to the root and return the height of that root&#39;s tree. Recursively, a tree&#39;s height is the height of its subtrees. So if we know the height of the subtrees, we know the height of the tree. For each node under the current root, we do the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;If the current node is null, we simply return 0 because a rooted tree with no root has height 0.&lt;/li&gt;
&lt;li&gt;Next we find the height of the left subtree and the right subtree.&lt;/li&gt;
&lt;li&gt;Lastly, either left or right subtree&#39;s height plus one is returned as the height of the current root&#39;s tree. Why do we add one into the return result? Well because the current node is counted as one height unit if it is not null.&lt;/li&gt;
&lt;/ol&gt; 

&lt;p&gt;By the end of the recursive calls, the returned sum is the height of the tree whose root is the argument to the function.&lt;/p&gt;

&lt;p&gt;That&#39;s the end of this post. Thanks for reading :)&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/6762682998608440049/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/05/determine-height-of-binary-trees.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/6762682998608440049'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/6762682998608440049'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/05/determine-height-of-binary-trees.html' title='Determine the Height of Binary Trees'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixzO_9S-qNU0dEH2qdzJJt6TxX64zntpFy9uRZ0yQkyJ5PFl8S4dOk_NzePJZej4YC65q0qwbub0IK_zzfmkjaW9BosxTERWHUbjUy4EVwlzre6NxlBkFXDaGQOlC8-7yg-RNEe-8yPFtz/s72-c/binaryTree.png" height="72" width="72"/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-3440006293230946841</id><published>2011-04-28T23:10:00.000-07:00</published><updated>2011-04-28T23:10:43.406-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>How to Shuffle an Array or the Fisher-Yates Algorithm</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; how can you shuffle an array in O(n) time and O(1) space? For example, if input is an array of (1, 2, 3, 4, 5), one of the output can be (5, 4, 3, 2, 1) or (4, 2, 3, 1, 5).&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; this problem can be solved using Knuth Shuffling Algorithm a.k.a Fisher-Yates Shuffling Algorithm. The core strategy behind the algorithm is to pick a random index between 0 and N, where N is the greatest index of the unshuffled array, and then move that element to the shuffled part of the array. In other words, the algorithm partitions the original array into two parts, the unshuffled and shuffled part. It randomly picks an element from the unshuffled part and puts it into the shuffled part. It does that until no elements left in the unshuffled part. Here is the implementation in C:&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
#include&amp;lt;stdio.h&gt;
#include&amp;lt;stdlib.h&gt;
#include&amp;lt;time.h&gt;

void knuthShuffle(int orgArray[], int arraySize)
{
   if (arraySize == 0 || arraySize == 1)
      return;

   srand(time(NULL));

   int i;
   int index, temp;
   for (i = arraySize - 1; i &gt; 0; i--)
   {
      index = rand() % (i+1);
      temp = orgArray[index];
      orgArray[index] = orgArray[i];
      orgArray[i] = temp;
   }
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation:&lt;/b&gt; in order to partition the array, we traverse the array from the end to start. The subarray from iterator index &lt;b&gt;i&lt;/b&gt; to the last index of the array (&lt;b&gt;arraySize - 1&lt;/b&gt;) is the shuffled part. And, the subarray from the first index (&lt;b&gt;0&lt;/b&gt;) to the iterator index &lt;b&gt;i&lt;/b&gt; is the unshuffled part. As, the index &lt;b&gt;i&lt;/b&gt; moves up the array, we randomly generate a number between 0 and &lt;b&gt;i + 1&lt;/b&gt; using C-function rand(). We then swap the element at the index that equals the random number with the element at the last index (&lt;b&gt;i&lt;/b&gt;) of the unshuffled part. As the result of decreasing &lt;b&gt;i&lt;/b&gt; by 1 for every loop iteration, the partitions are automatically reserved. Here is an example with illustration that will hopefully make everything clearer.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Example:&lt;/b&gt; we&#39;ll shuffle this array(1, 2, 3, 4, 5). Notice that the value for &lt;b&gt;index&lt;/b&gt; is randomly picked, so at run time the algorithm may not generate the values in the exact order that they are here. We just need to understand that, the random values are always greater than or equal 0 and less than &lt;b&gt;i&lt;/b&gt;. Here is what the array starts out with: &lt;/p&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3eCDNREsdIP3E0Sg5JN4GWZJeAY5aWzKiQY1kIEOiMPQl1jxcASjBvpGLpTgFeLa7peGmRJx-8AmKZPOgAWpqPh5fMO0pcUS7AiwibyYJnDfDStw0FoxGYpVByU0oeOjtwtMPfh4z-yON/s1600/knuth-shuffle-img-1.png&quot; imageanchor=&quot;1&quot; style=&quot;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;250&quot; width=&quot;550&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3eCDNREsdIP3E0Sg5JN4GWZJeAY5aWzKiQY1kIEOiMPQl1jxcASjBvpGLpTgFeLa7peGmRJx-8AmKZPOgAWpqPh5fMO0pcUS7AiwibyYJnDfDStw0FoxGYpVByU0oeOjtwtMPfh4z-yON/s400/knuth-shuffle-img-1.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;ol&gt;
&lt;li&gt;First iteration, i = arraySize - 1 = 4. Let&#39;s say that &lt;b&gt;index&lt;/b&gt; is randomly generated as 3, so we switch array[3] with array[4]. Here is the picture:&lt;br /&gt;&lt;br /&gt;
&lt;/li&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-IDU2AP9JhZ093OUcUQmZDUp8jYikKKfseYuYF0TCZZTCc9f01X2FS3J7nlT3XmATzDP9aEitOsbWLOAPzKxlAoPArLMg7BoO_G6dZ_URTWxYQiT0aqbFYpe1_ZwdCuSsRxe00LykmSNI/s1600/knuth-shuffle-img-2.png&quot; imageanchor=&quot;1&quot; style=&quot;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;250&quot; width=&quot;550&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-IDU2AP9JhZ093OUcUQmZDUp8jYikKKfseYuYF0TCZZTCc9f01X2FS3J7nlT3XmATzDP9aEitOsbWLOAPzKxlAoPArLMg7BoO_G6dZ_URTWxYQiT0aqbFYpe1_ZwdCuSsRxe00LykmSNI/s400/knuth-shuffle-img-2.png&quot; /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;

&lt;li&gt;Second iteration, decrement i by 1, so i = 3 and index randomly generated as 0. We swap array[0] and array[3]:&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjObZJDzIEY3OELRFNYIzLQzNDb6EhbZDSJuf8uwqKr9UiQYIWGohk4neNOnfJrobKcz7cpzR0yJV_kbCAlcDs9ESgvdASO1wBO0H93lCwGEX08zxmV0B2hsnYkSHKheRNYks8DmsiuQGTK/s1600/knuth-shuffle-img-3.png&quot; imageanchor=&quot;1&quot; style=&quot;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;250&quot; width=&quot;550&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjObZJDzIEY3OELRFNYIzLQzNDb6EhbZDSJuf8uwqKr9UiQYIWGohk4neNOnfJrobKcz7cpzR0yJV_kbCAlcDs9ESgvdASO1wBO0H93lCwGEX08zxmV0B2hsnYkSHKheRNYks8DmsiuQGTK/s400/knuth-shuffle-img-3.png&quot; /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;

&lt;li&gt;Third iteration, i = 2 and index = 1. Swap array[2] with array[1].&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhu2xfMMMypZ_58ut2_jFnDTRiibLpbTR5jUNOAPHyONK-km0RnqhWUxBXJpSFnyHlnq0tFSMOVMZGQW6Q5yTr9Tdx-vaJKmqCYWHuVAnHTMZgkzyZ-0iL0ihxwrkHdGvAcWJn4CnFu53Ho/s1600/knuth-shuffle-img-4.png&quot; imageanchor=&quot;1&quot; style=&quot;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;250&quot; width=&quot;550&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhu2xfMMMypZ_58ut2_jFnDTRiibLpbTR5jUNOAPHyONK-km0RnqhWUxBXJpSFnyHlnq0tFSMOVMZGQW6Q5yTr9Tdx-vaJKmqCYWHuVAnHTMZgkzyZ-0iL0ihxwrkHdGvAcWJn4CnFu53Ho/s400/knuth-shuffle-img-4.png&quot; /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;

&lt;li&gt;Fourth iteration, i = 1 and index = 0. Swap array[0] and array[1].&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjYxEq5hEsFBdMgN6kWROjck38FQgvD_rwhM6OSlKFzao9kWIpSigTHMdGdjLkeDI7YFAZonha0Ql9rGsLore1ETH3EsnMYDo3dPbFDQS4tEfetUYxUlGblQDM0xnpKph2JHCV6RUzCm9cw/s1600/knuth-shuffle-img-5.png&quot; imageanchor=&quot;1&quot; style=&quot;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;250&quot; width=&quot;550&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjYxEq5hEsFBdMgN6kWROjck38FQgvD_rwhM6OSlKFzao9kWIpSigTHMdGdjLkeDI7YFAZonha0Ql9rGsLore1ETH3EsnMYDo3dPbFDQS4tEfetUYxUlGblQDM0xnpKph2JHCV6RUzCm9cw/s400/knuth-shuffle-img-5.png&quot; /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;

&lt;li&gt;Fifth iteration: i = 0, so loop terminates. Nothing happens. Here is the final shuffled array:&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEif3uAggjcFyJ1PnI3CdTp_RMGe-MmED_ul7x1vMAROhMsE2Uf3yuRGzBsomk9tUd-NtXB0rK_WUeRI5i42mTtHCeYsJEt5xUiQN7nG7ucl2IhLj6pfBdoadG-MHFJgqR6vt15Gso1zphBA/s1600/knuth-shuffle-img-5+%25281%2529.png&quot; imageanchor=&quot;1&quot; style=&quot;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;250&quot; width=&quot;550&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEif3uAggjcFyJ1PnI3CdTp_RMGe-MmED_ul7x1vMAROhMsE2Uf3yuRGzBsomk9tUd-NtXB0rK_WUeRI5i42mTtHCeYsJEt5xUiQN7nG7ucl2IhLj6pfBdoadG-MHFJgqR6vt15Gso1zphBA/s400/knuth-shuffle-img-5+%25281%2529.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/ol&gt;

&lt;p&gt;If there is any bug or better solution, please let me know in the comment section below. Thanks for reading :)&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/3440006293230946841/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/04/how-to-shuffle-array-or-fisher-yates.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/3440006293230946841'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/3440006293230946841'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/04/how-to-shuffle-array-or-fisher-yates.html' title='How to Shuffle an Array or the Fisher-Yates Algorithm'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3eCDNREsdIP3E0Sg5JN4GWZJeAY5aWzKiQY1kIEOiMPQl1jxcASjBvpGLpTgFeLa7peGmRJx-8AmKZPOgAWpqPh5fMO0pcUS7AiwibyYJnDfDStw0FoxGYpVByU0oeOjtwtMPfh4z-yON/s72-c/knuth-shuffle-img-1.png" height="72" width="72"/><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-2339670149648222739</id><published>2011-04-22T14:21:00.000-07:00</published><updated>2011-04-22T15:08:48.732-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Sorting Array of Three Kinds or The Dutch National Flag Problem</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; given an array of three different kinds of value such as array(1, 2, 0, 2, 1) and array(a, b, a, c, b), write an algorithm to sort the array. For example, input array(1, 2, 0, 2, 1) becomes array(0, 1, 1, 2, 2) and input array(a, b, a, c, b) becomes array(a, a, b, b, c).&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; the Dutch National Flag Algorithm sorts an array of red, blue, and white objects by separating them from each other based on their colors. Hence, we can adopt the algorithm to sort any array of three different kinds of objects / values. Let&#39;s take a look at the implementation below where we sort an array of three different integers:&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
void dutchFlagSort(int inArray[], int arraySize, int high, int low)
{
  if (arraySize == 0)
    return;

  int lower = 0;
  while (inArray[lower] == low &amp;&amp; lower &lt; arraySize)
    lower++;

  int upper = arraySize - 1;
  while (inArray[upper] == high &amp;&amp; upper &gt;= 0)
    upper--;

  int temp = 0;
  int pivot;
  for (pivot = lower; pivot &lt;= upper;)
  {
    if (inArray[pivot] == low)
    {
      temp = inArray[pivot];
      inArray[pivot] = inArray[lower];
      inArray[lower] = temp;
      pivot++;
      lower++;
    }
    else if (inArray[pivot] == high)
    {
      temp = inArray[pivot];
      inArray[pivot] = inArray[upper];
      inArray[upper] = temp;
      upper--;
    }
    else
      pivot++;
  }
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation:&lt;/b&gt; the method above takes in an array of integers, the array&#39;s size, and the order of the integers (low and high) as arguments. Notice that &lt;b&gt;low&lt;/b&gt; indicates the lowest value in the array and &lt;b&gt;high&lt;/b&gt; indicates the highest value in the array. For example, if our array is (1, 2, 3, 1, 2, 3) then the &lt;b&gt;low&lt;/b&gt; maybe 1 and &lt;b&gt;high&lt;/b&gt; maybe 3. The algorithm uses those indicators to sort the array. We can actually specify &lt;b&gt;low&lt;/b&gt; and &lt;b&gt;high&lt;/b&gt; as any value in the array if we want to. It only affects how the array places the integers.&lt;/p&gt;

&lt;p&gt;The basic strategy behind the method is to partition the array into three regions, low, middle and high. These regions correspond to the three kinds of integers. Low integers whose values equal &lt;b&gt;low&lt;/b&gt;, high integers whose values equal &lt;b&gt;high&lt;/b&gt;, and the middle integers whose values are anything other than &lt;b&gt;high&lt;/b&gt; and &lt;b&gt;low&lt;/b&gt;.&lt;/p&gt;

&lt;p&gt;That&#39;s why we have three different iterators. Any integer before &lt;b&gt;lower&lt;/b&gt; is low integer, and any integer after &lt;b&gt;upper&lt;/b&gt; is high integer. The &lt;b&gt;pivot&lt;/b&gt; iterator traveses the array and swaps high and low integers to their correct places. However, it skips over the middle integers because they are supposed to be in the region between low and high integer regions. Let&#39;s do an example to clear things up.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Example:&lt;/b&gt; lets Dutch Flag sort this array (0, 2, 1, 0, 1, 2)&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;low = 0, high = 2&lt;/li&gt;
&lt;li&gt;After the first while loop, lower = 1. After the second while loop, upper = 4. Finally, pivot = 1.&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;

&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVsA4VxzFXhmvkvMkEd9yeqNhlxPLnK919oyJejGPzEkge4uL049N00ROl6bZZMV7rwhsUWv0L27mOgk8amJLwYTZpCXlauA8QIGQudNGBZsxHm9FY_HlmCP3WBLFsIysK4QmVF6TJTLMw/s1600/dutch-Flag-Sort-1.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left:1em; margin-right:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;200&quot; width=&quot;500&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVsA4VxzFXhmvkvMkEd9yeqNhlxPLnK919oyJejGPzEkge4uL049N00ROl6bZZMV7rwhsUWv0L27mOgk8amJLwYTZpCXlauA8QIGQudNGBZsxHm9FY_HlmCP3WBLFsIysK4QmVF6TJTLMw/s400/dutch-Flag-Sort-1.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;

&lt;li&gt;Entering the for loop:&lt;br /&gt;&lt;br /&gt;
First iteration: array[pivot] = 2 (high), so we swap array[pivot] with array[upper] and decrease upper by 1. &lt;br /&gt;&lt;br /&gt;


&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiD0ExQUDxV0E1nC_KdG2y3zOA2bmiT7u2hUoegQI_DtUDWD_aThCoob0tGp0f1o-sQFS-g3YZJmpc7S81l2n6Tkyff1Sg42MKVwp7DFLUA74N1gvjp2EAETsKie2dewtHN_vZqBdOHqZBo/s1600/dutch-flag-sort-2.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left:1em; margin-right:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;200&quot; width=&quot;500&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiD0ExQUDxV0E1nC_KdG2y3zOA2bmiT7u2hUoegQI_DtUDWD_aThCoob0tGp0f1o-sQFS-g3YZJmpc7S81l2n6Tkyff1Sg42MKVwp7DFLUA74N1gvjp2EAETsKie2dewtHN_vZqBdOHqZBo/s400/dutch-flag-sort-2.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;

Second iteration: pivot = 1, lower = 1, and upper = 3. Because array[pivot] = 1, we do nothing but increasing pivot by 1.&lt;br /&gt;&lt;br /&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj74dCjrrSx0ZjGX7g1lKEDsRQ-M1qxZbfDB0MB65FUjo913TgrUJ_m-qY4oZdLqQ5ZYftnDbCCAFBCrYa4iPeAl2bm7yPCCh3DZR1ZWNY57Jsy0EYQKPpTvCj9mxB5OLnf0D1gy7UvZHzW/s1600/dutch-flag-sort-3.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left:1em; margin-right:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;200&quot; width=&quot;500&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj74dCjrrSx0ZjGX7g1lKEDsRQ-M1qxZbfDB0MB65FUjo913TgrUJ_m-qY4oZdLqQ5ZYftnDbCCAFBCrYa4iPeAl2bm7yPCCh3DZR1ZWNY57Jsy0EYQKPpTvCj9mxB5OLnf0D1gy7UvZHzW/s400/dutch-flag-sort-3.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;

Third iteration: pivot = 2, lower = 1, and upper = 3. Again, array[pivot] = 1, we just increase pivot by 1 and move on.&lt;br /&gt;&lt;br /&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhjF7BnJp0yR8kZSN8kOfSJ-9mcVpiR2bgbM4ppIOgz6koZn40hFwEZ6zh4LBTOL8310hRn6xlTQTHM6R7j0NUf99_HFXvnRzjG5LEGWMXKitWAd0aXxC4qRWU4eJ1CbLrk3p__wYafGq_-/s1600/dutch-flag-sort-4.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left:1em; margin-right:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;200&quot; width=&quot;500&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhjF7BnJp0yR8kZSN8kOfSJ-9mcVpiR2bgbM4ppIOgz6koZn40hFwEZ6zh4LBTOL8310hRn6xlTQTHM6R7j0NUf99_HFXvnRzjG5LEGWMXKitWAd0aXxC4qRWU4eJ1CbLrk3p__wYafGq_-/s400/dutch-flag-sort-4.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;

Fourth iteration: pivot = 3, lower = 1, and upper = 3. Since array[pivot] = 0 (low), we swap array[pivot] and array[lower]. Then, we increase both pivot and lower by 1.&lt;br /&gt;&lt;br /&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEic4-8I5ys-GRHD6ZsgCtk1Ef21MKC-XEM-YPa-Wst8sT7WAjI1cUN06nI8fKVkb4wFnXHdbneAzCGTooYP7E0q3WmBiX6UN_kgNc5J4ZLcbsiE0pwrej0P-4c5hzt6PnxYYd0g8LLBg9lt/s1600/dutch-flag-sort-5.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left:1em; margin-right:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;200&quot; width=&quot;500&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEic4-8I5ys-GRHD6ZsgCtk1Ef21MKC-XEM-YPa-Wst8sT7WAjI1cUN06nI8fKVkb4wFnXHdbneAzCGTooYP7E0q3WmBiX6UN_kgNc5J4ZLcbsiE0pwrej0P-4c5hzt6PnxYYd0g8LLBg9lt/s400/dutch-flag-sort-5.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;

Fifth iteration: pivot = 4, lower = 2, and upper = 3. The loop terminates here because pivot is now greater than upper. Here is the final array. Notice how all the 0s, 1s and 2s are separated and sorted in ascending order.&lt;br /&gt;&lt;br /&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwO2jluvwR0oWltpIk5uY-9HYjJ35ZFvhSKMapLhwjbVVkAw69hEbuIinPzDA4JgRezeJTScsFObX1o0ez6p7z0OTkS6P0HUEnBTq2nINMV4RtHwasrLOwVVAeTddiW8tUIiui8buG6xHA/s1600/dutch-flag-sort-6.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left:1em; margin-right:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;150&quot; width=&quot;500&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwO2jluvwR0oWltpIk5uY-9HYjJ35ZFvhSKMapLhwjbVVkAw69hEbuIinPzDA4JgRezeJTScsFObX1o0ez6p7z0OTkS6P0HUEnBTq2nINMV4RtHwasrLOwVVAeTddiW8tUIiui8buG6xHA/s400/dutch-flag-sort-6.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;
&lt;/li&gt;

&lt;/ol&gt;
&lt;p&gt;Well, I hope everything is clear now after the example. If you have any question, please feel free to post it in the comment section below.&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/2339670149648222739/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/04/sorting-array-of-three-kinds-or-dutch.html#comment-form' title='9 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/2339670149648222739'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/2339670149648222739'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/04/sorting-array-of-three-kinds-or-dutch.html' title='Sorting Array of Three Kinds or The Dutch National Flag Problem'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVsA4VxzFXhmvkvMkEd9yeqNhlxPLnK919oyJejGPzEkge4uL049N00ROl6bZZMV7rwhsUWv0L27mOgk8amJLwYTZpCXlauA8QIGQudNGBZsxHm9FY_HlmCP3WBLFsIysK4QmVF6TJTLMw/s72-c/dutch-Flag-Sort-1.png" height="72" width="72"/><thr:total>9</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-34153942964839830</id><published>2011-04-15T16:55:00.000-07:00</published><updated>2011-04-15T16:55:59.601-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Calculate the Least Common Multiple of Two Integers</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; write an algorithm to return the least common multiple (LCM) of two integers. For example, if the inputs are 3 and 4, the function returns 12.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; least common multiple (LCM) is the lowest value that is a multiple of both integers. That means LCM is divisible by both integers or the modulus of LCM divided by either integers is 0 (LCM % num = 0). Thus, we just need to start with a reasonable number and keep increasing that number until it is divisible by both integers. The number is then the LCM of the integers.&lt;/p&gt;

&lt;p&gt;But where is the reasonable number to start out? Well, instead of starting out at 1, we can start out at the highest integer between the two integers. The reason is that a number that is less than either of those two integers can&#39;t be divisible by those integers. For example, if we are to find LCM of 2 and 3, then any number that is less than 3 is surely not the LCM. Thus, we can safely start our search at 3. Notice that one integer can be the LCM of another integer. That&#39;s why we start out at the higher number. For example, the LCM of 2 and 4 is 4. Here is the algorithm in C:&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
  int lcm(int num1, int num2)
  {
    if (num1 % num2 == 0)
      return num1;

    if (num2 % num1 == 0)
      return num2;
      
    int n = (num1 &lt;= num2) ? num2 : num1;
    
    for (; ; n++)
    {
      if(n % num1 == 0 &amp;&amp; n % num2 == 0)
         return n;
    }
  }
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation:&lt;/b&gt; our function takes two integers as arguments and returns the LCM of those integers.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First, we take the modulus of the first integer (&lt;b&gt;num1&lt;/b&gt;) and the second integer (&lt;b&gt;num2&lt;/b&gt;). If num1 % num2 equals 0, we know num1 is the LCM because num1 is divisible by num1 and is the smallest number that is not less than num1 and num2. Similarly, if num2 % num1 equals 0 then num2 is the LCM.&lt;/li&gt;

&lt;li&gt;When neither integer is the LCM, we find out which integer is greater and begin to find the LCM starting from that integer. That&#39;s exactly what the for loop does. For every iteration, we increase &lt;b&gt;n&lt;/b&gt; by 1 until we find a number that divisible by both &lt;b&gt;num1&lt;/b&gt; and &lt;b&gt;num2&lt;/b&gt;. This loop guarantees to find the solution. That&#39;s why we don&#39;t need any other return statement outside the loop. Nor we need a termination condition for the loop.&lt;/li&gt; 
&lt;/ol&gt;

&lt;p&gt;That&#39;s all we have for today. Thanks for reading!&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/34153942964839830/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/04/calculate-least-common-multiple-of-two.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/34153942964839830'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/34153942964839830'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/04/calculate-least-common-multiple-of-two.html' title='Calculate the Least Common Multiple of Two Integers'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-5041143917050709785</id><published>2011-04-07T16:34:00.000-07:00</published><updated>2011-04-07T16:34:59.065-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Convert Binary Tree to Double Linked List</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; write an algorithm to convert a binary tree into a double linked list. For example, if the input is the binary tree below: &lt;/p&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEif3nqsR9qo6i4QaU9otsisemTJWXelejq3cPDcZH7AwDvnn7AjlGzxSeFHz6u82VjthO3VWSKP7Lud7M3yFuLPWtLDtTdOQ7n8iqU2i4WsmmZVi_rC_D6oxNGO5RxYv-h0K1EoTpa0RZyk/s1600/binaryTree.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left:1em; margin-right:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;179&quot; width=&quot;246&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEif3nqsR9qo6i4QaU9otsisemTJWXelejq3cPDcZH7AwDvnn7AjlGzxSeFHz6u82VjthO3VWSKP7Lud7M3yFuLPWtLDtTdOQ7n8iqU2i4WsmmZVi_rC_D6oxNGO5RxYv-h0K1EoTpa0RZyk/s400/binaryTree.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;The output will be a double linked list like this:&lt;/p&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEht8VU_avnzk7CYkr0Dtwm4AbMehagnkkO5kOu4G4yQmohsBSkynU9mlQBklNBIYo3horlajCm_ouKUsqy42tKYThAhbsvIvfu1Qr-4C3FgCEP8z_0tv4FND_i4H6Me470XCHbwhedYO4ty/s1600/doubleLinkedList.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left:1em; margin-right:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;73&quot; width=&quot;400&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEht8VU_avnzk7CYkr0Dtwm4AbMehagnkkO5kOu4G4yQmohsBSkynU9mlQBklNBIYo3horlajCm_ouKUsqy42tKYThAhbsvIvfu1Qr-4C3FgCEP8z_0tv4FND_i4H6Me470XCHbwhedYO4ty/s400/doubleLinkedList.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; there are two tasks in converting a binary tree to a linked list. First of all, we must traverse the tree and visit all the nodes. Second of all, we must break each node from the tree and add it into the linked list.&lt;/p&gt;

&lt;p&gt;For traversing the tree, we&#39;ll use level / order traversal a.k.a breadth first search. If you are not familiar with that concept, here is &lt;a href=&quot;http://codesam.blogspot.com/2011/01/breadth-first-search-in-binary-tree.html&quot;&gt;the post&lt;/a&gt; for you :) Take your time to read it, I&#39;ll be right here when you come back!&lt;/p&gt;

&lt;p&gt;To construct the linked list, each node will have its left pointer point to the node in front of it and its right pointer point to the node behind it in the linked list. For instance, if node 1 is in front of node 2 and node 3 is behind node 2 in the linked list, we&#39;ll set left pointer of node 2 to node 1 and right pointer of node 2 to node 3 (see picture above)&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
#include&amp;lt;iostream&gt;
#include&amp;lt;queue&gt;
using namespace std;

struct Node
{
  int data;
  struct Node* left;
  struct Node* right;
};

struct Node* bt2DoubleLinkedList(struct Node* root)
{
  if (root == NULL)
    return NULL;

  queue&lt;struct Node*&gt; nodeQueue;

  struct Node* head = root; //reference to head of the linked list
  struct Node* listIT = NULL; //current node being processed
  struct Node* prevNode = NULL; //previous node processed

  //initialize the stack
  nodeQueue.push(root);

  //convert to double linked list
  while (!nodeQueue.empty())
  {
    //process next node in stack
    prevNode = listIT; 
    listIT = nodeQueue.front();
    
    nodeQueue.pop();

    //add left child to stack
    if (listIT-&gt;left != NULL)
      nodeQueue.push(listIT-&gt;left);

    //add right child to stack
    if (listIT-&gt;right != NULL)
      nodeQueue.push(listIT-&gt;right);

    //add current node to linked list
    if (prevNode != NULL)
      prevNode-&gt;right = listIT;
    listIT-&gt;left = prevNode;
  }
  
  //connect end node of list to null
  listIT-&gt;right = NULL;

  return head;
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation:&lt;/b&gt; the method accepts a pointer to the tree&#39;s root as argument and returns the pointer to the head node of the linked list: &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;If the root node is null, we return null because the tree is empty.&lt;/li&gt;
&lt;li&gt;If the root is not null, we proceed by first creating a queue to store the the nodes. Why do we use queue? That is how we traverse the tree by level. Every time we reach a node, we store its children in the queue for later processing. Thus, the queue will always have something in it as long as there are still unvisited node in the tree.&lt;/li&gt;
&lt;li&gt;Next, we create three pointers. &lt;b&gt;head&lt;/b&gt; points to the head node of the linked list. &lt;b&gt;listIT&lt;/b&gt; is our list iterator which used to build the list one node at a time. &lt;b&gt;prevNode&lt;/b&gt; is the last node added into the list. We need to keep track of such node because we have to change the right pointer of that node to the node immediate after it, which is the node that listIT will point to.&lt;/li&gt;
&lt;li&gt;We initialize the queue by adding the root into it. The reason is that we will use the condition of empty queue to end the while loop. &lt;/li&gt;
&lt;li&gt;The while loop will run until no node left in queue to process. For each node in the queue, we do the following:&lt;br/&gt;&lt;br/&gt;
&lt;b&gt;prevNode = listIT&lt;/b&gt; gets reference to the last processed node because we are about to process a new node&lt;br /&gt;&lt;br /&gt;
&lt;b&gt;listIT = nodeQueue.front()&lt;/b&gt; gets reference to the top in the queue because we&#39;re going to add it into the list.&lt;br /&gt;&lt;br /&gt;
&lt;b&gt;nodeQueue.pop()&lt;/b&gt; removes the top node out of the queue.&lt;br /&gt;&lt;br /&gt;
We then add the left and right child of the top node into the queue, so we can process them later. Notice that we only add the children if they are not null.&lt;br /&gt;&lt;br /&gt;
Finally, we connect the top node to the linked list. First, we set the right pointer of the previous node (prevNode) to the top node. Then, we set the left pointer of the top node to the previous node. As the result, the top node becomes the end node of the linked list and the previous node completely breaks off the tree.&lt;br /&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;When the last node is added into the linked list and the while loop exits, we have a double linked list. The only thing left is to  set the end node&#39;s right pointer (pointed to by listIT) to null because there is no more node to add into the list.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Whew! That was a long explanation. If you are still confused, you may want to read about &lt;a href=&quot;http://codesam.blogspot.com/2011/01/breadth-first-search-in-binary-tree.html&quot;&gt;breadth first traversal&lt;/a&gt; and do an example with pencil and paper. Also, please don&#39;t hesitate to ask questions in the comment section below!&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/5041143917050709785/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/04/convert-binary-tree-to-double-linked.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/5041143917050709785'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/5041143917050709785'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/04/convert-binary-tree-to-double-linked.html' title='Convert Binary Tree to Double Linked List'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEif3nqsR9qo6i4QaU9otsisemTJWXelejq3cPDcZH7AwDvnn7AjlGzxSeFHz6u82VjthO3VWSKP7Lud7M3yFuLPWtLDtTdOQ7n8iqU2i4WsmmZVi_rC_D6oxNGO5RxYv-h0K1EoTpa0RZyk/s72-c/binaryTree.png" height="72" width="72"/><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-946834958683118850</id><published>2011-03-31T14:32:00.000-07:00</published><updated>2011-03-31T14:32:50.442-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Find the maximum subarray of an integer array</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; given an unsorted array of integers, find the subarray that yields the largest sum. For instance, if the input is {5, 2, -1}, then the output is subarray {5, 2} because it gives the largest sum (7 vs. 5 vs. 2 or 6).&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; this problem can be solved by using a modified version of Kadane&#39;s Algorithm. The strategy is to calculate the sum of each subarray  and keep track of the sum, the start index and the end index of the subarray that gives the largest sum. Moreover, we calculate the sum of a subarray by adding the sum of the previous subarray with an additional element. For example, to calculate the sum of {5, 2, -1}, we add the sum of {5, 2}, which is 7, to the value of the next element, which is -1.&lt;/p&gt;

&lt;p&gt;Here is our C++ method to solve the problem:&lt;/p&gt;
 
&lt;pre class=&quot;example&quot;&gt;
void findMaxSumSequence (int inputArray[], int size)
{
  if (size == 0)
    throw &quot;Array Size is 0&quot;;

  int maxSum = inputArray[0];
  int maxStartIndex = 0;
  int maxEndIndex = 0;
  
  int curSum = inputArray[0];
  int curStartIndex = 0;
  

  for (int i = 1; i &lt; size; i++)
  {
    if (curSum &lt; 0)
    {
      curSum = 0;
      curStartIndex = i;
    }
    
    curSum = curSum + inputArray[i];

    if (curSum &gt; maxSum)
    {

      maxSum = curSum;
      maxStartIndex = curStartIndex;
      maxEndIndex = i;
    }
  } 

  cout &lt;&lt; &quot;Start index: &quot; &lt;&lt; maxStartIndex &lt;&lt; &quot; End index: &quot; 
        &lt;&lt; maxEndIndex &lt;&lt; &quot; Max sum: &quot; &lt;&lt; maxSum &lt;&lt; endl;
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation:&lt;/b&gt; this method accepts an array and its size as arguments. It prints out the start index, end index and the sum of the subarray that yields the max sum. Here are the main steps:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First, check if the array size is 0. If it is so, we throw an exception because there is nothing we need to do when the array is null.&lt;/li&gt;
&lt;li&gt;Then, initialize variables: &lt;b&gt;maxSum&lt;/b&gt; is the largest sum found. &lt;b&gt;maxStartIndex&lt;/b&gt; and &lt;b&gt;maxEndIndex&lt;/b&gt; are respectively the start index and end index of the subarray that yields the max sum. &lt;b&gt;curSum&lt;/b&gt; is the sum of the current subarray that we&#39;re examining. &lt;b&gt;curStartIndex&lt;/b&gt; is the start index of the current subarray we&#39;re checking.&lt;/li&gt;
&lt;li&gt;
Next, we loop through the array and start calculating the sum of subarrays one after another:&lt;br /&gt;&lt;br /&gt;
If the sum of the current subarray is less than 0, we reset &lt;b&gt;curSum&lt;/b&gt; to 0. Why? If the last subarray&#39;s sum is negative, we will only decrease the next subarray&#39;s sum by adding the previous subarray&#39;s sum with an additional number. For example, if the previous subarray&#39;s sum is -2, and the next element is 3, it&#39;s better to reset the sum to 0 and add 3 into 0 than to add -2 to 3.  &lt;br /&gt;&lt;br /&gt;
&lt;b&gt;curSum = curSum + inputArr[i]&lt;/b&gt; calculates the sum of the current subarray by adding the sum of the previous subarray with the next value in the array.&lt;br /&gt;&lt;br /&gt;
After that, if the sum of the current subarray is greater than the max sum then we replace the max sum with the sum of the current subarray. We also change the &lt;b&gt;maxStartIndex&lt;/b&gt; to the start index of the current subarray and the &lt;b&gt;maxEndIndex&lt;/b&gt; to the current index &lt;b&gt;i&lt;/b&gt;.&lt;br /&gt;&lt;br /&gt;
When the loop ends, &lt;b&gt;maxSum&lt;/b&gt; will contain the largest sum found. &lt;b&gt;maxEndIndex&lt;/b&gt; and &lt;b&gt;maxStartIndex&lt;/b&gt; contain respectively the end and start index of the subarray that gives the largest sum. Thus, we just have to print out those values.
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you have any comment or another solution to this problem, please post in the comment below. I would love to learn about it. Thanks for reading and until next post!&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/946834958683118850/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/03/find-maximum-subarray-of-integer-array.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/946834958683118850'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/946834958683118850'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/03/find-maximum-subarray-of-integer-array.html' title='Find the maximum subarray of an integer array'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-6441619122378715631</id><published>2011-03-24T12:37:00.000-07:00</published><updated>2011-03-24T12:37:16.712-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Finding an integer that repeats odd number of times in an array of positive integers</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; in an array of positive integers, all but one integer repeats odd number of times. Can you find that integers in O(n) time complexity?&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Answer:&lt;/b&gt; in order to solve this problem in O(n) time, we need to use bitwise manipulation. Since there is only one integer that repeats odd number of times, we can use the XOR operator to find out that number. When a number XOR with itself, it will become 0. Thus, if a number appears a even number of times, it yield a result of 0. For example, given the array {2, 3, 2, 3}, we have 2 and 3 repeat two times (even). Thus, if we XOR all of them together we should get 0 as the result. However, if there is an odd repeated number, the result will be the value of that number! Here is the algorithm in C++:&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
  public int getIntOddlyOccured(int[] inputArr)
  {
    int oddNum = inputArr[0];
   
    for(int i = 1; i &lt; inputArr.length; i++)
      oddNum = oddNum ^ inputArr[i];
   
    return oddNum;
  }
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation:&lt;/b&gt; our method takes an integer array as argument. It assumes that there is one and only one odd occurring number (conditions given by the question), so it will return that number and does no validation to see whether the input in fact has only one odd repeated number. In the body, the method loops through the array and XOR all the elements together. The result will be the oddly repeated number.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Example:&lt;/b&gt; let&#39;s do an example with this array {1, 4, 3, 4, 1}. The method first initializes the result &lt;b&gt;oddNum&lt;/b&gt; to 1 and then does the for loop:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First iteration: oddNum = 1(0001) ^ 4(0100) = 5(0101) and i = 1&lt;/li&gt;
&lt;li&gt;Second iteration: oddNum = 5(0101) ^ 3(0011) = 6(0110) and i = 2&lt;/li&gt;
&lt;li&gt;Third iteration: oddNum = 6(0110) ^ 4(0100) = 2(0010) and i = 3&lt;/li&gt;
&lt;li&gt;Fourth iteration: oddNum = 2(0010) ^ 1(0001) = 3(0011) and i = 4&lt;/li&gt;
&lt;li&gt;Loop ends because i = 5, so we return oddNum = 3 which is the oddly repeated number in the array&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This algorithm takes O(n) time complexity because it loops through the array only once. The space complexity is O(1) because we only need an additional integer for storage. Very efficient! That&#39;s all we have for now. Thanks for reading :)&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/6441619122378715631/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/03/finding-integer-that-repeats-odd-number.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/6441619122378715631'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/6441619122378715631'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/03/finding-integer-that-repeats-odd-number.html' title='Finding an integer that repeats odd number of times in an array of positive integers'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-5080457175999654118</id><published>2011-03-23T17:49:00.000-07:00</published><updated>2011-03-23T17:49:02.931-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Check if two singly-linked lists intersect</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; given two singly linked lists, determine if they intersect one another without modifying them.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Understand the question:&lt;/b&gt; first of all, we need to understand what intersecting linked lists are. Let&#39;s say we have two linked lists 1-&gt;2-&gt;3-&gt;4-&gt;&lt;b&gt;5&lt;/b&gt; and 10-&gt;20-&gt;30-&gt;&lt;b&gt;5&lt;/b&gt;, they intersect each other because each list passes through the node 5. It&#39;s hard to visualize it in our head, so here is the picture:&lt;/p&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhx601gzqVSbHX7V8vXkKdfaDnOSJr659DB_noXh-uws9BAa23utyp6bFfdd9zq7uwGCO61t1kUUu0jMcDsExT_u4wR08RwQZ_AFrtAPMnYxhjToK_2F5cWyr5dIZ1xmSJsduL7gmVPLMDq/s1600/intersecting-linked-list.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left:1em; margin-right:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;176&quot; width=&quot;400&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhx601gzqVSbHX7V8vXkKdfaDnOSJr659DB_noXh-uws9BAa23utyp6bFfdd9zq7uwGCO61t1kUUu0jMcDsExT_u4wR08RwQZ_AFrtAPMnYxhjToK_2F5cWyr5dIZ1xmSJsduL7gmVPLMDq/s400/intersecting-linked-list.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; to know whether two lists intersect, we just have to check if they share any common node. This is easy to be done with two pointers. One starts at the head of one list while the other starts at the head of the other list. Those pointers will run till the end of their lists or till they meet (pointing to the same node). If they meet, the two linked lists intersect. But if one pointer reaches the end of its list and hasn&#39;t met the other pointer yet, then the two linked lists do not intersect.&lt;/p&gt;

&lt;p&gt;However, there is a small problem with our approach. When the lists have different lengths such as the ones in our example, the two pointers may never meet even if the lists intersect. Thus, we need to take into account that situation.&lt;/p&gt;

&lt;p&gt;One way to solve that problem is to find out the lengths of the list. If they have different lengths, we&#39;ll calculate the difference in number of nodes between the shorter list and the longer list. Then, we&#39;ll move the pointer of the longer list ahead by that many nodes before starting to check for intersection. Our pointers are guaranteed to meet if there is intersection. Here is the implementation in Java:&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
private static boolean areListsIntersected(Node list1, Node list2)
{
    if (list1 == null || list2 == null)
      return false;

    if (list1 == list2)
      return true;

    int list1Len = 0;
    Node it1 = list1;
    while (it1 != null)
    {
      list1Len++;
      it1 = it1.next;
    }

    int list2Len = 0;
    Node it2 = list2;
    while (it2 != null)
    {
      list2Len++;
      it2 = it2.next;
    }

    int lenDiff = 0;
    it2 = list2;
    it1 = list1;

    if (list2Len &gt; list1Len)
    {
      lenDiff = list2Len - list1Len;
      
      while (lenDiff &gt; 0)
      {
        it2 = it2.next;
        lenDiff--;
      }
    }
    else if (list1Len &gt; list2Len)
    {
      lenDiff = list1Len - list2Len;
      while (lenDiff &gt; 0)
      {
        it1 = it1.next;
        lenDiff--;
      }
    }

    while (it2 != null &amp;&amp; it1 != null)
    {
      if (it2 == it1)
        return true;
      it1 = it1.next;
      it2 = it2.next;
    }

    return false;
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation:&lt;/b&gt; our method takes two lists as arguments. It returns true if those lists intersect and false if they don&#39;t. The first two if statements are used to check for null lists and special case where the head of one list is the end node of the other list. When there are no null or special lists, we do the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First while loop counts the number of nodes in the first list.&lt;/li&gt;
&lt;li&gt;Second while loop counts the number of nodes in the second list.&lt;/li&gt;
&lt;li&gt;After having the length of each list, we find the difference in number of nodes and then move whichever pointer that points to the longer list ahead using that difference.&lt;/li&gt;
&lt;li&gt;Finally, the while loop is used to find the intersection. We just loop until either of the pointers reaches the end of its list. During the loop, if the pointers meet, we return true immediately because it means that the lists intersect. But at the end of the loop and nothing has happened, we simply return false because the lists don&#39;t intersect.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You may notice that the pointers will meet at the first node that both lists share! Thus, this algorithm can be tweaked a little bit to return the intersection node of two intersecting lists. Or, this algorithm can be used to break two intersecting lists at their intersection node. Pretty neat huh?&lt;/p&gt;

&lt;p&gt;Anyway, time complexity is O(m + n) where m and n are the number of nodes in the first and second list respectively. The space complexity is O(1).&lt;/p&gt;

&lt;p&gt;Thanks for reading and until next time.&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/5080457175999654118/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/03/check-if-two-singly-linked-lists.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/5080457175999654118'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/5080457175999654118'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/03/check-if-two-singly-linked-lists.html' title='Check if two singly-linked lists intersect'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhx601gzqVSbHX7V8vXkKdfaDnOSJr659DB_noXh-uws9BAa23utyp6bFfdd9zq7uwGCO61t1kUUu0jMcDsExT_u4wR08RwQZ_AFrtAPMnYxhjToK_2F5cWyr5dIZ1xmSJsduL7gmVPLMDq/s72-c/intersecting-linked-list.png" height="72" width="72"/><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-8612919491718578205</id><published>2011-03-22T16:21:00.000-07:00</published><updated>2011-03-22T16:21:45.254-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Convert integer to binary or bit string</title><content type='html'>&lt;p&gt;&lt;b&gt;Question:&lt;/b&gt; write a function to convert an integer into a bit string. For example, if input is 2, the output is &quot;00000000000000000000000000000010&quot; if the system is 32-bit, &quot;0000000000000010&quot; if the system is 16-bit and so on.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; the strategy here is to use bitwise manipulation and convert one bit at a time to character. We look at the right most bit and if it is a 0 bit, we add &#39;0&#39; character into our bit string. Otherwise, we add &#39;1&#39; character into our bit string. Here is the code in C++:&lt;/p&gt; 

&lt;pre class=&quot;example&quot;&gt;
char* int2bin(int num)
{
  const int BITS_PER_BYTE = 8;

  int bitStrLen = sizeof(int) * BITS_PER_BYTE * sizeof(char); 

  char* p = (char*)malloc(bitStrLen);

  for (int i = (bitStrLen - 1); i &gt;= 0; i--)
  {
    int k = 1 &amp; num;
    *(p + i) = ((k == 1) ? &#39;1&#39; : &#39;0&#39;);
    num &gt;&gt;= 1;
  }
  
  return p;
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation:&lt;/b&gt; our function takes an int as the argument and returns a char pointer which points to the bit string. Also, remember that there are 8 bits per byte, that&#39;s why we have that constant declared in the first line.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
Allocating memory from the heap to store our bit string: each bit is represented by a char (&#39;0&#39; or &#39;1&#39;). Thus, to get the total number of bytes required, we need the total of bits our integer has, and the number of bytes each char needs. &lt;br /&gt;&lt;br /&gt;
To get the total number of bits each integer has, we use &lt;b&gt;sizeof(int) * BITS_PER_BYTE&lt;/b&gt;. sizeof(int) gives the number of bytes each integer has, and BITS_PER_BYTE is the number of bits each byte has. Thus, multiplying them together, we have the total number of bits each integer has.&lt;br /&gt;&lt;br /&gt;
To get the number of bytes each char needs, we just call &lt;b&gt;sizeof(char)&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;

By multiplying the number of bits the integer has with the number of bytes each char needs, we get the total number of bytes required to store the binary string representation of the integer. Hence, bitStrLen = sizeof(int) * BITS_PER_BYTE * sizeof(char).&lt;br /&gt;&lt;br /&gt;
&lt;/li&gt;

&lt;li&gt;
Next, we explicitly allocate enough memory from the heap to store our bit string by calling the malloc function.&lt;br /&gt;&lt;br /&gt;
&lt;/li&gt;

&lt;li&gt;
Finally, we convert the integer into bit string using the for loop. Notice that the number of bytes we need is also the number of characters the bit string has. That&#39;s why our loop needs to run from 0 to 32 only.&lt;br /&gt;&lt;br /&gt;
For each iteration, we check the right most bit of the integer by using bitwise manipulation: &lt;b&gt;1 &amp; num&lt;/b&gt;. If the outcome is 1, then the right most bit must be 1. Otherwise, the right most bit must be 0. This works because any number with 1 at the right most bit will give the result of 1 when it AND with the number 1. But if the right most bit is 0, then the result is 0. For example, 110&lt;b&gt;1&lt;/b&gt; &amp; 1 = 1 because 110&lt;b&gt;1&lt;/b&gt; has 1 as the right most bit.&lt;br /&gt;&lt;br /&gt;
After converting the current right most bit, we need to shift the integer to the right one position to convert the next bit. Hence, &lt;b&gt;num &gt;&gt;= 1&lt;/b&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That&#39;s all we have for this post. If there is any suggestion or better solution, please leave it in the comment section below :) Thanks for reading!&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/8612919491718578205/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/03/convert-integer-to-binary-or-bit-string.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/8612919491718578205'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/8612919491718578205'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/03/convert-integer-to-binary-or-bit-string.html' title='Convert integer to binary or bit string'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-6028171108746168605</id><published>2011-03-19T16:02:00.000-07:00</published><updated>2011-03-19T16:02:29.719-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Concurrency"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><title type='text'>Introduction to Thread in Java (part 2): Thread Life Cycle</title><content type='html'>&lt;p&gt;Welcome to the second installment of the series &quot;Introduction to Thread in Java.&quot; If you haven&#39;t read part 1, here is &lt;a href=&quot;http://codesam.blogspot.com/2011/02/introduction-to-multi-threaded.html&quot;&gt;the link&lt;/a&gt; for you. Please read it because we covered a lot of important and fundamental concepts in the first part.&lt;/p&gt;

&lt;p&gt;In this section, we&#39;ll learn more about the life cycle of threads. Specifically, we need to learn what states threads go through and why / how they end up in a particular state.&lt;/p&gt;

&lt;p class=&quot;header&quot;&gt;Overview&lt;/p&gt;
&lt;p&gt;
In the simplest form, a thread&#39;s life cycle consists of five states:
&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;b&gt;New state:&lt;/b&gt; this is when the threadable / Thread object is first created by calling the constructor of the Thread class. For example, our thread is in new state after this statement
&lt;b&gt;Thread newThread = new (runnableObj, threadName);&lt;/b&gt;
&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Runnable / Read-to-run state:&lt;/b&gt; after calling the &lt;b&gt;start()&lt;/b&gt; method on the thread, it enters the runnable state. That means it is ready to run or to go to some other states. As of the current version of Java, a thread must enter the runnable state before going to any other state.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Running state:&lt;/b&gt; a thread is in this state while its &lt;b&gt;run()&lt;/b&gt; method is executing. During this state, the thread can go to blocked state if it gets blocked or has to wait for other threads. When the run() method finishes, this state ends.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Blocked/waiting state:&lt;/b&gt; while running a thread can be put to sleep, interrupted or blocked by other threads. There are many reasons why this may happen. We&#39;ll go deeper in the next section.&lt;/p&gt;
&lt;li&gt;&lt;b&gt;Terminated / dead state:&lt;/b&gt; when a thread reaches this state, its life ends. It can never be revived again. Normally, a thread enters this state because its run() method has ended. However, a thread can also be terminated even before it is in the runnable state or during the waiting state by calling stop() or suspense() on the thread. I don&#39;t suggest using any of those methods to move a thread to its terminated state because those methods have been deprecated by Java and are not thread safe. Therefore, ending the run() method is the best way to go. We&#39;ll discuss more on how to do that later.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here is the UML state diagram that describes the states that a Java thread goes through and how it gets to those states.&lt;/p&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEja3wjXVyeS2Z7iKkyhp-8Qw88jVamMbxC9Ukkjes62yDVh6M_hzznpQ3gEVQAaAJpGOZCxiLdcESa6EqF2If2R1i37fIXnxuwJJeeajdLaIKTVXyv2Ki6ewR7fX0tzY-_JaQ6TTIfQmqiC/s1600/threadLifeCycle.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left:1em; margin-right:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;337&quot; width=&quot;400&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEja3wjXVyeS2Z7iKkyhp-8Qw88jVamMbxC9Ukkjes62yDVh6M_hzznpQ3gEVQAaAJpGOZCxiLdcESa6EqF2If2R1i37fIXnxuwJJeeajdLaIKTVXyv2Ki6ewR7fX0tzY-_JaQ6TTIfQmqiC/s400/threadLifeCycle.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;Next, let&#39;s examine the Blocked/Waiting state and the Terminated/Dead state. They are more complicated than other three states.&lt;/p&gt;

&lt;p class=&quot;header&quot;&gt;Blocked / Waiting state&lt;/p&gt;

&lt;p&gt;As we have seen, a thread can only enter this state while it is running. So why does a thread enter this state? There are many causes. The main three are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;b&gt;Yielding for another thread&lt;/b&gt;: current thread yields for another thread to run first. Sometimes, we have a particular thread that needs to run immediately, so we call the yield() method on any running thread to reclaim CPU and resources for the important thread. As the result, any running thread enters the blocked state until the important thread finishes and releases the CPU / resources.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Waiting for another thread&lt;/b&gt;: somewhat similar to yielding, there are times when a thread needs to wait for another thread to finish first before it can continue. For instance, if two threads share the same resource, and one of the two is holding that resource, then the other thread needs to wait for that resource to be released.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Waiting for I/O&lt;/b&gt;: as you may know, the I/O speed is extremely slow compared to  the CPU speed. Thus, if a thread needs some resources / inputs from I/O, it may need to enter the waiting state in order to let the CPU work on other threads. This practice is better for utilizing the CPU because it should be working on other threads / processes instead of siting idle and waiting for a particular thread.&lt;/p&gt; 
&lt;/ol&gt;

&lt;p&gt;The Java Thread API provides all functions needed to resolve all the situations above. For example, the &lt;b&gt;join()&lt;/b&gt; method allows one thread to wait for the completion of another thread. Moreover, you can always cause a thread to enter the waiting state at anytime by calling the method &lt;b&gt;interrupt()&lt;/b&gt; on that thread (there are some cases where threads are not interruptable however). Here is t&lt;a href=&quot;http://download.oracle.com/javase/6/docs/api/java/lang/Thread.html&quot;&gt;he link to the Java Thread API&lt;/a&gt; for further reading.&lt;/p&gt;

&lt;p class=&quot;header&quot;&gt;Terminated / Dead State&lt;/p&gt;

&lt;p&gt;Once a thread enters this state, it cannot come back to other states. There two distinct ways to terminate the thread, letting the run() method return and calling stop(), suspense() or destroy() method on the running thread. The former is recommended because it ensures thread safe. In fact, Java has already deprecated stop(), suspense() and destroy() method in the new API.&lt;/p&gt;

&lt;p&gt;Here is &lt;a href=&quot;http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html&quot;&gt;an excellent article&lt;/a&gt; that points out why those methods are bad and why stopping a thread through run() is a good practice.&lt;/p&gt;

&lt;p&gt;That&#39;s all for the second part of this series. Please leave any comment or suggestion because they are always helpful and appreciated :)&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/6028171108746168605/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/03/introduction-to-thread-in-java-part-2.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/6028171108746168605'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/6028171108746168605'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/03/introduction-to-thread-in-java-part-2.html' title='Introduction to Thread in Java (part 2): Thread Life Cycle'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEja3wjXVyeS2Z7iKkyhp-8Qw88jVamMbxC9Ukkjes62yDVh6M_hzznpQ3gEVQAaAJpGOZCxiLdcESa6EqF2If2R1i37fIXnxuwJJeeajdLaIKTVXyv2Ki6ewR7fX0tzY-_JaQ6TTIfQmqiC/s72-c/threadLifeCycle.png" height="72" width="72"/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-2143042672054677319</id><published>2011-03-16T15:22:00.000-07:00</published><updated>2011-03-16T15:22:51.330-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Removing a loop in a singly linked list</title><content type='html'>&lt;p&gt;&lt;b&gt;Challenge&lt;/b&gt;: remove a loop from a singly linked list if the list has a loop. For example, 1-&gt;2-&gt;3-&gt;4-&gt;1 (4 points to the head node 1) should become 1-&gt;2-&gt;3-&gt;4 while 1-&gt;2-&gt;3-&gt;4 should stay the same 1-&gt;2-&gt;3-&gt;4.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution&lt;/b&gt;: the first task is to determine if our linked list has a loop. If it does, we then need to figure our where the end of the loop is. The reason is that we will set the pointer of the loop&#39;s end node to NULL to break the loop. For instance, given the list 1-&gt;2-&gt;3-&gt;1, we must find out whether it has loop. Obviously, that list does have a loop and the loop&#39;s end node is 3 (3 points back to head of the loop which is 1). Thus, we need to make node 3 point to NULL so the list doesn&#39;t have a loop anymore. The result should be 1-&gt;2-&gt;3-&gt;NULL. Here is the C++ implementation of the algorithm:&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
#include&amp;lt;iostream&gt;
using namespace std;

struct Node
{
  int data;
  Node* next;
};

void removeLoop(Node* head)
{
  if (head == NULL)
    return;

  Node* slow = head;
  Node* fast = head;
  Node* last = NULL;
  
  bool hasLoop = false;

  while (fast-&gt;next != NULL &amp;&amp; fast-&gt;next-&gt;next != NULL) 
  {
    last = slow;
    slow = slow-&gt;next;
    fast = fast-&gt;next-&gt;next;
    
    if (slow == fast)
    {
      hasLoop = true;
      break;
    }
  }

  
  if (hasLoop)
  {
    slow = head;

    while (slow-&gt;next != fast-&gt;next)
    {
      slow = slow-&gt;next;
      fast = fast-&gt;next;
    }
    
    if (slow == head &amp;&amp; fast == head )
      last-&gt;next = NULL;
    else
      fast-&gt;next = NULL;
  }
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation:&lt;/b&gt; our method takes only the reference to the list&#39;s head node as an argument. The first while loop determines if the list has loop. And, the second while loop points the loop&#39;s end node to null, terminating the loop:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;If the list is empty (head points to NULL), there is nothing to do so return.&lt;/li&gt;
&lt;li&gt;Next, we need three different pointers. &lt;b&gt;slow&lt;/b&gt; will go through the list one node after another. &lt;b&gt;fast&lt;/b&gt; moves through the list two nodes at a time, so it goes twice as fast as the slow pointer. And, &lt;b&gt;last&lt;/b&gt; refers to the previous node visited by the slow pointer.&lt;/li&gt;
&lt;li&gt;We just have to loop through the list until &lt;b&gt;fast&lt;/b&gt; reaches NULL because if the linked list doesn&#39;t have loop, fast will reach NULL eventually. Moreover, if the list does have a loop, we&#39;ll break out of the while loop immediately.&lt;/li&gt;
&lt;li&gt;As the while loop runs, we check if slow and fast pointer point to the same node. When they do, it means the list has a loop. This is a very common technique to find out if a linked list has loop. Here is &lt;a href=&quot;http://codesam.blogspot.com/2011/03/algorithm-to-determine-if-linked-list.html&quot;&gt;a post about that technique&lt;/a&gt; if you are not familiar with it.&lt;/li&gt;
&lt;li&gt;As soon as we know that the list has loop, we set the flag &lt;b&gt;hasLoop&lt;/b&gt; to true. And then, we break out of the while loop immediately because fast will never reach NULL and the while loop will never end.&lt;/li&gt;
&lt;li&gt;If the list has loop as indicated by the flag &lt;b&gt;hasLoop&lt;/b&gt;, we enter the second while loop to remove that the list&#39;s loop.&lt;br/&gt;&lt;br /&gt;
a) First, we set the slow pointer back to the list&#39;s head node.&lt;br /&gt;&lt;br /&gt;
b) Then, we move both the slow and fast pointer one node at a time. They will eventually meet each other because the list still has a loop.&lt;br /&gt;&lt;br /&gt;
c) We stop the loop right before the pointers meet. That&#39;s how we get the reference to the end node of the loop:&lt;br /&gt;&lt;br /&gt;
d) If the slow and fast pointer both point to the head of the list, then the list is circular, meaning that the end node points back to the head node of the list (ie. 1-&gt;2-&gt;3-&gt;4-&gt;1). Thus, we&#39;ll get the reference to the end node by using the &lt;b&gt;last&lt;/b&gt; pointer. Remember that last is pointing to either the head of the list or the end node of the loop after the first while loop. That&#39;s why if slow and fast point at the head, then slow must be pointing at the end node.&lt;br /&gt;&lt;br /&gt;

e) On the other hand,if the end node is pointing to any node in the list other than the head node (ie. 1-&gt;2-&gt;3-&gt;4-&gt;2), then slow and fast is pointing to the end node and last is pointing to the head node. Thus, we use fast pointer instead of last pointer to break the loop.&lt;br /&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This algorithm takes O(n) time complexity and O(1) space complexity. It&#39;s very efficient!!&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/2143042672054677319/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/03/removing-loop-in-singly-linked-list.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/2143042672054677319'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/2143042672054677319'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/03/removing-loop-in-singly-linked-list.html' title='Removing a loop in a singly linked list'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-694868013723777289</id><published>2011-03-14T17:52:00.000-07:00</published><updated>2011-03-14T17:52:13.573-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Find all subsets of a given set</title><content type='html'>&lt;p&gt;If we&#39;re given a set of integers such that S = {1, 2, 3}, how can we find all the subsets of that set? For example, given S, the subsets are {}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, and {1, 2, 3}.&lt;/p&gt;

&lt;p&gt;To solve this problem there are two techniques that we need to understand:

&lt;ol&gt;
&lt;li&gt;&lt;b&gt;Determine the number of subsets using bit strings&lt;/b&gt;: we know that the number of subsets equals to 2 to the power of the number of elements in the superset: &lt;b&gt;#subsets = 2 ^ #elements&lt;/b&gt;. For instance, if our superset is S = {1, 2, 3}, then it has 2^3 = 8 subsets. If our superset has four elements then it has 2^4 = 16 subsets. Moreover, by shifting the bit representation of the number 1 by n, we also get 2^n. Thus, if we shift the bit string of 1 by the number of elements in the superset, we&#39;ll get the number of subsets for that superset. For example, if we have S = {1, 2, 3}, then there are 1 &lt;&lt; 3 = 2^3 subsets in S.&lt;/li&gt;

&lt;li&gt;&lt;b&gt;Keeping track of data using bit manipulation&lt;/b&gt;: for this problem, we will use a bit string to keep track of subsets and their elements. Take S = {1, 2, 3} as an example. If the bit string is 100 then the subset we&#39;re working on has only one element which is 1. If the bit string is 110 then the subset we&#39;re working on has two elements which are 1 and 2. We will use &amp; and &lt;&lt; bit operators to figure out which bit is 1 in the bit string.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you are not familiar with bit manipulation please read &quot;Bit manipulation tips &amp; tricks&quot; &lt;a href=&quot;http://codesam.blogspot.com/2011/01/bit-manipulation-tips-and-tricks-part-1.html&quot;&gt;part 1&lt;/a&gt; and &lt;a href=&quot;http://codesam.blogspot.com/2011/01/bit-manipulation-tips-tricks-part-2.html&quot;&gt;part 2&lt;/a&gt;. Here is the code for the algorithm written in Java:&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
private static void findSubsets(int array[])
{
  int numOfSubsets = 1 &lt;&lt; array.length; 

  for(int i = 0; i &lt; numOfSubsets; i++)
 {
    int pos = array.length - 1;
   int bitmask = i;

   System.out.print(&quot;{&quot;);
   while(bitmask &gt; 0)
   {
    if((bitmask &amp; 1) == 1)
     System.out.print(array[pos]+&quot;,&quot;);
    bitmask &gt;&gt;= 1;
    pos--;
   }
   System.out.print(&quot;}&quot;);
 }
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Code explanation:&lt;/b&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First, we find out the number of subsets that the superset has by shifting the bit representation of 1 by the number of elements in the superset.&lt;/li&gt;
&lt;li&gt;Next, we just loop through each subset and generate its elements accordingly.&lt;/li&gt;
&lt;li&gt;Inside the loop, we use &lt;b&gt;pos&lt;/b&gt; and &lt;b&gt;bitmask&lt;/b&gt; to keep track of the element. Specifically, &lt;b&gt;bitmask&lt;/b&gt; is the bit string that represents elements in the current subset. And, we use &lt;b&gt;post&lt;/b&gt; to retrieve the correct element from the superset.&lt;/li&gt;
&lt;li&gt;The while loop will add the correct element to the subset. Note that &lt;b&gt;bitmask &amp; 1&lt;/b&gt; equals to 1 only when bitmask has a &#39;1&#39; bit at the last position. For example, bitmask = &quot;001&quot; or &quot;011&quot; will make bitmask &amp; 1 equal to 1. That&#39;s when we&#39;ll add an element into the subset. Why does it work? Well, for each iteration of the while loop, we&#39;ll shift bitmask by one bit position to the right (bitmask &gt;&gt;= 1) and we decrement pos by 1 (pos--). Thus, whenever there is a &#39;1&#39; bit at the last bit position, we know exactly which element to add into the subset. If you are confused, don&#39;t worry because we&#39;ll do an example!&lt;/li&gt;
&lt;li&gt;After finishing one subset, we go to a new line and continue processing the rest.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;b&gt;Example:&lt;/b&gt; supposed that we have S = {1, 2} as our superset, then numOfSubsets = 0001 &lt;&lt; 2 = 0100 = 4 (subsets). The rest of the program runs like this:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;i = 0, pos = 1, and bitmask = 0. First while loop iteration, bitmask &amp; 1 = 0, bitmask &gt;&gt;= 1 = 0, and pos = 0. While loop exits because bitmask = 0.&lt;/li&gt;
&lt;li&gt;i = 1, pos = 1, and bitmask = 1. First while loop iteration, bitmask &amp; 1 = 1, so print out array[pos] = 2. bitmask &gt;&gt;= 1 = 0 and pos = 0. While loop exits because bitmask = 0.&lt;/li&gt;
&lt;li&gt;i = 2, pos = 1, and bitmask = 2. First while loop, bitmask &amp; 1 = 0, so print nothing. bitmask &gt;&gt;= 1 = 1 and pos = 0. Second while loop, bitmask &amp; 1 = 1, so print out array[pos] = 1. bitmask &gt;&gt;= 1 = 0 and pos = -1. While loop exits because bitmask = 0.&lt;/li&gt;
&lt;li&gt;i = 3, pos = 1, and bitmask = 3. First while loop, bitmask &amp; 1 = 1, so print out array[pos] = 2. bitmask &gt;&gt;= 1 = 1 and pos = 0. Second while loop, bitmask &amp; 1 = 1, so print array[pos] = 1. bitmask &gt;&gt;= 1 = 0, and pos = -1. While loop exits because bitmask = 0.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The result is 4 subsets: {}, {2}, {1} and {2, 1}&lt;/p&gt;

&lt;p&gt;This algorithm can be challenging to understand if you don&#39;t have any knowledge about bit manipulation. So, if you have a hard time making sense of it, try to read about bit manipulation first! That will help a lot! Well, thanks for reading and until next time.&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/694868013723777289/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/03/find-all-subsets-of-given-set.html#comment-form' title='17 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/694868013723777289'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/694868013723777289'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/03/find-all-subsets-of-given-set.html' title='Find all subsets of a given set'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>17</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-4166398816993888857</id><published>2011-03-10T20:26:00.000-08:00</published><updated>2011-03-10T20:26:26.166-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Algorithm to determine if a linked list is circular or has a loop</title><content type='html'>&lt;p&gt;&lt;b&gt;Problem:&lt;/b&gt; how do you find out if a linked list is circular (ie. 1-&gt;2-&gt;3-&gt;4-&gt;1) or has a loop (ie. 1-&gt;2-&gt;3-&gt;4-&gt;2)?&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Understand the problem:&lt;/b&gt; a circular linked is like a circle where the end node points to the head node instead of null like in a regular linked list. The example, 1-&gt;2-&gt;3-&gt;4-&gt;1, has the end node 4 points to the head node 1, creating a cycle. Similarly, a linked list is said to have a loop when it contains a cycle. However, the cycle doesn&#39;t have to start at the head node. It can start at any node in the list. For instance, 1-&gt;2-&gt;3-&gt;4-&gt;2 has a loop that starts at node 2 and ends at node 4.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Solution:&lt;/b&gt; to solve this problem, we&#39;ll have two pointers moving at different speeds over the list. The slow pointer will move through the list one one at a time while the fast pointer will move over two nodes at a time. In other words, the fast pointer will move twice as fast as the slow pointer. When the slow and fast pointer point at the same node, we know that the linked list either is circular or has a loop. But if the linked list is just a regular list, the fast pointer will reach null before the slow pointer.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Algorithm implementation:&lt;/b&gt; here is the algorithm implemented in C++&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
#include&amp;lt;iostream&gt;
using namespace std;

struct Node
{
  int data;
  Node* next;
};

bool hasLoopInList(Node* head)
{
  if (head == NULL)
    return false;

  Node* slow = head;
  Node* fast = head;

  while (fast-&gt;next != NULL &amp;&amp; fast-&gt;next-&gt;next != NULL)
  {
    slow = slow-&gt;next;
    fast = fast-&gt;next-&gt;next;

    if (slow == fast)
      return true;
  }

  return false;
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Code explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Check whether the list is empty. If it is, return false because an empty list neither is circular nor has loop.&lt;/li&gt;
&lt;li&gt;Create two pointers, &lt;b&gt;slow&lt;/b&gt; and &lt;b&gt;fast&lt;/b&gt;, that are used to traverse the list and determine if the list has loop or not. Initially, these pointers will point at the first node in the list.&lt;/li&gt;
&lt;li&gt;Next, we just need to loop until our fast pointer reaches null or until the slow and fast pointer points at the same node. If the list is just a regular list, nothing will happen inside the while loop. And, the while loop will end eventually because the fast pointer will reach null. On the other hand, if the list has loop or is circular, the slow and fast pointers will eventually point at the same node. That&#39;s why we check for that condition for every iteration of the while loop. And as soon as we know the list has a loop, we return true.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is a very efficient way to find out if a linked list has loop or is circular. The time complexity is O(n) where n is the number of nodes in the list. Moreover, the space complexity is O(1) because we only need two pointers no matter how long the list we need to check is.&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/4166398816993888857/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/03/algorithm-to-determine-if-linked-list.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/4166398816993888857'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/4166398816993888857'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/03/algorithm-to-determine-if-linked-list.html' title='Algorithm to determine if a linked list is circular or has a loop'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-3934302689980632674</id><published>2011-03-07T13:34:00.000-08:00</published><updated>2011-03-07T17:12:33.108-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Converting ASCII representation of positive numbers to integer</title><content type='html'>&lt;p&gt;A number can be represented as ASCII characters (char) or integers (int). Thus, the question is how we can convert from char to int. For example, we want to convert &#39;123&#39; to 123 or &#39;45&#39; to 45.&lt;/p&gt;

&lt;p&gt;To solve this problem, we need to revisit the ASCII table for a little bit. Moreover, we are interested in the characters &#39;0&#39; to &#39;9&#39; in the table. The special thing about those characters is that they stand consecutively in the table. That means their decimal values are consecutive positive integers. For example, &#39;0&#39; is 48; &#39;1&#39; is 49; and &#39;2&#39; is 50. Thus, if we have &#39;1&#39; - &#39;0&#39;, we&#39;ll get an integer value of 1 because 49 - 48 = 1. That&#39;s how we&#39;re gonna convert the number from char to int. Here is the algorithm in C++:&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
#include&amp;lt;iostream&gt;
#include&amp;lt;math.h&gt;
using namespace std;

int digitsToInt(char arrayOfChars[], int size)
{
  int digitPos = size - 1;
  int result = 0;
  for (int i = 0; i &lt; size; i++)
  {
    result += ((int)(arrayOfChars[i] - &#39;0&#39;)) * pow(10, digitPos);
    digitPos--;
  }
  return result;
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation&lt;/b&gt;: our function takes an array of characters containing the char representation of the number and the size of the array.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;b&gt;digitPos&lt;/b&gt; keeps track of which digit we&#39;re converting. It is important to do so because we must convert the digit into appropriate value in integer (remember that ASCII digits are between &#39;0&#39; and &#39;9&#39;). If the number passed in is &#39;102&#39;, then the first digit &#39;1&#39; represents 100 in integer. The algorithm must know that and multiply &#39;1&#39; with 100 after converting it into int 1.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;result&lt;/b&gt; is the final number in int. Our strategy here is to convert each digit into its appropriate int value and then add all of them up. That will give us the final result in integer. For example, if we need to convert &#39;12&#39;, we will convert &#39;1&#39; to 1 first and multiply it by 10. Next, we convert &#39;2&#39; to 2 and multiply it by 1 (2 is the last digit). Therefore, the final result is 10 + 2 = 12.&lt;/li&gt;
&lt;li&gt;We loops through the array and convert each digit into the appropriate int value and add that value into the result. As explained above, by subtracting the digit by &#39;0&#39; and casting the result into int we&#39;ll get the correct int number corresponding to that digit. However, that&#39;s not all. Notice how we use the function &lt;b&gt;pow(10, digitPos)&lt;/b&gt; to get the correct value for each digit. This method works because our numbers are base 10 numbers. Thus, by multiplying a number by 10 to the power of its position, we&#39;ll get the correct value for that number. Don&#39;t worry if you are confused, we&#39;ll do an example later.&lt;/li&gt;
&lt;li&gt;Lastly, we decrement digitPos by one because we will move to process the next digit which has one order less than the current number.&lt;/li&gt;
&lt;li&gt;Return the final result which is the sum of all the int values of our digits.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;b&gt;Example&lt;/b&gt;: we&#39;ll convert the number &#39;123&#39; into integer.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Our digitPos is 2 because we process the first digit &#39;1&#39; first and it is in the hundredth position. So, &#39;1&#39; - &#39;0&#39; gives int 1. Then, 1 * 10 ^ 2 = 100. Add that into our result. We have 100 after the first iteration. Moreover, digitPos decreases by 1 because we are about to process the tenth digit.&lt;/li&gt;
&lt;li&gt;Second iteration, digitPos is 1. And we have &#39;2&#39; - &#39;0&#39; = int 2. Multiplying 2 by ten to the power of its position, we have 2 * 10 ^ 1 = 20. Add that value to the result and we end up with the sum of 120. Finally, we decrement digitPos by 1.&lt;/li&gt;
&lt;li&gt;Last iteration, digitPos is 0. And, &#39;3&#39; - &#39;0&#39; = int 3. Multiplying 3 by ten to the power of its position, we have 3 * 10 ^ 0 = 3. Add 3 into the result and we have int 123. Loop ends and our algorithm returns the result of 123.&lt;/li&gt;  
&lt;/ol&gt;

&lt;p&gt;Thanks for reading and as always feel free to leave any comment or suggestion :)&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/3934302689980632674/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/03/converting-ascii-representation-of.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/3934302689980632674'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/3934302689980632674'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/03/converting-ascii-representation-of.html' title='Converting ASCII representation of positive numbers to integer'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-1056219656147640774</id><published>2011-02-28T12:42:00.000-08:00</published><updated>2011-02-28T12:42:24.876-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Check if two rectangles intersect</title><content type='html'>&lt;p&gt;This is a one of the classic problems in graphics programming and game development. So, let&#39;s see how we can solve it.&lt;/p&gt;

&lt;p&gt;Most computer (now cellphone) screens have an invisible coordinate system that is used to identify where graphical objects are on the screen. For example, the iPhone coordinate system has the origin at the top-left corner of the screen. As you move down the screen, the y value increases. And, as you move right the x value increases.&lt;/p&gt;

&lt;p&gt;For the general purpose of this post, assume that we have a right-handed coordinate system where the origin is at the bottom-left screen such that it is exactly like the coordinate system we learn in high school algebra. Also, the rectangles that we have to check are on that coordinate system and  are identified by the coordinates of their top-left corner and bottom right corner. For instance:&lt;/p&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9KmZPOUtQ8JC2ueIaAVBO3VFwN75aHyYaBDq6QYMjnAXg7YoYYXxhXXiKRjXzJxyqL4WFyHwdW7JK62zACNDyMLuD3dBqO_i9uUAi5ShbdiNbnYMVxO65wwojQ5rPJpZnyRwFUI-isEGh/s1600/intersectRectangles.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left:1em; margin-right:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;235&quot; width=&quot;400&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9KmZPOUtQ8JC2ueIaAVBO3VFwN75aHyYaBDq6QYMjnAXg7YoYYXxhXXiKRjXzJxyqL4WFyHwdW7JK62zACNDyMLuD3dBqO_i9uUAi5ShbdiNbnYMVxO65wwojQ5rPJpZnyRwFUI-isEGh/s400/intersectRectangles.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;Here are scenarios where we consider two rectangles as intersecting each other:&lt;/p&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg2zYVY3C2cTXtO0w6zOvQwp476pm-8_KPlAN1OV68DlUUheHkP0Bph1Ynq-PzcwHsZQeiAovKzODn5w8GQX9MhPc4ruTQatu8zl4XAtnogBd9KMj6DIE8meFDDgHHr1KlxyJYMUONIROVR/s1600/examplesOfIntersectRectangles.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left:1em; margin-right:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;192&quot; width=&quot;400&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg2zYVY3C2cTXtO0w6zOvQwp476pm-8_KPlAN1OV68DlUUheHkP0Bph1Ynq-PzcwHsZQeiAovKzODn5w8GQX9MhPc4ruTQatu8zl4XAtnogBd9KMj6DIE8meFDDgHHr1KlxyJYMUONIROVR/s400/examplesOfIntersectRectangles.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;Of course, those figures are just special cases of intersecting rectangles. There are many more ways to draw them, but four figures should give us enough information about what considered intersection. However, to solve this problem it is better to focus on when two rectangles do not intersect.&lt;/p&gt;

&lt;p&gt;Here are example of non-intersecting rectangles:&lt;/p&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg92MEacX-aNdkdzfSVcBBsQ1KIxSFSpAAi7GUXaJlwnNpsPIs0xYLb9mvwzwxkxDhCVeKUtyWCBnhu6gcfS4AA8-2fDh8wdNxKh0PqvkrHDaprKSd1HCRUNcdVtU6cv7fNYDnu0MVJ2NV0/s1600/exOfNonIntersectRects.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left:1em; margin-right:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;236&quot; width=&quot;400&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg92MEacX-aNdkdzfSVcBBsQ1KIxSFSpAAi7GUXaJlwnNpsPIs0xYLb9mvwzwxkxDhCVeKUtyWCBnhu6gcfS4AA8-2fDh8wdNxKh0PqvkrHDaprKSd1HCRUNcdVtU6cv7fNYDnu0MVJ2NV0/s400/exOfNonIntersectRects.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;From those pictures, we can infer that two rectangles are not intersecting each other if they have one of the four conditions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Right edge of blue is closer to the left of the screen than the left edge of red&lt;/li&gt;
&lt;li&gt;Bottom edge of blue is further from the bottom of the screen than the top edge of red&lt;/li&gt;
&lt;li&gt;Top edge of blue is closer to the bottom of the screen than the bottom edge of red&lt;/li&gt;
&lt;li&gt;Left edge of blue is further from the left of the screen than the right edge of red&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
So, if our rectangles don&#39;t have any of those conditions, then they intersect one another! Here is the code:
&lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
#include&amp;lt;iostream&gt;
using namespace std;

struct Point
{
  float x;
  float y;
};

struct Rect
{
  Point topLeft;
  Point bottomRight;
};

bool isIntersect(Rect rect1, Rect rect2)
{
  if (rect1.topLeft.x &gt;= rect2.bottomRight.x 
      || rect1.bottomRight.x &lt;= rect2.topLeft.x 
      || rect1.topLeft.y &lt;= rect2.bottomRight.y 
      || rect1.bottomRight.y &gt;= rect2.topLeft.y)
    return false;
    
  return true;
}
&lt;/pre&gt;

&lt;p&gt;Our rectangles are defined by their top-left and bottom-right vertices each of which is defined by a pair of x and y coordinates. Thus, there are two structs. One for the point and one for the rectangle.&lt;/p&gt;

&lt;p&gt;Our method to determine intersection is simple, we just have to check for all four conditions explained above. If any of those conditions is true then our rectangles do not intersect. Notice that we use x values when comparing the distance of right and left edges of the rectangles. Also, we only use y values when comparing the distances of top and bottom edges of the rectangles.&lt;/p&gt;

&lt;p&gt;That&#39;s it for this post. Please leave a comment if you have any question / suggestion. Thanks&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/1056219656147640774/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/02/check-if-two-rectangles-intersect.html#comment-form' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/1056219656147640774'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/1056219656147640774'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/02/check-if-two-rectangles-intersect.html' title='Check if two rectangles intersect'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9KmZPOUtQ8JC2ueIaAVBO3VFwN75aHyYaBDq6QYMjnAXg7YoYYXxhXXiKRjXzJxyqL4WFyHwdW7JK62zACNDyMLuD3dBqO_i9uUAi5ShbdiNbnYMVxO65wwojQ5rPJpZnyRwFUI-isEGh/s72-c/intersectRectangles.png" height="72" width="72"/><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8242511539054593745.post-3319338871498265863</id><published>2011-02-22T17:43:00.000-08:00</published><updated>2011-02-22T17:43:52.798-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Retrieve middle node of a singly linked list</title><content type='html'>&lt;p&gt;&lt;b&gt;Question&lt;/b&gt;: find the middle node in a singly linked list. If the linked list has even number of nodes, return either of the middle nodes. For example, 1-&gt;2-&gt;3 returns 2 but 1-&gt;2-&gt;3-&gt;4 returns either 2 or 3.&lt;/p&gt;

&lt;p&gt;This is a common algorithm concerning linked lists. The trick here is to have two pointers moving at different paces. When the faster pointer reaches the end of the list, the slow pointer is pointing to the middle node in the list. Here is the algorithm implemented in C++: &lt;/p&gt;

&lt;pre class=&quot;example&quot;&gt;
#include&amp;lt;iostream&gt;
using namespace std;

struct Node
{
  Node *next;
  int data;
};

Node* findMidofLinkedList(Node* head)
{
  Node *fast = head;
  Node *slow = head;

  while (fast-&gt;next != NULL &amp;&amp; fast-&gt;next-&gt;next != NULL)
  {
    fast = fast-&gt;next-&gt;next;
    slow = slow-&gt;next;
  }

  return slow;
}
&lt;/pre&gt;

&lt;p&gt;&lt;b&gt;Explanation:&lt;/b&gt;
We maintain two pointers &lt;b&gt;fast&lt;/b&gt; and &lt;b&gt;slow&lt;/b&gt;. For every iteration of the while loop, we move the fast pointer two nodes forward and move the slow pointer one node forward. When the node next to the fast pointer is NULL or when the node next to the next node of the fast pointer is NULL, the slow pointer has reached the middle node. We simply returns the slow pointer.
&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Example:&lt;/b&gt;
Let&#39;s trace our algorithm with this linked list 1-&gt;2-&gt;3-&gt;4-&gt;5:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;First iteration: fast points to 3. slow points to 2. fast-&gt;next is 4. fast-&gt;next-&gt;next is 5.&lt;/li&gt;
&lt;li&gt;Second iteration: fast points to 5. slow points to 3. fast-&gt;next is NULL. fast-&gt;next-&gt;next is NULL. So we stop after this iteration. Slow is now pointing at 3 which is the middle node.&lt;/li&gt;
&lt;/ol&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesam.blogspot.com/feeds/3319338871498265863/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesam.blogspot.com/2011/02/retrieve-middle-node-of-singly-linked.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/3319338871498265863'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8242511539054593745/posts/default/3319338871498265863'/><link rel='alternate' type='text/html' href='http://codesam.blogspot.com/2011/02/retrieve-middle-node-of-singly-linked.html' title='Retrieve middle node of a singly linked list'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry></feed>