<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>AlgoPill</title>
	<atom:link href="http://www.algopill.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.algopill.com</link>
	<description>One Algorithm Everyday</description>
	<lastBuildDate>Sat, 27 Aug 2011 17:34:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Horner&#8217;s Rule</title>
		<link>http://www.algopill.com/2011/08/27/horners-rule/</link>
		<comments>http://www.algopill.com/2011/08/27/horners-rule/#comments</comments>
		<pubDate>Sat, 27 Aug 2011 17:08:57 +0000</pubDate>
		<dc:creator>AlgoPill</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.algopill.com/?p=363</guid>
		<description><![CDATA[function hornersRule(coeff, c) {
    var result = 0,
        i = 0;
    for (i = coeff.length - 1; i &#62;= 0; i--) {
        result = coeff[i] + result * c;
    }
    return result;
}]]></description>
			<content:encoded><![CDATA[<div>
<p>Problem Statement: Find the value of a given polynomial P(x) = a<sub>0</sub> + a<sub>1</sub>x + a<sub>2</sub>x<sup>2</sup> + a<sub>3</sub>x<sup>3</sup>&#8230; a<sub>n-1</sub>x<sup>n-1</sup> for a given value of x</p>
<p>Solution: Horner&#8217;s rule can be used to solve this problem in O(n) time where n is the maximum power of variable x in the polynomial.</p>
<p>this method works by evaluating the polynomial in a different form which requires reduced number of operations.</p>
<p>P(x) = a<sub>0</sub> + a<sub>1</sub>x + a<sub>2</sub>x<sup>2</sup> + a<sub>3</sub>x<sup>3</sup>&#8230; a<sub>n-1</sub>x<sup>n-1</sup></p>
<p>P(x) = a<sub>0</sub> + x(a<sub>1</sub> + x(a<sub>2</sub> + x(a<sub>3</sub>+&#8230; +(a<sub>n-2</sub>+ xa<sub>n-1</sub>)  &#8230; )))</p>
<p>The input to this algorithm is an array of co-efficient  in the polynomial, i.e. coeff[i] = a<sub>i</sub>, and a number c which is the given value of x at which we have to calculate P(x)</p>
<p>The algorithm maintains a loop invariant which we state below.</p>
<p>Loop Invariant: at the start of the loop the variable result contains a partially calculated polynomial Q<sub>i</sub>(x)</p>
<p>Q<sub>i</sub>(x) = a<sub>i+1</sub> + a<sub>i+2</sub>x + a<sub>i+3</sub>x<sup>2</sup> &#8230;.. a<sub>n-1</sub>x<sup>n-2-i</sup></p>
<p>Intialization: i=n-1</p>
<p>Q<sub>n-1</sub>(x) = 0</p>
<p>Maintenance:</p>
<p>Q<sub>n-2</sub>(x) = a<sub>n-1</sub></p>
<p>Q<sub>n-3</sub>(x) = a<sub>n-2</sub> + x*a<sub>n-1</sub></p>
<p>Q<sub>i </sub>(x) = a<sub>i+1</sub> + a<sub>i+2</sub>x + a<sub>i+3</sub>x<sup>2</sup> + &#8230;. a<sub>n-1</sub>x<sup>n-2-i</sup></p>
<p><sup> </sup></p>
<p>Q<sub>i-1</sub>(x) = a<sub>i</sub> + x*Q<sub>i</sub>(x)</p>
<p>= a<sub>i</sub> + a<sub>i+1</sub>x + a<sub>i+2</sub>x<sup>2</sup> + a<sub>i+3</sub>x<sup>3</sup> + &#8230; a<sub>n-1</sub>x<sup>n-1-i</sup></p>
<p>= Q<sub>i-1</sub>(x)</p>
<p>Termination:</p>
<p>Q<sub>-1</sub>(x) = a<sub>0</sub> + a<sub>1</sub>x + a<sub>2</sub>x<sup>2</sup> + &#8230;. a<sub>n-1</sub>x<sup>n-2 +1</sup></p>
<p>Q<sub>-1 </sub>(x) = a<sub>0</sub> + a<sub>1</sub>x + a<sub>2</sub>x<sup>2</sup> + &#8230;. a<sub>n-1</sub>x<sup>n-1</sup></p>
<p>which is equivalent to P(c) if we substitute  c for x.</p>
<p>Thus this algorithm correctly calculates</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.algopill.com/2011/08/27/horners-rule/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Number of Inversions</title>
		<link>http://www.algopill.com/2011/08/27/number-of-inversions/</link>
		<comments>http://www.algopill.com/2011/08/27/number-of-inversions/#comments</comments>
		<pubDate>Sat, 27 Aug 2011 16:22:06 +0000</pubDate>
		<dc:creator>AlgoPill</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.algopill.com/?p=361</guid>
		<description><![CDATA[function number_of_inversions(list) {
    function merge_inversions(lst, beg1, end1, beg2, end2, aux) {
        var c = beg1,
                // counter for auxiliary array
            beg = beg1,
            // copy beg and end
            end = end2,
            count = 0;
        while (beg1 &#60;= end1 &#38;&#38; beg2 &#60;= end2) {
            if (lst[beg1] &#60;= lst[beg2]) {
                aux[c++] = lst[beg1++];       
            } else {
                aux[c++] = lst[beg2++];
                count += end1 - beg1 + 1;
            }
        }          // copy remaining items if any
                 
        while (beg1 &#60;= end1) {
            aux[c++] = lst[beg1++];
        }
        while (beg2 &#60;= end2) {
             aux[c++] = lst[beg2++];
        }          // now copy sorted elements from aux to actual list
                 
        while (beg &#60;= end) {
            lst[beg] = aux[beg++];
        }
        return count;
    } 
    function count_inversions(lst, start, end, aux) {
        if (end === start) {   // we have just one element to sort, so its already sorted
            return 0;
        }         // partition the list portion into two and sort them
        // this is first step 1. Divide

        var mid = Math.floor((start + end) / 2),
            inversions = 0;
        inversions += count_inversions(lst, start, mid, aux);
        inversions += count_inversions(lst, mid + 1, end, aux);         // Now merge the two
        // this is second step. 2. Conquer
        inversions += merge_inversions(lst, start, mid, mid + 1, end, aux);
        return inversions;
    }

     // merge sort the entire array
    // create and auxiliary memory, which is required by merge sort     
    var i = 0,
         aux = [];
    while (i &#60; list.length) {
        aux[i++] = 0;
    }
    return count_inversions(list, 0, list.length - 1, aux);
}]]></description>
			<content:encoded><![CDATA[<div>Problem Statement: Given a list of numbers count the number of inversions.</div>
<div>Solution:Modified merge sort is used to find invesion in a list of numbers.</div>
<div>this resursive solution can be written as follows</div>
<div>inversions(i,j) = inversions(i,k) + inversions(k+1,j) + merge(i,k,j)</div>
<div>where</div>
<div>inversions routine sort subarray [i,...,j] and  returns number of inversions in it.</div>
<div>and k = floor((i+j)/2)</div>
<div>merge procedure can be easily explained as follows.</div>
<div>Let A be a sorted sub array {2,6,7,9}</div>
<div>Let B be a sorted sub array {1,3,4,10}</div>
<div>number of inversion in concatenated array AB i.e {2,6,7,9,1,3,4,10} can be found in linear time.</div>
<div>We merge the two list using same method as used in merge sort and when we pick element from second list we increment</div>
<div>number of inversions by the number of element remaining to be processed in first list. Let current item in first b c1</div>
<div>and current item in second list be c2</div>
<div>if B[c2] is less that A[c1] then all remaining elements in A ( from c1 to end} are larger than B[c2] because A and B are sorted lists</div>
<div>but as B[c2] comes after all remaining elements in A all those  elements are inversions of the AB combined list.</div>
]]></content:encoded>
			<wfw:commentRss>http://www.algopill.com/2011/08/27/number-of-inversions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Recursive Insertion Sort</title>
		<link>http://www.algopill.com/2011/08/19/recursive-insertion-sort/</link>
		<comments>http://www.algopill.com/2011/08/19/recursive-insertion-sort/#comments</comments>
		<pubDate>Fri, 19 Aug 2011 06:04:19 +0000</pubDate>
		<dc:creator>AlgoPill</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[insertion]]></category>
		<category><![CDATA[sort]]></category>

		<guid isPermaLink="false">http://www.algopill.com/?p=357</guid>
		<description><![CDATA[function recursiveInsertionSort(list) {
    // insert subroutine, 
    // inserts nth elelement in sorted lst[0...n-1] list

    function insert(lst, n) {
        var key = lst[n];
        var i = n - 1;
        while (i &#62;= 0 &#38;&#38; lst[i] &#62; key) {
            lst[i + 1] = lst[i];
            i = i - 1;
        }
        lst[i + 1] = key;
    }
    // the main recursive sort routine

    function sort(lst, n) {
        if (n &#62; 0) {
            sort(lst, n - 1);
            insert(lst, n);
        }
        return lst;
    }
    // do the sorting
    return sort(list, list.length - 1);
}]]></description>
			<content:encoded><![CDATA[<p><strong>Problem Statement</strong>: Sort a given list of numbers</p>
<p><strong>Solution</strong>: We use a recursive variant of insertion sort to solve this problem. the main sort function recursively sorts first n-1 elements and inserts nth element in its proper location using insert routine. Running time of this algorithm can be expressed as T(n) = T(n-1) + O(n) OR, T(n) = O(n²)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algopill.com/2011/08/19/recursive-insertion-sort/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generate Valid Parentheses</title>
		<link>http://www.algopill.com/2011/03/15/generate-valid-parentheses/</link>
		<comments>http://www.algopill.com/2011/03/15/generate-valid-parentheses/#comments</comments>
		<pubDate>Tue, 15 Mar 2011 18:22:11 +0000</pubDate>
		<dc:creator>AlgoPill</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.algopill.com/?p=354</guid>
		<description><![CDATA[function generateValidParentheses(n){
    function generate(l,r,n,p){
        var output=[];
        if(r&#62;=n){
            output.push(p.join(&#039;&#039;));
            return output;
        }
        if(r&#60;l){
            p[l+r]=&#039;)&#039;;
            output = output.concat(generate(l,r+1,n,p));
        }
        if(l&#60;n){
            p[l+r]=&#039;(&#039;;
            output = output.concat(generate(l+1,r,n,p));
        }
        return output;
    }

    return generate(0,0,n,[]);
}]]></description>
			<content:encoded><![CDATA[<p>Problem Statement: Given n pairs of parentheses, generate set of all valid parentheses permutations</p>
<p>Solution: Given n pairs of parentheses this solution uses a simple logic that  left parentheses can be place in the string as long number of left parentheses used so far is less than n, and a right parentheses can be place in the string as long as number of right parentheses used so far is less than the number of left parentheses used so far.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algopill.com/2011/03/15/generate-valid-parentheses/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Number of Valid Parentheses Permutations</title>
		<link>http://www.algopill.com/2011/03/14/number-of-valid-parentheses-permutations/</link>
		<comments>http://www.algopill.com/2011/03/14/number-of-valid-parentheses-permutations/#comments</comments>
		<pubDate>Mon, 14 Mar 2011 18:23:34 +0000</pubDate>
		<dc:creator>AlgoPill</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.algopill.com/?p=346</guid>
		<description><![CDATA[function validParentheses(n){
    /**
     * recusive function
     * @param l number left paren so far
     * @param r number of right paren so far
     * @param n total number of paren pairs
     */
    function calc(l,r,n){
        if(l==n){
            return 1; // leaf node
        }
        var c=0;
        if(r&#60;l){
            c+=calc(l,r+1,n);
        }
        c+=calc(l+1,r,n);
        return c;
    }
    
    return  calc(0,0,n);
}]]></description>
			<content:encoded><![CDATA[<p>Problem Statement: Given n pair of parentheses find how many different valid combination of parentheses are possible.</p>
<p>Solution: In order to under solution to this problem lets take an example. Assume that we are given three pairs of parentheses. A valid permutation of these parentheses will always have left number of left parentheses more than or equal to number of right p arentheses. Lets see an example</p>
<p>Let the pair [l,r] represent number of left parentheses and number of right parentheses encountered in the permutation so far.</p>
<p>a. Valid Parentheses ,</p>
<p>( [1,0]      ( [2,0]      ) [2,1]     ) [2,2]      ( [3,2]      ) [3,3]</p>
<p>b. Invalid Parentheses</p>
<p>([1,0]   )[1,1]   )[1,2  invalid    ]   (    (    )</p>
<p>Above examples demonstrate that for a permutation to be valid number of left parentheses in the permutation at any position should be more than or equal to number right parentheses</p>
<p>Now lets try to find out all possible permutation for 3 pairs of parentheses.  It can be noted that all permutations will have six characters , and any character can be either &#8216;(&#8216; left parentheses or &#8216;)&#8217; right parentheses as long as it does not violate above property, let us represent left parentheses &#8216;(&#8216; by 0 and right parentheses &#8216;)&#8217; by 1. So that a string of zeros and ones represent a permutation of parentheses</p>
<p>﻿﻿﻿                                     <a href="http://www.algopill.com/wp-content/uploads/2011/03/parenthesis.png"><img class="alignnone size-large" src="http://www.algopill.com/wp-content/uploads/2011/03/parenthesis.png" alt="" width="800" height="602" /></a></p>
<p>As you can see in the above tree that the tree is binary and that tree stops branching as long as number of left parentheses becomes 3 which is equal to the number of pairs of parenthesis. Thus number of valid parentheses is equal to number of node which have l ( number of left parentheses)  equal to n (number of pairs of parentheses). and for all other cases we have two choices we increment l and if r &lt; l we can increment r also where r is number of right parentheses. The presented algorithm does exactly that</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algopill.com/2011/03/14/number-of-valid-parentheses-permutations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Modified Preorder Traversal (Recursive)</title>
		<link>http://www.algopill.com/2011/03/14/modified-preorder-traversal-recursive/</link>
		<comments>http://www.algopill.com/2011/03/14/modified-preorder-traversal-recursive/#comments</comments>
		<pubDate>Mon, 14 Mar 2011 12:39:19 +0000</pubDate>
		<dc:creator>AlgoPill</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.algopill.com/?p=340</guid>
		<description><![CDATA[function modifiedPreOrderTraversal(root){
    /**
     * inner recursive function 
     * Node:{val:number,left:Node,right:Node}
     * sample input
     * var tree={ val:&#34;F&#34;,
     *                 left:{ val:&#34;B&#34;,
     *                        left:{ val:&#34;A&#34; },
     *                                right:{ val:&#34;D&#34;,
     *                                          left:{val:&#34;C&#34;},
     *                                          right:{val:&#34;E&#34;}
     *                              }
     *                      },
     *                right:{val:&#34;G&#34;,
     *                         right:{ val:&#34;I&#34;,
     *                                   left:{val:&#34;H&#34;}
     *                                 }
     *                       }
     *   };
     */
    function mptt(root,counter){
        if(root){
            root.first= counter.count++;
            mptt(root.left,counter);
            mptt(root.right,counter);
            root.second=counter.count++;
        }
        return root;
    }
    return mptt(root,{count:1});
}
]]></description>
			<content:encoded><![CDATA[<p>Problem Statement: Given a binary tree find its Modified Pre-order Traversal.</p>
<p>Solution:  Modified Preorder Traversal (MPTT) is an implementation of Nested Set Model. In this implementaion tree is traversed in preoder traveresal, i.e. root first then , its left child and finally its right child. In MPTT each node is visited twice and two numbers associated with each node. If first number is n then second number is [n+(2*no_children)+1].  Thus while numbering a node N, with set the first number to x, then we visit all its children from left to right assigning , first and second numbers to each and keep incrementing the counter in the process, then we visi the node N again and assign the current value of counter as second number. In the given algorithm. We first start with number1 with node root and assign root.start=1, then we recursively number its left children and the its right children , then we come back and set root.second to current value of the counter.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algopill.com/2011/03/14/modified-preorder-traversal-recursive/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FizzBuzz</title>
		<link>http://www.algopill.com/2011/03/13/fizzbuzz/</link>
		<comments>http://www.algopill.com/2011/03/13/fizzbuzz/#comments</comments>
		<pubDate>Sun, 13 Mar 2011 18:24:55 +0000</pubDate>
		<dc:creator>AlgoPill</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.algopill.com/?p=338</guid>
		<description><![CDATA[function fizzBuzz(n){
    var i,output = [];
    for(i=0;i&#60;=n;i++){
        if(i%15===0){
            output.push(&#34;FizzBuzz&#34;);
        } else if(i%3===0){
            output.push(&#34;Fizz&#34;);
        } else if(i%5===0){
            output.push(&#34;Buzz&#34;);
        } else {
            output.push(i);
        }
    }
    return output;
}]]></description>
			<content:encoded><![CDATA[<p>Problem Statement: Given a positive integer n, for all numbers between zero and n (inclusive) , output &#8220;Fizz&#8221; if number is a multiple of three, output &#8220;Buzz&#8221; if number is multiple of five, output &#8220;FizzBuzz&#8221; if number is a multiple of 15, otherwise output the number itself.</p>
<p>Solution: Solution is very simple. The only trick is to first test for 15 then for 5 and 3 because 15 is also a multiple of 3 and 5 and therefore all multiples of 15 are also multiple of 3 and/or 5.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algopill.com/2011/03/13/fizzbuzz/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lexicographic Permutations (Iterative)</title>
		<link>http://www.algopill.com/2011/03/13/lexicographic-permutations-iterative/</link>
		<comments>http://www.algopill.com/2011/03/13/lexicographic-permutations-iterative/#comments</comments>
		<pubDate>Sun, 13 Mar 2011 14:12:38 +0000</pubDate>
		<dc:creator>AlgoPill</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.algopill.com/?p=335</guid>
		<description><![CDATA[function lexicographicPermutations(str){
    function swap(ar,a,b){
        var tmp = ar[a];
        ar[a] = ar[b];
        ar[b] = tmp;
    }
    
    function next(mstr){
        var i = mstr.length - 2;
        /* Find the largest i */
        while ((i &#62;= 0) &#38;&#38; (mstr[i] &#62; mstr[i + 1])){
            --i;
        }
        if (i &#60; 0)
            return true;
        var k = mstr.length - 1;
        /* Find the largest element after vi but not larger than vi */
        while (mstr[i] &#62; mstr[k]){
            --k;
        }
        swap(mstr,i,k);
        var j;
        k = 0;
          /* Swap the last n - i elements. */
        for (j = i + 1; j &#60; Math.floor((mstr.length + i) / 2 + 1); ++j, ++k){
            swap(mstr,j, mstr.length - k - 1);
        }
        return false;
    }
    var permutations = [],
        mstr = str.split(&#039;&#039;); // mutable string
        permutations.push(mstr.join(&#34;&#34;)); // add the given
        var done = true;
    do {
        if (!(done = next(mstr))){
        permutations.push(mstr.join(&#34;&#34;));  /* P3 */
        }
    } while (!done);
        
    return permutations;
}]]></description>
			<content:encoded><![CDATA[<p>Problem Statement : Given a string of characters generate all permutations of string in lexicographic order.<br />
Solution: This algorithm has been taken from <a href="http://compprog.wordpress.com/2007/10/08/generating-permutations-2/">http://compprog.wordpress.com/2007/10/08/generating-permutations-2/</a></p>
<p>This algorithm will generate all permutations of a string in lexicographic using an iterative algorithm. The input string to this algorithm must have all the characters in lexicographic order. For example, if we want to generate permutations of &#8220;bcad&#8221; string. Then input string should be &#8220;abcd&#8221; because a&lt;b&lt;c&lt;d. This algorithm cannot handle duplicate characters so all characters must be unique.</p>
<p>The key routine of this algorithm is the routine &#8220;next&#8221;. Given a permutation &#8220;next&#8221; routine will find another permutation that comes next in lexicographic order.  This algorithm uses &#8220;next&#8221; to generate next permutation iteratively until all the characters in the string are in reverse lexicographic order. For example give &#8220;abcd&#8221; string , it will generate all permutaion until we reach &#8220;dcba&#8221; since this is the last permutation in lexicographic order. Now the working of &#8220;next&#8221; routine  is explained below with an example.</p>
<p>consider a permutaion of &#8220;abcdefghij&#8221;      p1  =  &#8221;chdafijgeb&#8221;</p>
<p>now lets find out next permutation in lexicographic order.</p>
<p>Step1. Starting with last char i.e. &#8216;b&#8217; , decrease  the counter as long as characters are in increasing order and find first character that breaks this trend. In this example we started &#8216;b&#8217;, thus &#8216;e&#8217;&gt;&#8217;b',  &#8217;g'&gt;&#8217;e&#8217;  ,  &#8217;j'&gt;&#8217;e',  but &#8216;i&#8217;&lt;&#8217;j&#8217; , thus the character that break this trend is &#8216;i&#8217;.</p>
<p>Step2 . Find the largest element starting from last element i.e. &#8216;b&#8217; such that it is smaller than the element found in last step i.e. &#8216;i&#8217;. &#8216;b&#8217;&lt;&#8217;i', &#8216;e&#8217;&lt;&#8217;i',&#8217;g'&lt;&#8217;i',&#8217;j&#8217; &gt; &#8216;i&#8217; , therefore the character is &#8216;g&#8217;;</p>
<p>Step 3  Now swap &#8216;g&#8217; and &#8216;i&#8217;; after this step we get    p1&#8242;  =  &#8221;chdafgjieb&#8221;;</p>
<p>Step 4 now reverse the string starting after &#8216;g&#8217; to the end. which gives us p1&#8221;  = &#8220;chdafgbeij&#8221;, this gives us smallest string that is larger than the input string and thus next in the lexicographic order</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algopill.com/2011/03/13/lexicographic-permutations-iterative/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Permutations (recursive) 2</title>
		<link>http://www.algopill.com/2011/03/13/permutations-recursive-2/</link>
		<comments>http://www.algopill.com/2011/03/13/permutations-recursive-2/#comments</comments>
		<pubDate>Sun, 13 Mar 2011 12:29:12 +0000</pubDate>
		<dc:creator>AlgoPill</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.algopill.com/?p=333</guid>
		<description><![CDATA[function permutationsRecursive(str){
    function rotate(ar,a,b){
      var i,save = ar[b-1];
      for(i=b-1;i&#62;a;i--){
          ar[i]=ar[i-1];
      }
      ar[a]=save;
    }
    function permute(buff,arr,start,end){
        var i,range = end-start;
        if(end-start==1){
            buff.push(arr.join(&#34;&#34;));
        } else {
            for(i=0;i&#60;range;i++){
                rotate(arr,start,end);
                permute(buff,arr,start+1,end);
            }
        }
    }
    var buff = [];
    permute(buff,str.split(&#34;&#34;),0,str.length);
    return buff;
}
]]></description>
			<content:encoded><![CDATA[<p>Problem Statement:Given a string find all permutations of string. It can be assumed that string does not had repeated characters.<br />
Solution: This is a simple algorithm for generating permutations. It uses a recursive construction. There are two points to be understood in order to this understand this algorithm<br />
1. The recursive construction<br />
consider finding all permutions of the string “abcd”, all permutations of this string are union of following<br />
permutaion(“abcd”) =<br />
1. “d” + permutations(“abc”)<br />
2 “c” + permutations(“dab”)<br />
3 “b” + permutaions(“cda”)<br />
4 “a” + permutations(“bcd”);<br />
where “+” is concatenation operator<br />
the permutation of “abc”, “dab”,”cda”,”bcd” can be calculated similarly.</p>
<p>2. Rotate part<br />
   as noted above in order to generate permutations we place all characters one by at position 0. The first case where “d” is moved to first place by rotating the string such that every character&#8217;s index  is increased by one and last character i.e &#8220;d&#8221; is moved to first. At second step characters are moved by one place which bring &#8220;c&#8221; in first place. This is done four times since the length of string is four. </p>
<p>This solution does NOT generate permutations in lexicographic order and it does NOT take care of repeated characters.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algopill.com/2011/03/13/permutations-recursive-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Post-Order Tree Traversal (Iterative)</title>
		<link>http://www.algopill.com/2011/03/06/post-order-tree-traversal/</link>
		<comments>http://www.algopill.com/2011/03/06/post-order-tree-traversal/#comments</comments>
		<pubDate>Sun, 06 Mar 2011 17:48:50 +0000</pubDate>
		<dc:creator>AlgoPill</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.algopill.com/?p=327</guid>
		<description><![CDATA[function postorderTraversalIterative(root){
    /**
     * Node:{val:number,left:Node,right:Node}
     * sample input
     * var tree={ val:&#34;F&#34;,
     *                 left:{ val:&#34;B&#34;,
     *                        left:{ val:&#34;A&#34; },
     *                                right:{ val:&#34;D&#34;,
     *                                          left:{val:&#34;C&#34;},
     *                                          right:{val:&#34;E&#34;}
     *                              }
     *                      },
     *                right:{val:&#34;G&#34;,
     *                         right:{ val:&#34;I&#34;,
     *                                   left:{val:&#34;H&#34;}
     *                                 }
     *                       }
     *   };
     */
    
   function peek(stack){
       return stack[stack.length-1];
   }
   
   var  stack = [root],
        output = [],top;
        
   while(stack.length&#62;0){
       while(peek(stack).right){
           output.push(peek(stack).val);
           stack.push(peek(stack).right);
       }
       output.push(peek(stack).val);
       // backup to parent which has a left child
       while((top=stack.pop()) &#38;&#38; !top.left){}
       // if parent was found, then push its left child
       if(top){
           stack.push(top.left);
       }
   }
 
   return output.reverse();
}
]]></description>
			<content:encoded><![CDATA[<p>Problem Statement: Given a binary tree find its post order traversal.<br />
Solution:  In post-order traversal of a node&#8217;s right child  is printed first then its left child and then the node  and this order must be valid for all subtrees in the tree. It can be noticed that post-order traversal is reverse of the pre-order traversal of the with right children swaped with left children of the tree.<br />
Following algorithm makes use of stack to first find pre-order traversal iteratively and it treats right child as if it were the left child , this will produce a pre-order traversal which can then be reversed to produce correct post-order traversal of the input tree . We start with having root node at the top of the stack, we drill down the tree rooted at the node at top of stack along the right most side , and output each node we encounter them. We then start poping until we find a node that has a left child. This left child is pushed onto the stack and above procedure gets repeated for subtree rooted at this node. Finally we reverse the traversal to give correct post-order traversal.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algopill.com/2011/03/06/post-order-tree-traversal/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

