<?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-3098638925089993315</id><updated>2025-11-18T13:53:57.847+05:30</updated><category term="kodeknight"/><category term="CrackingTheCodingInterview"/><category term="brainteaser"/><category term="incomplete"/><category term="Algorithms"/><category term="array"/><category term="Binary Search Tree / BST"/><category term="String"/><category term="tree"/><category term="linux / unix"/><category term="sorting"/><category term="Dynamic Programming / DP"/><category term="cpp"/><category term="Data Structure"/><category term="bits"/><category term="java"/><category term="recursion"/><category term="DS / Data Structures"/><category term="c"/><category term="stack"/><category term="Single Link List"/><category term="link list"/><category term="Puzzles"/><category term="duplicate"/><category term="interview"/><category term="Amazon"/><category term="Graph"/><category term="maths"/><category term="Page"/><category term="Binary Tree / BT"/><category term="balanced trees"/><category term="programming"/><category term="conversion"/><category term="search"/><category term="sorted-array"/><category term="useful linux commands"/><category term="Interview Question"/><category term="max"/><category term="min"/><category term="object-oriented-design / OOD"/><category term="pointers"/><category term="time complexity"/><category term="traversal"/><category term="count"/><category term="integer"/><category term="merge"/><category term="networking"/><category term="divide and conquer"/><category term="hard"/><category term="inorder"/><category term="linked list"/><category term="reverse"/><category term="understand"/><category term="graph-search"/><category term="queue"/><category term="BFS"/><category term="DLL/Doubly Linked List"/><category term="Low Level"/><category term="binary search"/><category term="distance"/><category term="heap"/><category term="k5kced"/><category term="trie"/><category term="ArraySearch"/><category term="Database"/><category term="Moderate"/><category term="Threads and Locks"/><category term="backtracking"/><category term="limited memory"/><category term="prime"/><category term="programCPP"/><category term="Adobe"/><category term="Microsoft"/><category term="Operating System / OS"/><category term="dynamic allocation"/><category term="hashtable"/><category term="java-code"/><category term="probability"/><category term="ranged-array"/><category term="unsorted-array"/><category term="StringAlgo"/><category term="System Design And Memory Limits"/><category term="anagrams"/><category term="avl"/><category term="greedy Algo"/><category term="matrix"/><category term="pattern matching"/><category term="quicksort"/><category term="sorting-and-searching"/><category term="subsequence"/><category term="substring"/><category term="two-sorted-arrays"/><category term="2DArray"/><category term="AbstractDataType/ADT"/><category term="DFS"/><category term="File handling"/><category term="Inorder traversal"/><category term="Software Engg"/><category term="Testing"/><category term="coordinate geometry"/><category term="integer-sort"/><category term="kth-largest"/><category term="largest"/><category term="memory management"/><category term="operators"/><category term="palindrome"/><category term="rbt / red black tree"/><category term="rectangle"/><category term="rotated array"/><category term="two-arrays"/><category term="Input Output / IO"/><category term="Mathematical"/><category term="Special Nos."/><category term="aptitude"/><category term="coding style"/><category term="delete"/><category term="factorization"/><category term="insertion-sort"/><category term="iterative"/><category term="merge-sort"/><category term="minmax"/><category term="postorder"/><category term="preprocessor"/><category term="prime-factor"/><category term="remove-duplicates"/><category term="string-udf"/><category term="swap"/><category term="unique"/><category term="zero"/><category term="Data Structure Templates"/><category term="Permutation"/><category term="Permutation and Combination"/><category term="Sorting Algorithm"/><category term="binary array"/><category term="bubble sort"/><category term="cleaner code"/><category term="data types"/><category term="define"/><category term="flipkart"/><category term="google"/><category term="hashes"/><category term="inmobi"/><category term="integer-array"/><category term="intersection"/><category term="interval"/><category term="interview-set"/><category term="level-order-traversal"/><category term="loop"/><category term="master-method"/><category term="preorder"/><category term="programming Questions"/><category term="random"/><category term="selection"/><category term="shortest-path"/><category term="smallest"/><category term="string-search"/><category term="udf"/><category term="virtualization"/><category term="2DSortedArray"/><category term="2Sum"/><category term="AlgorithmAnalysis"/><category term="ArithematicPuzzle"/><category term="Comparison Sort"/><category term="Directed Graph"/><category term="K-Distance"/><category term="PriorityQueue"/><category term="Selection Sort"/><category term="check"/><category term="companies"/><category term="compare"/><category term="concurrency"/><category term="connectivity"/><category term="db-design"/><category term="directi"/><category term="encoding"/><category term="fab.com"/><category term="fast pointer"/><category term="geometric-search"/><category term="github"/><category term="graphics"/><category term="inorder successor"/><category term="mathematics"/><category term="median"/><category term="morgan-stanley"/><category term="parentheses"/><category term="powerOf2"/><category term="programs"/><category term="randomized algorithm"/><category term="references"/><category term="skip-list"/><category term="sorting arrays"/><category term="stock"/><category term="subset"/><category term="sum"/><category term="theory"/><category term="window"/><category term="yahoo"/><category term="AptitudeConcepts"/><category term="Bit Vector"/><category term="DS Concepts"/><category term="Input"/><category term="KMP algorithm"/><category term="LCA/Least Common Ancestor"/><category term="O(1)"/><category term="Omega Time complexity"/><category term="Postorder traversal"/><category term="Preorder traversal"/><category term="Resources"/><category term="STL"/><category term="Undirected Graph"/><category term="application"/><category term="balls"/><category term="boolean"/><category term="cTricks"/><category term="cache"/><category term="celebrity"/><category term="coin"/><category term="compression"/><category term="const functions"/><category term="constructors"/><category term="cpp vs java"/><category term="cppimpl"/><category term="cryptography"/><category term="cut"/><category term="deque"/><category term="enum"/><category term="fileIO"/><category term="fileRead"/><category term="formatting-needed"/><category term="functions"/><category term="generic classes"/><category term="git"/><category term="goto"/><category term="jabong"/><category term="knapsack problem"/><category term="map-reduce"/><category term="matrix-multiplication"/><category term="maxima"/><category term="memoization"/><category term="min-heap"/><category term="mincut"/><category term="minima"/><category term="next-big-number"/><category term="number"/><category term="number theory"/><category term="operations"/><category term="process"/><category term="product"/><category term="projecteuler"/><category term="range"/><category term="sequence"/><category term="series"/><category term="shuffle"/><category term="spaces"/><category term="sub-array"/><category term="time"/><category term="two-string"/><category term="union"/><category term="verbal"/><category term="vmware"/><category term="Adjacency"/><category term="AdjacencyList"/><category term="Amortize"/><category term="AsymptoticUpperBound"/><category term="Big Omega"/><category term="Breadth-First Traversal"/><category term="Bucket Sort"/><category term="Combination"/><category term="Complete Binary tree"/><category term="Cram it"/><category term="Depth-First Traversal"/><category term="Distribution Sort"/><category term="If statement"/><category term="ImplementOperatorWithConditions"/><category term="In-place sorting"/><category term="Java Arrays"/><category term="LCS"/><category term="Linear datastructure"/><category term="Looping construct"/><category term="Object oriented programming / OOP"/><category term="Predefined Values in headers"/><category term="Relational Database"/><category term="Remember"/><category term="Sequential statement"/><category term="Threaded binary Tree"/><category term="UML"/><category term="UX"/><category term="angular"/><category term="average"/><category term="b-tree"/><category term="bank-bazaar"/><category term="beautiful codes"/><category term="big data"/><category term="binary-sort"/><category term="bitonic"/><category term="blog"/><category term="bottom-up"/><category term="browserstack"/><category term="c implementation"/><category term="c#"/><category term="calloc"/><category term="catalan"/><category term="chess"/><category term="circular stack"/><category term="cloud computing"/><category term="coding"/><category term="common math functions"/><category term="concatenate"/><category term="confused"/><category term="console input"/><category term="const"/><category term="contiguous"/><category term="counting-sort"/><category term="date-time"/><category term="declarations"/><category term="destructor"/><category term="differences"/><category term="dijkshtra"/><category term="double link list"/><category term="dynamic arrays"/><category term="endianness"/><category term="errors"/><category term="exceptions"/><category term="exit"/><category term="expressions"/><category term="external sort"/><category term="facebook"/><category term="factor"/><category term="fibonacci"/><category term="files"/><category term="floating point values"/><category term="frequency"/><category term="fun"/><category term="game"/><category term="gist"/><category term="good practice"/><category term="greater"/><category term="grep"/><category term="hackerrank"/><category term="hashmap"/><category term="hiding"/><category term="histogram"/><category term="identical"/><category term="increasing-sequence"/><category term="integer series"/><category term="inversion"/><category term="kadane"/><category term="keyword"/><category term="leetcode"/><category term="library functions"/><category term="linkage"/><category term="list"/><category term="local-minima"/><category term="logical questions"/><category term="macro"/><category term="malloc"/><category term="match string"/><category term="maze"/><category term="medium"/><category term="memory leaks"/><category term="middle"/><category term="minimum spanning tree / mst"/><category term="mirror"/><category term="multiplication"/><category term="non-linear datastructure"/><category term="non-linear datastrucutre"/><category term="number theoryQ"/><category term="optimization"/><category term="overflow"/><category term="overloading"/><category term="overriding"/><category term="pair"/><category term="parse"/><category term="partition"/><category term="pascal"/><category term="path"/><category term="pathological data"/><category term="plane"/><category term="polymorphism"/><category term="polynomial"/><category term="programming language / PL"/><category term="progression"/><category term="psychometry test"/><category term="pythagorean triplet"/><category term="queen"/><category term="quiz"/><category term="radix-sort"/><category term="regular expression"/><category term="replace"/><category term="scanf"/><category term="scoping"/><category term="search string"/><category term="second-largest"/><category term="selection-sort"/><category term="shell-sort"/><category term="size"/><category term="snapdeal"/><category term="sorted-list"/><category term="spanning tree"/><category term="square matrix"/><category term="squares"/><category term="stream"/><category term="suffix tree"/><category term="sweep-line"/><category term="templates"/><category term="text editors"/><category term="thread"/><category term="toc2"/><category term="top-down"/><category term="twin-prime"/><category term="two-lists"/><category term="ugly-number"/><category term="union-find"/><category term="variable argument functions"/><category term="variables"/><category term="vdopia"/><category term="vectors_cpp"/><category term="vi editor"/><category term="virtual function"/><category term="vocab"/><category term="web"/><category term="xml"/><category term="xor"/><category term="zigzag"/><title type='text'>KodeKnight</title><subtitle type='html'>Data structures, Algorithms, Coding, Technical Interview Questions and much more. (Still work in progress)</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default?start-index=26&amp;max-results=25&amp;redirect=false'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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>1055</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-3098638925089993315.post-3164157997333294327</id><published>2016-03-30T10:02:00.004+05:30</published><updated>2025-01-09T02:03:15.663+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="k5kced"/><category scheme="http://www.blogger.com/atom/ns#" term="leetcode"/><category scheme="http://www.blogger.com/atom/ns#" term="String"/><category scheme="http://www.blogger.com/atom/ns#" term="zigzag"/><title type='text'>Convert String to ZigZag Bottom Up</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div class=&quot;callout&quot;&gt;
    This updated information has been further expanded upon on my new website. You can find the updated details here: &lt;a href=&quot;https://k5kc.com/cs/algorithms/zigzag-conversion-problem/&quot;&gt;https://k5kc.com/cs/problems/zigzag-conversion/&lt;/a&gt;.
&lt;/div&gt;
&lt;h4 style=&quot;text-align: left;&quot;&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/h4&gt;&lt;h4 style=&quot;text-align: left;&quot;&gt;
&lt;b&gt;Problem&lt;/b&gt;&lt;/h4&gt;
&lt;div style=&quot;-webkit-text-stroke-width: 0px; background-color: white; color: #333333; font-family: &amp;quot;Helvetica Neue Light&amp;quot;, HelveticaNeue-Light, &amp;quot;Helvetica Neue&amp;quot;, Helvetica, Arial, sans-serif; font-size: 14px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 19.6px; margin: 0px; orphans: auto; outline: none; padding: 0px; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px;&quot;&gt;
The string&amp;nbsp;&lt;code style=&quot;background-color: #f9f2f4; border-radius: 4px; box-sizing: border-box; color: #c7254e; font-family: Monaco, Menlo, Consolas, &amp;quot;Courier New&amp;quot;, monospace; font-size: 12.2222px; padding: 2px 4px; white-space: nowrap;&quot;&gt;&quot;PAYPALISHIRING&quot;&lt;/code&gt;&amp;nbsp;is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)&lt;/div&gt;
&lt;br class=&quot;Apple-interchange-newline&quot; /&gt;
&lt;h4 style=&quot;text-align: left;&quot;&gt;
Example&lt;/h4&gt;
&lt;br /&gt;
&lt;div style=&quot;-webkit-text-stroke-width: 0px; background-color: white; color: #333333; font-family: &amp;quot;Helvetica Neue Light&amp;quot;, HelveticaNeue-Light, &amp;quot;Helvetica Neue&amp;quot;, Helvetica, Arial, sans-serif; font-size: 14px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 19.6px; margin: 0px; orphans: auto; outline: none; padding: 0px; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 1; word-spacing: 0px;&quot;&gt;
&lt;pre style=&quot;background-color: whitesmoke; border-radius: 4px; border: 1px solid rgb(204, 204, 204); box-sizing: border-box; font-family: Monaco, Menlo, Consolas, &amp;quot;Courier New&amp;quot;, monospace; font-size: 13px; line-height: 1.42857; margin-bottom: 10px; overflow-wrap: break-word; padding: 9.5px; white-space: pre-wrap; word-break: break-all; word-wrap: break-word;&quot;&gt;P   A   H   N
A P L S I I G
Y   I   R
&lt;/pre&gt;
And then read line by line:&amp;nbsp;&lt;code style=&quot;background-color: #f9f2f4; border-radius: 4px; box-sizing: border-box; color: #c7254e; font-family: Monaco, Menlo, Consolas, &amp;quot;Courier New&amp;quot;, monospace; font-size: 12.2222px; padding: 2px 4px; white-space: nowrap;&quot;&gt;&quot;PAHNAPLSIIGYIR&quot;&lt;/code&gt;&lt;br /&gt;
&lt;div style=&quot;box-sizing: border-box; margin: 0px 0px 10px; outline: none; padding: 0px;&quot;&gt;
Write the code that will take a string and make this conversion given a number of rows:&lt;/div&gt;
&lt;pre style=&quot;background-color: whitesmoke; border-radius: 4px; border: 1px solid rgb(204, 204, 204); box-sizing: border-box; font-family: Monaco, Menlo, Consolas, &amp;quot;Courier New&amp;quot;, monospace; font-size: 13px; line-height: 1.42857; margin-bottom: 10px; overflow-wrap: break-word; padding: 9.5px; white-space: pre-wrap; word-break: break-all; word-wrap: break-word;&quot;&gt;string convert(string text, int nRows);&lt;/pre&gt;
&lt;code style=&quot;background-color: #f9f2f4; border-radius: 4px; box-sizing: border-box; color: #c7254e; font-family: Monaco, Menlo, Consolas, &amp;quot;Courier New&amp;quot;, monospace; font-size: 12.2222px; padding: 2px 4px; white-space: nowrap;&quot;&gt;convert(&quot;PAYPALISHIRING&quot;, 3)&lt;/code&gt;&amp;nbsp;should return&amp;nbsp;&lt;code style=&quot;background-color: #f9f2f4; border-radius: 4px; box-sizing: border-box; color: #c7254e; font-family: Monaco, Menlo, Consolas, &amp;quot;Courier New&amp;quot;, monospace; font-size: 12.2222px; padding: 2px 4px; white-space: nowrap;&quot;&gt;&quot;PAHNAPLSIIGYIR&quot;&lt;/code&gt;.&lt;/div&gt;
&lt;br /&gt;
&lt;br class=&quot;Apple-interchange-newline&quot; /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Solution&lt;/h3&gt;
&lt;h4&gt;
Method 1 - Use list to save the substrings&lt;/h4&gt;
&lt;br /&gt;
A straightforward solution is to actually build up the zigzag character matrix and read the matrix into a string.
&lt;br /&gt;
Here is the basic algo:
&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Maintain down boolean which tells whether you are going up or down in zig zag order.
 
&lt;/li&gt;
&lt;li&gt;As soon as rows = 0 means you need to go down now and as soon as rows = nRows - 1 you need to go up now
&lt;/li&gt;
&lt;li&gt;Just keep on doing this until whole string is exhausted
&lt;/li&gt;
&lt;li&gt;Using StringBuilder list/array to store elements in zig zag order and in the end just append all characters from each StringBuilder to return output.

&lt;/li&gt;
&lt;/ul&gt;
Here is the code in java:
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;import java.util.ArrayList;

public class Solution {
    public String convert(String s, int nRows) {
        if(s == null || s.length() &amp;lt;= 1 || nRows &amp;lt;= 1){
            return s;
        }
        
        ArrayList&amp;lt;StringBuilder&amp;gt; list = new ArrayList&amp;lt;StringBuilder&amp;gt;();
        for(int i = 0; i &amp;lt; nRows; i++){
            list.add(new StringBuilder());
        }
        
        int i = 0;
        boolean down = false;
        int row = 0;
        
        while(i &amp;lt; s.length()){
            list.get(row).append(s.charAt(i));
            if(row == 0){
                down = true;
            }else if(row == nRows - 1){
                down = false;
            }
            
            if(down){
                row++;
            }else{
                row--;
            }
            
            i++;
        }
        
        i = 0;
        StringBuilder output = new StringBuilder();
        while( i &amp;lt; list.size()){
            output.append(list.get(i).toString());
            i++;
        }
        return output.toString();
    }
}

&lt;/pre&gt;
&lt;br /&gt;
Though time complexity is good O(n), but the space is complexity is O(nRows*Max_column_in_a_row) = O(n)
&lt;br /&gt;
&lt;br /&gt;
&lt;h4 style=&quot;text-align: left;&quot;&gt;
Method 2 - Append the character on the fly
&lt;/h4&gt;
Another way is to calculate the corresponding index on the fly and append the character into a string.
&lt;br /&gt;
Take &lt;code&gt;convert(&quot;PAYPALISHIRING&quot;, 4)&lt;/code&gt; as an example. The matrix will look as follows :
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;P   I   N
A L S I G
Y A H R
P   I
&lt;/pre&gt;
&lt;br /&gt;
which can be expended as below (You will see why we rewrite like this soon.).&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;P   I   N
A   S   G
Y   H
P   I
A   R
L   I
&lt;/pre&gt;
&lt;br /&gt;
Some useful properties:





&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;For any full columns, the odd ones have nRows characters, even ones have (nRows - 2) characters.
&lt;/li&gt;
&lt;li&gt;For the first and last rows, we read one single character from each expended column;
&lt;/li&gt;
&lt;li&gt;For the rest of rows, we read two characters, one from top part and one from bottom part, from each expended column.
&lt;/li&gt;
&lt;li&gt;One edge case is that nRows = 1, where (nRows*2 - 2) becomes 0. In this case, we should simply return the original string.
&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public String convert(String s, int nRows) {  
  if (nRows == 1) return s;  
  
  StringBuilder ss = new StringBuilder();  
  int n = nRows + nRows - 2;  
  // rest rows  
  for (int i = 0; i &amp;lt; nRows; ++i) {  
    int cur = i;  
    while (cur &amp;lt; s.length()) {  
      ss.append(s.charAt(cur));  
      cur += n;  
      if (i &amp;gt; 0 &amp;amp;&amp;amp; i &amp;lt; nRows - 1 &amp;amp;&amp;amp; (cur - i - i) &amp;lt; s.length()) {  
        ss.append(s.charAt(cur - i - i));  
      }  
    }  
  }  
  return ss.toString();  
}  

&lt;/pre&gt;
&lt;br /&gt;
Thanks.&lt;br /&gt;
&lt;b&gt;Reference&lt;/b&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.params.me/2014/04/leetcode-zigzag-conversion-in-java.html&quot;&gt;http://www.params.me/2014/04/leetcode-zigzag-conversion-in-java.html&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://n00tc0d3r.blogspot.in/2013/06/zigzag-conversion.html&quot;&gt;http://n00tc0d3r.blogspot.in/2013/06/zigzag-conversion.html&lt;/a&gt;
&lt;br /&gt;
&lt;a href=&quot;https://leetcode.com/problems/zigzag-conversion/&quot;&gt;https://leetcode.com/problems/zigzag-conversion/&lt;/a&gt;
 &lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/3164157997333294327/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2016/03/convert-string-to-zigzag-bottom-up.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/3164157997333294327'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/3164157997333294327'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2016/03/convert-string-to-zigzag-bottom-up.html' title='Convert String to ZigZag Bottom Up'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-4492975206086166753</id><published>2016-03-11T10:24:00.002+05:30</published><updated>2016-07-13T02:18:29.395+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="AlgorithmAnalysis"/><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Growth Rate - The Importance of Asymptotics</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
It really is true that if algorithm A is o(algorithm B) then for
large problems A will take &lt;b&gt;much&lt;/b&gt; less time than B.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Definition&lt;/b&gt;: If (the number of operations in)
algorithm A is o(algorithm B), we call A
&lt;b&gt;asymptotically faster&lt;/b&gt; than B.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example:&lt;/b&gt;: The following sequence of functions are
ordered by &lt;b&gt;growth rate&lt;/b&gt;, i.e., each function is
little-oh of the subsequent function.
&lt;br /&gt;
log(log(n)), log(n), (log(n))&lt;sup&gt;2&lt;/sup&gt;, n&lt;sup&gt;1/3&lt;/sup&gt;,
n&lt;sup&gt;1/2&lt;/sup&gt;, n, nlog(n), n&lt;sup&gt;2&lt;/sup&gt;/(log(n)), n&lt;sup&gt;2&lt;/sup&gt;,
n&lt;sup&gt;3&lt;/sup&gt;, 2&lt;sup&gt;n&lt;/sup&gt;, 4n, n!&lt;br /&gt;
&lt;br /&gt;
One way to compare 2 functions, is using L&#39;Hospital rule. Here is good explanation:&lt;br /&gt;
&lt;a href=&quot;https://www.youtube.com/watch?v=6IjVGfbhe9w&quot;&gt;Growth Rates of Functions and L&#39;Hospital&#39;s Rule&lt;/a&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;iframe allowfullscreen=&quot;&quot; class=&quot;YOUTUBE-iframe-video&quot; data-thumbnail-src=&quot;https://i.ytimg.com/vi/6IjVGfbhe9w/0.jpg&quot; frameborder=&quot;0&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/6IjVGfbhe9w?feature=player_embedded&quot; width=&quot;320&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;br /&gt;
Here is the snapshot of how the growth looks in increasing order&lt;br /&gt;
&lt;table border=&quot;0&quot; style=&quot;width: 520px;&quot;&gt;&lt;tbody&gt;
&lt;tr align=&quot;right&quot;&gt;&lt;td width=&quot;70&quot;&gt;1&lt;/td&gt;
    &lt;td width=&quot;70&quot;&gt;loglog&lt;i&gt;&lt;b&gt;n&lt;/b&gt;&lt;/i&gt;&lt;/td&gt;
&lt;td width=&quot;70&quot;&gt;log&lt;i&gt;&lt;b&gt;n&lt;/b&gt;&lt;/i&gt;&lt;/td&gt;
    &lt;td width=&quot;60&quot;&gt;&lt;b&gt;&lt;i&gt;n&lt;/i&gt;&lt;/b&gt;&lt;/td&gt;
    &lt;td width=&quot;80&quot;&gt;&lt;b&gt;&lt;i&gt;n&lt;/i&gt;&lt;/b&gt;log&lt;b&gt;&lt;i&gt;n&lt;/i&gt;&lt;/b&gt;&lt;/td&gt;
    &lt;td width=&quot;60&quot;&gt;&lt;b&gt;&lt;span style=&quot;color: black;&quot;&gt;&lt;i&gt;n&lt;sup&gt;2&lt;/sup&gt;&lt;/i&gt;&lt;/span&gt;&lt;/b&gt;&lt;/td&gt;
    &lt;td width=&quot;60&quot;&gt;&lt;b&gt;&lt;span style=&quot;color: black;&quot;&gt;&lt;i&gt;2&lt;sup&gt;n&lt;/sup&gt;&lt;/i&gt;&lt;/span&gt;&lt;/b&gt;&lt;/td&gt;
    &lt;td width=&quot;60&quot;&gt;&lt;b&gt;&lt;span style=&quot;color: black;&quot;&gt;&lt;i&gt;n&lt;/i&gt;!&lt;/span&gt;&lt;/b&gt;&lt;/td&gt;
    &lt;td width=&quot;60&quot;&gt;&lt;b&gt;&lt;span style=&quot;color: black;&quot;&gt;&lt;i&gt;n&lt;sup&gt;n&lt;/sup&gt;&lt;/i&gt;&lt;/span&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;br /&gt;
&lt;b&gt;Reference&lt;/b&gt;&lt;br /&gt;
&lt;a href=&quot;https://cs.nyu.edu/courses/fall02/V22.0310-002/class-notes.html&quot;&gt;https://cs.nyu.edu/courses/fall02/V22.0310-002/class-notes.html&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;http://www.cs.odu.edu/~cs381/cs381content/function/growth.html&quot;&gt;http://www.cs.odu.edu/~cs381/cs381content/function/growth.html&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/4492975206086166753/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2016/03/growth-rate-importance-of-asymptotics.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/4492975206086166753'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/4492975206086166753'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2016/03/growth-rate-importance-of-asymptotics.html' title='Growth Rate - The Importance of Asymptotics'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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://img.youtube.com/vi/6IjVGfbhe9w/default.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3098638925089993315.post-6527296793374584675</id><published>2016-03-11T10:24:00.001+05:30</published><updated>2016-07-13T02:18:29.406+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="AlgorithmAnalysis"/><category scheme="http://www.blogger.com/atom/ns#" term="Algorithms"/><title type='text'>Asymptotic Notation</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Its been a while, since I have blogged. To start with I am posting a basics of asymptotic analysis of algorithm, which we study at the start of the course.&lt;br /&gt;
Now we are going to be less precise and worry only about approximate
answers for large inputs.

&lt;br /&gt;
&lt;h3&gt;
The &lt;q&gt;Big-Oh&lt;/q&gt; Notation&lt;/h3&gt;
&lt;b&gt;Definition&lt;/b&gt;: Let f(n) and g(n) be real-valued
functions of a single non-negative integer argument.
We write &lt;tt&gt;f(n)&lt;/tt&gt; is &lt;tt&gt;O(g(n))&lt;/tt&gt; if there is a positive real
number &lt;tt&gt;c&lt;/tt&gt; and a positive integer &lt;tt&gt;n&lt;sub&gt;0&lt;/sub&gt;&lt;/tt&gt;
such that &lt;tt&gt;f(n)≤cg(n)&lt;/tt&gt; for all &lt;tt&gt;n≥n&lt;sub&gt;0&lt;/sub&gt;&lt;/tt&gt;.

&lt;br /&gt;
What does this mean?

&lt;br /&gt;
For large inputs (&lt;tt&gt;n≤n&lt;sub&gt;0&lt;/sub&gt;&lt;/tt&gt;), &lt;tt&gt;f&lt;/tt&gt; is not much
bigger than &lt;tt&gt;g&lt;/tt&gt; (&lt;tt&gt;f(n)≤cg(n)&lt;/tt&gt;).

&lt;br /&gt;
Examples to do on the board

&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;&lt;tt&gt;3n-6&lt;/tt&gt; is &lt;tt&gt;O(n)&lt;/tt&gt;.  So, what f(n) = 3n-6&lt;tt&gt; &amp;lt;= c*n. For example, c=4.&lt;/tt&gt; Some less common ways of
    saying the same thing follow.
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;3x-6&lt;/tt&gt; is &lt;tt&gt;O(x)&lt;/tt&gt;.
&lt;/li&gt;
&lt;li&gt;If &lt;tt&gt;f(y)=3y-6&lt;/tt&gt; and &lt;tt&gt;id(y)=y&lt;/tt&gt;,
    then &lt;tt&gt;f(y)&lt;/tt&gt; is &lt;tt&gt;O(id(y))&lt;/tt&gt;.
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;3n-6&lt;/tt&gt; is &lt;tt&gt;O(2n)&lt;/tt&gt;
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;9n&lt;sup&gt;4&lt;/sup&gt;+12n&lt;sup&gt;2&lt;/sup&gt;+1234&lt;/tt&gt; is
&lt;tt&gt;O(n&lt;sup&gt;4&lt;/sup&gt;)&lt;/tt&gt;.
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;innerProduct&lt;/tt&gt; is &lt;tt&gt;O(n)&lt;/tt&gt;
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;innerProductBetter&lt;/tt&gt; is &lt;tt&gt;O(n)&lt;/tt&gt;
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;innerProductFixed&lt;/tt&gt; is &lt;tt&gt;O(n)&lt;/tt&gt;
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;countPositives&lt;/tt&gt; is &lt;tt&gt;O(n)&lt;/tt&gt;
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;n+log(n)&lt;/tt&gt; is &lt;tt&gt;O(n)&lt;/tt&gt;.
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;log(n)+5log(log(n))&lt;/tt&gt; is &lt;tt&gt;O(log(n))&lt;/tt&gt;.
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;12345&lt;sup&gt;54321&lt;/sup&gt;&lt;/tt&gt; is &lt;tt&gt;O(1)&lt;/tt&gt;.
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;3/n&lt;/tt&gt; is &lt;tt&gt;O(1)&lt;/tt&gt;.  True but not the best.
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;3/n&lt;/tt&gt; is &lt;tt&gt;O(1/n)&lt;/tt&gt;.  Much better.
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;innerProduct&lt;/tt&gt; is &lt;tt&gt;O(100n+log(n)+34.5)&lt;/tt&gt;.  True, but
    awful.
&lt;/li&gt;
&lt;/ol&gt;
A few theorems give us rules that make calculating big-Oh easier.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Theorem (arithmetic)&lt;/b&gt;: Let &lt;tt&gt;d(n)&lt;/tt&gt;,
&lt;tt&gt;e(n)&lt;/tt&gt;, &lt;tt&gt;f(n)&lt;/tt&gt;, and &lt;tt&gt;g(n)&lt;/tt&gt; be nonnegative
real-valued functions of a nonnegative integer argument and assume
&lt;tt&gt;d(n)&lt;/tt&gt; is &lt;tt&gt;O(f(n))&lt;/tt&gt; and &lt;tt&gt;e(n)&lt;/tt&gt; is
&lt;tt&gt;O(g(n))&lt;/tt&gt;.  Then

&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;&lt;tt&gt;ad(n)&lt;/tt&gt; is &lt;tt&gt;O(f(n))&lt;/tt&gt; for any nonnegative a
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;d(n)+e(n)&lt;/tt&gt; is &lt;tt&gt;O(f(n)+g(n))&lt;/tt&gt;
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;d(n)e(n)&lt;/tt&gt; is &lt;tt&gt;O(f(n)g(n))&lt;/tt&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;b&gt;Theorem (transitivity)&lt;/b&gt;: Let &lt;tt&gt;d(n)&lt;/tt&gt;,
&lt;tt&gt;f(n)&lt;/tt&gt;, and &lt;tt&gt;g(n)&lt;/tt&gt; be nonnegative real-valued functions
of a nonnegative integer argument and assume &lt;tt&gt;d(n)&lt;/tt&gt; is
&lt;tt&gt;O(f(n))&lt;/tt&gt; and &lt;tt&gt;f(n)&lt;/tt&gt; is &lt;tt&gt;O(g(n))&lt;/tt&gt;.  Then
&lt;tt&gt;d(n)&lt;/tt&gt; is &lt;tt&gt;O(g(n))&lt;/tt&gt;.

&lt;br /&gt;
&lt;b&gt;Theorem&lt;/b&gt; (special functions): (Only &lt;tt&gt;n&lt;/tt&gt; varies)

&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;If &lt;tt&gt;f(n)&lt;/tt&gt; is a polynomial of degree d, then
    &lt;tt&gt;f(n)&lt;/tt&gt; is &lt;tt&gt;O(n&lt;sup&gt;d&lt;/sup&gt;)&lt;/tt&gt;.
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;n&lt;sup&gt;x&lt;/sup&gt;&lt;/tt&gt; is &lt;tt&gt;O(a&lt;sup&gt;n&lt;/sup&gt;)&lt;/tt&gt; for any
    &lt;tt&gt;x&amp;gt;0&lt;/tt&gt; &lt;tt&gt;and a&amp;gt;1&lt;/tt&gt;.
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;log(n&lt;sup&gt;x&lt;/sup&gt;)&lt;/tt&gt; is &lt;tt&gt;O(log(n))&lt;/tt&gt; for any &lt;tt&gt;x&amp;gt;0&lt;/tt&gt;
&lt;/li&gt;
&lt;li&gt;&lt;tt&gt;(log(n))&lt;sup&gt;x&lt;/sup&gt;&lt;/tt&gt; is &lt;tt&gt;O(n&lt;sup&gt;y&lt;/sup&gt;)&lt;/tt&gt; for any
    &lt;tt&gt;x&amp;gt;0&lt;/tt&gt; and &lt;tt&gt;y&amp;gt;0&lt;/tt&gt;.
&lt;/li&gt;
&lt;/ol&gt;
&lt;br /&gt;
&lt;b&gt;Definitions&lt;/b&gt;: (Common names)
&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;If a function is &lt;tt&gt;O(log(n))&lt;/tt&gt; we call it &lt;b&gt;logarithmic&lt;/b&gt;.
&lt;/li&gt;
&lt;li&gt;If a function is &lt;tt&gt;O(n)&lt;/tt&gt; we call it &lt;b&gt;linear&lt;/b&gt;.
&lt;/li&gt;
&lt;li&gt;If a function is &lt;tt&gt;O(n&lt;sup&gt;2&lt;/sup&gt;)&lt;/tt&gt; we call it
    &lt;b&gt;quadratic&lt;/b&gt;.
&lt;/li&gt;
&lt;li&gt;If a function is &lt;tt&gt;O(n&lt;sup&gt;k&lt;/sup&gt;&lt;/tt&gt;) with &lt;tt&gt;k≥1&lt;/tt&gt;, we call it
    &lt;b&gt;polynomial&lt;/b&gt;.
&lt;/li&gt;
&lt;li&gt;If a function is &lt;tt&gt;O(a&lt;sup&gt;n&lt;/sup&gt;)&lt;/tt&gt; with &lt;tt&gt;a&amp;gt;1&lt;/tt&gt;,
    we call it &lt;b&gt;exponential&lt;/b&gt;.
&lt;/li&gt;
&lt;/ol&gt;
&lt;b&gt;Remark&lt;/b&gt;: The last definitions would be better with a
relative of big-Oh, namely big-Theta, since, for example &lt;tt&gt;3log(n)&lt;/tt&gt; is
&lt;tt&gt;O(n&lt;sup&gt;2&lt;/sup&gt;)&lt;/tt&gt;, but we do &lt;i&gt;not&lt;/i&gt; call
&lt;tt&gt;3log(n)&lt;/tt&gt; quadratic.&lt;br /&gt;
&lt;h3&gt;
1.2.2 &lt;q&gt;Relatives&lt;/q&gt; of the Big-Oh&lt;/h3&gt;
&lt;h4&gt;
Big-Omega and Big-Theta&lt;/h4&gt;
Recall that f(n) is O(g(n)) if for large n, f is not much bigger
than g.  That is g is some sort of &lt;b&gt;upper&lt;/b&gt; bound on f.
How about a definition for the case when g is (in the same sense) a
&lt;b&gt;lower&lt;/b&gt; bound for f?

&lt;br /&gt;
&lt;b&gt;Definition&lt;/b&gt;: Let f(n) and g(n) be real valued
functions of an integer value.  Then &lt;b&gt;f(n) is
Ω(g(n))&lt;/b&gt; if g(n) is O(f(n)).

&lt;br /&gt;
&lt;b&gt;Remarks&lt;/b&gt;:
&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;We pronounce f(n) is Ω(g(n)) as &quot;f(n) is big-Omega of g(n)&quot;.
&lt;/li&gt;
&lt;li&gt;What the last definition says is that we say f(n) is not much smaller
    than g(n) if g(n) is not much bigger than f(n), which sounds
    reasonable to me.
&lt;/li&gt;
&lt;li&gt;What if f(n) and g(n) are about equal, i.e., neither is much
    bigger than the other?
&lt;/li&gt;
&lt;/ol&gt;
&lt;b&gt;Definition&lt;/b&gt;: We write
&lt;b&gt;f(n) is Θ(g(n))&lt;/b&gt; if &lt;b&gt;both&lt;/b&gt;
f(n) is O(g(n)) &lt;b&gt;and&lt;/b&gt; f(n) is Ω(g(n)).

&lt;br /&gt;
&lt;b&gt;Remarks&lt;/b&gt;
We pronounce f(n) is Θ(g(n)) as &quot;f(n) is big-Theta of g(n)&quot;

&lt;br /&gt;
Examples to do on the board.
&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;2x&lt;sup&gt;2&lt;/sup&gt;+3x is θ(x&lt;sup&gt;2&lt;/sup&gt;).
&lt;/li&gt;
&lt;li&gt;2x&lt;sup&gt;3&lt;/sup&gt;+3x is &lt;b&gt;not&lt;/b&gt; θ(x&lt;sup&gt;2&lt;/sup&gt;).
&lt;/li&gt;
&lt;li&gt;2x&lt;sup&gt;3&lt;/sup&gt;+3x is Ω(x&lt;sup&gt;2&lt;/sup&gt;).
&lt;/li&gt;
&lt;li&gt;innerProductRecutsive is Θ(n).
&lt;/li&gt;
&lt;li&gt;binarySearch is Θ(log(n)).  Unofficial for now.
&lt;/li&gt;
&lt;li&gt;If f(n) is Θ(g(n)), the f(n) is &amp;amp;Omega(g(n)).
&lt;/li&gt;
&lt;li&gt;If f(n) is Θ(g(n)), then f(n) is O(g(n)).
&lt;/li&gt;
&lt;/ol&gt;
&lt;h4&gt;
Little-Oh and Little-Omega&lt;/h4&gt;
Recall that big-Oh captures the idea that for large n, f(n) is not
much bigger than g(n).  Now we want to capture the idea that, for
large n, f(n) is tiny compared to g(n).

&lt;br /&gt;
If you remember limits from calculus, what we want is that
f(n)/g(n)→0 as n→∞.  However, the definition we give
does not use limits (it essentially has the definition of a limit
built in).&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Definition&lt;/b&gt;:  Let f(n) and g(n) be real valued
functions of an integer variable.  We say
&lt;b&gt;f(n) is o(g(n))&lt;/b&gt;
if for &lt;b&gt;any&lt;/b&gt; c&amp;gt;0,
there is an n&lt;sub&gt;0&lt;/sub&gt; such that
f(n)≤g(n) for all n&amp;gt;n&lt;sub&gt;0&lt;/sub&gt;.
This is pronounced as &quot;f(n) is little-oh of g(n)&quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Definition&lt;/b&gt;: Let f(n) and g(n) be real valued
functions of an integer variable.  We say
&lt;b&gt;f(n) is ω(g(n)&lt;/b&gt; if
g(n) is o(f(n)).  This is pronounced as &quot;f(n) is little-omega of g(n)&quot;.

&lt;br /&gt;
&lt;b&gt;Examples&lt;/b&gt;: log(n) is o(n) and x&lt;sup&gt;2&lt;/sup&gt; is
ω(nlog(n)).

&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Properties of Notations&lt;/h3&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;div style=&quot;direction: ltr;&quot;&gt;

&lt;table border=&quot;1&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; style=&quot;border-collapse: collapse; border-color: #A3A3A3; border-style: solid; border-width: 1pt; direction: ltr;&quot; valign=&quot;top&quot;&gt;
 &lt;tbody&gt;
&lt;tr&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: .9145in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
&lt;span style=&quot;font-weight: bold;&quot;&gt;Notations&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 1.2555in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
&lt;span style=&quot;font-weight: bold;&quot;&gt;Reflexive&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 2.0451in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
&lt;span style=&quot;font-weight: bold;&quot;&gt;Transitive&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 1.0909in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
&lt;span style=&quot;font-weight: bold;&quot;&gt;Symmetric&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 2.293in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
&lt;span style=&quot;font-weight: bold;&quot;&gt;Transpose Symmetric&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;
 &lt;/tr&gt;
&lt;tr&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: .8958in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
&lt;span style=&quot;font-weight: bold;&quot;&gt;O&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 1.2555in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
Yes&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 2.0451in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
Yes&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 1.0798in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
No&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 2.3013in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
No&lt;/div&gt;
&lt;/td&gt;
 &lt;/tr&gt;
&lt;tr&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: .8958in;&quot;&gt;
  &lt;div lang=&quot;el-GR&quot; style=&quot;font-family: &amp;quot;times new roman&amp;quot;; font-size: 10.0pt; margin: 0in;&quot;&gt;
&lt;span style=&quot;font-weight: bold;&quot;&gt;Ω&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 1.2555in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
Yes&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 2.0451in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
Yes&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 1.0798in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
No&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 2.5819in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
Yes&lt;br /&gt;
  &amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;margin: 0in;&quot;&gt;
&lt;span lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt;&quot;&gt;Yes i.e. f(n) = O(g(n)), iff&lt;span style=&quot;mso-spacerun: yes;&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
  &lt;/span&gt;g(n) = &lt;/span&gt;&lt;span lang=&quot;el-GR&quot; style=&quot;font-family: &amp;quot;times new roman&amp;quot;; font-size: 10.0pt;&quot;&gt;Ω&lt;/span&gt;&lt;span lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt;&quot;&gt;(f(n))&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;
 &lt;/tr&gt;
&lt;tr&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: .8958in;&quot;&gt;
  &lt;div lang=&quot;el-GR&quot; style=&quot;font-family: &amp;quot;times new roman&amp;quot;; font-size: 12.0pt; margin: 0in;&quot;&gt;
&lt;span style=&quot;font-weight: bold;&quot;&gt;Θ&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 1.2555in;&quot;&gt;
  &lt;div style=&quot;font-size: 12.0pt; margin: 0in;&quot;&gt;
&lt;span lang=&quot;en-US&quot; style=&quot;font-family: Helvetica;&quot;&gt;Yes&lt;br /&gt;
  i.e.f(n) = &lt;/span&gt;&lt;span lang=&quot;el-GR&quot; style=&quot;font-family: &amp;quot;times new roman&amp;quot;;&quot;&gt;Θ&lt;/span&gt;&lt;span lang=&quot;en-US&quot; style=&quot;font-family: &amp;quot;times new roman&amp;quot;;&quot;&gt;
  (f(n))&lt;/span&gt;&lt;/div&gt;
&lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 2.0451in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
Yes&lt;/div&gt;
&lt;div style=&quot;font-size: 12.0pt; margin: 0in;&quot;&gt;
&lt;span lang=&quot;en-US&quot; style=&quot;font-family: Helvetica;&quot;&gt;f(n)=&lt;/span&gt;&lt;span lang=&quot;el-GR&quot; style=&quot;font-family: &amp;quot;times new roman&amp;quot;;&quot;&gt;Θ&lt;/span&gt;&lt;span lang=&quot;en-US&quot; style=&quot;font-family: Helvetica;&quot;&gt;(g(n)) and
  g(n)=&lt;/span&gt;&lt;span lang=&quot;el-GR&quot; style=&quot;font-family: &amp;quot;times new roman&amp;quot;;&quot;&gt;Θ&lt;/span&gt;&lt;span lang=&quot;en-US&quot; style=&quot;font-family: Helvetica;&quot;&gt;(h(n))&lt;br /&gt;
  &lt;span style=&quot;mso-spacerun: yes;&quot;&gt;&amp;nbsp;&lt;/span&gt;implies f(n) = &lt;/span&gt;&lt;span lang=&quot;el-GR&quot; style=&quot;font-family: &amp;quot;times new roman&amp;quot;;&quot;&gt;Θ&lt;/span&gt;&lt;span lang=&quot;en-US&quot; style=&quot;font-family: Helvetica;&quot;&gt;(h(n))&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 1.0798in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
Yes&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 2.3013in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
No&lt;/div&gt;
&lt;/td&gt;
 &lt;/tr&gt;
&lt;tr&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: .8958in;&quot;&gt;
  &lt;div style=&quot;font-family: arial; font-size: 10.0pt; margin: 0in;&quot;&gt;
&lt;span style=&quot;font-weight: bold;&quot;&gt;o&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 1.2555in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
No&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 2.0451in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
Yes&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 1.0798in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
No&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 2.3013in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
No&lt;/div&gt;
&lt;/td&gt;
 &lt;/tr&gt;
&lt;tr&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: .8958in;&quot;&gt;
  &lt;div lang=&quot;el-GR&quot; style=&quot;font-family: &amp;quot;times new roman&amp;quot;; font-size: 10.0pt; margin: 0in;&quot;&gt;
&lt;span style=&quot;font-weight: bold;&quot;&gt;ω&lt;/span&gt;&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 1.2555in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
No&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 2.0451in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
Yes&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 1.0798in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
No&lt;/div&gt;
&lt;/td&gt;
  &lt;td style=&quot;border-color: #A3A3A3; border-style: solid; border-width: 1pt; padding: 4pt 4pt 4pt 4pt; vertical-align: top; width: 2.3013in;&quot;&gt;
  &lt;div lang=&quot;en-US&quot; style=&quot;font-family: Helvetica; font-size: 12.0pt; margin: 0in;&quot;&gt;
No&lt;/div&gt;
&lt;/td&gt;
 &lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Source&lt;/b&gt;&lt;br /&gt;
&lt;a href=&quot;https://cs.nyu.edu/courses/fall02/V22.0310-002/class-notes.html&quot;&gt;https://cs.nyu.edu/courses/fall02/V22.0310-002/class-notes.html&lt;/a&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/6527296793374584675/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2016/03/asymptotic-notation.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/6527296793374584675'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/6527296793374584675'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2016/03/asymptotic-notation.html' title='Asymptotic Notation'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-5334812550194615995</id><published>2015-09-04T06:24:00.003+05:30</published><updated>2025-01-09T02:00:05.209+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Binary Search Tree / BST"/><category scheme="http://www.blogger.com/atom/ns#" term="inorder"/><category scheme="http://www.blogger.com/atom/ns#" term="k5kced"/><title type='text'>Given a BST with 2 nodes swapped, fix it</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div class=&quot;callout&quot;&gt;
    This updated information has been further expanded upon on my new website. You can find the updated details here: &lt;a href=&quot;https://k5kc.com/cs/problems/recover-binary-search-tree/&quot;&gt;  https://k5kc.com/cs/algorithms/recover-binary-search-tree-problem/&lt;/a&gt;.
&lt;/div&gt;

&lt;h3 style=&quot;text-align: left;&quot;&gt;
Problem&lt;/h3&gt;
Given a BST with 2 nodes swapped fix it.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example&lt;/b&gt;&lt;br /&gt;
Consider the BST:&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;Following is the correct BST 
         10
        /  \
       5    20
      / \
     2   8&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
Now we swap&amp;nbsp; 8 and 20, and BST is changed.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;Input Tree:
         10
        /  \
       5    8
      / \
     2   20

In the above tree, nodes 20 and 8 must be swapped to fix the tree.  

&lt;/pre&gt;
In the &lt;a href=&quot;http://k2code.blogspot.in/2015/09/given-binary-search-tree-with-2-nodes.html&quot;&gt;previous post&lt;/a&gt;, we saw how many pairs in the input tree violate the BST property. Here we will fix it.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;1.&lt;/b&gt; The swapped nodes are not adjacent in the inorder traversal of the BST.
&lt;br /&gt;
&lt;pre&gt; For example, Nodes 5 and 25 are swapped in {3 5 7 8 10 15 20 25}. 
 The inorder traversal of the given tree is 3 25 7 8 10 15 20 5 
&lt;/pre&gt;
If we observe carefully, during inorder traversal, we find node 7 is 
smaller  than the previous visited node 25. Here save the context of 
node 25 (previous node). Again, we find that node 5 is smaller than the 
previous node 20. This time, we save the context of node 5 ( current 
node ). Finally swap the two node’s values.&lt;br /&gt;
&lt;b&gt;2.&lt;/b&gt; The swapped nodes are adjacent in the inorder traversal of BST.
&lt;br /&gt;
&lt;pre&gt;  For example, Nodes 7 and 8 are swapped in {3 5 7 8 10 15 20 25}. 
  The inorder traversal of the given tree is 3 5 8 7 10 15 20 25 &lt;/pre&gt;
Unlike case #1, here only one point exists where a node value is 
smaller than previous node value. e.g. node 7 is smaller than node 8.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;How to Solve?&lt;/b&gt; &lt;i&gt;We will maintain three pointers, 
first, middle and last. When we find the first point where current node 
value is smaller than previous node value, we update the first with the 
previous node &amp;amp; middle with the current node. When we find the 
second point where current node value is smaller than previous node 
value, we update the last with the current node. In case #2, we will 
never find the second point. So, last pointer will not be updated. After
 processing, if the last node value is null, then two swapped nodes of 
BST are adjacent&lt;/i&gt;.&lt;br /&gt;
&lt;br /&gt;
code:&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt; private void swap(Node a, Node b) {  
   if (n1 == null || n2 == null)  return;
   int tmp = a.val;  
   a.val = b.val;  
   b.val = tmp;  
 }  
   
 public void recoverTree(Node root) {  
   Node cur = root, pre = null, first = null, second = null;  
   // in order travesal should return a sorted list  
   Stack&lt;node&gt; stack = new Stack&lt;node&gt;();  
   while (cur != null) { // find the left most child  
     stack.push(cur);  
     cur = cur.left;  
   }  
   while (!stack.isEmpty()) {  
     cur = stack.pop();  

     // is it wrong?  
     if (pre != null &amp;amp;&amp;amp; cur.val &amp;lt; pre.val) {  
       if (first == null) {  
         // the first wrong item should be the bigger one  
         first = pre;  
         second = cur; // there is a chance that the two were swapped  
       } else {  
         // the second wrong item should be the smaller one  
         second = cur;  
         break;  
       }  
     }  

     // go to right child and repeat  
     pre = cur;  
     cur = cur.right;  
     while (cur != null) {  
       stack.push(cur);  
       cur = cur.left;  
     }  
   }  
   
   swap(first, second);  
 }  
&lt;/node&gt;&lt;/node&gt;&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;References&lt;/b&gt;&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;a href=&quot;http://www.geeksforgeeks.org/fix-two-swapped-nodes-of-bst/&quot;&gt;http://www.geeksforgeeks.org/fix-two-swapped-nodes-of-bst/&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/5334812550194615995/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/09/given-bst-with-2-nodes-swapped-fix-it.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/5334812550194615995'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/5334812550194615995'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/09/given-bst-with-2-nodes-swapped-fix-it.html' title='Given a BST with 2 nodes swapped, fix it'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-3107265464914668404</id><published>2015-09-04T05:44:00.004+05:30</published><updated>2024-05-28T21:13:49.643+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="bank-bazaar"/><category scheme="http://www.blogger.com/atom/ns#" term="Binary Search Tree / BST"/><category scheme="http://www.blogger.com/atom/ns#" term="count"/><category scheme="http://www.blogger.com/atom/ns#" term="inorder"/><category scheme="http://www.blogger.com/atom/ns#" term="Inorder traversal"/><category scheme="http://www.blogger.com/atom/ns#" term="k5kced"/><title type='text'>Given a binary search tree with 2 nodes swapped find number of pairs not following BST properties</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
  &lt;div class=&quot;callout&quot;&gt;
    This updated information has been further expanded upon on my new website. You can find the updated details here: &lt;a href=&quot;https://k5kc.com/cs/algorithms/given-a-binary-search-tree-with-2-nodes-swapped-find-number-of-pairs-not-following-bst-properties/&quot;&gt;https://k5kc.com/cs/algorithms/given-a-binary-search-tree-with-2-nodes-swapped-find-number-of-pairs-not-following-bst-properties/&lt;/a&gt;.
&lt;/div&gt;
  
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Problem&lt;/h3&gt;
Given a binary search tree with 2 nodes swapped, give the number of nodes not following bst property. Follow up - Fix the BST, in the &lt;a href=&quot;http://k2code.blogspot.in/2015/09/given-bst-with-2-nodes-swapped-fix-it.html&quot;&gt;next post&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example&lt;/b&gt;&lt;br /&gt;
Consider the BST:&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;Following is the correct BST 
         10
        /  \
       5    20
      / \
     2   8&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
Now we swap&amp;nbsp; 8 and 20, and BST is changed.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;Input Tree:
         10
        /  \
       5    8
      / \
     2   20

In the above tree, nodes 20 and 8 must be swapped to fix the tree.  

&lt;/pre&gt;
Now number of pairs not following BST property are 3. The reason is :&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;10-20&lt;/li&gt;
&lt;li&gt;10-8&lt;/li&gt;
&lt;li&gt;20-8&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
&amp;nbsp;Solution&lt;/h3&gt;
&lt;b&gt;Method 1 - Using in-order traversal&lt;/b&gt;&lt;br /&gt;
We can have following solution:&lt;br /&gt;
&lt;ol style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Find the inorder traversal of the input tree. Example - 2, 5, 20, 10, 8&lt;/li&gt;
&lt;li&gt;Find the number of &lt;a href=&quot;http://k2code.blogspot.in/2013/08/inversions.html&quot;&gt;inversions&lt;/a&gt; in the inorder traversal. That is the answer. Here the inversions are 20-10, 20-8, and 10-8.&amp;nbsp;&lt;/li&gt;
&lt;/ol&gt;
Time complexity - O(n logn) as O(n) time for inorder traversal and O(nlogn) for number of inversions in the sorted array.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/3107265464914668404/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/09/given-binary-search-tree-with-2-nodes.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/3107265464914668404'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/3107265464914668404'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/09/given-binary-search-tree-with-2-nodes.html' title='Given a binary search tree with 2 nodes swapped find number of pairs not following BST properties'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-6237508224451512724</id><published>2015-09-04T05:12:00.003+05:30</published><updated>2025-01-09T02:06:36.187+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Binary Tree / BT"/><category scheme="http://www.blogger.com/atom/ns#" term="distance"/><category scheme="http://www.blogger.com/atom/ns#" term="K-Distance"/><category scheme="http://www.blogger.com/atom/ns#" term="k5kced"/><category scheme="http://www.blogger.com/atom/ns#" term="kodeknight"/><title type='text'>For a Given node of a binary tree, print the K distance nodes.</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div class=&quot;callout&quot;&gt;
    This updated information has been further expanded upon on my new website. You can find the updated details here: &lt;a href=&quot;https://k5kc.com/cs/algorithms/all-nodes-distance-k-in-binary-tree-problem/&quot;&gt;https://k5kc.com/cs/problems/all-nodes-distance-k-in-binary-tree/&lt;/a&gt;.
&lt;/div&gt;
&lt;b&gt;Problem&lt;/b&gt;&lt;br /&gt;
&lt;div class=&quot;post-text&quot; itemprop=&quot;text&quot;&gt;
You are given a function printKDistanceNodes which takes in a root 
node of a binary tree, a start node and an integer K.  Complete the 
function to print the value of all the nodes (one-per-line) which are a K
 distance from the given start node in sorted order. Distance can be 
upwards or downwards.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example&lt;/b&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/AVvXsEglnI7FqXdZew88Hggfxr1HTtayMu_2FEbvyWiFQDjVJlrSZ893RxK15GsP9zYvKANXC5RYHpHgFBvwlYRSV9UTPQ-KTZJnWELBjxPEoKbJxCB64gSfP8di6VB_vFDCtKt3RoQpl27HTamV/s1600/bst-remove-case-2-1_1child.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;267&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglnI7FqXdZew88Hggfxr1HTtayMu_2FEbvyWiFQDjVJlrSZ893RxK15GsP9zYvKANXC5RYHpHgFBvwlYRSV9UTPQ-KTZJnWELBjxPEoKbJxCB64gSfP8di6VB_vFDCtKt3RoQpl27HTamV/s320/bst-remove-case-2-1_1child.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
start node = 18, k = 2 , then output = 2, 19, 25&lt;/div&gt;
&lt;div class=&quot;post-text&quot; itemprop=&quot;text&quot;&gt;
start node = 18, k = 3,&amp;nbsp; then output = -4, 3&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Solution &lt;/h3&gt;
We have already seen a similar problem, where we have to find &lt;a href=&quot;http://k2code.blogspot.in/2014/01/print-nodes-at-k-distance-from-root.html&quot;&gt;k distance from the root&lt;/a&gt; and &lt;a href=&quot;http://k2code.blogspot.in/2015/09/print-all-nodes-that-are-at-distance-k.html&quot; target=&quot;_blank&quot;&gt;k distance from the leaf&lt;/a&gt;. Find the distance from root is easy. In the second case of printing from bottom to top (k distance from leaves), we know the direction, i.e. we have to go up. But here we have to find the k elements even going upwards.&lt;br /&gt;
&lt;br /&gt;
Note :- Parent pointer is not given.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Method 1 - Using the recursion&lt;/b&gt; &lt;br /&gt;
&lt;br /&gt;
(Printing nodes at a disance of K&amp;nbsp; downwards&amp;nbsp; is easy). Its a simple 
recursive function.So moving to nodes which are in upwards direction.&lt;br /&gt;
&lt;br /&gt;
There are two types of nodes to be considered.&lt;br /&gt;
&lt;b&gt;1)&lt;/b&gt; Nodes in the subtree rooted with target node. For example if the target node is 18 and k is 2, then such nodes are 19 and 25.&lt;br /&gt;
&lt;b&gt;2) &lt;/b&gt;Other nodes, may be an ancestor of target, or a node
 in some other subtree.  For target node 18 and k is 2, the node 2 comes
 in this category.&lt;br /&gt;
&lt;br /&gt;
Finding the first type of nodes is easy to implement. Just traverse 
subtrees rooted with the target node and decrement k in recursive call. 
When the k becomes 0, print the node currently being traversed (See &lt;a href=&quot;http://k2code.blogspot.in/2014/01/print-nodes-at-k-distance-from-root.html&quot; target=&quot;_blank&quot;&gt;this &lt;/a&gt;for more details).  Here we call the function as &lt;i&gt;printkdistanceNodeDown()&lt;/i&gt;.&lt;br /&gt;
&lt;br /&gt;
How to find nodes of second type? For the output nodes not lying in 
the subtree with the target node as the root, we must go through all 
ancestors.  For every ancestor, we find its distance from target node, 
let the distance be d, now we go to other subtree (if target was found 
in left subtree, then we go to right subtree and vice versa) of the 
ancestor and find all nodes at k-d distance from the ancestor.&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;// Recursive function to print all the nodes at distance k in the
// tree (or subtree) rooted with given root. See  
void printkdistanceNodeDown(Node root, int k)
{
    // Base Case
    if (root == null || k &amp;lt; 0)  return;
 
    // If we reach a k distant node, print it
    if (k==0)
    {
        System.out.println(root.data);
        return;
    }
 
    // Recur for left and right subtrees
    printkdistanceNodeDown(root.left, k-1);
    printkdistanceNodeDown(root.right, k-1);
}
 
// Prints all nodes at distance k from a given target node.
// The k distant nodes may be upward or downward.  This function
// Returns distance of root from target node, it returns -1 if target
// node is not present in tree rooted with root.
int printkdistanceNode(Node root, Node target , int k)
{
    // Base Case 1: If tree is empty, return -1
    if (root == null) return -1;
 
    // If target is same as root.  Use the downward function
    // to print all nodes at distance k in subtree rooted with
    // target or root
    if (root == target)
    {
        printkdistanceNodeDown(root, k);
        return 0;
    }
 
    // Recur for left subtree
    int dl = printkdistanceNode(root.left, target, k);
 
    // Check if target node was found in left subtree
    if (dl != -1)
    {
         // If root is at distance k from target, print root
         // Note that dl is Distance of root&#39;s left child from target
         if (dl + 1 == k)
            System.out.println(root.data) endl;
 
         // Else go to right subtree and print all k-dl-2 distant nodes
         // Note that the right child is 2 edges away from left child
         else
            printkdistanceNodeDown(root.right, k-dl-2);
 
         // Add 1 to the distance and return value for parent calls
         return 1 + dl;
    }
 
    // MIRROR OF ABOVE CODE FOR RIGHT SUBTREE
    // Note that we reach here only when node was not found in left subtree
    int dr = printkdistanceNode(root.right, target, k);
    if (dr != -1)
    {
         if (dr + 1 == k)
            System.out.println(root.data) endl;
         else
            printkdistanceNodeDown(root.left, k-dr-2);
         return 1 + dr;
    }
 
    // If target was neither present in left nor in right subtree
    return -1;
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Method 2 - Using the queue &lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Use a queue of size K to store the root to node path.&lt;br /&gt;
Now since, the queue is of size K.As soon as we find the NODE&amp;nbsp; in tree, 
the node at front of queue is at a distance K from NODE. It can be the 
case that the front node is less than K distant from NODE.&lt;br /&gt;
So, maintain a counter.&lt;br /&gt;
&lt;br /&gt;
Now start popping a node from queue which is at distant&amp;nbsp; i from NODE, 
and print all downwards nodes at distance K-i&amp;nbsp; in its other subtree.We 
only need to print the nodes in other&amp;nbsp; subtree to avoid Error.&lt;br /&gt;
&lt;br /&gt;
Note :- Since we need to print the nodes in sorted order, we can 
maintain a priority queue to store the nodes and after processing the 
nodes, we can print it.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;References&lt;/b&gt;&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;a href=&quot;http://www.geeksforgeeks.org/print-nodes-distance-k-given-node-binary-tree/&quot;&gt;http://www.geeksforgeeks.org/print-nodes-distance-k-given-node-binary-tree/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://stackoverflow.com/questions/7865055/nodes-at-a-distance-k-in-binary-tree&quot;&gt;stackoverflow.com/questions/7865055/nodes-at-a-distance-k-in-binary-tree&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://stackoverflow.com/questions/27813998/how-to-find-nodes-at-a-distance-k-from-the-given-node-in-binary-tree&quot;&gt;http://stackoverflow.com/questions/27813998/how-to-find-nodes-at-a-distance-k-from-the-given-node-in-binary-tree&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/6237508224451512724/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/09/for-given-node-of-binary-tree-print-k.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/6237508224451512724'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/6237508224451512724'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/09/for-given-node-of-binary-tree-print-k.html' title='For a Given node of a binary tree, print the K distance nodes.'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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/AVvXsEglnI7FqXdZew88Hggfxr1HTtayMu_2FEbvyWiFQDjVJlrSZ893RxK15GsP9zYvKANXC5RYHpHgFBvwlYRSV9UTPQ-KTZJnWELBjxPEoKbJxCB64gSfP8di6VB_vFDCtKt3RoQpl27HTamV/s72-c/bst-remove-case-2-1_1child.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3098638925089993315.post-1078210451637644127</id><published>2015-09-04T04:12:00.002+05:30</published><updated>2025-01-09T03:27:08.139+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Binary Tree / BT"/><category scheme="http://www.blogger.com/atom/ns#" term="distance"/><category scheme="http://www.blogger.com/atom/ns#" term="K-Distance"/><category scheme="http://www.blogger.com/atom/ns#" term="k5kced"/><title type='text'> Print all nodes that are at distance k from a leaf node</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div class=&quot;callout&quot;&gt;
    This updated information has been further expanded upon on my new website. You can find the updated details here: &lt;a href=&quot;https://k5kc.com/cs/problems/nodes-at-distance-k-from-leaf-nodes-in-binary-tree/&quot;&gt;https://k5kc.com/cs/problems/nodes-at-distance-k-from-leaf-nodes-in-binary-tree/&lt;/a&gt;.
&lt;/div&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Problem &lt;/h3&gt;
Given a Binary Tree and a positive integer k, print all nodes that are distance k from a leaf node.&lt;br /&gt;
&lt;br /&gt;
Here the meaning of distance is different from &lt;a href=&quot;http://k2code.blogspot.in/2015/09/find-distance-between-2-nodes-in-binary.html&quot; target=&quot;_blank&quot;&gt;previous post&lt;/a&gt;.
  Here k distance from a leaf means k levels higher than a leaf node.  
For example if k is more than height of Binary Tree, then nothing should
 be printed.  Expected time complexity is O(n) where n is the number 
nodes in the given Binary Tree.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example&lt;/b&gt;&lt;br /&gt;
(&lt;i&gt;Please ignore the empty node, and consider it null&lt;/i&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/AVvXsEgzyhC4QnWmXMDw-lcaZ9dVTcRkgJo_j6zROk9vrsQuZfX7UbJ5FTmOfRviogvORG7jfvz722w-5C7JYyIy6UgkZFqeTMH_1Wo3PP8dAs_NtSFa_HcyDymCNb98ThexF9_Qv1jF-PPLkycU/s1600/bst-remove-case-3-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;174&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzyhC4QnWmXMDw-lcaZ9dVTcRkgJo_j6zROk9vrsQuZfX7UbJ5FTmOfRviogvORG7jfvz722w-5C7JYyIy6UgkZFqeTMH_1Wo3PP8dAs_NtSFa_HcyDymCNb98ThexF9_Qv1jF-PPLkycU/s320/bst-remove-case-3-6.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
k = 1, Answer = 2, 19 , 21&lt;br /&gt;
k = 2, Answer = 5, 18 , 19&lt;br /&gt;
&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Solution&lt;/h3&gt;
The idea is to traverse the tree. Keep storing all ancestors till we 
hit a leaf node.  When we reach a leaf node, we print the ancestor at 
distance k.  We also need to keep track of nodes that are already 
printed as output. For that we use a boolean array visited[].&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;// This function prints all nodes that are distance k from a leaf node
//   path[] - Store ancestors of a node
//   visited[] - Stores true if a node is printed as output.  A node may be k
//                 distance away from many leaves, we want to print it once 
void kDistantFromLeafUtil(Node node, int path[], bool visited[],
                          int pathLen, int k)
{
    // Base case
    if (node==null) return;
 
    // append this Node to the path array 
    path[pathLen] = node.data;
    visited[pathLen] = false;
    pathLen++;
 
    // it&#39;s a leaf, so print the ancestor at distance k only
    // if the ancestor is not already printed  
    if (node.left == null &amp;amp;&amp;amp; node.right == null &amp;amp;&amp;amp;
        pathLen-k-1 &amp;gt;= 0 &amp;amp;&amp;amp; visited[pathLen-k-1] == false)
    {
        System.out.print(path[pathLen-k-1] + &quot; &quot;);
        visited[pathLen-k-1] = true;
        return;
    }
 
    // If not leaf node, recur for left and right subtrees 
    kDistantFromLeafUtil(node.left, path, visited, pathLen, k);
    kDistantFromLeafUtil(node.right, path, visited, pathLen, k);
}
 
// Given a binary tree and a nuber k, print all nodes that are k
//   distant from a leaf
void printKDistantfromLeaf(Node node, int k)
{
    int[] path = new int[MAX_HEIGHT];
    boolean[] visited = new boolean[MAX_HEIGHT];
    //all the elements false in visited
    Arrays.fill(visited, false);
    kDistantFromLeafUtil(node, path, visited, 0, k);
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;References&lt;/b&gt;&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;a href=&quot;http://www.geeksforgeeks.org/print-nodes-distance-k-leaf-node/&quot;&gt;http://www.geeksforgeeks.org/print-nodes-distance-k-leaf-node/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/1078210451637644127/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/09/print-all-nodes-that-are-at-distance-k.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/1078210451637644127'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/1078210451637644127'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/09/print-all-nodes-that-are-at-distance-k.html' title=' Print all nodes that are at distance k from a leaf node'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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/AVvXsEgzyhC4QnWmXMDw-lcaZ9dVTcRkgJo_j6zROk9vrsQuZfX7UbJ5FTmOfRviogvORG7jfvz722w-5C7JYyIy6UgkZFqeTMH_1Wo3PP8dAs_NtSFa_HcyDymCNb98ThexF9_Qv1jF-PPLkycU/s72-c/bst-remove-case-3-6.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3098638925089993315.post-6031492343175204678</id><published>2015-09-04T03:45:00.003+05:30</published><updated>2025-03-15T16:37:52.314+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Binary Tree / BT"/><category scheme="http://www.blogger.com/atom/ns#" term="distance"/><category scheme="http://www.blogger.com/atom/ns#" term="k5kced"/><category scheme="http://www.blogger.com/atom/ns#" term="kodeknight"/><category scheme="http://www.blogger.com/atom/ns#" term="LCA/Least Common Ancestor"/><title type='text'>Find the distance between 2 nodes in Binary Tree</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div class=&quot;callout&quot;&gt;
    This updated information has been further expanded upon on my new website. You can find the updated details here: &lt;a href=&quot;https://k5kc.com/cs/problems/distance-between-two-nodes-in-binary-tree/&quot;&gt;https://k5kc.com/cs/problems/distance-between-two-nodes-in-binary-tree/&lt;/a&gt;.
&lt;/div&gt;  
&lt;h3 style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;&lt;/h3&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;
Problem&lt;/h3&gt;
Find the distance between two keys in a binary tree, no parent pointers are given.  &lt;span id=&quot;more-127078&quot;&gt;&lt;/span&gt;Distance between two nodes is the minimum number of edges to be traversed to reach one node from other.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example&lt;/b&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/AVvXsEgdk1rCBRXopXkKY5242OAdOPEUlC7LjY8xyKRhqHXb9s1nmMgFyKmrLwLIsboREsOSAxXLb_rYd6n-Xhq-Y_-c4wXFQYjDdmzXch2U_vnB7r7bPQeNgR94W5kvZWa9SrPf46Vx-UZsi2tg/s1600/bst-remove-case-2-3.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgdk1rCBRXopXkKY5242OAdOPEUlC7LjY8xyKRhqHXb9s1nmMgFyKmrLwLIsboREsOSAxXLb_rYd6n-Xhq-Y_-c4wXFQYjDdmzXch2U_vnB7r7bPQeNgR94W5kvZWa9SrPf46Vx-UZsi2tg/s1600/bst-remove-case-2-3.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
Dist(-4,3) = 2,&lt;br /&gt;
Dist (-4,19) = 4&lt;br /&gt;
Dist(21,-4) = 3&lt;br /&gt;
Dist(2,-4) = 1&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Solution&lt;/h3&gt;
The distance between two nodes can be obtained in terms of &lt;a href=&quot;http://k2code.blogspot.in/2009/12/find-closest-ancestor-of-two-nodes-in.html&quot; target=&quot;_blank&quot;&gt;lowest common ancestor&lt;/a&gt;. Following is the formula.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;Dist(n1, n2) = Dist(root, n1) + Dist(root, n2) - 2*Dist(root, lca) 
&#39;n1&#39; and &#39;n2&#39; are the two given keys
&#39;root&#39; is root of given Binary Tree.
&#39;lca&#39; is lowest common ancestor of n1 and n2
Dist(n1, n2) is the distance between n1 and n2.
&lt;/pre&gt;
&lt;br /&gt;
Example take the case of Dist(-4,3)&lt;br /&gt;
LCA(-4,3) = 2&lt;br /&gt;
Dist(-4,3) = Dist(5,-4)+Dist(5,3) - 2 * (5,2) = 3 + 3 - 2 * 2 = 2&lt;br /&gt;
&lt;br /&gt;
Now lets do the coding.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Code&lt;/b&gt; &lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;// Returns level of key k if it is present in tree, otherwise returns -1
int findLevel(Node root, int k, int level)
{
    // Base Case
    if (root == null)
        return -1;
 
    // If key is present at root, or in left subtree or right subtree,
    // return true;
    if (root.key == k)
        return level;
 
    int l = findLevel(root.left, k, level+1);
    return (l != -1)? l : findLevel(root.right, k, level+1);
}
 
// This function returns pointer to LCA of two given values n1 and n2. 
// It also sets d1, d2 and dist if one key is not ancestor of other
// Note that we set the value in findDistUtil for d1,d2 and dist
// d1 -. To store distance of n1 from root
// d2 -. To store distance of n2 from root
// lvl -. Level (or distance from root) of current node
// dist -. To store distance between n1 and n2
Node findDistUtil(Node root, int n1, int n2, Integer d1, Integer d2, 
                   Integer dist, int lvl)
{
    // Base case
    if (root == null) return null;
 
    // If either n1 or n2 matches with root&#39;s key, report
    // the presence by returning root (Note that if a key is
    // ancestor of other, then the ancestor key becomes LCA
    if (root.key == n1)
    {
         d1 = lvl;
         return root;
    }
    if (root.key == n2)
    {
         d2 = lvl;
         return root;
    }
 
    // Look for n1 and n2 in left and right subtrees
    Node left_lca  = findDistUtil(root.left, n1, n2, d1, d2, dist, lvl+1);
    Node right_lca = findDistUtil(root.right, n1, n2, d1, d2, dist, lvl+1);
 
    // If both of the above calls return Non-null, then one key
    // is present in once subtree and other is present in other,
    // So this node is the LCA
    if (left_lca!=null &amp;amp;&amp;amp; right_lca!=null)
    {
        dist = d1 + d2 - 2*lvl;
        return root;
    }
 
    // Otherwise check if left subtree or right subtree is LCA
    return (left_lca != null)? left_lca: right_lca;
}
 
// The main function that returns distance between n1 and n2
// This function returns -1 if either n1 or n2 is not present in
// Binary Tree.
int findDistance(Node root, int n1, int n2)
{
    // Initialize d1 (distance of n1 from root), d2 (distance of n2 
    // from root) and dist(distance between n1 and n2)
    Integer d1 = -1, d2 = -1, dist;
    Node lca = findDistUtil(root, n1, n2, d1, d2, dist, 1);
 
    // If both n1 and n2 were present in Binary Tree, return dist
    if (d1 != -1 &amp;amp;&amp;amp; d2 != -1)
        return dist;
 
    // If n1 is ancestor of n2, consider n1 as root and find level 
    // of n2 in subtree rooted with n1
    if (d1 != -1)
    {
        dist = findLevel(lca, n2, 0);
        return dist;
    }
 
    // If n2 is ancestor of n1, consider n2 as root and find level 
    // of n1 in subtree rooted with n2
    if (d2 != -1)
    {
        dist = findLevel(lca, n1, 0);
        return dist;
    }
 
    return -1;
}
&lt;/pre&gt;
&lt;br /&gt;
findDistance() is the main function which calculates the distance, which calls findDistUtil which calculates distance as well as find the LCA in case n1 is not the ancestor of n2 or vice versa.&lt;br /&gt;
If n1 is ancestor of n2 or vice versa, we use findLevel to simply find the difference between 2 levels.&lt;br /&gt;
&lt;br /&gt;
Time Complexity - O(n) as we do single traversal on the tree&lt;br /&gt;
&lt;br /&gt;
Note that in java we dont have out parameters in function, like we have in c#. Hence I have used Integer Object, so that I can set the value in d1,d2 and dist as we have pass by value for primitive types in java, but we needed pass by reference.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;References&lt;/b&gt;&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;a href=&quot;http://www.geeksforgeeks.org/find-distance-two-given-nodes/&quot;&gt;http://www.geeksforgeeks.org/find-distance-two-given-nodes/&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/6031492343175204678/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/09/find-distance-between-2-nodes-in-binary.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/6031492343175204678'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/6031492343175204678'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/09/find-distance-between-2-nodes-in-binary.html' title='Find the distance between 2 nodes in Binary Tree'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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/AVvXsEgdk1rCBRXopXkKY5242OAdOPEUlC7LjY8xyKRhqHXb9s1nmMgFyKmrLwLIsboREsOSAxXLb_rYd6n-Xhq-Y_-c4wXFQYjDdmzXch2U_vnB7r7bPQeNgR94W5kvZWa9SrPf46Vx-UZsi2tg/s72-c/bst-remove-case-2-3.png" height="72" width="72"/><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3098638925089993315.post-1736733686807280758</id><published>2015-09-04T03:06:00.005+05:30</published><updated>2025-03-14T02:47:22.451+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Binary Tree / BT"/><category scheme="http://www.blogger.com/atom/ns#" term="count"/><category scheme="http://www.blogger.com/atom/ns#" term="kodeknight"/><title type='text'>Program to count leaf nodes in a binary tree</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div class=&quot;callout&quot;&gt;
    This updated information has been further expanded upon on my new website. You can find the updated details here: &lt;a href=&quot;https://k5kc.com/cs/problems/count-number-of-leaf-nodes-in-binary-tree/&quot;&gt;https://k5kc.com/cs/problems/count-number-of-leaf-nodes-in-binary-tree/&lt;/a&gt;.
&lt;/div&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Problem&lt;/h3&gt;
Count leaf nodes in a binary tree&lt;br /&gt;
&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Solution&lt;/h3&gt;
&lt;b&gt;Method 1 - Recursive&lt;/b&gt;&lt;br /&gt;
Here is the logic:&lt;br /&gt;
&lt;ol style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;If node is NULL then return 0.&lt;/li&gt;
&lt;li&gt;Else If left and right child nodes are NULL return 1.&lt;/li&gt;
&lt;li&gt;Else recursively calculate leaf count of the tree using below formula.&lt;br /&gt;Leaf count of a tree = Leaf count of left subtree + Leaf count of right subtree&lt;/li&gt;
&lt;/ol&gt;
&lt;br /&gt;
Here is the recursive solution:&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;int countLeaves(Node node){
  if( node == null )
    return 0;
  if( node.left == null &amp;amp;&amp;amp; node.right == null ) {
    return 1;
  } else {
    return countLeaves(node.left) + countLeaves(node.right);
  }
}
&lt;/pre&gt;
&lt;br /&gt;
Time complexity - O(n)&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Method 2 - Iterative&lt;/b&gt;&lt;br /&gt;
Here we can use Queue. Idea is to use Level Order traversal.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;int countLeaves(Node root)
{
  int count=0;
    if(root==null)
      return 0;

    Queue&amp;lt;Node&amp;gt; myqueue = new Queue&amp;lt;Node&amp;gt;();
    myqueue.push(root);

    while(!myqueue.empty())
    {
      Node temp;
       temp=myqueue.pop();//take the top element from the queue
      if(temp.left==null &amp;amp;&amp;amp; temp.right==null)
       count++;
      if(temp.left!=null)
       myqueue.push(temp.left);
      if(temp.right!=null)
       myqueue.push(temp.right);
    }
  return count;
}
&lt;/pre&gt;
&lt;br /&gt;
Time complexity - O(n)&lt;br /&gt;
Space Complexity - O(n)&amp;nbsp; for queue&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Referenes&lt;/b&gt;&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;a href=&quot;http://www.geeksforgeeks.org/write-a-c-program-to-get-count-of-leaf-nodes-in-a-binary-tree/&quot;&gt;http://www.geeksforgeeks.org/write-a-c-program-to-get-count-of-leaf-nodes-in-a-binary-tree/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://stackoverflow.com/questions/5949882/counting-number-of-leaf-nodes-in-binary-tree&quot;&gt;http://stackoverflow.com/questions/5949882/counting-number-of-leaf-nodes-in-binary-tree&lt;/a&gt;&amp;nbsp; &lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/1736733686807280758/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/09/program-to-count-leaf-nodes-in-binary.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/1736733686807280758'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/1736733686807280758'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/09/program-to-count-leaf-nodes-in-binary.html' title='Program to count leaf nodes in a binary tree'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-4266454485915702379</id><published>2015-06-26T22:28:00.005+05:30</published><updated>2025-03-14T02:45:33.473+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="hackerrank"/><category scheme="http://www.blogger.com/atom/ns#" term="incomplete"/><category scheme="http://www.blogger.com/atom/ns#" term="k5kced"/><category scheme="http://www.blogger.com/atom/ns#" term="kodeknight"/><title type='text'>Friend Circle - Hackerrank</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Problem Reference - &lt;a href=&quot;https://www.hackerrank.com/contests/juniper-hackathon/challenges/friend-circles&quot;&gt;Hackerrank&lt;/a&gt;&lt;/h3&gt;
&lt;div class=&quot;callout&quot;&gt;
    This updated information has been further expanded upon on my new website. You can find the updated details here: &lt;a href=&quot;https://k5kc.com/cs/problems/number-of-provinces/&quot;&gt;https://k5kc.com/cs/problems/number-of-provinces/&lt;/a&gt;.
&lt;/div&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Problem&lt;/h3&gt;
There are &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-1-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-1&quot; style=&quot;display: inline-block; width: 0.903em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 0.723em;&quot;&gt;&lt;span style=&quot;clip: rect(1.741em, 1000em, 2.68em, -0.427em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-2&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-3&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;N&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.06em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 0.933em; overflow: hidden; vertical-align: -0.074em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt; students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature, i.e., if &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-2-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-4&quot; style=&quot;display: inline-block; width: 0.792em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 0.632em;&quot;&gt;&lt;span style=&quot;clip: rect(1.726em, 1000em, 2.665em, -0.458em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-5&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-6&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;A&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 0.933em; overflow: hidden; vertical-align: -0.056em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt; is friend of &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-3-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-7&quot; style=&quot;display: inline-block; width: 0.792em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 0.632em;&quot;&gt;&lt;span style=&quot;clip: rect(1.741em, 1000em, 2.665em, -0.415em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-8&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-9&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;B&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 0.914em; overflow: hidden; vertical-align: -0.056em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt; and &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-4-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-10&quot; style=&quot;display: inline-block; width: 0.792em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 0.632em;&quot;&gt;&lt;span style=&quot;clip: rect(1.741em, 1000em, 2.665em, -0.415em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-11&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-12&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;B&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 0.914em; overflow: hidden; vertical-align: -0.056em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt; is friend of &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-5-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-13&quot; style=&quot;display: inline-block; width: 0.847em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 0.678em;&quot;&gt;&lt;span style=&quot;clip: rect(1.728em, 1000em, 2.683em, -0.341em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-14&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-15&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;C&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.022em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 0.952em; overflow: hidden; vertical-align: -0.078em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt;, then &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-6-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-16&quot; style=&quot;display: inline-block; width: 0.792em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 0.632em;&quot;&gt;&lt;span style=&quot;clip: rect(1.726em, 1000em, 2.665em, -0.458em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-17&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-18&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;A&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 0.933em; overflow: hidden; vertical-align: -0.056em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt; is also friend of &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-7-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-19&quot; style=&quot;display: inline-block; width: 0.847em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 0.678em;&quot;&gt;&lt;span style=&quot;clip: rect(1.728em, 1000em, 2.683em, -0.341em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-20&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-21&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;C&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.022em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 0.952em; overflow: hidden; vertical-align: -0.078em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt;. A friend circle is a group of students who are directly or indirectly friends.  &lt;br /&gt;
You are given a &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-8-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-22&quot; style=&quot;display: inline-block; width: 7.903em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 6.414em;&quot;&gt;&lt;span style=&quot;clip: rect(1.74em, 1000em, 2.69em, -0.427em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-23&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-24&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;N&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.06em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-25&quot; style=&quot;font-family: STIXGeneral; padding-left: 0.25em;&quot;&gt;×&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-26&quot; style=&quot;font-family: STIXGeneral; font-style: italic; padding-left: 0.25em;&quot;&gt;N&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.06em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-27&quot; style=&quot;font-family: STIXGeneral; padding-left: 0.25em;&quot;&gt;−&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-28&quot; style=&quot;font-family: STIXGeneral; font-style: italic; padding-left: 0.25em;&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-29&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-30&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;t&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.018em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-31&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;r&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.023em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-32&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-33&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;x&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.003em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 0.946em; overflow: hidden; vertical-align: -0.086em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt; &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-9-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-34&quot; style=&quot;display: inline-block; width: 1.069em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 0.858em;&quot;&gt;&lt;span style=&quot;clip: rect(1.741em, 1000em, 2.665em, -0.425em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-35&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-36&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;M&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.039em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 0.914em; overflow: hidden; vertical-align: -0.056em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt; which consists of characters &lt;code&gt;Y&lt;/code&gt; or &lt;code&gt;N&lt;/code&gt;.  If &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-10-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-37&quot; style=&quot;display: inline-block; width: 5.792em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 4.697em;&quot;&gt;&lt;span style=&quot;clip: rect(1.732em, 1000em, 2.872em, -0.425em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-38&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-39&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;M&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.039em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-40&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-41&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-42&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-43&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-44&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;j&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.001em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-45&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-46&quot; style=&quot;font-family: STIXGeneral; padding-left: 0.313em;&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-47&quot; style=&quot;font-family: STIXGeneral; font-style: italic; padding-left: 0.313em;&quot;&gt;Y&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.077em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 1.18em; overflow: hidden; vertical-align: -0.31em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt;, then &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-11-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-48&quot; style=&quot;display: inline-block; width: 1.125em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 0.903em;&quot;&gt;&lt;span style=&quot;clip: rect(1.214em, 1000em, 2.36em, -0.358em); left: 0em; position: absolute; top: -2.213em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-49&quot;&gt;&lt;span class=&quot;msubsup&quot; id=&quot;MathJax-Span-50&quot;&gt;&lt;span style=&quot;display: inline-block; height: 0px; position: relative; width: 0.888em;&quot;&gt;&lt;span style=&quot;clip: rect(1.74em, 1000em, 2.676em, -0.358em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-51&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;i&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;left: 0.271em; position: absolute; top: -2.685em;&quot;&gt;&lt;span class=&quot;texatom&quot; id=&quot;MathJax-Span-52&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-53&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-54&quot; style=&quot;font-family: STIXGeneral; font-size: 70.7%; font-style: italic;&quot;&gt;t&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.013em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-55&quot; style=&quot;font-family: STIXGeneral; font-size: 70.7%; font-style: italic;&quot;&gt;h&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.304em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.213em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 1.187em; overflow: hidden; vertical-align: -0.069em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt; and &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-12-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-56&quot; style=&quot;display: inline-block; width: 1.181em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 0.949em;&quot;&gt;&lt;span style=&quot;clip: rect(1.216em, 1000em, 2.556em, -0.531em); left: 0em; position: absolute; top: -2.213em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-57&quot;&gt;&lt;span class=&quot;msubsup&quot; id=&quot;MathJax-Span-58&quot;&gt;&lt;span style=&quot;display: inline-block; height: 0px; position: relative; width: 0.938em;&quot;&gt;&lt;span style=&quot;clip: rect(1.742em, 1000em, 2.872em, -0.531em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-59&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;j&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.001em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;left: 0.321em; position: absolute; top: -2.683em;&quot;&gt;&lt;span class=&quot;texatom&quot; id=&quot;MathJax-Span-60&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-61&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-62&quot; style=&quot;font-family: STIXGeneral; font-size: 70.7%; font-style: italic;&quot;&gt;t&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.013em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-63&quot; style=&quot;font-family: STIXGeneral; font-size: 70.7%; font-style: italic;&quot;&gt;h&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.304em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.213em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 1.426em; overflow: hidden; vertical-align: -0.31em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt; students are friends with each other, otherwise not. You have to print the total number of friend circles in the class.  &lt;br /&gt;
&lt;b&gt;Input Format&lt;/b&gt; &lt;br /&gt;
First line of the input contains an integer &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-13-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-64&quot; style=&quot;display: inline-block; width: 0.903em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 0.723em;&quot;&gt;&lt;span style=&quot;clip: rect(1.741em, 1000em, 2.68em, -0.427em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-65&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-66&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;N&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.06em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 0.933em; overflow: hidden; vertical-align: -0.074em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt; - (size of the matrix), followed by N lines each having N characters.  &lt;br /&gt;
&lt;b&gt;Output Format&lt;/b&gt; &lt;br /&gt;
Print the maximum number of friend circles.  &lt;br /&gt;
&lt;b&gt;Constraints&lt;/b&gt; &lt;br /&gt;
&lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-14-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-67&quot; style=&quot;display: inline-block; width: 6.569em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 5.33em;&quot;&gt;&lt;span style=&quot;clip: rect(1.718em, 1000em, 2.768em, -0.296em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-68&quot;&gt;&lt;span class=&quot;mn&quot; id=&quot;MathJax-Span-69&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-70&quot; style=&quot;font-family: STIXGeneral; padding-left: 0.313em;&quot;&gt;≤&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-71&quot; style=&quot;font-family: STIXGeneral; font-style: italic; padding-left: 0.313em;&quot;&gt;N&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.06em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-72&quot; style=&quot;font-family: STIXGeneral; padding-left: 0.313em;&quot;&gt;≤&lt;/span&gt;&lt;span class=&quot;mn&quot; id=&quot;MathJax-Span-73&quot; style=&quot;font-family: STIXGeneral; padding-left: 0.313em;&quot;&gt;300&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 1.069em; overflow: hidden; vertical-align: -0.182em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt; &lt;br /&gt;
Each element of matrix friends will be &lt;code&gt;Y&lt;/code&gt; or &lt;code&gt;N&lt;/code&gt;. &lt;br /&gt;
Number of rows and columns will be equal in the matrix.  &lt;br /&gt;
&lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-15-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-74&quot; style=&quot;display: inline-block; width: 5.792em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 4.697em;&quot;&gt;&lt;span style=&quot;clip: rect(1.732em, 1000em, 2.821em, -0.425em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-75&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-76&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;M&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.039em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-77&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-78&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-79&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-80&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-81&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-82&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-83&quot; style=&quot;font-family: STIXGeneral; padding-left: 0.313em;&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-84&quot; style=&quot;font-family: STIXGeneral; font-style: italic; padding-left: 0.313em;&quot;&gt;Y&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.077em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 1.117em; overflow: hidden; vertical-align: -0.247em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt;, where &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-16-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-85&quot; style=&quot;display: inline-block; width: 5.069em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 4.11em;&quot;&gt;&lt;span style=&quot;clip: rect(1.718em, 1000em, 2.768em, -0.383em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-86&quot;&gt;&lt;span class=&quot;mn&quot; id=&quot;MathJax-Span-87&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-88&quot; style=&quot;font-family: STIXGeneral; padding-left: 0.313em;&quot;&gt;≤&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-89&quot; style=&quot;font-family: STIXGeneral; font-style: italic; padding-left: 0.313em;&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-90&quot; style=&quot;font-family: STIXGeneral; padding-left: 0.313em;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-91&quot; style=&quot;font-family: STIXGeneral; font-style: italic; padding-left: 0.313em;&quot;&gt;N&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.06em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 1.069em; overflow: hidden; vertical-align: -0.182em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt; &lt;br /&gt;
&lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-17-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-92&quot; style=&quot;display: inline-block; width: 3.403em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 2.755em;&quot;&gt;&lt;span style=&quot;clip: rect(1.732em, 1000em, 2.872em, -0.425em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-93&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-94&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;M&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.039em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-95&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-96&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-97&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-98&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-99&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;j&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.001em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-100&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;]&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 1.18em; overflow: hidden; vertical-align: -0.31em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt; = &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-18-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-101&quot; style=&quot;display: inline-block; width: 3.403em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 2.755em;&quot;&gt;&lt;span style=&quot;clip: rect(1.732em, 1000em, 2.872em, -0.425em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-102&quot;&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-103&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;M&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.039em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-104&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-105&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;j&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.001em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-106&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-107&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-108&quot; style=&quot;font-family: STIXGeneral; font-style: italic;&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-109&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;]&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 1.18em; overflow: hidden; vertical-align: -0.31em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt;, where &lt;span class=&quot;MathJax_Preview&quot;&gt;&lt;/span&gt;&lt;span class=&quot;MathJax&quot; id=&quot;MathJax-Element-19-Frame&quot; role=&quot;textbox&quot;&gt;&lt;nobr&gt;&lt;span class=&quot;math&quot; id=&quot;MathJax-Span-110&quot; style=&quot;display: inline-block; width: 7.069em;&quot;&gt;&lt;span style=&quot;display: inline-block; font-size: 123%; height: 0px; position: relative; width: 5.736em;&quot;&gt;&lt;span style=&quot;clip: rect(1.718em, 1000em, 2.872em, -0.383em); left: 0em; position: absolute; top: -2.529em;&quot;&gt;&lt;span class=&quot;mrow&quot; id=&quot;MathJax-Span-111&quot;&gt;&lt;span class=&quot;mn&quot; id=&quot;MathJax-Span-112&quot; style=&quot;font-family: STIXGeneral;&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-113&quot; style=&quot;font-family: STIXGeneral; padding-left: 0.313em;&quot;&gt;≤&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-114&quot; style=&quot;font-family: STIXGeneral; font-style: italic; padding-left: 0.313em;&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-115&quot; style=&quot;font-family: STIXGeneral; padding-left: 0.313em;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-116&quot; style=&quot;font-family: STIXGeneral; font-style: italic; padding-left: 0.313em;&quot;&gt;j&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.001em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mo&quot; id=&quot;MathJax-Span-117&quot; style=&quot;font-family: STIXGeneral; padding-left: 0.313em;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mi&quot; id=&quot;MathJax-Span-118&quot; style=&quot;font-family: STIXGeneral; font-style: italic; padding-left: 0.313em;&quot;&gt;N&lt;span style=&quot;display: inline-block; height: 1px; overflow: hidden; width: 0.06em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;display: inline-block; height: 2.529em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;border-left: 0em solid; display: inline-block; height: 1.197em; overflow: hidden; vertical-align: -0.31em; width: 0px;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Here is the code&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/kinshuk4/fd93f7898b3120dcc065.js&quot;&gt;&lt;/script&gt;&lt;br /&gt;
Thanks
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/4266454485915702379/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/06/friend-circle-hackerrank.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/4266454485915702379'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/4266454485915702379'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/06/friend-circle-hackerrank.html' title='Friend Circle - Hackerrank'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-6527344477088286719</id><published>2015-06-10T10:54:00.005+05:30</published><updated>2025-03-14T02:45:57.427+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Interview Question"/><category scheme="http://www.blogger.com/atom/ns#" term="k5kced"/><category scheme="http://www.blogger.com/atom/ns#" term="kodeknight"/><category scheme="http://www.blogger.com/atom/ns#" term="mathematics"/><title type='text'>Lazy Caterer&#39;s sequence</title><content type='html'>&lt;div class=&quot;callout&quot;&gt;
    This updated information has been further expanded upon on my new website. You can find the updated details here: &lt;a href=&quot;https://k5kc.com/cs/problems/lazy-caterer-s-sequence/&quot;&gt;https://k5kc.com/cs/problems/lazy-caterer-s-sequence/&lt;/a&gt;.
&lt;/div&gt;
&lt;b&gt;Problem &lt;/b&gt;&lt;br /&gt;
Given a circular (or regular polygon) cake and a knife by which you can only cut vertically, find the maximum number of pieces of cake you can get by making n cuts. Write a program to do that.&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;span style=&quot;font-size: large;&quot;&gt;Solution&lt;/span&gt;&lt;/div&gt;
The solution to this is very simple, if you know mathematics. :P&lt;br /&gt;
&lt;br /&gt;
Number of pieces p&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;p = ( n^2+n+2)/2
p = C(n+1,2) + 1
&lt;/pre&gt;
&amp;nbsp; &lt;br /&gt;
More on wikipedia - &lt;a href=&quot;http://en.wikipedia.org/wiki/Lazy_caterer%27s_sequence&quot;&gt;http://en.wikipedia.org/wiki/Lazy_caterer%27s_sequence&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: large;&quot;&gt;Proof&lt;/span&gt;&lt;br /&gt;
When a circle is cut &lt;i&gt;n&lt;/i&gt; times to produce the maximum number of pieces, represented as &lt;i&gt;p&lt;/i&gt;&amp;nbsp;=&amp;nbsp;&lt;i&gt;ƒ&lt;/i&gt;(&lt;i&gt;n&lt;/i&gt;), the &lt;i&gt;n&lt;/i&gt;th cut must be considered; the number of pieces before the last cut is &lt;i&gt;ƒ&lt;/i&gt;(&lt;i&gt;n&lt;/i&gt;&amp;nbsp;−&amp;nbsp;1), while the number of pieces added by the last cut is &lt;i&gt;n&lt;/i&gt;.&lt;br /&gt;
To obtain the maximum number of pieces, the &lt;i&gt;n&lt;/i&gt;th cut line 
should cross all the other previous cut lines inside the circle, but not
 cross any intersection of previous cut lines. Thus, the &lt;i&gt;n&lt;/i&gt;th line itself is cut in &lt;i&gt;n&lt;/i&gt; − 1 places, and into &lt;i&gt;n&lt;/i&gt; line segments. Each segment divides one piece of the (&lt;i&gt;n&lt;/i&gt;&amp;nbsp;−&amp;nbsp;1)-cut pancake into 2 parts, adding exactly &lt;i&gt;n&lt;/i&gt;
 to the number of pieces. The new line can&#39;t have any more segments 
since it can only cross each previous line once. A cut line can always 
cross over all previous cut lines, as rotating the knife at a small 
angle around a point that is not an existing intersection will, if the 
angle is small enough, intersect all the previous lines including the 
last one added.&lt;br /&gt;
Thus, the total number of pieces after &lt;i&gt;n&lt;/i&gt; cuts is&lt;br /&gt;
&lt;br /&gt;
f(n) = n + f(n-1) &lt;br /&gt;
&lt;dl&gt;&lt;dd&gt;&lt;/dd&gt;&lt;/dl&gt;
This &lt;a href=&quot;http://en.wikipedia.org/wiki/Recurrence_relation&quot; title=&quot;Recurrence relation&quot;&gt;recurrence relation&lt;/a&gt; can be solved. If &lt;i&gt;ƒ&lt;/i&gt;(&lt;i&gt;n&lt;/i&gt;&amp;nbsp;−&amp;nbsp;1) is expanded one term the relation becomes&lt;br /&gt;
f(n) = n + n-1 + f(n-2) &lt;br /&gt;
&lt;dl&gt;&lt;dd&gt;&lt;/dd&gt;&lt;/dl&gt;
Expansion of the term &lt;i&gt;ƒ&lt;/i&gt;(&lt;i&gt;n&lt;/i&gt;&amp;nbsp;−&amp;nbsp;2) can continue until the last term is reduced to &lt;i&gt;ƒ&lt;/i&gt;(0), thus,&lt;br /&gt;
f(n) = n + n-1 + n-2 ..... + 1 + f(0) &lt;br /&gt;
&lt;dl&gt;&lt;dd&gt;&lt;/dd&gt;&lt;/dl&gt;
But f(0) = 1 , because there is one piece before any cuts are made, this can be rewritten as&lt;br /&gt;
&lt;dl&gt;&lt;dd&gt;f(n) = 1 + (1+2+3 + .... n)&lt;/dd&gt;&lt;/dl&gt;
This can be simplified, using the formula for the sum of an &lt;a href=&quot;http://en.wikipedia.org/wiki/Arithmetic_progression&quot; title=&quot;Arithmetic progression&quot;&gt;arithmetic progression&lt;/a&gt;:&lt;br /&gt;
&lt;dl&gt;&lt;dd&gt;&amp;nbsp;f(n) = 1+ n*(n+1)/2 = ( n^2+n+2)/2&lt;/dd&gt;&lt;/dl&gt;
&lt;br /&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/6527344477088286719/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/06/lazy-caterer.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/6527344477088286719'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/6527344477088286719'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/06/lazy-caterer.html' title='Lazy Caterer&#39;s sequence'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-3938864662904723979</id><published>2015-06-02T18:38:00.001+05:30</published><updated>2015-06-02T18:38:50.213+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Dynamic Programming / DP"/><category scheme="http://www.blogger.com/atom/ns#" term="gist"/><category scheme="http://www.blogger.com/atom/ns#" term="incomplete"/><category scheme="http://www.blogger.com/atom/ns#" term="kodeknight"/><title type='text'>Lego Blocks Problem </title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;br /&gt;
Problem statement - https://www.hackerrank.com/challenges/lego-blocks&lt;br /&gt;
solution - http://stackoverflow.com/questions/15424945/lego-blocks-dynamic-programming&lt;br /&gt;
http://stackoverflow.com/questions/913566/has-anyone-seen-a-programming-puzzle-similar-to-this&lt;br /&gt;
&lt;br /&gt;
Code -&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/kinshuk4/2758b2a9a76e0630886c.js&quot;&gt;&lt;/script&gt;
&lt;br /&gt;
Thanks.&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/3938864662904723979/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/06/lego-blocks-problem.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/3938864662904723979'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/3938864662904723979'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/06/lego-blocks-problem.html' title='Lego Blocks Problem '/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-5736975070473454731</id><published>2015-05-25T08:47:00.001+05:30</published><updated>2015-05-25T08:47:56.343+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="jabong"/><category scheme="http://www.blogger.com/atom/ns#" term="kodeknight"/><category scheme="http://www.blogger.com/atom/ns#" term="link list"/><category scheme="http://www.blogger.com/atom/ns#" term="reverse"/><category scheme="http://www.blogger.com/atom/ns#" term="Single Link List"/><title type='text'>K reverse a linked list with increasing K</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;b&gt;Problem&lt;/b&gt;&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
Reverse k elements in the linked list such that k goes on increasing&lt;/blockquote&gt;
&lt;br /&gt;
&lt;b&gt;Example&lt;/b&gt;&lt;br /&gt;
Eg.&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 1 - 2 - 3 - 4 - 5 - 6 - 7&lt;br /&gt;
output - 1 - 3 - 2 - 6 - 5- 4 - 7&lt;br /&gt;
&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Solution&lt;/h3&gt;
You can take this problem &lt;a href=&quot;http://k2code.blogspot.in/2012/01/k-reverse-linked-list.html&quot;&gt;here&lt;/a&gt;. Here we are just increasing k.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;   public static ListNode&amp;lt;Integer&amp;gt; reverseSubLinkLists(ListNode&amp;lt;Integer&amp;gt; headerNode) {
        
        ListNode&amp;lt;Integer&amp;gt; nextNode = headerNode.next;
        ListNode&amp;lt;Integer&amp;gt; startNode = null;
        ListNode&amp;lt;Integer&amp;gt; endNode = null;
        
        int k = 2;
        while (nextNode != null) {
            
            startNode = nextNode;
            endNode = nextNode;
            
            for (int i = 1; i &amp;lt; k; i++) {
                endNode = endNode.next;
                if (endNode == null) {
                    break;
                }
            }



            if (endNode != null) {
                // Save the node next to endNode
                nextNode = endNode.next;
                // Unlink the endNode
                endNode.next = null;
                // Reverse the list starting from startNode

                startNode = reverseListIterative(startNode);
                k++;
            } else {
                nextNode = null;
//              // Save the node next to endNode
//              nextNode = endNode.next;
//              // Unlink the endNode
//              endNode.next = null;
                // Reverse the list starting from startNode

                startNode = reverseListIterative(startNode);
            }

            if (headerNode == null) {
                headerNode = startNode;
            } else {
                headerNode.next = startNode;
                ListNode&amp;lt;Integer&amp;gt; temp = startNode;
                while(temp!=null){
                    if(temp.next==null){
                        break;
                    }
                    temp = temp.next;
                }
                headerNode = temp;
            }
        }

        return headerNode;
    }

    public static ListNode&amp;lt;Integer&amp;gt; reverseListIterative(ListNode&amp;lt;Integer&amp;gt; headerNode) {
        ListNode&amp;lt;Integer&amp;gt; prevNode = null;
        ListNode&amp;lt;Integer&amp;gt; currNode = headerNode;
        ListNode&amp;lt;Integer&amp;gt; nextNode = null;

        while (currNode != null) {
            nextNode = currNode.next;
            currNode.next = prevNode;
            prevNode = currNode;
            currNode = nextNode;
        }

        return prevNode;
    }
    
&lt;/pre&gt;
&lt;br /&gt;
Time complexity - O(n)&lt;br /&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/5736975070473454731/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/05/k-reverse-linked-list-with-increasing-k.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/5736975070473454731'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/5736975070473454731'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/05/k-reverse-linked-list-with-increasing-k.html' title='K reverse a linked list with increasing K'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-2884945334365800994</id><published>2015-05-16T14:51:00.000+05:30</published><updated>2015-05-16T14:51:45.160+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Binary Tree / BT"/><category scheme="http://www.blogger.com/atom/ns#" term="conversion"/><category scheme="http://www.blogger.com/atom/ns#" term="DLL/Doubly Linked List"/><category scheme="http://www.blogger.com/atom/ns#" term="incomplete"/><category scheme="http://www.blogger.com/atom/ns#" term="kodeknight"/><title type='text'>Convert Binary Tree to Doubly linked list in level order </title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&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;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/AVvXsEjkMWNwUSqPhvE9-xdASWwOsbyJEgIV4P7IYdgcn8LYbFDnEjy_5SlHSsBUgPjHz9KiGnHF9RjTjrWKSavWX5kY57LdmWhu1XnJTyO9VBjxf1TInKtB8ly3hi2uUlbSkSqRTrQD4O8ZoOmX/s1600/bst2dll_tree.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjkMWNwUSqPhvE9-xdASWwOsbyJEgIV4P7IYdgcn8LYbFDnEjy_5SlHSsBUgPjHz9KiGnHF9RjTjrWKSavWX5kY57LdmWhu1XnJTyO9VBjxf1TInKtB8ly3hi2uUlbSkSqRTrQD4O8ZoOmX/s1600/bst2dll_tree.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
The output will be a double linked list like this:&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/AVvXsEi25AU7465FG3bE5I1QzNZsbT8X4jCCodbIz9YQBR0HaM-BPYetwuiDWI_k8Jvu79qnW9lsQFTqIaY4aV-0r6LbjKC_IT_J_Uc7lGBsXipRnd5NbpkJvt8Wfcd27qNvMsFaF56qOmJqrtZl/s1600/bst2dll_dll.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;58&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi25AU7465FG3bE5I1QzNZsbT8X4jCCodbIz9YQBR0HaM-BPYetwuiDWI_k8Jvu79qnW9lsQFTqIaY4aV-0r6LbjKC_IT_J_Uc7lGBsXipRnd5NbpkJvt8Wfcd27qNvMsFaF56qOmJqrtZl/s1600/bst2dll_dll.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&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;br /&gt;
For traversing the tree, we&#39;ll use level / order traversal a.k.a breadth first search.&lt;br /&gt;
&lt;br /&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;br /&gt;
&lt;pre class=&quot;brush:cpp&quot;&gt;#include&amp;lt;iostream&amp;gt;
#include&amp;lt;queue&amp;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 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-&amp;gt;left != NULL)
      nodeQueue.push(listIT-&amp;gt;left);
    //add right child to stack
    if (listIT-&amp;gt;right != NULL)
      nodeQueue.push(listIT-&amp;gt;right);
    //add current node to linked list
    if (prevNode != NULL)
      prevNode-&amp;gt;right = listIT;
    listIT-&amp;gt;left = prevNode;
  }
 
  //connect end node of list to null
  listIT-&amp;gt;right = NULL;
  return head;
}
&lt;/pre&gt;
&lt;br /&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;br /&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;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/2884945334365800994/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/05/convert-binary-tree-to-doubly-linked.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/2884945334365800994'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/2884945334365800994'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/05/convert-binary-tree-to-doubly-linked.html' title='Convert Binary Tree to Doubly linked list in level order '/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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/AVvXsEjkMWNwUSqPhvE9-xdASWwOsbyJEgIV4P7IYdgcn8LYbFDnEjy_5SlHSsBUgPjHz9KiGnHF9RjTjrWKSavWX5kY57LdmWhu1XnJTyO9VBjxf1TInKtB8ly3hi2uUlbSkSqRTrQD4O8ZoOmX/s72-c/bst2dll_tree.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3098638925089993315.post-3209901514216325401</id><published>2015-05-03T20:13:00.003+05:30</published><updated>2015-05-03T20:13:50.630+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="conversion"/><category scheme="http://www.blogger.com/atom/ns#" term="directi"/><category scheme="http://www.blogger.com/atom/ns#" term="Dynamic Programming / DP"/><category scheme="http://www.blogger.com/atom/ns#" term="incomplete"/><title type='text'>Number of steps required to convert string 1 to string2 when only bring character to first index operation is giving</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;b&gt;Problem&lt;/b&gt;&lt;br /&gt;
Given 2 strings - s1 and s2, when only 1 operation is allowed - Moving character at a time but only to the first position.&lt;br /&gt;
&lt;br /&gt;
Example&lt;br /&gt;
Example 1 &lt;br /&gt;
Input &lt;br /&gt;
s1 = abcd&lt;br /&gt;
s2 = bacd&lt;br /&gt;
&lt;br /&gt;
Output&lt;br /&gt;
Ans = 1&lt;br /&gt;
Reason, just move b forward and we get it. &lt;br /&gt;
&lt;br /&gt;
Example 2&lt;br /&gt;
Input&lt;br /&gt;
A = (a)b(cd)e(f)g(hij)&lt;br /&gt;B = ahdjcifbeg&lt;br /&gt;
Output&lt;br /&gt;
Ans =7&lt;br /&gt;
Explanation&lt;br /&gt;
A = (a)b(cd)e(f)g(hij)&lt;br /&gt;B = ahdjcifbeg&lt;br /&gt;
Characters b,e,g are in the order, rest characters have to brought first.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Solution&lt;/h3&gt;
This is a DP problem,&amp;nbsp; LCS of the 2 strings is adf, and rest of the character are moved forward, and rest of the characters will be moved forward.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/3209901514216325401/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/05/number-of-steps-required-to-convert.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/3209901514216325401'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/3209901514216325401'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/05/number-of-steps-required-to-convert.html' title='Number of steps required to convert string 1 to string2 when only bring character to first index operation is giving'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-1930267534806023961</id><published>2015-05-03T20:13:00.002+05:30</published><updated>2015-05-03T20:13:37.273+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="directi"/><category scheme="http://www.blogger.com/atom/ns#" term="Dynamic Programming / DP"/><category scheme="http://www.blogger.com/atom/ns#" term="kadane"/><category scheme="http://www.blogger.com/atom/ns#" term="product"/><title type='text'>Maximize the number of magical gems by passing through array of house</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;b&gt;Problem&lt;/b&gt;&lt;br /&gt;
There was a thief, he has to pass through colored house - which can be red or blue, and contain 0 or more gems. The property of these gems is they multiply the previous gems by the current gems in the house. The houses are in array and thief can only visit once to steal the gems, with the goal of maximizing the gems. Find the range of house where he can maximize the gems in such a way that number of red houses are even.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example&lt;/b&gt;&lt;br /&gt;
Gem array = 1 2 0 4 5 6 2 3&lt;br /&gt;
color array = 0 0 1 1 1 0 0 1  (r=1,b=0)&lt;br /&gt;
o/p = 20 (4*5)&lt;br /&gt;
&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Solution&lt;/h3&gt;
This is similar to maximum product subarray, but there is another condition of red color.&lt;br /&gt;
&lt;br /&gt;
Here is the code below:&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;int maximumMoney(int n, int[] colour, int[] gems) {
    int max = 1;
    int red = 0;
    int start = 0, end = 0;
    int actualMax=1;
    for(int i=0;i&amp;lt;gems.length;i++){
        if(gems[i]&amp;gt;0)
        {
            max = max*gems[i];
            end++;
            if(colour[i] == 1)
               red++;
            
               
        }else{
            if(actualMax &amp;lt; max){
                if(red%2==0)
                {
                    actualMax = max;

                }else{
                    int temp = max;
                    int startRed = -1, endRed = -1;
                    for(int i=start;i&amp;lt;end;i++){
                        if(colour[i]==1 &amp;amp;&amp;amp; startRed==-1){
                           startRed = i;
                           endRed = i;
                        }else if(colour[i]==1)
                            endRed = i;
                    }
                    int tempProdStart = 1; tempEndProd = 1;
                    for(int i=start;i&amp;lt;=startRed;i++){
                        tempProdStart = a[i]*tempProdStart ;
                        
                    }
                    
                     for(int i=endRed;i&amp;lt;=end;i++){
                        tempEndProd= a[i]*tempEndProd;
                        
                    }
                    int minProd = Math.min(tempProdStart, tempEndProd);
                    
                    max = temp/minProd;
                    if(max &amp;gt; actualMax){
                        actualMax = max;
                    }
                        
                    
                }
                   
            }
              
            start = end+1;
            end = end + 1;
            
        }
    }
}
&lt;/pre&gt;
&lt;br /&gt;
Time complexity - O(n)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/1930267534806023961/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/05/maximize-number-of-magical-gems-by.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/1930267534806023961'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/1930267534806023961'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/05/maximize-number-of-magical-gems-by.html' title='Maximize the number of magical gems by passing through array of house'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-3888486574478922132</id><published>2015-05-03T19:12:00.003+05:30</published><updated>2015-05-03T19:12:54.317+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="directi"/><title type='text'>Find the least wastage in cutting the Trees?</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;b&gt;Problem&lt;/b&gt;&lt;br /&gt;
You are given n Trees with their heights in an array.
and you are given a value k units , that much wood you need to collect.
You can have an axe of any height you want but you can use only 1 axe when you choose.&lt;br /&gt;
&lt;br /&gt;
Assume height to be integral value.&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Solution &lt;/h3&gt;
So, if height of the tree is H, and you cut it at height X from the ground then H-X will be used will be used. If there is only 1 tree, we will cut it at height X, such that H-X = k. &lt;br /&gt;
&lt;br /&gt;
It is always possible to choose an axe height such that chopping &lt;i&gt;all&lt;/i&gt; trees above this height will result in zero waste.&lt;br /&gt;
To see this, just sort the trees in descending order of height, and 
consider moving the axe height gradually down from the top of the 
tallest tree.&lt;br /&gt;
&lt;br /&gt;
Suppose the tallest tree has height h.  Notice that the 
function:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;f(x) = total amount of wood cut by using an axe of height h - x to
       chop all trees of at least this height
&lt;/pre&gt;
&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Sort the trees by their height in descending order&lt;/li&gt;
&lt;li&gt;&amp;nbsp;starts at 0 when x = 0, and is an increasing piecewise linear 
function of x, with no discontinuities.  Every time x increases past the
 point when one or more trees just start to become choppable, the rate 
of change of f(x) increases, but this doesn&#39;t cause problems.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;So for 
any desired level of wood y, just (conceptually) intersect a horizontal 
line of height y with the graph f(x), and drop a vertical line from this
 point down to the x axis to find its value.  (How to actually do this 
in a program I leave as an exercise, but here&#39;s a hint: consider trees 
in decreasing height order to find the pair of adjacent x values x1, x2 
such that chopping at h - x1 produces too little wood, and h - x2 
produces too much.)&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;b&gt;Reference&lt;/b&gt;&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;a href=&quot;http://stackoverflow.com/questions/18053325/algorithm-find-the-least-wastage-in-cutting-the-trees&quot;&gt;http://stackoverflow.com/questions/18053325/algorithm-find-the-least-wastage-in-cutting-the-trees&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/3888486574478922132/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/05/find-least-wastage-in-cutting-trees.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/3888486574478922132'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/3888486574478922132'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/05/find-least-wastage-in-cutting-trees.html' title='Find the least wastage in cutting the Trees?'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-253624674577760804</id><published>2015-05-03T17:33:00.000+05:30</published><updated>2015-05-03T17:33:48.796+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Dynamic Programming / DP"/><category scheme="http://www.blogger.com/atom/ns#" term="vmware"/><title type='text'>Implement a function similar to diff command in linux</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Problem&lt;/h3&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
Give logic for implementing &quot;diff&quot; command in Linux.&lt;br /&gt;
Consider various test cases and explain what will happen in each. The two files are source code and are huge..&lt;br /&gt;
For e.g.&lt;br /&gt;
File 1: 1-2-3-4&lt;br /&gt;
File 2: 1-3-4-2&lt;/blockquote&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Solution&lt;/h3&gt;
The operation of diff is based on solving the longest common sub-sequence problem.&lt;br /&gt;
In this problem, you have two sequences of items:&lt;br /&gt;
a b c d f g h j q z&lt;br /&gt;
a b c d e f g i j k r x y z&lt;br /&gt;
and you want to find a longest sequence of items that is present in both original sequences in the same order. That is, you want to find a new sequence which can be obtained from the first sequence by deleting some items, and from the second sequence by deleting other items. You also want this sequence to be as long as possible. In this case it is&lt;br /&gt;
a b c d f g j z&lt;br /&gt;
From a longest common subsequence it&#39;s only a small step to get diff-like output: if an item is absent in the subsequence but present in the original, it must have been deleted. (The &#39;–&#39; marks, below.) If it is absent in the subsequence but present in the second sequence, it must have been added in. (The &#39;+&#39; marks.)&lt;br /&gt;
e h i q k r x y&lt;br /&gt;
+ - + - + + + +&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Resource&lt;/b&gt;&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;a href=&quot;http://www.careercup.com/questionthread?id=98911&quot;&gt;http://www.careercup.com/questionthread?id=98911&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/253624674577760804/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/05/implement-function-similar-to-diff.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/253624674577760804'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/253624674577760804'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/05/implement-function-similar-to-diff.html' title='Implement a function similar to diff command in linux'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-8771736554702681940</id><published>2015-04-30T22:17:00.000+05:30</published><updated>2016-03-15T17:29:15.228+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="array"/><category scheme="http://www.blogger.com/atom/ns#" term="divide and conquer"/><category scheme="http://www.blogger.com/atom/ns#" term="Dynamic Programming / DP"/><category scheme="http://www.blogger.com/atom/ns#" term="max"/><category scheme="http://www.blogger.com/atom/ns#" term="maxima"/><category scheme="http://www.blogger.com/atom/ns#" term="minima"/><category scheme="http://www.blogger.com/atom/ns#" term="stock"/><title type='text'>Maximum single sell profit from stock</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;b&gt;Problem&lt;/b&gt;&lt;br /&gt;
Suppose we are given an array of n integers representing stock prices
 on a single day.  We want to find a pair (buyDay, sellDay), with buyDay
 ≤ sellDay, such that if we bought the stock on buyDay and sold it on 
sellDay, we would maximize our profit.&lt;br /&gt;
&lt;br /&gt;
OR&lt;br /&gt;
&lt;br /&gt;
Given an array arr[] of integers, find out the difference between any two elements &lt;b&gt;such that larger element appears after the smaller number&lt;/b&gt; in arr[]. &lt;br /&gt;
&lt;br /&gt;
&lt;span id=&quot;more-6463&quot;&gt;&lt;/span&gt;&lt;br /&gt;
&lt;b&gt;Example&lt;/b&gt;&lt;br /&gt;
Input = {5&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 10&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 4&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 6&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 7}&lt;br /&gt;
Output = 5,10 =&amp;gt; buy at 5 and sell at 7&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Solution&lt;/h3&gt;
&lt;br /&gt;
&lt;b&gt;Method 1 - Brute force&lt;/b&gt;&lt;br /&gt;
Clearly there is an O(n&lt;sup&gt;2&lt;/sup&gt;) solution to the algorithm by 
trying out all possible (buyDay, sellDay) pairs and taking the best out 
of all of them.  However, is there a better algorithm, perhaps one that 
runs in O(n) time?&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;int maxDiff(int arr[], int arr_size)
{     
  int max_diff = arr[1] - arr[0];
  int i, j;
  for(i = 0; i &amp;lt; arr_size; i++)
  {
    for(j = i+1; j &amp;lt; arr_size; j++)
    {        
      if(arr[j] - arr[i] &amp;gt; max_diff)   
         max_diff = arr[j] - arr[i];
    }    
  }          
  return max_diff;
}    
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;Method 2 - Divide and Conquer&lt;/b&gt;&lt;br /&gt;
If we have a single day, the best option is to buy on that day and 
then sell it back on the same day for no profit.  Otherwise, split the 
array into two halves.  If we think about what the optimal answer might 
be, it must be in one of three places:

&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;The correct buy/sell pair occurs completely within the first half.&lt;/li&gt;
&lt;li&gt;The correct buy/sell pair occurs completely within the second half.&lt;/li&gt;
&lt;li&gt;The correct buy/sell pair occurs across both halves - we buy in the first half, then sell in the second half.&lt;/li&gt;
&lt;/ol&gt;
We can get the values for (1) and (2) by recursively invoking our 
algorithm on the first and second halves.  For option (3), the way to 
make the highest profit would be to buy at the lowest point in the first
 half and sell in the greatest point in the second half.  We can find 
the minimum and maximum values in the two halves by just doing a simple 
linear scan over the input and finding the two values.  This then gives 
us an algorithm with the following recurrence:&lt;br /&gt;
&lt;pre&gt;&lt;code&gt;T(1) &amp;lt;= O(1)
T(n) &amp;lt;= 2T(n / 2) + O(n)
&lt;/code&gt;&lt;/pre&gt;
Using the &lt;a href=&quot;http://en.wikipedia.org/wiki/Master_theorem&quot;&gt;Master Theorem&lt;/a&gt;
 to solve the recurrence, we find that this runs in O(n lg n) time and 
will use O(lg n) space for the recursive calls.  We&#39;ve just beaten the 
naive O(n&lt;sup&gt;2&lt;/sup&gt;) solution!&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Method 3 - Optimized divide and conquer&lt;/b&gt;&lt;br /&gt;
But wait!  We can do much better than this.  Notice that the only 
reason we have an O(n) term in our recurrence is that we had to scan the
 entire input trying to find the minimum and maximum values in each 
half.  Since we&#39;re already recursively exploring each half, perhaps we 
can do better by having the recursion also hand back the minimum and 
maximum values stored in each half!  In other words, our recursion hands
 back three things:&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;The buy and sell times to maximize profit.&lt;/li&gt;
&lt;li&gt;The minimum value overall in the range.&lt;/li&gt;
&lt;li&gt;The maximum value overall in the range.&lt;/li&gt;
&lt;/ol&gt;
These last two values can be computed recursively using a 
straightforward recursion that we can run at the same time as the 
recursion to compute (1):&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;The max and min values of a single-element range are just that element.&lt;/li&gt;
&lt;li&gt;The max and min values of a multiple element range can be found by 
splitting the input in half, finding the max and min values of each 
half, then taking their respective max and min.&lt;/li&gt;
&lt;/ol&gt;
If we use this approach, our recurrence relation is now&lt;br /&gt;
&lt;pre&gt;&lt;code&gt;T(1) &amp;lt;= O(1)
T(n) &amp;lt;= 2T(n / 2) + O(1)
&lt;/code&gt;&lt;/pre&gt;
Using the Master Theorem here gives us a runtime of O(n) with O(lg n) space, which is even better than our original solution!&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Method 4 - Use the difference between adjacent element&lt;/b&gt;&lt;br /&gt;
First find the difference between the adjacent elements of the array and
 store all differences in an auxiliary array diff[] of size n-1. Now 
this problems turns into finding the maximum sum subarray of this 
difference array. &lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;int maxDiff(int arr[], int n)
{
    // Create a diff array of size n-1. The array will hold
    //  the difference of adjacent elements
    int diff[n-1];
    for (int i=0; i &amp;lt; n-1; i++)
        diff[i] = arr[i+1] - arr[i];
 
    // Now find the maximum sum subarray in diff array
    int max_diff = diff[0];
    for (int i=1; i&amp;lt;n-1; i++)
    {
        if (diff[i-1] &amp;gt; 0)
            diff[i] += diff[i-1];
        if (max_diff &amp;lt; diff[i])
            max_diff = diff[i];
    }
    return max_diff;
}
&lt;/pre&gt;
&lt;br /&gt;
Example&lt;br /&gt;
input =&amp;nbsp; &lt;br /&gt;
Time Complexity: O(n)&lt;br /&gt;
Auxiliary Space: O(n)&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Method 5 - Optimizing the diff approach&lt;/b&gt;&lt;br /&gt;
We can modify the above method to work in O(1) extra space. Instead of creating an auxiliary array, we can calculate diff and max sum in same loop. Following is the space optimized version.&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;int maxDiff (int arr[], int n)
{
    // Initialize diff, current sum and max sum
    int diff = arr[1]-arr[0];
    int curr_sum = diff;
    int max_sum = curr_sum;
 
    for(int i=1; i&amp;lt;n-1; i++)
    {
        // Calculate current diff
        diff = arr[i+1]-arr[i];
 
        // Calculate current sum
        if (curr_sum &amp;gt; 0)
           curr_sum += diff;
        else
           curr_sum = diff;
 
        // Update max sum, if needed
        if (curr_sum &amp;gt; max_sum)
           max_sum = curr_sum;
    }
 
    return max_sum;
}
&lt;/pre&gt;
&lt;br /&gt;
Time Complexity: O(n),
Auxiliary Space: O(1)&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Method 6 -&amp;nbsp; Dynamic programming (Preferred and easy :))&lt;/b&gt;&lt;br /&gt;
But wait a minute - we can do even better than this!  Let&#39;s think 
about solving this problem using dynamic programming.  The idea will be 
to think about the problem as follows.  Suppose that we knew the answer 
to the problem after looking at the first k elements.  Could we use our 
knowledge of the (k+1)st element, combined with our initial solution, to
 solve the problem for the first (k+1) elements?  If so, we could get a 
great algorithm going by solving the problem for the first element, then
 the first two, then the first three, etc. until we&#39;d computed it for 
the first n elements.&lt;br /&gt;
Let&#39;s think about how to do this.  If we have just one element, we 
already know that it has to be the best buy/sell pair.  Now suppose we 
know the best answer for the first k elements and look at the (k+1)st 
element.  Then the only way that this value can create a solution better
 than what we had for the first k elements is if the difference between 
the smallest of the first k elements and that new element is bigger than
 the biggest difference we&#39;ve computed so far.  So suppose that as we&#39;re
 going across the elements, we keep track of two values - the minimum 
value we&#39;ve seen so far, and the maximum profit we could make with just 
the first k elements.  Initially, the minimum value we&#39;ve seen so far is
 the first element, and the maximum profit is zero.  When we see a new 
element, we first update our optimal profit by computing how much we&#39;d 
make by buying at the lowest price seen so far and selling at the 
current price.  If this is better than the optimal value we&#39;ve computed 
so far, then we update the optimal solution to be this new profit.  
Next, we update the minimum element seen so far to be the minimum of the
 current smallest element and the new element.&lt;br /&gt;
&lt;br /&gt;
Since at each step we do only O(1) work and we&#39;re visiting each of 
the n elements exactly once, this takes O(n) time to complete!  
Moreover, it only uses O(1) auxiliary storage.  This is as good as we&#39;ve
 gotten so far!&lt;br /&gt;
As an example, on your inputs, here&#39;s how this algorithm might run.  
The numbers in-between each of the values of the array correspond to the
 values held by the algorithm at that point.  You wouldn&#39;t actually 
store all of these (it would take O(n) memory!),&lt;br /&gt;
&lt;br /&gt;
Time - O(n), Space - O(1) solution:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public static int findMaxProfit(int[] stockPriceSamples) {
 int maxProfit = 0;
 int minTillNow = stockPriceSamples[0];
 for (int i = 0; i &amp;lt; stockPriceSamples.length; i++) {
  int profit = stockPriceSamples[i] - minTillNow;
  maxProfit = Math.max(profit, maxProfit);
  minTillNow = Math.min(stockPriceSamples[i], minTillNow);
 }
 return maxProfit;
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;Example&lt;/b&gt;&lt;br /&gt;
input = {5&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 10&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 4&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 6&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 7}&lt;br /&gt;
i = 0, maxProfit = 0, minTillNow=5&lt;br /&gt;
i = 1, maxProfit=5, minTillNow=5&lt;br /&gt;
i= 2, maxProfit = 5,minTillNow=4&lt;br /&gt;
i=3,maxProfit=5,minTillNow=4&lt;br /&gt;
i= 4,maxProfit=5,minTillNow=5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;References&lt;/b&gt;&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;a href=&quot;http://stackoverflow.com/questions/7086464/maximum-single-sell-profit&quot;&gt;http://stackoverflow.com/questions/7086464/maximum-single-sell-profit&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.geeksforgeeks.org/maximum-difference-between-two-elements/&quot;&gt;http://www.geeksforgeeks.org/maximum-difference-between-two-elements/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://programming4interviews.wordpress.com/2012/02/27/maximize-the-single-sell-profit-of-a-stock/&quot;&gt;https://programming4interviews.wordpress.com/2012/02/27/maximize-the-single-sell-profit-of-a-stock/&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/8771736554702681940/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/04/maximum-single-sell-profit.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/8771736554702681940'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/8771736554702681940'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/04/maximum-single-sell-profit.html' title='Maximum single sell profit from stock'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-386371252360265819</id><published>2015-04-18T22:56:00.001+05:30</published><updated>2016-03-28T02:40:49.846+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="DLL/Doubly Linked List"/><category scheme="http://www.blogger.com/atom/ns#" term="reverse"/><title type='text'>Reverse the doubly linked list</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Problem&lt;/h3&gt;
Reverse the doubly linked list&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Input&lt;/b&gt;&lt;br /&gt;
10 - 8 - 4 - 2&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Output&lt;/b&gt;&lt;br /&gt;
2 - 4 - 8 - 12&lt;br /&gt;
&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Solution&lt;/h3&gt;
&lt;br /&gt;
&lt;b&gt;Method 1 - Reversing the prev and next references&lt;/b&gt; &lt;br /&gt;
Reversing a doubly linked list is much simpler as compared to reversing a singly linked list. We just need to swap the &lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot;;&quot;&gt;prev&lt;/span&gt; &amp;amp; &lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot;;&quot;&gt;next&lt;/span&gt; references&amp;nbsp; in all the nodes of the list and need to make head point to 
the last node of original list (which will be the first node in the 
reversed list).&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;void reverseDLL(Node head)
 {
    while(head!=null)
    {
       // Swapping the prev &amp;amp; next pointer of each node
       Node t = head.prev;
       head.prev = head.next;
       head.next = t;
 
       if(head.prev != null)
          head = head.prev;  // Move to the next node in original list
       else
          break;              // reached the end. so terminate
    }
 }
&lt;/pre&gt;
&lt;br /&gt;
Time complexity - O(n)&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Reference&lt;/b&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.geeksforgeeks.org/reverse-a-doubly-linked-list/&quot;&gt;http://www.geeksforgeeks.org/reverse-a-doubly-linked-list/&lt;/a&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/386371252360265819/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/04/reverse-doubly-linked-list.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/386371252360265819'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/386371252360265819'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/04/reverse-doubly-linked-list.html' title='Reverse the doubly linked list'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-6456255110812806309</id><published>2015-04-18T20:58:00.002+05:30</published><updated>2015-04-18T21:05:43.154+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="DLL/Doubly Linked List"/><category scheme="http://www.blogger.com/atom/ns#" term="kodeknight"/><title type='text'>Doubly linked list ADT</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
A doubly-linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two&amp;nbsp; fields, called links, that are references to the previous and to the next node in the sequence of nodes.&lt;br /&gt;
&lt;br /&gt;
The beginning and ending nodes previous and next&amp;nbsp; links, respectively, point to some kind of terminator, typically a sentinel node or null, to facilitate traversal of the list. If there is only one sentinel node, then the list is circularly linked via the sentinel node. It can be conceptualized as two singly linked lists formed from the same data items,&amp;nbsp; but in opposite sequential orders. &lt;br /&gt;
&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
ADT&lt;/h3&gt;
&lt;pre class=&quot;brush:java&quot;&gt;    class Node {
        E element;
        Node next;
        Node prev;
 
        public Node(E element, Node next, Node prev) {
            this.element = element;
            this.next = next;
            this.prev = prev;
        }
    }
&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Operations&lt;/h3&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Insert&lt;/li&gt;
&lt;li&gt;Delete&lt;/li&gt;
&lt;li&gt;Update&lt;/li&gt;
&lt;li&gt;Find&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Java usage&lt;/h3&gt;
&lt;a href=&quot;http://download.oracle.com/javase/6/docs/api/java/util/LinkedList.html&quot;&gt;&lt;code&gt;java.util.LinkedList&lt;/code&gt;&lt;/a&gt; is a doubly-linked list.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Reference&lt;/b&gt;&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;a href=&quot;http://java2novice.com/data-structures-in-java/linked-list/doubly-linked-list/&quot;&gt;http://java2novice.com/data-structures-in-java/linked-list/doubly-linked-list/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/6456255110812806309/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/04/doubly-linked-list-adt.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/6456255110812806309'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/6456255110812806309'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/04/doubly-linked-list-adt.html' title='Doubly linked list ADT'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-5986341122238701852</id><published>2015-04-17T03:06:00.001+05:30</published><updated>2015-04-30T12:09:27.508+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="array"/><category scheme="http://www.blogger.com/atom/ns#" term="Dynamic Programming / DP"/><category scheme="http://www.blogger.com/atom/ns#" term="incomplete"/><category scheme="http://www.blogger.com/atom/ns#" term="sub-array"/><category scheme="http://www.blogger.com/atom/ns#" term="sum"/><title type='text'>Find the largest subarray with sum of 0 in the given array</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;b&gt;Problem&lt;/b&gt;&lt;br /&gt;
&lt;div class=&quot;post-text&quot; itemprop=&quot;text&quot;&gt;
An array contains both positive and negative elements, find the largest subarray whose 
sum equals 0.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example&lt;/b&gt;&lt;br /&gt;
int[] input = {4,&amp;nbsp; 6,&amp;nbsp; 3, -9, -5, 1, 3, 0, 2}&lt;br /&gt;
int output = {4,&amp;nbsp; 6,&amp;nbsp; 3, -9, -5, 1} of length 6&lt;br /&gt;
&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Solution&lt;/h3&gt;
&lt;b&gt;Method 1 - Brute force&lt;/b&gt;&lt;br /&gt;
This is simple. Will write later (&lt;span style=&quot;color: red;&quot;&gt;incomplete&lt;/span&gt;)&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Method 2 - Storing the sum upto ith element in temp array&lt;/b&gt;&lt;br /&gt;
Given an &lt;code&gt;int[] input&lt;/code&gt; array, you can create an &lt;code&gt;int[] tmp&lt;/code&gt; array where &lt;code&gt;&amp;nbsp;&lt;/code&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;tmp[i] = tmp[i - 1] + input[i];&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
Each element of tmp will store the sum of the input up to that element.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;Example&lt;/u&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;int[] input = {4 |&amp;nbsp; 6| 3| -9| -5| 1| 3| 0| 2}
int[] tmp =&amp;nbsp;&amp;nbsp; {4 | 10|13|&amp;nbsp; 4| -1| 0| 3| 3| 5}&lt;/pre&gt;
&lt;br /&gt;
Now if you check tmp, you&#39;ll notice that there might be values that are equal to each other.For example, take the element 4 at index 0 and 3, element 3 at index 6 and 7. So, it means sum between these 2 indices has remained the same, i.e. all the elements between them add upto 0. So, based on that we get {6, 3, -9} and {0}.&lt;br /&gt;
&lt;br /&gt;
Also, we know tmp[-1] = 0. When we have not started the array we have no element added to it. So, if we find a zero inside the tmp array, that means all the numbers starting 0th index to 5th index(where 0 exists in temp) are all 0s, so our subarray becomes {4,6,3, -9,-5,1}.&lt;br /&gt;
&lt;br /&gt;
Out of {6, 3, -9}, {0} and {4,6,3, -9,-5,1}, last one is our answer as it is the largest sub array.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;To sum it up&lt;/u&gt;&lt;br /&gt;
We notice that some values are same in tmp array. Let&#39;s say that this values are at indexes &lt;code&gt;j an k with j &amp;lt; k&lt;/code&gt;, then the sum of the input till &lt;code&gt;j&lt;/code&gt; is equal to the sum till &lt;code&gt;k&lt;/code&gt; and this means that the sum of the portion of the array between &lt;code&gt;j&lt;/code&gt; and &lt;code&gt;k&lt;/code&gt; is 0! Specifically the 0 sum subarray will be from index j + 1 to k.

&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;NOTE: if &lt;code&gt;j + 1 == k&lt;/code&gt;, then &lt;code&gt;k is 0&lt;/code&gt; and that&#39;s it! ;)&lt;/li&gt;
&lt;li&gt;NOTE: The algorithm should consider a virtual &lt;code&gt;tmp[-1] = 0&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;NOTE: An empty array has sum 0 and it&#39;s minimal and this special 
case should be brought up as well in an interview. Then the interviewer 
will say that doesn&#39;t count but that&#39;s another problem! ;)&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;br /&gt;
Here is the code&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;    public static string[] SubArraySumList(int[] array, int sum)
    {
        int tempsum;
        List&amp;lt;string&amp;gt; list = new List&amp;lt;string&amp;gt;();

        for (int i = 0; i &amp;lt; array.Length; i++)
        {
            tempsum = 0;

            for (int j = i; j &amp;lt; array.Length; j++)
            {
                tempsum += array[j];

                if (tempsum == sum)
                {
                    list.Add(String.Format(&quot;[{0}-{1}]&quot;, i, j));
                }
            }
        }
        return list.ToArray();
    }
&lt;/pre&gt;
&lt;br /&gt;
Here is the solution using Hashmap, iterate over it again to get the max subarray:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public static void subArraySumsZero() {
    int [] seed = new int[] {1,2,3,4,-9,6,7,-8,1,9};
    int currSum = 0;
    HashMap&amp;lt;Integer, Integer&amp;gt; sumMap = new HashMap&amp;lt;Integer, Integer&amp;gt;();
    for(int i = 0 ; i &amp;lt; seed.length ; i ++){
        currSum += seed[i];
        if(currSum == 0){
            System.out.println(&quot;subset : { 0 - &quot; + i + &quot; }&quot;);
        }else if(sumMap.get(currSum) != null){
            System.out.println(&quot;subset : { &quot; + (sumMap.get(currSum) + 1) + &quot; - &quot; + i + &quot; }&quot;);
            sumMap.put(currSum, i);
        }else
            sumMap.put(currSum, i);
    }
    System.out.println(&quot;HASH MAP HAS: &quot; + sumMap);
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;References&lt;/b&gt;&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;a href=&quot;http://stackoverflow.com/questions/5534063/zero-sum-subarray&quot;&gt;http://stackoverflow.com/questions/5534063/zero-sum-subarray&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/5986341122238701852/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/04/find-largest-subarray-with-sum-of-0-in.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/5986341122238701852'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/5986341122238701852'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/04/find-largest-subarray-with-sum-of-0-in.html' title='Find the largest subarray with sum of 0 in the given array'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-7226452575490480221</id><published>2015-04-17T02:36:00.003+05:30</published><updated>2015-04-17T02:36:43.650+05:30</updated><title type='text'>Einsteen&#39;s 5 house riddle</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Problem&lt;br /&gt;
&lt;h4&gt;
Einstein wrote this riddle early during the 19th century. He said 98% of the world could not solve it.&amp;nbsp;&lt;/h4&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
&lt;div class=&quot;clearfix&quot;&gt;
&quot;There are 5 houses in 5 different colors. In each 
house lives a person with a different nationality. The 5 owners drink a 
certain type of beverage, smoke a certain brand of cigar, and keep a 
certain pet. No owners have the same pet, smoke the same brand of cigar,
 or drink the same beverage.&quot;&lt;/div&gt;
&lt;/blockquote&gt;
&lt;div class=&quot;clearfix&quot;&gt;
&lt;b&gt;The question is:&lt;/b&gt; Who owns the fish?&lt;/div&gt;
&lt;div class=&quot;clearfix&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;clearfix&quot;&gt;
&lt;b&gt;Hints:&lt;/b&gt;&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt;The Brit lives in the red house.&lt;/li&gt;
&lt;li&gt;The Swede keeps dogs as pets.&lt;/li&gt;
&lt;li&gt;The Dane drinks tea.&lt;/li&gt;
&lt;li&gt;The green house is on the left of the white house.&lt;/li&gt;
&lt;li&gt;The green homeowner drinks coffee.&lt;/li&gt;
&lt;li&gt;The person who smokes Pall Mall rears birds.&lt;/li&gt;
&lt;li&gt;The owner of the yellow house smokes Dunhill.&lt;/li&gt;
&lt;li&gt;The man living in the center house drinks milk.&lt;/li&gt;
&lt;li&gt;The Norwegian lives in the first house.&lt;/li&gt;
&lt;li&gt;The man who smokes Blend lives next to the one who keeps cats.&lt;/li&gt;
&lt;li&gt;The man who keeps the horse lives next to the man who smokes Dunhill.&lt;/li&gt;
&lt;li&gt;The owner who smokes Bluemaster drinks beer.&lt;/li&gt;
&lt;li&gt;The German smokes prince.&lt;/li&gt;
&lt;li&gt;The Norwegian lives next to the blue house.&lt;/li&gt;
&lt;li&gt;The man who smokes Blend has a neighbor who drinks water.&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&quot;clearfix&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&amp;nbsp;Solution&lt;br /&gt;
a) We know that Norwegian lives in the 1st house (Hint: #9) and next 
to him lives a &amp;nbsp;guy who stays in a blue house (Hint: #14). So far we 
have the following:&lt;br /&gt;
&lt;table border=&quot;0&quot;&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;b&gt;1st House&lt;/b&gt;&lt;/td&gt;
&lt;td&gt;&lt;b&gt;2nd House&lt;/b&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Norwegian&lt;/td&gt;
&lt;td&gt;Blue House&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;br /&gt;
b) We know that the green house is on the left of the white house 
(Hint: 4), therefore we can form a new group with the Green and White 
house next to each other.&lt;br /&gt;
&lt;table border=&quot;0&quot;&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Green House&lt;/td&gt;
&lt;td&gt;White House&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;br /&gt;
c) Now think carefully the combination of (a) and (b). We should 
reach to the conclusion that the Norwegean guy who lives in the first 
house, he either lives in the Red or Yellow house since the Green &amp;amp; 
White houses group can only have a position of either 3-4 or 4-5.&lt;br /&gt;
d) Since the Brit is the guy who lives in the Red house (Hint: 1), 
now we definitely know that the Norwegian lives in the Yellow house. So 
far we have the following information:&lt;br /&gt;
&lt;table border=&quot;0&quot;&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1st House&lt;/td&gt;
&lt;td&gt;2nd House&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Norwegian&lt;br /&gt;
Yellow&lt;/td&gt;
&lt;td&gt;Blue&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;br /&gt;
&lt;table border=&quot;0&quot;&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;British&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Red&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;br /&gt;
Group:&lt;br /&gt;
&lt;table border=&quot;0&quot;&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Green House&lt;/td&gt;
&lt;td&gt;White House&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;br /&gt;
e) Next, we know that the owner of the Green house drinks coffee 
(Hint: 5) and the man living in the center house drinks milk (Hint: 8). 
As a result, we conclude that the group of Green and Yellow house are 
the 4th and 5th house in order and that the center house (number 3) is 
the Brit.&lt;br /&gt;
&lt;table border=&quot;0&quot;&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Norwegian&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;British&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Yellow&lt;/td&gt;
&lt;td&gt;&lt;span style=&quot;color: black; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10.909090995788574px; line-height: normal;&quot;&gt;Blue&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;Red&lt;/td&gt;
&lt;td&gt;Green&lt;/td&gt;
&lt;td&gt;White&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;Milk&lt;/td&gt;
&lt;td&gt;Coffee&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;br /&gt;
f) Hint 7 gives us another information on the first house (The owner 
of the yellow house smokes Dunhill). In-addition, the man who keeps the 
horse lives next to the man who smokes Dunhill (Hint 11), therefore the 
man living in house #2 keeps horses.&lt;br /&gt;
&lt;table border=&quot;0&quot;&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;House&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Nation&lt;/td&gt;
&lt;td&gt;Norwegian&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;British&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Color&lt;/td&gt;
&lt;td&gt;Yellow&lt;/td&gt;
&lt;td&gt;Blue&lt;/td&gt;
&lt;td&gt;Red&lt;/td&gt;
&lt;td&gt;Green&lt;/td&gt;
&lt;td&gt;White&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Drink&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;Milk&lt;/td&gt;
&lt;td&gt;Coffee&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pet&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Horses&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;span style=&quot;color: black; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10.909090995788574px; line-height: normal;&quot;&gt;Smoke&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;&lt;span style=&quot;color: black; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10.909090995788574px; line-height: normal;&quot;&gt;Dunhill&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;br /&gt;
g) Hint 15 states that &quot;The man who smokes Blend has a neighbor who 
drinks water.&quot; &amp;nbsp;We conclude that only 2 people can have a neighbor who 
drinks water (House 1&amp;amp;2), but since House #1 already smokes Dunhill 
that means that House #2 smokes Blend and House #1 drinks water.&lt;br /&gt;
&lt;table border=&quot;0&quot;&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;House&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Nation&lt;/td&gt;
&lt;td&gt;Norwegian&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;British&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Color&lt;/td&gt;
&lt;td&gt;Yellow&lt;/td&gt;
&lt;td&gt;Blue&lt;/td&gt;
&lt;td&gt;Red&lt;/td&gt;
&lt;td&gt;Green&lt;/td&gt;
&lt;td&gt;White&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Drink&lt;/td&gt;
&lt;td&gt;Water&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;Milk&lt;/td&gt;
&lt;td&gt;Coffee&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pet&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Horses&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Smoke&lt;/td&gt;
&lt;td&gt;Dunhill&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Blend&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;br /&gt;
h) Hint 12 states &quot;The owner who smokes Bluemaster drinks beer.&quot; See 
the table above and you will notice that we are missing the drink only 
for houses 2 and 5 but since we already know that the owner of house 2 
smokes Blend, then the combination of Hint 12 applies to house #5.&lt;br /&gt;
&lt;br /&gt;
&lt;table border=&quot;0&quot;&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;House&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Nation&lt;/td&gt;
&lt;td&gt;Norwegian&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;British&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Color&lt;/td&gt;
&lt;td&gt;Yellow&lt;/td&gt;
&lt;td&gt;Blue&lt;/td&gt;
&lt;td&gt;Red&lt;/td&gt;
&lt;td&gt;Green&lt;/td&gt;
&lt;td&gt;White&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Drink&lt;/td&gt;
&lt;td&gt;Water&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;Milk&lt;/td&gt;
&lt;td&gt;Coffee&lt;/td&gt;
&lt;td&gt;Beer&amp;nbsp;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pet&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Horses&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Smoke&lt;/td&gt;
&lt;td&gt;Dunhill&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Blend&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Bluemaster&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;br /&gt;
&amp;nbsp;i) Hint 3 states that &quot;The Dane drinks tea.&quot;. We are missing only the drink for house #2 therefore this applies to house #2.&lt;br /&gt;
&lt;table border=&quot;0&quot;&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;House&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Nation&lt;/td&gt;
&lt;td&gt;Norwegian&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Danish&lt;/td&gt;
&lt;td&gt;British&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Color&lt;/td&gt;
&lt;td&gt;Yellow&lt;/td&gt;
&lt;td&gt;Blue&lt;/td&gt;
&lt;td&gt;Red&lt;/td&gt;
&lt;td&gt;Green&lt;/td&gt;
&lt;td&gt;White&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Drink&lt;/td&gt;
&lt;td&gt;Water&lt;/td&gt;
&lt;td&gt;Tea&amp;nbsp;&lt;/td&gt;
&lt;td&gt;Milk&lt;/td&gt;
&lt;td&gt;Coffee&lt;/td&gt;
&lt;td&gt;Beer&amp;nbsp;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pet&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Horses&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Smoke&lt;/td&gt;
&lt;td&gt;Dunhill&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Blend&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Bluemaster&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;br /&gt;
j) Hint 10 states &quot;The man who smokes Blend lives next to the one who
 keeps cats.&quot; As a result, house #1 keeps cats since house #2 has the 
owner who smokes Blend.&lt;br /&gt;
&lt;br /&gt;
&lt;table border=&quot;0&quot;&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;House&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Nation&lt;/td&gt;
&lt;td&gt;Norwegian&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Danish&lt;/td&gt;
&lt;td&gt;British&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Color&lt;/td&gt;
&lt;td&gt;Yellow&lt;/td&gt;
&lt;td&gt;Blue&lt;/td&gt;
&lt;td&gt;Red&lt;/td&gt;
&lt;td&gt;Green&lt;/td&gt;
&lt;td&gt;White&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Drink&lt;/td&gt;
&lt;td&gt;Water&lt;/td&gt;
&lt;td&gt;Tea&amp;nbsp;&lt;/td&gt;
&lt;td&gt;Milk&lt;/td&gt;
&lt;td&gt;Coffee&lt;/td&gt;
&lt;td&gt;Beer&amp;nbsp;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pet&lt;/td&gt;
&lt;td&gt;Cats&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Horses&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Smoke&lt;/td&gt;
&lt;td&gt;Dunhill&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Blend&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Bluemaster&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;br /&gt;
k) Hint #13 states that &quot;The German smokes prince&quot;. We are missing 
the nationalities of the owners who live in house #4 and #5 but since 
the owner of house #5 smokes Bluemaster, this hint applies to house #4.&lt;br /&gt;
&lt;table border=&quot;0&quot;&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;House&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Nation&lt;/td&gt;
&lt;td&gt;Norwegian&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Danish&lt;/td&gt;
&lt;td&gt;British&lt;/td&gt;
&lt;td&gt;German&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Color&lt;/td&gt;
&lt;td&gt;Yellow&lt;/td&gt;
&lt;td&gt;Blue&lt;/td&gt;
&lt;td&gt;Red&lt;/td&gt;
&lt;td&gt;Green&lt;/td&gt;
&lt;td&gt;White&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Drink&lt;/td&gt;
&lt;td&gt;Water&lt;/td&gt;
&lt;td&gt;Tea&amp;nbsp;&lt;/td&gt;
&lt;td&gt;Milk&lt;/td&gt;
&lt;td&gt;Coffee&lt;/td&gt;
&lt;td&gt;Beer&amp;nbsp;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pet&lt;/td&gt;
&lt;td&gt;Cats&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Horses&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Smoke&lt;/td&gt;
&lt;td&gt;Dunhill&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Blend&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;Prince&amp;nbsp;&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Bluemaster&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;br /&gt;
l) Hint #6 states that &quot;The person who smokes Pall Mall rears birds&quot;. We are only missing the tabacco of House #3 therefore:&lt;br /&gt;
&lt;table border=&quot;0&quot;&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;House&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Nation&lt;/td&gt;
&lt;td&gt;Norwegian&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Danish&lt;/td&gt;
&lt;td&gt;British&lt;/td&gt;
&lt;td&gt;German&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Color&lt;/td&gt;
&lt;td&gt;Yellow&lt;/td&gt;
&lt;td&gt;Blue&lt;/td&gt;
&lt;td&gt;Red&lt;/td&gt;
&lt;td&gt;Green&lt;/td&gt;
&lt;td&gt;White&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Drink&lt;/td&gt;
&lt;td&gt;Water&lt;/td&gt;
&lt;td&gt;Tea&amp;nbsp;&lt;/td&gt;
&lt;td&gt;Milk&lt;/td&gt;
&lt;td&gt;Coffee&lt;/td&gt;
&lt;td&gt;Beer&amp;nbsp;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pet&lt;/td&gt;
&lt;td&gt;Cats&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Horses&lt;/td&gt;
&lt;td&gt;Birds&amp;nbsp;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Smoke&lt;/td&gt;
&lt;td&gt;Dunhill&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Blend&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Pall Mall&lt;/td&gt;
&lt;td&gt;Prince&amp;nbsp;&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Bluemaster&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;br /&gt;
m) Finally hint #2 states that &quot;The Swede keeps dogs as pets&quot;. This combination can only be applied to house #5.&lt;br /&gt;
&lt;table border=&quot;0&quot;&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;House&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Nation&lt;/td&gt;
&lt;td&gt;Norwegian&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Danish&lt;/td&gt;
&lt;td&gt;British&lt;/td&gt;
&lt;td&gt;German&lt;/td&gt;
&lt;td&gt;Swedish&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Color&lt;/td&gt;
&lt;td&gt;Yellow&lt;/td&gt;
&lt;td&gt;Blue&lt;/td&gt;
&lt;td&gt;Red&lt;/td&gt;
&lt;td&gt;Green&lt;/td&gt;
&lt;td&gt;White&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Drink&lt;/td&gt;
&lt;td&gt;Water&lt;/td&gt;
&lt;td&gt;Tea&amp;nbsp;&lt;/td&gt;
&lt;td&gt;Milk&lt;/td&gt;
&lt;td&gt;Coffee&lt;/td&gt;
&lt;td&gt;Beer&amp;nbsp;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pet&lt;/td&gt;
&lt;td&gt;Cats&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Horses&lt;/td&gt;
&lt;td&gt;Birds&amp;nbsp;&lt;/td&gt;
&lt;td&gt;&lt;br /&gt;&lt;/td&gt;
&lt;td&gt;Dogs&amp;nbsp;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Smoke&lt;/td&gt;
&lt;td&gt;Dunhill&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Blend&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Pall Mall&lt;/td&gt;
&lt;td&gt;Prince&amp;nbsp;&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Bluemaster&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;br /&gt;
n) Now who owns the fish? The &lt;b&gt;German&lt;/b&gt; owns the fish!!!&lt;br /&gt;
&lt;b&gt;Congratulations, according to Einstein you now belong to the 2% of the people who can solve this riddle!!!&lt;/b&gt;&lt;br /&gt;
&lt;table border=&quot;0&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;House&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Nation&lt;/td&gt;
&lt;td&gt;Norwegian&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Danish&lt;/td&gt;
&lt;td&gt;British&lt;/td&gt;
&lt;td&gt;German&lt;/td&gt;
&lt;td&gt;Swedish&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Color&lt;/td&gt;
&lt;td&gt;Yellow&lt;/td&gt;
&lt;td&gt;Blue&lt;/td&gt;
&lt;td&gt;Red&lt;/td&gt;
&lt;td&gt;Green&lt;/td&gt;
&lt;td&gt;White&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Drink&lt;/td&gt;
&lt;td&gt;Water&lt;/td&gt;
&lt;td&gt;Tea&amp;nbsp;&lt;/td&gt;
&lt;td&gt;Milk&lt;/td&gt;
&lt;td&gt;Coffee&lt;/td&gt;
&lt;td&gt;Beer&amp;nbsp;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pet&lt;/td&gt;
&lt;td&gt;Cats&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Horses&lt;/td&gt;
&lt;td&gt;Birds&amp;nbsp;&lt;/td&gt;
&lt;td&gt;&lt;b&gt;FISH&lt;/b&gt;&lt;/td&gt;
&lt;td&gt;Dogs&amp;nbsp;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Smoke&lt;/td&gt;
&lt;td&gt;Dunhill&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Blend&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Pall Mall&lt;/td&gt;
&lt;td&gt;Prince&amp;nbsp;&lt;/td&gt;
&lt;td&gt;&amp;nbsp;Bluemaster&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Reference&lt;/b&gt;&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;a href=&quot;http://einsteinriddle.com/index.php/einstein-s-riddle-solution-explained&quot;&gt;http://einsteinriddle.com/index.php/einstein-s-riddle-solution-explained&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/7226452575490480221/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/04/einsteens-5-house-riddle.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/7226452575490480221'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/7226452575490480221'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/04/einsteens-5-house-riddle.html' title='Einsteen&#39;s 5 house riddle'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-7147239430065740106</id><published>2015-04-17T01:33:00.000+05:30</published><updated>2015-04-17T01:33:29.275+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="kodeknight"/><category scheme="http://www.blogger.com/atom/ns#" term="Puzzles"/><title type='text'> Find the maximum distance covered using n bikes</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Problem&lt;/h3&gt;
There are n bikes and each can cover 100 km when fully fueled. What is the maximum amount of distance you can go using n bikes? &lt;span id=&quot;more-123895&quot;&gt;&lt;/span&gt; You may assume that all bikes are similar and a bike takes 1 litre to cover 1 km.&lt;br /&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
Solution&lt;/h3&gt;
There are couple of ways. Lets find the right solution. Say n = 50. &lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Naive Solution:&lt;/strong&gt;&lt;br /&gt;

&lt;div style=&quot;padding-left: 30px;&quot;&gt;
The most naive solution would be to just make all the bikes go together. Hence, the maximum distance travelled will be 100km.&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;strong&gt;Better Solution:&lt;/strong&gt;&lt;br /&gt;

&lt;div style=&quot;padding-left: 30px;&quot;&gt;
Move all the bikes 50km, so that each bike has half tank empty.&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
Now pour the fuel of 25 bikes (whose 
tanks are half filled) into other 25 bikes. Now we have 25 bikes will 
full tanks and these 25 bikes can go upto 100km each&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
Repeat the same after next 50 km.&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
Hence the number of bikes will go down after every 50 km, like:&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
50 -&amp;gt; 25 -&amp;gt; 12 -&amp;gt; 6 -&amp;gt; 3 -&amp;gt; 1&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
Total distance covered will be 5*50 + 100= 350 kms &lt;i&gt;(At the end you have a bike filled with 100km fuel)&lt;/i&gt;.&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
&lt;strong&gt;Note:&lt;/strong&gt; You can further 
optimize few more km, because we are ignoring one bike’s (50 km fuel) 
when 25-&amp;gt;12 and 3-&amp;gt;1.. Since it is not the best solution, I have 
ignored that.&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;strong&gt;Best Solution (Actual solution) :&lt;/strong&gt;&lt;br /&gt;

&lt;div style=&quot;padding-left: 30px;&quot;&gt;
In this solution we will vacate the tank 
of a bike as soon as there is capacity in other bikes (not waiting for 
50 km). Lets do it by breaking into the cases.&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
&lt;u&gt;Case 1 - Only 1 bike&lt;/u&gt; - The biker will drive for 100 km&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
&lt;u&gt;Case 2 - Only 2 bikes&lt;/u&gt; -&amp;nbsp; Both bikers will drive to the point such that first biker can transfer the fuel to the other guy. So, for the 1st 50km they will go together, and then the fuel in both will be 50L and then 1st biker will give fuel to the other biker, and that biker will cover the rest with 100L of fuel.&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
So, Distance = Distance covered together + distance covered by fuel transfer = 50 + 100 = 150 km&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
&lt;u&gt;Case 3 - Only 3 bikes&lt;/u&gt; - All the bikers will travel together to the point where fuel of the 1st biker can fill the oil in other 2 bikes. So, first distance will be 33.3 km. After this other 2 bikers will take fuel from 1st one and it will become like the old case of 2 bikes. Answer = 33.3 + 150 = 100/3 + 100/2 + 100 /1 = 183.3 km.&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
So empty one bike into rest 49 bikes. (49*2 = 98).&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
Again travel a distance of 100/49km, that is sufficient to vacate the fuel of one more bike in other 48 bikes.&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
The actual number of km traveled will be:&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
= 100/50 + 100/49 +......+100/1 =&amp;nbsp; &lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
&lt;/div&gt;
&lt;div style=&quot;padding-left: 30px;&quot;&gt;
&lt;strong&gt;= 449.92 km&lt;/strong&gt;&lt;/div&gt;
&lt;br /&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;References&lt;/b&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.geeksforgeeks.org/find-maximum-distance-covered-100-bikes/&quot;&gt;http://www.geeksforgeeks.org/find-maximum-distance-covered-100-bikes/&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.ritambhara.in/maximum-distance-with-50-bikes-each-having-fuel-capacity-of-100-kms/&quot;&gt;http://www.ritambhara.in/maximum-distance-with-50-bikes-each-having-fuel-capacity-of-100-kms/&lt;/a&gt;&lt;br /&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/7147239430065740106/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/04/find-maximum-distance-covered-using-n.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/7147239430065740106'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/7147239430065740106'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/04/find-maximum-distance-covered-using-n.html' title=' Find the maximum distance covered using n bikes'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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-3098638925089993315.post-2995399987701398497</id><published>2015-02-17T10:06:00.000+05:30</published><updated>2015-02-17T10:06:16.624+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="angular"/><category scheme="http://www.blogger.com/atom/ns#" term="Page"/><category scheme="http://www.blogger.com/atom/ns#" term="UX"/><title type='text'>Angular JS interview questions</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Some good resources on Angular JS:&lt;br /&gt;
&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;a href=&quot;http://angularinterviewquestions.blogspot.in/2014/12/list-of-angular-interview-questions.html&quot;&gt;http://angularinterviewquestions.blogspot.in/2014/12/list-of-angular-interview-questions.html&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://k2code.blogspot.com/feeds/2995399987701398497/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://k2code.blogspot.com/2015/02/angular-js-interview-questions.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/2995399987701398497'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3098638925089993315/posts/default/2995399987701398497'/><link rel='alternate' type='text/html' href='http://k2code.blogspot.com/2015/02/angular-js-interview-questions.html' title='Angular JS interview questions'/><author><name>Kinshuk Chandra</name><uri>http://www.blogger.com/profile/01344610750518430564</uri><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></feed>