<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom="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" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-6038272452605714757</atom:id><lastBuildDate>Fri, 03 Apr 2026 01:28:14 +0000</lastBuildDate><category>Arrays/Strings</category><category>Algorithm</category><category>tree</category><category>Cloud Computing</category><category>General</category><category>Dynamic programming</category><category>Amazon Interview</category><category>Ruby</category><category>Brain Teasers</category><category>Link List</category><category>Interviews</category><category>Google Interview</category><category>Amazon S3</category><category>Amazon SimpleDB</category><category>MIcrosoft Interview</category><category>Amazon EC2</category><category>Architecture</category><category>C++</category><category>Facebook Interview</category><category>Mathematics</category><category>python</category><category>Design Pattern</category><category>Git</category><category>Mac</category><category>Amazon SQS</category><category>Humour</category><category>Miscellany</category><category>backtracking</category><category>queue</category><category>web development</category><title>PROGRAMMING INTERVIEWS</title><description></description><link>http://tech-queries.blogspot.com/</link><managingEditor>noreply@blogger.com (Akash)</managingEditor><generator>Blogger</generator><openSearch:totalResults>136</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-6869030873596729474</guid><pubDate>Mon, 25 Jan 2016 08:26:00 +0000</pubDate><atom:updated>2016-05-25T13:16:35.944+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Interviews</category><title>Find integer average of 2 integers</title><description>I generally start with a very simple question with my interview candidates. I ask the for writing a program for giving the integer average of 2 integers using only integer type variables. Assume that input will always be with in integer limits.&lt;br /&gt;
&lt;br /&gt;
The definition of integer average is the highest smaller integer if average is floating point number. Also the condition if that they can not use any typecasting or any datatype other than int.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example:&lt;/b&gt;&lt;br /&gt;
a = 4, b = 5, avg = 4&lt;br /&gt;
a = 4, b = 6, avg = 5&lt;br /&gt;
a = -4, b = -6, avg = -5&lt;br /&gt;
a = 4, b = -5, avg = -1&lt;br /&gt;
a = -4, b = -5, avg = -5&lt;br /&gt;
&lt;br /&gt;
95% of candidates smell some issues in this problem and when I say nothing is there they don&#39;t even ask any clarification and come up with something like this:
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;
int get_average(int a, int b)
{
 return (a+b)/2;
}
&lt;/pre&gt;
&lt;br /&gt;
Then I ask them to have a look if this is correct on definition and then they see that it is. But there test failed on very first floating point negative average. Then most of them do a quick fix and come up with something below:&lt;br /&gt;
&lt;pre class=&quot;cpp&quot; name=&quot;code&quot;&gt;int get_average(int a, int b)
{
 int sum = (a+b);
 if (sum &amp;lt; 0)
  return sum/2 - 1;
 return sum/2;
}
&lt;/pre&gt;
&lt;br /&gt;
The above solution is obviously wrong if sum if a even negative number. I am disheartened to see why do these candidates just solve a test case and show the solution. They don&#39;t even care to run this with some examples.&lt;br /&gt;
&lt;br /&gt;
On pointing this, most of them correct the code. Others face the rejection at this stage.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;cpp&quot; name=&quot;code&quot;&gt;int get_average(int a, int b)
{
 int sum = (a+b);
 if (sum &amp;lt; 0 &amp;amp;&amp;amp; sum%2 != 0)
  return sum/2 - 1;
 return sum/2;
}
&lt;/pre&gt;
&lt;br /&gt;
Now I ask them to make it production worthy and taking care of boundary conditions. Many of them are not able to do so but some of them go through it for my second question.&lt;br /&gt;
&lt;br /&gt;
Though I expect this problem to be concluded within 30 minutes depending of their experience but candidates do a lot of silly mistakes and stretch.&lt;br /&gt;
&lt;br /&gt;
Lets see if you can code this correctly.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;cpp&quot; name=&quot;code&quot;&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;


int get_average (int a, int b)
{
 int a_half = a/2;
 int b_half = b/2;
 bool a_even = a%2==0? true:false;
 bool b_even = b%2==0? true:false;
 if (a&amp;gt;=0 &amp;amp;&amp;amp; b&amp;gt;=0)
 {
  if (!a_even &amp;amp;&amp;amp;  !b_even)
   return a_half + b_half + 1;
  return a_half + b_half;
 }
 else if (a&amp;lt;0 &amp;amp;&amp;amp; b&amp;lt;0)
 {
  if (a_even &amp;amp;&amp;amp;  b_even)
   return a_half + b_half;
  return a_half + b_half - 1;
 }
 else
 {
  int sum = a+b;
  if (sum &amp;lt; 0 &amp;amp;&amp;amp; sum%2 != 0)
    return sum/2 - 1;
   return sum/2;
 }

}

int main()
{
 int n, a, b;
 cout &amp;lt;&amp;lt; &quot;number of test cases: &quot;;
 cin &amp;gt;&amp;gt; n;
 for (int i=0; i&amp;lt;n; i++)
 {
  cout &amp;lt;&amp;lt; endl &amp;lt;&amp;lt; &quot;Enter a and b: &quot;;
  cin &amp;gt;&amp;gt; a &amp;gt;&amp;gt;b;
  cout &amp;lt;&amp;lt; &quot;average = &quot; &amp;lt;&amp;lt; get_average(a,b) &amp;lt;&amp;lt; endl;
 }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;Edit:&lt;/b&gt; We get a more efficient and concise solution in comments. Please go through it.&amp;nbsp;
&lt;br /&gt;&lt;br /&gt;
Notably most of the solution for binary search are wrong because of above reason. &lt;a href=&quot;http://bugs.java.com/bugdatabase/view_bug.do?bug_id=5045582&quot; target=&quot;_blank&quot;&gt;This bug&lt;/a&gt; was fixed in Java SDK after 9 years. Please read more about it &lt;a href=&quot;http://googleresearch.blogspot.in/2006/06/extra-extra-read-all-about-it-nearly.html&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.
&lt;br /&gt;
&lt;br /&gt;</description><link>http://tech-queries.blogspot.com/2016/01/find-integer-average-of-2-integers.html</link><author>noreply@blogger.com (Akash)</author><thr:total>64</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-3276755642835609921</guid><pubDate>Sun, 02 Aug 2015 13:18:00 +0000</pubDate><atom:updated>2016-01-27T13:12:45.399+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Algorithm</category><title>Print all tuple combinations for a given tuple</title><description>&lt;b&gt;Question:&lt;/b&gt;&lt;br /&gt;
Given a Tuple for eg. (a, b, c).&lt;br /&gt;
Output : (*, *, *), (*, *, c), (*, b, *), (*, b, c), (a, *, *), (a, *, c), (a, b, *), (a, b, c)&lt;br /&gt;
&lt;br /&gt;
This question can also be asked as print all subsets of a given set.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Answer:&lt;/b&gt;&lt;br /&gt;
This looks that a character in the tuple can either be &#39;*&#39;&#39; or itself. So we simply need to choose one character at a time, print combination on remaining substring and add them with &#39;*&#39; and earlier chosen character.&lt;br /&gt;
&lt;br /&gt;
If we notice, it will be like below in reality:&lt;br /&gt;
&lt;span id=&quot;goog_237499636&quot;&gt;&lt;/span&gt;&lt;span id=&quot;goog_237499637&quot;&gt;&lt;/span&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/AVvXsEgkCHi_r0kuqebrtToDJpAt9PYkdpe4Dsebb_pwf2XfcV0I6pMHTHwgDontnlGh-xKjZzjJcFGeaELgXxRe_uvkMGhpxxOJG6DSOPURrXB65lPZe4eY8Pgbwv63yLkDNjUYgku5wBngrtM/s1600/pattern.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;210&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkCHi_r0kuqebrtToDJpAt9PYkdpe4Dsebb_pwf2XfcV0I6pMHTHwgDontnlGh-xKjZzjJcFGeaELgXxRe_uvkMGhpxxOJG6DSOPURrXB65lPZe4eY8Pgbwv63yLkDNjUYgku5wBngrtM/s400/pattern.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
This can be simply achieved by recursion. We just need to identify correct boundary conditions. Below is the code for the same. In this code, I have taken string in place of tuple but the logic stays same.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;ruby&quot; name=&quot;code&quot;&gt;def pattern(prefix, input, len)
  # boundary condition
  if (prefix.length == len)
    puts prefix
    return
  end
 
  pattern(prefix+input[0], input[1..-1], len)
  pattern(prefix+&#39;*&#39;, input[1..-1], len)
end

# for test, I took only abc, you can take the input as argument
input = &quot;abc&quot;
pattern(&quot;&quot;, input, input.length)
&lt;/pre&gt;
&lt;br /&gt;</description><link>http://tech-queries.blogspot.com/2015/08/print-all-tuple-combinations-for-given.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkCHi_r0kuqebrtToDJpAt9PYkdpe4Dsebb_pwf2XfcV0I6pMHTHwgDontnlGh-xKjZzjJcFGeaELgXxRe_uvkMGhpxxOJG6DSOPURrXB65lPZe4eY8Pgbwv63yLkDNjUYgku5wBngrtM/s72-c/pattern.png" height="72" width="72"/><thr:total>20</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-1264951110071328605</guid><pubDate>Mon, 28 Apr 2014 15:07:00 +0000</pubDate><atom:updated>2014-04-28T20:41:36.609+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Dynamic programming</category><title>Max price by selling pieces of a rod</title><description>&lt;b&gt;Question:&lt;/b&gt; You are given a rod of length &#39;L&#39; and an array of prices where price at each index is the price obtained by selling rod of length equal to that index. You need to find the maximum price, you can get by selling pieces of rod.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Note:&lt;/b&gt; Rod can be sold in as many pieces of integer length as you want. You may also sell the rod as a whole if that gets you maximum price.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example:&lt;/b&gt; Lets say, there is rod of length 8 units with price array given below:&lt;br /&gt;
&lt;br /&gt;
[0, 3, 7, 8, 9, 12, 13, 19, 20]&lt;br /&gt;
&lt;br /&gt;
We have put 0 at 0th index to show price of length 0.&lt;br /&gt;
&lt;br /&gt;
For this particular example, maximum selling price will be 28 by cutting the rod in 4 pieces of length 2.&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/AVvXsEgAP2Cm9vgVJ8V1NiHbLhF3cdkDJW1kzaEBMQpZPemuINi5a-mNO2qTCDvvxICkt59o1HFb3SZvjSnNtQ76_p1VeUXyfwW_RhMlZEvOn48Hh-p_TdLvxXCEZ2tYhgmOlsUveqazZ9XVqCM/s1600/Screen+Shot+2014-04-28+at+8.03.23+PM.png&quot; imageanchor=&quot;1&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/AVvXsEgAP2Cm9vgVJ8V1NiHbLhF3cdkDJW1kzaEBMQpZPemuINi5a-mNO2qTCDvvxICkt59o1HFb3SZvjSnNtQ76_p1VeUXyfwW_RhMlZEvOn48Hh-p_TdLvxXCEZ2tYhgmOlsUveqazZ9XVqCM/s320/Screen+Shot+2014-04-28+at+8.03.23+PM.png&quot; height=&quot;106&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;b&gt;Answer:&lt;/b&gt; How will you approach this problem?&lt;br /&gt;
&lt;br /&gt;
Since we can cut the rod in pieces of any integer length, then we can start by thinking in a top-down fashion. First we will cut the rod in 2 pieces, which have maximum price of themselves. The cut should be in such a position that addition of prices for these 2 pieces obtain maximum selling price. Now we have to find the maximum prices of these 2 pieces by taking a piece at a time.&lt;br /&gt;
&lt;br /&gt;
In this process, these 2 pieces can be of length L (original length of rod) and ZERO as well. Now we will repeat the process for these 2 pieces as well recursively until we get pieces of length 1 or ZERO.&lt;br /&gt;
&lt;br /&gt;
&lt;blockquote&gt;
find_maximum_price(L) = MAX(&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; for x in 0..L&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; find_maximum_price(x) + find_maximum_price(L-x)&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; )&lt;/blockquote&gt;
&lt;br /&gt;
But if we notice, there will be a lot of similar problem in order to solve all the problems for different length pieces of the rod. If we go bottom up, solve smaller problems first and save results for them, we can avoid solving same problem again and again. As many of you may get it by now, this is simple &lt;a href=&quot;http://tech-queries.blogspot.in/search/label/Dynamic%20programming&quot; target=&quot;_blank&quot;&gt;Dynamic Programming&lt;/a&gt; problem now. Where you solve for smaller problems, memoize results and solve actual problem using these results.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Code:&lt;/b&gt;&lt;br /&gt;
Below is the ruby code for the same. The logic is very simple. First iterate the rod length from 0 to L and save maximum selling price for each sub part in the result array. Once your result array is filled, return value for of result array for length L.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;ruby&quot; name=&quot;code&quot;&gt;# @param [Array&amp;lt;Fixnum&amp;gt;] price Price array for rod
# @return [Fixnum] maximum selling price
def find_maximum_price(price)
  # initialize result array as 0 for price of rod length 0
  maxprice = [0]

  for i in 1..(price.length-1)
      maxprice[i] = price[i]
    for j in 0..i
      p = maxprice[j] + maxprice[i-j]
      if p &amp;gt; maxprice[i]
        maxprice[i] = p
      end
    end
  end
  return maxprice[-1] # return maxprice for length L
end

price = [0, 3, 7, 8, 9, 12, 17, 17, 20]  # input price array
puts &quot;maximum price obtained = #{find_maximum_price(price)}&quot;&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;Complexity: &lt;/b&gt;As we can see there are 2 loops, outer loop from 0 to L and intter from 0 to outer-loop-index. So the run time complexity is O(n&lt;sup&gt;2&lt;/sup&gt;).&lt;br /&gt;
&lt;br /&gt;
We can also find the length of rod pieces to obtain maximum selling price. I am leaving that part to readers.&lt;br /&gt;
&lt;br /&gt;</description><link>http://tech-queries.blogspot.com/2014/04/max-price-by-selling-pieces-of-rod.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgAP2Cm9vgVJ8V1NiHbLhF3cdkDJW1kzaEBMQpZPemuINi5a-mNO2qTCDvvxICkt59o1HFb3SZvjSnNtQ76_p1VeUXyfwW_RhMlZEvOn48Hh-p_TdLvxXCEZ2tYhgmOlsUveqazZ9XVqCM/s72-c/Screen+Shot+2014-04-28+at+8.03.23+PM.png" height="72" width="72"/><thr:total>15</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-7859491863284557567</guid><pubDate>Wed, 23 Apr 2014 13:23:00 +0000</pubDate><atom:updated>2014-04-28T20:39:28.290+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Brain Teasers</category><category domain="http://www.blogger.com/atom/ns#">Dynamic programming</category><title>2 Egg Puzzle</title><description>&lt;b&gt;Question:&lt;/b&gt; You are given 2 identical eggs such that eggs always break if dropped from floors above a particular floor of a 100-storey building. You need to find that particular floor in minimum number of egg droppings.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Answer:&lt;/b&gt; What would be the minimum number of drops in worst case if we have only one egg. We have to drop the egg from every floor starting from 1st floor up to 100&lt;sup&gt;th&lt;/sup&gt;. So in worst case scenario, number of droppings will be 100.&lt;br /&gt;
&lt;br /&gt;
And What would be the minimum number of drops in worst case if we have infinite supply of eggs. In that case, we can follow a binary search approach; drop from 50&lt;sup&gt;th&lt;/sup&gt; floor, if broken drop from 25&lt;sup&gt;th&lt;/sup&gt; else from 75&lt;sup&gt;th&lt;/sup&gt; and so on. So in this case, minimum number of drops will be 7 (log&lt;sub&gt;2&lt;/sub&gt;100) in worst case.&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/AVvXsEhKLtp1_3Mqa8GbwGEYfc7i0CwzmAQAXlq5kwUXB-6XW5HpDOM5WPSSU6f-0ajir-dUpBW90gwySmGu-DjcUS_J4ocrLASksDTdU7tmgKD2j18ZGwjlkera_4LqAuPDrfPp-qQKNavK1qE/s1600/egg.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: right; float: right; margin-bottom: 1em; margin-left: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhKLtp1_3Mqa8GbwGEYfc7i0CwzmAQAXlq5kwUXB-6XW5HpDOM5WPSSU6f-0ajir-dUpBW90gwySmGu-DjcUS_J4ocrLASksDTdU7tmgKD2j18ZGwjlkera_4LqAuPDrfPp-qQKNavK1qE/s1600/egg.png&quot; height=&quot;400&quot; width=&quot;273&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
Coming back to original problem of 2 eggs, we need to divide the floors in some blocks but will that be optimal. For example, if we divide building in 10 floor groups, drop from 10&lt;sup&gt;th&lt;/sup&gt; floor; if egg doesn&#39;t break then drop from 20&lt;sup&gt;th&lt;/sup&gt; else start from 1 to 9. Now if the egg breaks from 20&lt;sup&gt;th&lt;/sup&gt; floor, we need to check only for floors 11&lt;sup&gt;th&lt;/sup&gt; to 19&lt;sup&gt;th&lt;/sup&gt;. In worst case, there will be 19 drops for floor number 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 91, 92, 93, 94, 95, 96, 97, 98, 99.&lt;br /&gt;
&lt;br /&gt;
If we want optimal results, we should divide the building such that for every additional drop, remaining max drop decreases by 1. If our starting floor for first egg is &#39;k&#39;, there are 2 cases:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;The egg breaks:&amp;nbsp;&lt;/b&gt;&amp;nbsp;In this case, total number of drops will be 1 + (k-1) i.e. &amp;nbsp;k as we have to drop from each floor from 1 to (k-1).&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;The egg doesn&#39;t break:&lt;/b&gt; In this case, we are remaining with (100-k) floors and for optimal performance, max number of drops should be k. Also we verified that the egg doesn&#39;t break till k floors, so we need to check floors (k+1) to 100. If we choose i&lt;sup&gt;th&lt;/sup&gt; floor for 2nd drop of first egg again and egg breaks here, then max droppings needed = 1 + (i-k) (1 for k&lt;sup&gt;th&lt;/sup&gt; floor in first attempt and (i-k) for (k+1)&lt;sup&gt;st&lt;/sup&gt; to i&lt;sup&gt;th&lt;/sup&gt; floor)&lt;br /&gt;
&lt;br /&gt;
As we have discussed it should be equal to k.&lt;br /&gt;
&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
k = 1 + (i-k)&lt;br /&gt;
i = 2k - 1&lt;/blockquote&gt;
&lt;br /&gt;
This means i&lt;sup&gt;th&lt;/sup&gt; floor is (k-1) floors above kth. So this tell us that every time, we need to go up by (f-1) floors, where f is floors went up in last drop.&lt;br /&gt;
&lt;br /&gt;
This means that for minimum droppings, egg should be dropped after k floors, then (k-1) floors, then (k-2) floors and so on. The sum of this series should equal 100 and last entry in this series should be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
&amp;nbsp; k + (k-1) + (k-2) ... + 1 = 100&lt;br /&gt;
&amp;nbsp; k(k+1)/2 = 100&lt;br /&gt;
&amp;nbsp; k2 + k - 200 = 0;&lt;br /&gt;
&amp;nbsp; k2 + k + (0.5)2 = 200 + (0.5)2&lt;br /&gt;
&amp;nbsp; (k + 0.5)2 = 200.25&lt;br /&gt;
&amp;nbsp; k = 200.25 1/2 - 0.5&lt;br /&gt;
&amp;nbsp; k = 13.65&lt;/blockquote&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/AVvXsEjo73sRiEmt4ugQqrFu8jbiFjp_gJoFpdjRjFEmBl7lnh8zyjbZEtp0AYmNWS7nn0C-sqTbn8KOR8TPIkUg7GcHUd7MpEywZb7oJT7Ues5LmeWdQoIoqvmVOQigvKHtkggpqhzLfHlQO3Y/s1600/2_eggs.png&quot; imageanchor=&quot;1&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/AVvXsEjo73sRiEmt4ugQqrFu8jbiFjp_gJoFpdjRjFEmBl7lnh8zyjbZEtp0AYmNWS7nn0C-sqTbn8KOR8TPIkUg7GcHUd7MpEywZb7oJT7Ues5LmeWdQoIoqvmVOQigvKHtkggpqhzLfHlQO3Y/s1600/2_eggs.png&quot; height=&quot;128&quot; width=&quot;200&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
Since floor can not be in fraction, we need our first drop from 14t&lt;sup&gt;th&lt;/sup&gt;floor then from (14 + 13 =) 27&lt;sup&gt;th&lt;/sup&gt;, then (27 + 12 =) 39&lt;sup&gt;th&lt;/sup&gt; and so on. Also for 2 eggs, &lt;b&gt;maximum number of droppings will be 14&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;How to solve for generalized case?&lt;/b&gt;&lt;br /&gt;
We can see that if we drop an egg form k&lt;sup&gt;th&lt;/sup&gt; floor, there are 2 possibilities:&lt;br /&gt;
&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
&lt;u&gt;&lt;i&gt;egg breaks:&lt;/i&gt;&lt;/u&gt; then we have (k-1) floors and 1 less egg.&lt;br /&gt;
&lt;u&gt;&lt;i&gt;egg doesn&#39;t break:&lt;/i&gt;&lt;/u&gt; then we have (100-k) floors and same number of eggs.&lt;/blockquote&gt;
&lt;br /&gt;
We can apply this logic to any number of building and any number of floors.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Code:&lt;/b&gt;&lt;br /&gt;
A recursive solution is quite easy. If maxdrop(f, e) implies maximum drops with &#39;e&#39; eggs for a &#39;f&#39; floor building then:&lt;br /&gt;
&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
maxdrop(F, E) = for k from 1..F minimum of&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; 1 + MAX(&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;maxdrop(F-k, E), &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; //if egg doesn&#39;t break&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;maxdrop(k-1, E-1) &amp;nbsp; &amp;nbsp; &amp;nbsp; // if egg breaks&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; )&lt;/blockquote&gt;
&lt;br /&gt;
but there will be many redundant calls while calculating this. So lets go for a &lt;a href=&quot;http://tech-queries.blogspot.in/search/label/Dynamic%20programming&quot; target=&quot;_blank&quot;&gt;dynamic programing&lt;/a&gt; approach and save previously calculated maxdrop(f, e).&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;ruby&quot; name=&quot;code&quot;&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

#define max(a,b) (a&amp;gt;b?a:b)

int min_num_drops(int num_floors, int num_eggs)
{
  int min_throws[num_floors+1][num_eggs+1];
  int f, e, i;
  if (num_eggs == 1)
    return num_floors;
  
  for(i=0; i&amp;lt;num_floors+1; i++){
    min_throws[i][1] = i;
    min_throws[i][0] = 0;
    }
    
  for(i=0; i&amp;lt;num_eggs+1; i++)
  {
    min_throws[0][i] = 0;
    min_throws[1][i] = 1;
  }
  
  for(e=2; e&amp;lt;=num_eggs; e++)
  {
    for(f=2; f&amp;lt;=num_floors; f++)
    {
      min_throws[f][e] = INT_MAX;
      for(i=1; i&amp;lt;=f; i++)
      {
        int drops = 1 + max(min_throws[i-1][e-1], min_throws[f-i][e]);
        if(drops &amp;lt; min_throws[f][e])
          min_throws[f][e] = drops;
      }
    }
  }
  
  return min_throws[num_floors][num_eggs];
}

int main()
{
  int num_floors, num_eggs;
  cout &amp;lt;&amp;lt; &quot;Enter number of floors: &quot;;
  cin &amp;gt;&amp;gt; num_floors;
  cout &amp;lt;&amp;lt; &quot;Enter number of eggs: &quot;;
  cin &amp;gt;&amp;gt; num_eggs;
  cout &amp;lt;&amp;lt; &quot;minimum number of drops: &quot; &amp;lt;&amp;lt; min_num_drops(num_floors, num_eggs) &amp;lt;&amp;lt; endl;
}
&lt;/pre&gt;
</description><link>http://tech-queries.blogspot.com/2014/04/question-you-are-given-2-identical-eggs.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhKLtp1_3Mqa8GbwGEYfc7i0CwzmAQAXlq5kwUXB-6XW5HpDOM5WPSSU6f-0ajir-dUpBW90gwySmGu-DjcUS_J4ocrLASksDTdU7tmgKD2j18ZGwjlkera_4LqAuPDrfPp-qQKNavK1qE/s72-c/egg.png" height="72" width="72"/><thr:total>16</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-8362313461601564214</guid><pubDate>Tue, 15 Apr 2014 10:59:00 +0000</pubDate><atom:updated>2014-04-16T12:22:01.217+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">backtracking</category><title>[Backtracking] place N queens on NxN chess board</title><description>&lt;b&gt;Question:&lt;/b&gt; &lt;a href=&quot;http://en.wikipedia.org/wiki/Eight_queens_puzzle&quot; target=&quot;_blank&quot;&gt;N queen problem&lt;/a&gt; is a very famous problem in computer science. This problem ask user to place N chess queens on a NxN chessboard so that no two queens attack each other.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Answer:&lt;/b&gt; As the queen can move in any of the eight directions and any number of steps in a single move, there are few solutions, which fit the bill. For N=8, there are 92 distinct solutions. And if solutions that differ only by symmetry operations (rotations and reflections) of the board are counted as one, the puzzle has only 12 solutions.&lt;br /&gt;
&lt;br /&gt;
Lets assume that we already have some queens placed on the chess board so that no queen can attack each other. Now if we need to place another queen on the board, how will we go about it? Please note that a queen is safe if:&lt;br /&gt;
&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;There is no queen in same row.&lt;/li&gt;
&lt;li&gt;There is no queen in same column.&lt;/li&gt;
&lt;li&gt;There is no queen in diagonal paths going from that queen.&lt;/li&gt;
&lt;/ol&gt;
&lt;br /&gt;
&lt;br /&gt;
Lets say that there are 2 queens at position (i, j) and (x, y). By above theory, that are NOT safe if:&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
&lt;ul&gt;
&lt;li&gt;i = x &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; same row&lt;/li&gt;
&lt;li&gt;j = y &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; same row&lt;/li&gt;
&lt;li&gt;|i-x| = |j-y| &amp;nbsp; same diagonal paths&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;br /&gt;
We can simply avoid the first constraint by placing each queen in different rows. So lets put 1st queen in 1st row, 2nd queen in 2nd row and so on. Now we need to check for same column and same diagonal. Lets have an array &#39;pos[]&#39; of size N showing where pos[i] is column for i&lt;sup&gt;th&lt;/sup&gt; queen. Now if (k-1) queens are already placed in first (k-1) rows and we need to place k&lt;sup&gt;th&lt;/sup&gt; queen in k&lt;sup&gt;th&lt;/sup&gt; row then we need to check its column and diagonals with all previously placed (k-1) queens.&lt;br /&gt;
&lt;br /&gt;
If we find no place for k&lt;sup&gt;th&lt;/sup&gt; queen in k&lt;sup&gt;th&lt;/sup&gt; row because of placement of earlier queens, we will go back to (k-1)&lt;sup&gt;th&lt;/sup&gt; queen and place it in a different column. Then we try again to place k&lt;sup&gt;th&lt;/sup&gt; queen. If we still have problem in placing k&lt;sup&gt;th&lt;/sup&gt; queen, we will go back to (k-1)&lt;sup&gt;th&lt;/sup&gt; queen and try another safe position for it. This process will be repeated till we try all the possible position for (k-1)&lt;sup&gt;th&lt;/sup&gt; queen. If there is no safe position to place (k-1)&amp;nbsp;and k&lt;sup&gt;th&lt;/sup&gt; queen, we will go 2 step back and find alternate safe column for (k-2)&lt;sup&gt;th&lt;/sup&gt; queen.&lt;br /&gt;
&lt;br /&gt;
This process will be repeated till 1&lt;sup&gt;st&lt;/sup&gt; queen until we don&#39;t find a solution. Since we are going back and finding alternate safe place, this kind of algorithmic approach is called &lt;a href=&quot;http://en.wikipedia.org/wiki/Backtracking&quot; target=&quot;_blank&quot;&gt;backtracking&lt;/a&gt;. Below is an animated figure for the same. (source: Wikipedia)&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/AVvXsEhFRLhvgRVdDjpxnsXsdsNtbAnpESw9NNFTO02JHueQWgIOQPZTYZXq8r-fP0ztIc0Saqc8tNRRkF5CnttTt5eDt19ytTOPObUMCmuN9Wv75WSnoMgu-BxkSHcFTVffTbcnJfDpK10H5Jo/s1600/Eight-queens-animation.gif&quot; imageanchor=&quot;1&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/AVvXsEhFRLhvgRVdDjpxnsXsdsNtbAnpESw9NNFTO02JHueQWgIOQPZTYZXq8r-fP0ztIc0Saqc8tNRRkF5CnttTt5eDt19ytTOPObUMCmuN9Wv75WSnoMgu-BxkSHcFTVffTbcnJfDpK10H5Jo/s1600/Eight-queens-animation.gif&quot; height=&quot;320&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Below is the ruby implementation for the same:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;ruby&quot; name=&quot;code&quot;&gt;require &#39;pp&#39;

@pos = []

def print(size)
  for i in 0..size
    s = &quot;&quot;
    for j in 0..size
      if @pos[i] == j
        s &amp;lt;&amp;lt; &#39;Q &#39;
      else
        s &amp;lt;&amp;lt; &#39;_ &#39;
      end
    end
    puts s
  end
  # exit #remove this exit if u want to see all solutions
end

# check if putting a queen in (row, col) is safe
def is_safe(row, col)
  for i in 0..(row-1)
    if (col == @pos[i]) or ((row-i).abs == (col-@pos[i]).abs)
      return false
    end
  end
  return true
end

# place queen in row r
def nqueen(r, n)
  for i in 0..n
    if is_safe(r, i)
      @pos[r] = i
      if (r == n)
        print(n)
        puts &quot;&quot;
      else
        nqueen(r+1, n)
      end
    end
  end
end

if __FILE__ == $0
  if ARGV.length &amp;lt; 1
    puts &quot;Usage: ruby #{$0} size&quot;
    exit
  end
  size = ARGV[0].to_i-1
  if size &amp;lt; 3
    puts &quot;No solution possible&quot;
  else
    nqueen(0, size)
  end
end
&lt;/pre&gt;
</description><link>http://tech-queries.blogspot.com/2014/04/backtracking-place-n-chess-queens-on.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFRLhvgRVdDjpxnsXsdsNtbAnpESw9NNFTO02JHueQWgIOQPZTYZXq8r-fP0ztIc0Saqc8tNRRkF5CnttTt5eDt19ytTOPObUMCmuN9Wv75WSnoMgu-BxkSHcFTVffTbcnJfDpK10H5Jo/s72-c/Eight-queens-animation.gif" height="72" width="72"/><thr:total>9</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-4747552413277096862</guid><pubDate>Sat, 05 Apr 2014 13:22:00 +0000</pubDate><atom:updated>2014-04-15T20:59:54.126+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Arrays/Strings</category><title>Find the presence of a given word in a given grid</title><description>&lt;b&gt;Question:&lt;/b&gt; There is a 2D grid of characters. You need to find if a given word can be matched in any direction in the grid. The direction can be up-down, down-up, left-right, right-left, both diagonals up and down. This problem is also famous with the name &#39;&lt;a href=&quot;http://uva.onlinejudge.org/index.php?option=onlinejudge&amp;amp;page=show_problem&amp;amp;problem=951&quot; target=&quot;_blank&quot;&gt;Where&#39;s Waldorf&lt;/a&gt;?&#39;.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example:&lt;/b&gt; You are given a character grid like below. You need to find patterns &#39;Akash and &#39;coDe&#39; in this grid. They can appear in any direction. Also the search should be case insensitive.&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/AVvXsEg1yfgs5MdnNjqmETOo1fauPnmquXdlAAvUtGmt40zg9a_9oxEz-Bui5UCDumjEUlhyphenhyphenz5VxL8aCEonh8k7LMym2OBkgkO54rYYl-q9HpmS3HT9mcovVIa4_sDiVGcISlMtB1-dkvYk42z8/s1600/Screen+Shot+2014-04-05+at+5.56.08+PM.png&quot; imageanchor=&quot;1&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/AVvXsEg1yfgs5MdnNjqmETOo1fauPnmquXdlAAvUtGmt40zg9a_9oxEz-Bui5UCDumjEUlhyphenhyphenz5VxL8aCEonh8k7LMym2OBkgkO54rYYl-q9HpmS3HT9mcovVIa4_sDiVGcISlMtB1-dkvYk42z8/s1600/Screen+Shot+2014-04-05+at+5.56.08+PM.png&quot; height=&quot;200&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Below are the result of finding &#39;Akash and &#39;coDe&#39;.&lt;br /&gt;
&lt;br /&gt;
&lt;div&gt;
&lt;/div&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/AVvXsEhkhyphenhyphenxDr9vDXSpDXhP3TBgrKztCAjtbNL0Nkqiwl3MeXrMusyKRDD9Osx7rXRFy2EH9c8K_Kk4N_YhH3b8ttuKDOac99awT7IbLpH-wOYXiJJL1LkniL2V87XUqi9V6HLdD2WBNCRSxtHg/s1600/Screen+Shot+2014-04-05+at+5.58.56+PM.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em; text-align: justify;&quot;&gt;&lt;span style=&quot;color: white;&quot;&gt;&amp;nbsp;&lt;/span&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhkhyphenhyphenxDr9vDXSpDXhP3TBgrKztCAjtbNL0Nkqiwl3MeXrMusyKRDD9Osx7rXRFy2EH9c8K_Kk4N_YhH3b8ttuKDOac99awT7IbLpH-wOYXiJJL1LkniL2V87XUqi9V6HLdD2WBNCRSxtHg/s1600/Screen+Shot+2014-04-05+at+5.58.56+PM.png&quot; height=&quot;123&quot; width=&quot;200&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;
&amp;nbsp;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-_m3ktXEr-CcPLBW1zTGliZxlCa6qP0RBnFTiQzb9njdbPNqrivdZVrWZz6JMs4GMQ3Ru9kFB9myBODwPkwVwDiptLuRz3XYOxjEvipGFvp4HlMGYybbXFm09jQdRI39itrSvw4d2ABw/s1600/Screen+Shot+2014-04-05+at+5.59.06+PM.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em; text-align: center;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-_m3ktXEr-CcPLBW1zTGliZxlCa6qP0RBnFTiQzb9njdbPNqrivdZVrWZz6JMs4GMQ3Ru9kFB9myBODwPkwVwDiptLuRz3XYOxjEvipGFvp4HlMGYybbXFm09jQdRI39itrSvw4d2ABw/s1600/Screen+Shot+2014-04-05+at+5.59.06+PM.png&quot; height=&quot;125&quot; width=&quot;200&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Input:&lt;/b&gt; The input begins with a pair of integers, m followed by n, 1 &amp;lt; m,n &amp;lt; 50 in decimal notation on a single line. The next m lines contain n letters each; this is the grid of letters in which the words of the list must be found. After that another integer k appears on a line by itself (1 &amp;lt; k &amp;lt; 20). The next k lines of input contain the list of words to search for, one word per line to be found in the grid in case insensitive manner.&lt;br /&gt;
&lt;br /&gt;
For our example, sample input will be:&lt;br /&gt;
5 5&lt;br /&gt;
HQWCS&lt;br /&gt;
ESPKD&lt;br /&gt;
DXAFL&lt;br /&gt;
OCHKH&lt;br /&gt;
CTYCA&lt;br /&gt;
2&lt;br /&gt;
Akash&lt;br /&gt;
coDe&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Output:&lt;/b&gt;&lt;br /&gt;
For each word in the word list, a pair of integers representing the location of the corresponding word in the grid must be output.&lt;br /&gt;
&lt;br /&gt;
For our example, sample output will be:&lt;br /&gt;
5 5&lt;br /&gt;
5 1&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Algorithm:&lt;/b&gt;&lt;br /&gt;
This is a very straight forward problem. We first need to find the first character match of word (to be found) in the grid. One we find the start point, we need to go in all 8 directions till the end of word (or the grid). If we reach end of the word, print the starting coordinates and move on to next word.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Code (C++):&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;cpp&quot; name=&quot;code&quot;&gt;#include &amp;lt;iostream&amp;gt;

using namespace std;
#define N 50

// We can search is all 8 directions
char DIR[8][2] = {
  {1,0}, {1,-1}, {1,1}, {0,-1}, {0,1}, {-1,0}, {-1,-1}, {-1,1}
};
// for toal array size
int m, n;

// method for finding word presence in the array in a specific direction
bool match(char CharMat[50][50], char word[], int i, int j, int dir_index)
{
  int k=0;
  for( ; i&amp;lt;m  &amp;amp;&amp;amp; j&amp;lt;n  &amp;amp;&amp;amp; i&amp;gt;=0  &amp;amp;&amp;amp; j &amp;gt;=0  &amp;amp;&amp;amp; word[k] != &#39;\0&#39;; i = i+DIR[dir_index][0],  j = j+DIR[dir_index][1], k++)
    if(toupper(word[k]) != toupper(CharMat[i][j]))
      return false;

  if (word[k] == &#39;\0&#39;)
    return true;

  return false;  
}

void find_presence(char CharMat[50][50], char word[])
{
  for(int i=0; i&amp;lt;m; i++)
    for(int j=0; j&amp;lt;n; j++)
      if (toupper(CharMat[i][j]) == toupper(word[0]))
        for (int k=0; k&amp;lt;8; k++)
          if (match(CharMat, word, i, j, k))
          {
            cout &amp;lt;&amp;lt; i+1 &amp;lt;&amp;lt; &quot; &quot; &amp;lt;&amp;lt; j+1 &amp;lt;&amp;lt; endl;
            return;
          }
  cout &amp;lt;&amp;lt; &quot;&#39;&quot; &amp;lt;&amp;lt; word &amp;lt;&amp;lt; &quot;&#39; was not found in the grid&quot; &amp;lt;&amp;lt; endl;
}

int main()
{
  char CharMat[N][N];
  cin &amp;gt;&amp;gt; m;
  cin &amp;gt;&amp;gt; n;
  for (int i=0; i&amp;lt;m; i++)
    cin &amp;gt;&amp;gt; CharMat[i];
  
  int num_words;
  char word[N];
  cin &amp;gt;&amp;gt; num_words;
  for (int j=0; j&amp;lt;num_words; j++)
  {
    cin &amp;gt;&amp;gt; word;
    find_presence(CharMat, word);
  }
}
&lt;/pre&gt;
</description><link>http://tech-queries.blogspot.com/2014/04/find-presence-of-given-word-in-given.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1yfgs5MdnNjqmETOo1fauPnmquXdlAAvUtGmt40zg9a_9oxEz-Bui5UCDumjEUlhyphenhyphenz5VxL8aCEonh8k7LMym2OBkgkO54rYYl-q9HpmS3HT9mcovVIa4_sDiVGcISlMtB1-dkvYk42z8/s72-c/Screen+Shot+2014-04-05+at+5.56.08+PM.png" height="72" width="72"/><thr:total>11</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-4081598656390999231</guid><pubDate>Fri, 21 Mar 2014 10:40:00 +0000</pubDate><atom:updated>2014-03-21T16:10:14.818+05:30</atom:updated><title>Checking your Ubuntu Version</title><description>To find out Ubuntu version you are running, you can run a short command in the Terminal. 

&lt;br /&gt;
&lt;blockquote&gt;
lsb_release -a&lt;/blockquote&gt;
You will get detailed information about your Linux distribution here. There is a &#39;Release&#39; field in the out, which have the version of Ubuntu, you are running.&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/AVvXsEheBv6HdMd9wwt9jqfN-Ftekh-x0Wr9oKf09RHmZn2Ryrt0Hzf8k2wVCiDFElg4bNXrmx5T3ZNdsdHbJBs4Zo-yfb1nv0BkWJbbhGSnfJyoZBU2fnwcQrDwK1O7OY32FM_Hk2duM7uwl2E/s1600/Screen+Shot+2014-03-21+at+3.09.22+PM.png&quot; imageanchor=&quot;1&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/AVvXsEheBv6HdMd9wwt9jqfN-Ftekh-x0Wr9oKf09RHmZn2Ryrt0Hzf8k2wVCiDFElg4bNXrmx5T3ZNdsdHbJBs4Zo-yfb1nv0BkWJbbhGSnfJyoZBU2fnwcQrDwK1O7OY32FM_Hk2duM7uwl2E/s320/Screen+Shot+2014-03-21+at+3.09.22+PM.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&#39;lsb_release&#39; command prints distribution-specific information. Here are other option you can use with this command:

&lt;br /&gt;
&lt;br /&gt;
Usage: lsb_release [options]&lt;br /&gt;
&lt;br /&gt;
Options:&lt;br /&gt;
&amp;nbsp; -h, --help &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; show this help message and exit&lt;br /&gt;
&amp;nbsp; -v, --version&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; &amp;nbsp; show LSB modules this system supports&lt;br /&gt;
&amp;nbsp; -i, --id &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;show distributor ID&lt;br /&gt;
&amp;nbsp; -d, --description &amp;nbsp; &amp;nbsp; &amp;nbsp; show description of this distribution&lt;br /&gt;
&amp;nbsp; -r, --release &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;show release number of this distribution&lt;br /&gt;
&amp;nbsp; -c, --codename &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;show code name of this distribution&lt;br /&gt;
&amp;nbsp; -a, --all &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; show all of the above information&lt;br /&gt;
&amp;nbsp; -s, --short &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; show requested information in short format&lt;br /&gt;
&lt;br /&gt;</description><link>http://tech-queries.blogspot.com/2014/03/checking-your-ubuntu-version.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEheBv6HdMd9wwt9jqfN-Ftekh-x0Wr9oKf09RHmZn2Ryrt0Hzf8k2wVCiDFElg4bNXrmx5T3ZNdsdHbJBs4Zo-yfb1nv0BkWJbbhGSnfJyoZBU2fnwcQrDwK1O7OY32FM_Hk2duM7uwl2E/s72-c/Screen+Shot+2014-03-21+at+3.09.22+PM.png" height="72" width="72"/><thr:total>30</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-2388669918220393086</guid><pubDate>Sat, 08 Sep 2012 19:21:00 +0000</pubDate><atom:updated>2012-09-09T01:01:25.817+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Architecture</category><category domain="http://www.blogger.com/atom/ns#">web development</category><title>Is Quora wasting too many ajax calls to implement its live search feature?</title><description>&lt;br /&gt;
&lt;span style=&quot;color: #333333; font-family: Helvetica Neue, Arial, sans-serif;&quot;&gt;&lt;span style=&quot;font-size: 15px;&quot;&gt;I love &lt;a href=&quot;http://www.quora.com/&quot;&gt;Quora&lt;/a&gt; as a product. This is a Q&amp;amp;A site where each&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15px;&quot;&gt;question or answer is&lt;/span&gt;&lt;span style=&quot;color: #333333; font-family: Helvetica Neue, Arial, sans-serif;&quot;&gt;&lt;span style=&quot;font-size: 15px;&quot;&gt;&amp;nbsp;created, edited, and organized by everyone who uses it. Quora has a live search box in its top navigation bar. This box is it&#39;s single point of interaction with user input: for searching a question, for asking a question etc. You start getting&amp;nbsp;suggestions&amp;nbsp;as soon as you start typing in this box.&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;I was looking into Quora&#39;s live search feature and found something unusual. I noticed that as soon as I put my cursor in the search box on top navigation bar, browser starts sending search ajax calls to quora servers. It also sends ajax calls too frequently for a live search feature.&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px; margin: 0px; padding: 0px; text-align: center;&quot;&gt;
&lt;img class=&quot;qtext_image zoomable_in zoomable_in_feed&quot; master_h=&quot;651&quot; master_src=&quot;http://qph.cf.quoracdn.net/main-qimg-34163e7599bc7bad3b7bba83a9a42876&quot; master_w=&quot;1042&quot; src=&quot;http://qph.cf.quoracdn.net/main-qimg-929e2ca9b870a5fff9e58809fe9d4fec&quot; style=&quot;border: 0px; display: inline; margin: 3px 0px 2px; max-width: 100%; padding: 0px;&quot; /&gt;&lt;/div&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;&lt;span style=&quot;font-size: 15.454545021057129px;&quot;&gt;(Quora search calls)&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;&lt;span style=&quot;font-size: 15.454545021057129px;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;
&lt;/span&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;After noticing above stuff from Quora, I decided to compare&amp;nbsp;&lt;/span&gt;&lt;span class=&quot;qlink_container&quot; style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px; margin: 0px; padding: 0px;&quot;&gt;&lt;a href=&quot;http://www.quora.com/Quora&quot; routing=&quot;q://topic/(787)&quot; style=&quot;color: #19558d; margin: 0px; padding: 0px; text-decoration: none;&quot;&gt;Quora&lt;/a&gt;&amp;nbsp;&lt;/span&gt;&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;and&amp;nbsp;&lt;/span&gt;&lt;span class=&quot;qlink_container&quot; style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px; margin: 0px; padding: 0px;&quot;&gt;&lt;a href=&quot;http://www.quora.com/StackOverflow&quot; routing=&quot;q://topic/(7092)&quot; style=&quot;color: #19558d; margin: 0px; padding: 0px; text-decoration: none;&quot;&gt;StackOverflow&lt;/a&gt;&lt;/span&gt;&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;&amp;nbsp;live search feature. Results are given below. For the same text in a question (assuming same typing speed), &lt;/span&gt;&lt;b style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px; margin: 0px; padding: 0px;&quot;&gt;Stackoverflow sent 6 calls to their servers while Quora sent 29 ajax calls to their servers.&lt;/b&gt;&lt;br /&gt;
&lt;br style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px; margin: 0px; padding: 0px;&quot; /&gt;
&lt;div style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px; margin: 0px; padding: 0px; text-align: center;&quot;&gt;
&lt;img class=&quot;qtext_image zoomable_in zoomable_in_feed&quot; master_h=&quot;900&quot; master_src=&quot;http://qph.cf.quoracdn.net/main-qimg-48ecf5fe2b99d40baa906431a72d6c71&quot; master_w=&quot;1440&quot; src=&quot;http://qph.cf.quoracdn.net/main-qimg-6ce19c74f9c285a8a5d2e4ef05f4637e&quot; style=&quot;border: 0px; cursor: -webkit-zoom-in; display: inline; margin: 3px 0px 2px; max-width: 100%; padding: 0px;&quot; /&gt;&lt;/div&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;&lt;span style=&quot;font-size: 15.454545021057129px;&quot;&gt;(stackoverflow search calls)&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;
&lt;/span&gt;
&lt;br /&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px; margin: 0px; padding: 0px; text-align: center;&quot;&gt;
&lt;img class=&quot;qtext_image zoomable_in zoomable_in_feed&quot; master_h=&quot;900&quot; master_src=&quot;http://qph.cf.quoracdn.net/main-qimg-73c0183fa242989d0ad653f4421d19a9&quot; master_w=&quot;1440&quot; src=&quot;http://qph.cf.quoracdn.net/main-qimg-b36c089e5712b245aa08543cf91b6389&quot; style=&quot;border: 0px; cursor: -webkit-zoom-in; display: inline; margin: 3px 0px 2px; max-width: 100%; padding: 0px;&quot; /&gt;&lt;/div&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;&lt;span style=&quot;font-size: 15.454545021057129px;&quot;&gt;(Quora search calls)&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;&lt;span style=&quot;font-size: 15.454545021057129px;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;
&lt;/span&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;On studying further, I found that stackoverflow waits for a minimum number of characters before showing any result but that&#39;s not true in case of quora. Quora sent ajax calls as soon as I put my cursor in search box. This means that Quora send an ajax call for blank search box also.&lt;/span&gt;&lt;br /&gt;
&lt;br style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px; margin: 0px; padding: 0px;&quot; /&gt;
&lt;div style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px; margin: 0px; padding: 0px; text-align: center;&quot;&gt;
&lt;img class=&quot;qtext_image zoomable_in zoomable_in_feed&quot; master_h=&quot;397&quot; master_src=&quot;http://qph.cf.quoracdn.net/main-qimg-a1d3903f4a32aef39bed78b92a3f5234&quot; master_w=&quot;1217&quot; src=&quot;http://qph.cf.quoracdn.net/main-qimg-4ceab5c39f97b3e5c0f48a241a7cfe53&quot; style=&quot;border: 0px; cursor: -webkit-zoom-in; display: inline; margin: 3px 0px 2px; max-width: 100%; padding: 0px;&quot; /&gt;&lt;/div&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;&lt;span style=&quot;font-size: 15.454545021057129px;&quot;&gt;(an ajax call for blank search box)&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;
&lt;/span&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;My concerns are:&lt;/span&gt;&lt;br /&gt;
&lt;ol style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px; margin: 5px 0px 0px 1.6em; padding: 0px;&quot;&gt;
&lt;li style=&quot;margin: 0px; padding: 0px;&quot;&gt;Can Quora better their frequency of ajax calls for search?&lt;/li&gt;
&lt;li style=&quot;margin: 0px; padding: 0px;&quot;&gt;Why should user pay for unnecessary bandwidth in this case (even if it is few bytes)?&lt;/li&gt;
&lt;li style=&quot;margin: 0px; padding: 0px;&quot;&gt;What is the use of search with insignificant number of characters in search box? Does it gives any relevant results in that case.&amp;nbsp;&lt;i style=&quot;margin: 0px; padding: 0px;&quot;&gt;For example:&amp;nbsp;&lt;/i&gt;try typing &quot;&lt;b style=&quot;margin: 0px; padding: 0px;&quot;&gt;what&lt;/b&gt;&quot; in search box.&lt;/li&gt;
&lt;/ol&gt;
&lt;br style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px; margin: 0px; padding: 0px;&quot; /&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;Had Quora search results been personal, this feature might be much more benefitial but I don&#39;t think that we need this much speed for sending ajax calls.&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif;&quot;&gt;&lt;span style=&quot;font-size: 15.454545021057129px;&quot;&gt;&lt;b&gt;PS:&lt;/b&gt; I have &lt;a href=&quot;http://www.quora.com/Quora-Infrastructure/Is-Quora-wasting-too-many-ajax-calls-to-implement-its-live-search-feature&quot;&gt;posted a same question on Quora&lt;/a&gt; and am&amp;nbsp;&lt;/span&gt;&lt;span style=&quot;font-size: 15px;&quot;&gt;waiting&lt;/span&gt;&lt;span style=&quot;font-size: 15.454545021057129px;&quot;&gt;&amp;nbsp;for response on that.&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;span style=&quot;color: #333333; font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif; font-size: 15.454545021057129px;&quot;&gt;&lt;br /&gt;&lt;/span&gt;</description><link>http://tech-queries.blogspot.com/2012/09/is-quora-wasting-too-many-ajax-calls-to.html</link><author>noreply@blogger.com (Akash)</author><thr:total>10</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-7862835362617524385</guid><pubDate>Sat, 02 Jun 2012 18:20:00 +0000</pubDate><atom:updated>2012-06-03T00:16:05.435+05:30</atom:updated><title>How did identifying descriptive log file name save us?</title><description>&lt;br /&gt;
We had a task to batch process around 10 million old slideshows at Slideshare. These slideshows were being processed in parallel and we are supposed to maintain logs to debug if something fails during the process. Each slideshow has an id associated with it and these ids were ranged from 1 to 13 million. It means we have some deleted slideshows in between.&lt;br /&gt;
&lt;br /&gt;
Everything went fine when we were in early stage. We had processed from 1 to 100 thousand slideshows without any problem. When an engineer declared that first 1 million are done, we were happy that 1mn mark is reached much before anticipated time. While verification, we noticed that there were around 300 thousands slideshows, which were not processed. To add more problems, these slideshows were not in continuous range but divided almost equally between 100,000 and 1 mn.&lt;br /&gt;
&lt;br /&gt;
Irrespective of how good logs we captured, It was not easy to parse logs and make a list of unprocessed slideshows. To add more problems, we captured really detailed logs so it was a nightmare to parse logs. Also we learnt that these 3 lakh slideshows were missed and not failed and finding them in DB wasn’t a option.&lt;br /&gt;
&lt;br /&gt;
When we were writing this script, we did a good thing. We wrote script to ask start and end slideshow id as arguments and process slideshows between them. We created separate log file for each script instance (for each batch) and appended start and end slidehow_id in log file name. &lt;span style=&quot;background-color: yellow;&quot;&gt;Log filenames followed the nomenclature ‘batch_process_start#_end#.log’.&lt;/span&gt; This also gave us flexibility to run script paralelly for small batches.&lt;br /&gt;
&lt;br /&gt;
When we identified missing 3 lakh slideshows problem, we arranged log files in order of their start id. When we draw a sequence from start_id to end_id for each log file, we noticed some gaps between end_id of one batch and start_id of next batch. There were many batches for which we noticed this gap.&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/AVvXsEiWq_A2IDI7LFna_BQp80cT_iSF8O7hdyHnx40jzCdl-vlBnzhdKGfjDFxYKL4WdqQdE3OVIu9yIX6BK2kWGA7Qu1BBdKpELPS5p3qkIeQc3DvWytBameqxQOiAA-FFvQRnayb6iAFtpX8/s1600/Screen+Shot+2012-06-02+at+11.05.09+PM.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;147&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWq_A2IDI7LFna_BQp80cT_iSF8O7hdyHnx40jzCdl-vlBnzhdKGfjDFxYKL4WdqQdE3OVIu9yIX6BK2kWGA7Qu1BBdKpELPS5p3qkIeQc3DvWytBameqxQOiAA-FFvQRnayb6iAFtpX8/s640/Screen+Shot+2012-06-02+at+11.05.09+PM.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
Once we identified all the missing batches, we ran our script only for missing batches. After completion, when we rearranged log file as earlier, we saw no gaps between end_id of one batch and start_id of next batch. Also while verifying if all the data is processed, we find it was so.&lt;br /&gt;
&lt;br /&gt;
This particular naming convention saved us from parsing log files and identifying which files are missing. So not only identifying which logs are going to help, it helps how are you saving those logs.&lt;br /&gt;
&lt;br /&gt;</description><link>http://tech-queries.blogspot.com/2012/06/how-did-identifying-descriptive-log.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWq_A2IDI7LFna_BQp80cT_iSF8O7hdyHnx40jzCdl-vlBnzhdKGfjDFxYKL4WdqQdE3OVIu9yIX6BK2kWGA7Qu1BBdKpELPS5p3qkIeQc3DvWytBameqxQOiAA-FFvQRnayb6iAFtpX8/s72-c/Screen+Shot+2012-06-02+at+11.05.09+PM.png" height="72" width="72"/><thr:total>6</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-8468866565471965764</guid><pubDate>Tue, 20 Mar 2012 18:59:00 +0000</pubDate><atom:updated>2012-03-21T00:42:36.055+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">General</category><title>Catch a linux signal in a C program</title><description>&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSYOFsmWt3nGjtZrSXJpS56YaERmFSkhRbmx-yzNGZANgG0Jnu1tztEEKXR8HLEgDyJxaeVCBEniaCounmbaQFlKqKOQZ0IPz3iVdowrMqUASzRmpRB43ISh_5P-sBzGOfDlk7stw7Zl0/s1600/signal.jpg&quot;&gt;&lt;img style=&quot;float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 200px; height: 200px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSYOFsmWt3nGjtZrSXJpS56YaERmFSkhRbmx-yzNGZANgG0Jnu1tztEEKXR8HLEgDyJxaeVCBEniaCounmbaQFlKqKOQZ0IPz3iVdowrMqUASzRmpRB43ISh_5P-sBzGOfDlk7stw7Zl0/s200/signal.jpg&quot; border=&quot;0&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5722058887606121794&quot; /&gt;&lt;/a&gt;&lt;br /&gt;&lt;div&gt;Did you ever wonder what happens when an user hits ctrl-c? A SIGINT signal is generated and sent to the process running. This is the way to terminate programs from terminal.&lt;br /&gt;&lt;br /&gt;When the &lt;a href=&quot;http://en.wikipedia.org/wiki/Signal_(computing)#List_of_signals&quot; style=&quot;font-weight: normal; &quot;&gt;signal&lt;/a&gt; occurs, the process has to tell the kernel what to do with it. Your process can ignore signal, catch signal or let the default action apply. &lt;div&gt;&lt;br /&gt;&lt;blockquote&gt;&lt;b&gt;Note:&lt;/b&gt; SIGKILL and SIGSTOP cannot be ignored.&lt;/blockquote&gt;&lt;br /&gt;If a process wishes to handle a signal then in the code, the process has to register a signal handling function to the kernel. The following is the prototype of a signal handling function :&lt;br /&gt;&lt;br /&gt;&lt;blockquote style=&quot;font-weight: normal; &quot;&gt;void &amp;lt;signal handler function&amp;gt; (int sig)&lt;br /&gt;&lt;/blockquote&gt;&lt;br /&gt;You can specify in this function how you want to handle it.&lt;br /&gt;&lt;br /&gt;To invoke above function when a signal occurs, you need to register this function to kernal. To get the signal handler function registered to the kernel, the signal handler function pointer is passed as second argument to the ‘&lt;a href=&quot;http://www.cplusplus.com/reference/clibrary/csignal/signal/&quot; style=&quot;font-weight: normal; &quot;&gt;signal&lt;/a&gt;’ function. The prototype of the signal function is :&lt;br /&gt;&lt;br /&gt;&lt;blockquote style=&quot;font-weight: normal; &quot;&gt;void (*signal(int signo, void (*func )(int)))(int);&lt;br /&gt;&lt;/blockquote&gt;&lt;br /&gt;Where func is the signal handler function, we defined.&lt;br /&gt;&lt;br /&gt;Below is a program to handle SIGTERM signal. Run this program and send a SIGTERM signal to this to see what happens.&lt;br /&gt;&lt;br /&gt;&lt;pre name=&quot;code&quot; class=&quot;cpp&quot;&gt;#include&amp;lt;cstdio&amp;gt;&lt;br /&gt;#include&amp;lt;csignal&amp;gt;&lt;br /&gt;&lt;br /&gt;void sig_handler(int signo)&lt;br /&gt;{&lt;br /&gt; if (signo == SIGTERM)&lt;br /&gt;   printf(&quot;received SIGTERM\n&quot;);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main(void)&lt;br /&gt;{&lt;br /&gt; if (signal(SIGTERM, sig_handler) == SIG_ERR)&lt;br /&gt; printf(&quot;\ncan&#39;t catch SIGTERM\n&quot;);&lt;br /&gt; // wait so that we can easily issue a signal to this process&lt;br /&gt; while(1)&lt;br /&gt;   sleep(1);&lt;br /&gt; return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;As told earlier that KILL and STOP cannot be handled. Change above program to handle these two signals to see how the ‘signal’ system call responds in that case.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold; &quot;&gt;PS:&lt;/span&gt; Apart from handling the standard signals, we can also have user defined signals that can be sent and handled. &lt;div style=&quot;font-weight: normal; &quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;</description><link>http://tech-queries.blogspot.com/2012/03/catch-linux-signal-in-c-program.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSYOFsmWt3nGjtZrSXJpS56YaERmFSkhRbmx-yzNGZANgG0Jnu1tztEEKXR8HLEgDyJxaeVCBEniaCounmbaQFlKqKOQZ0IPz3iVdowrMqUASzRmpRB43ISh_5P-sBzGOfDlk7stw7Zl0/s72-c/signal.jpg" height="72" width="72"/><thr:total>5</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-7105454662513210440</guid><pubDate>Tue, 27 Dec 2011 17:17:00 +0000</pubDate><atom:updated>2011-12-27T23:03:59.872+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">General</category><title>Some lesser known but useful Unix commands</title><description>&lt;div&gt;&lt;b&gt;&lt;a href=&quot;http://www.manpagez.com/man/1/more/&quot;&gt;less&lt;/a&gt;:&lt;/b&gt; You might be familiar with ‘&lt;a href=&quot;http://www.manpagez.com/man/1/cat/&quot;&gt;cat&lt;/a&gt;’. ‘less’ is a much better way to inspect large files on the command line. You’ll get a screen-full of text at a time, but no more. You can move a line or window up or down. You can search for a pattern by typing /pattern. When you’re done, hit q to exit the less viewer.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;a href=&quot;http://www.manpagez.com/man/1/touch/&quot;&gt;touch&lt;/a&gt;:&lt;/b&gt; ‘touch’ is basically for changing file access and modification times. But it’s a bonus that if the file doesn’t exist, it will create it.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;a href=&quot;http://www.manpagez.com/man/n/history/&quot;&gt;history&lt;/a&gt;, !!, and !$:&lt;/b&gt; ‘history’ shows a numbered list of many of your recent commands on console. Then, to execute one of them, just type an exclamation mark and the history number. It’s even quicker to access the last command and last argument you used. For the latest command, use !!; the usual use case given for this is adding sudo to the front of a command. For the latest argument, use !$; &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;a href=&quot;http://www.manpagez.com/man/1/yes/&quot;&gt;yes&lt;/a&gt;:&lt;/b&gt; ‘yes’ outputs argument forever. By default, it prints ‘y’ forever.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;a href=&quot;http://www.manpagez.com/man/1/cal/&quot;&gt;cal&lt;/a&gt;:&lt;/b&gt; Displays a very nice calendar with current date highlighted.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;a href=&quot;http://www.manpagez.com/man/1/seq/&quot;&gt;seq&lt;/a&gt;:&lt;/b&gt; This command prints sequences of numbers. User can define start number, interval, end number and many other options.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;a href=&quot;http://www.manpagez.com/man/1/bc/&quot;&gt;bc&lt;/a&gt;:&lt;/b&gt; A very precise calculator. Really useful for performing calculations on large numbers.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;a href=&quot;http://manpages.unixforum.co.uk/man-pages/unix/solaris-10-11_06/1/factor-man-page.html&quot;&gt;factor&lt;/a&gt;:&lt;/b&gt; A very good mathematical utility for finding prime integer factors.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;stat:&lt;/b&gt; display file or file system status&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;a href=&quot;http://linux.die.net/man/1/tac&quot;&gt;tac&lt;/a&gt;:&lt;/b&gt; reverse of &#39;cat&#39;, print a file line by line in reverse order.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;a href=&quot;http://compute.cnr.berkeley.edu/cgi-bin/man-cgi?ldd+1&quot;&gt;ldd&lt;/a&gt;:&lt;/b&gt; prints shared library information. In OS X, we use &lt;a href=&quot;http://tech-queries.blogspot.com/2011/04/dynamic-library-dependency-on-mac-os-x.html&quot;&gt;otool&lt;/a&gt; for the same purpose.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;a href=&quot;http://www.manpagez.com/man/8/iostat/&quot;&gt;iostat&lt;/a&gt;:&lt;/b&gt; CPU and disk usage stats&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;a href=&quot;http://linux.die.net/man/8/lsof&quot;&gt;lsof&lt;/a&gt;:&lt;/b&gt; List Open Files&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;a href=&quot;http://www.manpagez.com/man/1/netstat/&quot;&gt;netstat&lt;/a&gt;:&lt;/b&gt; show network status&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;PS:&lt;/b&gt; I&#39;ve not given examples but linked to man pages on purpose, so that readers can learn by experiment.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;</description><link>http://tech-queries.blogspot.com/2011/12/some-lesser-known-but-useful-unix.html</link><author>noreply@blogger.com (Akash)</author><thr:total>5</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-4478884038631587076</guid><pubDate>Sat, 19 Nov 2011 18:11:00 +0000</pubDate><atom:updated>2011-11-19T23:44:47.309+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">tree</category><title>Print a Binary Tree in Zig Zag Level Order</title><description>&lt;b&gt;Question:&lt;/b&gt; Print a binary tree in zig-zag level order. Zig-zag means print 1st level from left to right, then 2nd level right to left and alternate thereafter.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Example:&lt;/b&gt; zig-zag level order traversal of below tree will be&lt;br /&gt;0 2 1 3 4 5 6 14 13 12 11 10 9 8 7&lt;br /&gt;&lt;br /&gt;&lt;img style=&quot;display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 320px; height: 156px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiCcfqBpPPgnqdGqnt_AsUsq8zvawX2FNsRKzsUJBGswmNOJAz_D67XR0iC5pzbPxLvg-7MS8Ki7P_PS5-xZHEJzamPnrisimNfhxaPDFoIg7IfJeDyLp4Sj2XAUvmTYtjjVx_TjBcgwrU/s320/zigzag+tree.png&quot; border=&quot;0&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5676771453619221954&quot; /&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;div&gt;&lt;b&gt;Answer:&lt;/b&gt; We usually use a queue for level order traversal of a queue. If we want to use the same here, how will we change direction of traversal on every alternate level?&lt;br /&gt;&lt;br /&gt;If we think logically then we will see that we need stack in place of queue. Now again a single stack won’t serve our purpose here, we need 2 stacks: stack1 for right to left and stack2 for left to right. For identifying, whether we need to put data in stack1 or stack2, we need a flag (left2right) to indicate direction (after a level finishes).&lt;br /&gt;&lt;br /&gt;Initially, left2right is true and we push root node in stack1 and that’s our beginning point. Now since after root node, first level fished, we toggle left2right. Until stack1 is empty, we pop values from stack1 and push values based on left2right flag. Once stack1 finishes, we toggle left2right again and switch stack’s role.&lt;br /&gt;&lt;br /&gt;For clarification, when left2right is true, push left node first in stack and then right node. Similarly left2right is false, push right node first in stack and then left node.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Code:&lt;/b&gt;&lt;br /&gt;&lt;pre name=&quot;code&quot; class=&quot;cpp&quot;&gt;void ZigZagLevelOrder(tree *root) {&lt;br /&gt; stack&amp;lt;tree*&amp;gt; stack1, stack2, *cur_level, *next_level, *temp;&lt;br /&gt; bool left2right = true;&lt;br /&gt;&lt;br /&gt; cur_level = &amp;amp;stack1;&lt;br /&gt; next_level = &amp;amp;stack2;&lt;br /&gt;&lt;br /&gt; // push root in stack&lt;br /&gt; cur_level-&amp;gt;push(root); &lt;br /&gt; while (!cur_level-&amp;gt;empty()) {&lt;br /&gt;   tree *node = cur_level-&amp;gt;top();&lt;br /&gt;   cur_level-&amp;gt;pop();&lt;br /&gt;   if (node) {&lt;br /&gt;     cout &amp;lt;&amp;lt; node-&amp;gt;data &amp;lt;&amp;lt; &quot; &quot;;&lt;br /&gt;     if (left2right) {&lt;br /&gt;       next_level-&amp;gt;push(node-&amp;gt;left);&lt;br /&gt;       next_level-&amp;gt;push(node-&amp;gt;right);&lt;br /&gt;     } else {&lt;br /&gt;       next_level-&amp;gt;push(node-&amp;gt;right);&lt;br /&gt;       next_level-&amp;gt;push(node-&amp;gt;left);&lt;br /&gt;     }&lt;br /&gt;   }&lt;br /&gt;   if (cur_level-&amp;gt;empty()) {&lt;br /&gt;     left2right = !left2right;&lt;br /&gt;     // swap stacks&lt;br /&gt;     temp = Cur_level;&lt;br /&gt;     cur_level = next_level;&lt;br /&gt;     next_level = temp;     &lt;br /&gt;   }&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;</description><link>http://tech-queries.blogspot.com/2011/11/print-binary-tree-in-zig-zag-level.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiCcfqBpPPgnqdGqnt_AsUsq8zvawX2FNsRKzsUJBGswmNOJAz_D67XR0iC5pzbPxLvg-7MS8Ki7P_PS5-xZHEJzamPnrisimNfhxaPDFoIg7IfJeDyLp4Sj2XAUvmTYtjjVx_TjBcgwrU/s72-c/zigzag+tree.png" height="72" width="72"/><thr:total>7</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-6844098190616769546</guid><pubDate>Mon, 05 Sep 2011 17:32:00 +0000</pubDate><atom:updated>2011-11-09T11:41:18.006+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Arrays/Strings</category><title>Find largest sub-matrix with all 1s (not necessarily square)</title><description>In last post, we saw a dynamic programming approach to for&lt;a href=&quot;http://tech-queries.blogspot.com/2011/09/maximum-size-square-sub-matrix-with-all.html&quot;&gt; finding maximum size square sub-matrix with all 1s&lt;/a&gt;.  In this post, we will discuss how to find largest all 1s sub-matrix in a binary matrix. The resultant sub-matrix is not necessarily a square sub-matrix.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Example:&lt;/b&gt;&lt;pre&gt;&lt;blockquote&gt;&lt;div style=&quot;text-align: center;&quot;&gt;1  1  0  0  1  0&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;0  1  1  1  1  1&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;1  1  1  1  1  0&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;0  0  1  1  0  0&lt;/div&gt;&lt;/blockquote&gt;&lt;/pre&gt;Largest all 1s sub-matrix is from (1,1) to (2,4).&lt;blockquote&gt;&lt;pre&gt;&lt;div style=&quot;text-align: center;&quot;&gt;1  1  1  1&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;1  1  1  1&lt;/div&gt;&lt;/pre&gt;&lt;/blockquote&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&lt;b&gt;Algorithm:&lt;/b&gt; If we draw a histogram of all 1’s cells in above rows (until we find a 0) for a particular row, then maximum all 1s sub-matrix ending in that row will the equal to &lt;a href=&quot;http://tech-queries.blogspot.com/2011/03/maximum-area-rectangle-in-histogram.html&quot;&gt;maximum area rectangle in that histogram&lt;/a&gt;. Below is the example for 3rd row in above discussed matrix:&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_XrSVYA_le0F-UoN0-wBCpbxSwS_oZHPJSWqkiS9TRRV-D9UM4TDN2vPnizPGDRCKZeMHmQOVCA9Gq2Gxk2aJznGhtnmhStCb7CdtXfnJSlSxlgllpkzyjT3j6TW72UWAzcIcwt4NSFs/s1600/Screen+shot+2011-11-09+at+11.38.39+AM.png&quot;&gt;&lt;img style=&quot;display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 320px; height: 190px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_XrSVYA_le0F-UoN0-wBCpbxSwS_oZHPJSWqkiS9TRRV-D9UM4TDN2vPnizPGDRCKZeMHmQOVCA9Gq2Gxk2aJznGhtnmhStCb7CdtXfnJSlSxlgllpkzyjT3j6TW72UWAzcIcwt4NSFs/s320/Screen+shot+2011-11-09+at+11.38.39+AM.png&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5672874357336993538&quot; border=&quot;0&quot; /&gt;&lt;/a&gt;&lt;/div&gt;If we calculate this area for all the rows, maximum area will be our answer. We can extend our solution very easily to find start and end co-ordinates.&lt;br /&gt;&lt;br /&gt;For above purpose, we need to generate an auxiliary matrix S[][] where each element represents the number of 1s above and including it, up until the first 0. S[][] for above matrix will be as shown below:&lt;br /&gt;&lt;pre&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;/div&gt;&lt;blockquote&gt;&lt;div style=&quot;text-align: center;&quot;&gt;1  1  0  0  1  0&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;0  2  1  1  2  1&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;1  3  2  2  3  0&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;0  0  3  3  0  0&lt;/div&gt;&lt;/blockquote&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;/div&gt;&lt;/pre&gt;Now we can simple call our maximum rectangle in histogram on every row in S[][] and update the maximum area every time.&lt;br /&gt;&lt;br /&gt;Also we don’t need any extra space for saving S. We can update original matrix (A) to S and after calculation, we can convert S back to A.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Code:&lt;/b&gt; I am not writing the code for largestArea() function. One can find its definition in &lt;a href=&quot;http://tech-queries.blogspot.com/2011/03/maximum-area-rectangle-in-histogram.html&quot;&gt;this post&lt;/a&gt;.&lt;br /&gt;&lt;pre name=&quot;code&quot; class=&quot;cpp&quot;&gt;#define ROW 10&lt;br /&gt;#define COL 10&lt;br /&gt;&lt;br /&gt;int find_max_matrix(int A[ROW][COL])&lt;br /&gt;{&lt;br /&gt; int i, j;&lt;br /&gt; int max, cur_max;&lt;br /&gt; cur_max = 0;&lt;br /&gt;&lt;br /&gt; //Calculate Auxilary matrix&lt;br /&gt; for (i=1; i&amp;lt;ROW; i++)&lt;br /&gt;     for(j=0; j&amp;lt;COL; j++)&lt;br /&gt;     {&lt;br /&gt;         if(A[i][j] == 1)&lt;br /&gt;             A[i][j] = A[i-1][j] + 1;&lt;br /&gt;     }&lt;br /&gt;&lt;br /&gt; //Calculate maximum area in S for each row&lt;br /&gt; for (i=0; i&amp;lt;ROW; i++)&lt;br /&gt; {     &lt;br /&gt;     max = largestArea(A[i], COL);&lt;br /&gt;     if (max &amp;gt; cur_max)&lt;br /&gt;         cur_max = max;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; //Regenerate Oriignal matrix&lt;br /&gt; for (i=ROW-1; i&amp;gt;0; i--)&lt;br /&gt;     for(j=0; j&amp;lt;COL; j++)&lt;br /&gt;     {&lt;br /&gt;         if(A[i][j])&lt;br /&gt;             A[i][j] = A[i][j] - A[i-1][j];&lt;br /&gt;     }&lt;br /&gt;&lt;br /&gt; return cur_max;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;b&gt;Complexity:&lt;/b&gt; Lets say that total number of rows and columns in A are m and n respectively and N = m*n&lt;br /&gt;&lt;br /&gt;Complexity of calculating S = O(m*n) = O(N)&lt;br /&gt;&lt;br /&gt;Complexity of LargestArea() for every row = O(n) since there are n elements in every row. Since we called LargestArea() m times so total complexity of calculating largest area = O(m*n) = O(N)&lt;br /&gt;&lt;br /&gt;Complexity of converting S to A = O(m*n) = O(N)&lt;br /&gt;&lt;br /&gt;So total time complexity = O(N)&lt;br /&gt;&lt;br /&gt;Since we are not using any extra space, so space complexity is O(1).&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Note:&lt;/b&gt; Above function only returns largest area, which can be very easily modified to get start and row indexes as well.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;</description><link>http://tech-queries.blogspot.com/2011/09/find-largest-sub-matrix-with-all-1s-not.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_XrSVYA_le0F-UoN0-wBCpbxSwS_oZHPJSWqkiS9TRRV-D9UM4TDN2vPnizPGDRCKZeMHmQOVCA9Gq2Gxk2aJznGhtnmhStCb7CdtXfnJSlSxlgllpkzyjT3j6TW72UWAzcIcwt4NSFs/s72-c/Screen+shot+2011-11-09+at+11.38.39+AM.png" height="72" width="72"/><thr:total>13</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-6640943475214569041</guid><pubDate>Sat, 03 Sep 2011 16:50:00 +0000</pubDate><atom:updated>2011-09-03T22:35:52.567+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Arrays/Strings</category><category domain="http://www.blogger.com/atom/ns#">Dynamic programming</category><title>Maximum size square sub-matrix with all 1s</title><description>&lt;b&gt;Question: &lt;/b&gt;Given a matrix consisting only 0s and 1s, find the maximum size square sub-matrix with all 1s.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Example:&lt;/b&gt; Consider the below matrix.&lt;br /&gt;&lt;blockquote&gt;&lt;pre&gt;&lt;div style=&quot;text-align: center;&quot;&gt;   0  1  1  0  1&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;   1  1  0  1  0&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;   0  1  1  1  0&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;   1  1  1  1  0&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;   1  1  1  1  1&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;   0  0  0  0  0&lt;/div&gt;&lt;/pre&gt;&lt;/blockquote&gt;  The maximum square sub-matrix with all &#39;1&#39; bits is from (2,1) to (4,3)&lt;br /&gt;&lt;blockquote&gt;&lt;pre&gt;&lt;div style=&quot;text-align: center;&quot;&gt;    1  1  1&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;    1  1  1&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;    1  1  1&lt;/div&gt;&lt;/pre&gt;&lt;/blockquote&gt;&lt;b&gt;Answer: &lt;/b&gt;This is a classic &lt;a href=&quot;http://tech-queries.blogspot.com/search/label/Dynamic%20programming&quot;&gt;Dynamic Programming&lt;/a&gt; problem. Lets calculate the maximum size square sub-matrix as we traverse the original matrix M[][]. We will use a auxiliary matrix S[][] of same size for memoization. S[i][j] represents size of the square sub-matrix with all 1s including M[i][j]. &#39;i&#39; and &#39;j&#39; will be the last row and column respectively in square sub-matrix.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;How to calculate S[i][j]:&lt;/b&gt;&lt;br /&gt;We should note that if M[i][j] is &#39;0&#39; then S[i][j] will obviously be &#39;0&#39;. If M[i][j] is &#39;1&#39; then S[i][j] depends on earlier values.&lt;br /&gt;&lt;br /&gt;If M[i][j] is &#39;1&#39; then it will contribute to the all 1s square sub-matrix ending at either M[i][j-1] or M[i-1][j] or M[i-1][j-1]. If we visualize the conditions then, we will see:&lt;br /&gt;&lt;blockquote style=&quot;text-align: center;&quot;&gt;S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1&lt;br /&gt;&lt;/blockquote&gt;&lt;br /&gt;&lt;b&gt;How did we arrive at above relationship?&lt;/b&gt;&lt;br /&gt;Note if we include M[i][j] in earlier calculated sub-matrix then we are adding S[i][j] elements from i&lt;sup&gt;th&lt;/sup&gt; row and j&lt;sup&gt;th&lt;/sup&gt; columns. They all should be &#39;1&#39; if we wanna include M[i][j]. On visualizing with some examples, readers will analyze why, minimum of 3 neighbors is taken.&lt;br /&gt;&lt;br /&gt;For the given M[][] in above example, constructed S[][] would be:&lt;br /&gt;&lt;blockquote&gt;&lt;pre&gt;&lt;div style=&quot;text-align: center;&quot;&gt;   0  1  1  0  1&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;   1  1  0  1  0&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;   0  1  1  1  0&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;   1  1  2  2  0&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;   1  2  2  3  1&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;   0  0  0  0  0&lt;/div&gt;&lt;/pre&gt;&lt;/blockquote&gt;The value of maximum entry in above matrix is 3 and coordinates of the entry are (4, 3). Using the maximum value and its coordinates, we can find out the required sub-matrix.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Code:&lt;/b&gt;&lt;br /&gt;&lt;pre name=&quot;code&quot; class=&quot;cpp&quot;&gt;#define ROW 10&lt;br/&gt;#define COL 10&lt;br/&gt;&lt;br/&gt;void FindMaxSubSquare(bool M[ROW][COL], int &amp;amp;max_i, int &amp;amp;max_j, int &amp;amp;size)&lt;br/&gt;{&lt;br/&gt;    int i,j;&lt;br/&gt;    int S[ROW][COL];&lt;br/&gt; &lt;br/&gt;    /* Set first column of S[][]*/&lt;br/&gt;    for(i = 0; i &amp;lt; ROW; i++)&lt;br/&gt;        S[i][0] = M[i][0];&lt;br/&gt; &lt;br/&gt;    /* Set first row of S[][]*/&lt;br/&gt;    for(j = 0; j &amp;lt; COL; j++)&lt;br/&gt;        S[0][j] = M[0][j];&lt;br/&gt; &lt;br/&gt;    /* Construct other entries of S[][]*/&lt;br/&gt;    for(i = 1; i &amp;lt; ROW; i++)&lt;br/&gt;    {&lt;br/&gt;        for(j = 1; j &amp;lt; COL; j++)&lt;br/&gt;        {&lt;br/&gt;            if(M[i][j] == 1)&lt;br/&gt;                S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1;&lt;br/&gt;            else&lt;br/&gt;                S[i][j] = 0;&lt;br/&gt;        }&lt;br/&gt;    } &lt;br/&gt; &lt;br/&gt;    /* Find the maximum entry, and indexes of maximum entry in S[][] */&lt;br/&gt;    size = S[0][0]; max_i = 0; max_j = 0;&lt;br/&gt;    for(i = 0; i &amp;lt; ROW; i++)&lt;br/&gt;    {&lt;br/&gt;        for(j = 0; j &amp;lt; COL; j++)&lt;br/&gt;        {&lt;br/&gt;            if(size &amp;lt; S[i][j])&lt;br/&gt;            {&lt;br/&gt;                size = S[i][j];&lt;br/&gt;                max_i = i;&lt;br/&gt;                max_j = j;&lt;br/&gt;            }&lt;br/&gt;        }&lt;br/&gt;    }     &lt;br/&gt;    return&lt;br/&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;b&gt;Complexity:&lt;/b&gt;&lt;br /&gt;Time Complexity: O(m*n) where m is number of rows and n is number of columns in the given matrix.&lt;br /&gt;Space Complexity: O(m*n) where m is number of rows and n is number of columns in the given matrix.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Note:&lt;/b&gt; Part of this post is taken from &lt;a href=&quot;http://geeksforgeeks.org/archives/6257&quot;&gt;geeksforgeeks&lt;/a&gt;.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;</description><link>http://tech-queries.blogspot.com/2011/09/maximum-size-square-sub-matrix-with-all.html</link><author>noreply@blogger.com (Akash)</author><thr:total>3</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-7570256176808070990</guid><pubDate>Wed, 24 Aug 2011 16:11:00 +0000</pubDate><atom:updated>2011-08-27T08:42:41.834+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Miscellany</category><title>Weekend Miscellany</title><description>&lt;span style=&quot;font-weight: bold;&quot;&gt;Maths:&lt;/span&gt;&lt;br /&gt;&lt;a href=&quot;http://www.amnh.org/nationalcenter/youngnaturalistawards/2011/aidan.html&quot;&gt;The Secret of the Fibonacci Sequence in Trees&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;C/C++:&lt;/span&gt;&lt;br /&gt;&lt;a href=&quot;http://www.elpauer.org/?p=971&quot;&gt;The most stupid C bug ever&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Computer Science:&lt;/span&gt;&lt;br /&gt;&lt;a href=&quot;http://www.catonmat.net/blog/busy-beaver/&quot;&gt;The Busy Beaver Problem - good coders code, great reuse&lt;/a&gt;&lt;div&gt;&lt;a href=&quot;http://www.sorting-algorithms.com/&quot;&gt;Sorting Algorithm Animations&lt;br /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;a href=&quot;http://www.sorting-algorithms.com/&quot;&gt;&lt;br /&gt;&lt;/a&gt;&lt;/div&gt;Music produced by different sorting algorithms&lt;br /&gt;&lt;br /&gt;&lt;iframe width=&quot;420&quot; height=&quot;345&quot; src=&quot;http://www.youtube.com/embed/t8g-iYGHpEA&quot; frameborder=&quot;0&quot; allowfullscreen=&quot;&quot;&gt;&lt;/iframe&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;</description><link>http://tech-queries.blogspot.com/2011/08/weekend-miscellany.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/t8g-iYGHpEA/default.jpg" height="72" width="72"/><thr:total>4</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-7844757625294291441</guid><pubDate>Wed, 24 Aug 2011 12:14:00 +0000</pubDate><atom:updated>2011-08-24T17:54:52.811+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Mathematics</category><title>Divisibility by 7</title><description>&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJbajBtUkA5PxtYuMTlua6kW5G6K1JX6QPTHwCYbV_a5M6QAmqvai-FM7PVk45n8hX1NZyJLPO-TCxZy7B2ElXdpYTdNaIBK7Q0pBDVGn-0acWIOhxafFbbuwnKIkfFtnU8DXwOQhoPV4/s1600/seven.png&quot;&gt;&lt;img style=&quot;float:right; margin:0 0 10px 10px;cursor:pointer; cursor:hand;width: 200px; height: 67px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJbajBtUkA5PxtYuMTlua6kW5G6K1JX6QPTHwCYbV_a5M6QAmqvai-FM7PVk45n8hX1NZyJLPO-TCxZy7B2ElXdpYTdNaIBK7Q0pBDVGn-0acWIOhxafFbbuwnKIkfFtnU8DXwOQhoPV4/s200/seven.png&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5644396232110287330&quot; border=&quot;0&quot; /&gt;&lt;/a&gt;How can you tell whether a number is divisible by 7? Almost everyone knows tricks to test divisibility by 2, 3, 5, or 9. Testing divisibility by 4, 6, 8, or 11 is a bit trickier. But not many people have ever seen a trick for testing divisibility by 7.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;How to test:&lt;/span&gt; Remove the last digit from the number, double it, and subtract it from the first part of the number. Do this repeatedly until you get something you recognize as being divisible by 7 or not.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Example:&lt;/span&gt; Lets test for 826. Split 826 into 82 and 6. Subtract 12(6*2) from 82 to get 70. Since 70 is divisible by 7, so is 826.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Another Example: &lt;/span&gt;For 8632. Split 8632 into 863 and 2. Subtract 4(2*2) from 863 to get 859.&lt;br /&gt;&lt;br /&gt;Now split 859 into 85 and 9. Subtract 18(9*2) from 85 to get 67, which isn’t divisible by 7. Hence, we conclude that 8632 isn’t divisible by 7.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Why does this work?&lt;/span&gt; Let b be the last digit of a number n and let a be the number we get when we split off b. That says n = 10a + b. Now n is divisible by 7 if and only if n – 21b is divisible by 7. But&lt;br /&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;blockquote&gt;n – 21b = 10a + b - 21b = 10(a – 2b)&lt;/blockquote&gt;&lt;/div&gt;&lt;br /&gt;Above is divisible by 7 if and only if a – 2b is divisible by 7.&lt;br /&gt;&lt;br /&gt;Similarly, we can find divisibility by 13, 17, 19 etc.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Divisibility by 13:&lt;/span&gt; Add four times the last digit to the remaining leading truncated number to make it (n + 39b) = 10(a + 4b)&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Divisibility by 17:&lt;/span&gt;  Subtract five times the last digit from the remaining leading truncated number to make it (n - 51b) = 10(a - 5b)&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Divisibility by 19:&lt;/span&gt; Add two times the last digit to the remaining leading truncated number to make it (n + 19b) = 10(a + 2b)&lt;br /&gt;&lt;br /&gt;Test above divisibility yourselves with examples.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;PS:&lt;/span&gt; Thanks &lt;a href=&quot;http://www.johndcook.com/blog/2010/10/27/divisibility-by-7/&quot;&gt;John D. Cook&lt;/a&gt; for this trick.&lt;br /&gt;</description><link>http://tech-queries.blogspot.com/2011/08/divisibility-by-7.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJbajBtUkA5PxtYuMTlua6kW5G6K1JX6QPTHwCYbV_a5M6QAmqvai-FM7PVk45n8hX1NZyJLPO-TCxZy7B2ElXdpYTdNaIBK7Q0pBDVGn-0acWIOhxafFbbuwnKIkfFtnU8DXwOQhoPV4/s72-c/seven.png" height="72" width="72"/><thr:total>3</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-7140972547076854578</guid><pubDate>Tue, 23 Aug 2011 10:46:00 +0000</pubDate><atom:updated>2011-08-23T16:21:22.482+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Amazon S3</category><category domain="http://www.blogger.com/atom/ns#">Cloud Computing</category><category domain="http://www.blogger.com/atom/ns#">Ruby</category><title>Change Headers Of S3 Object</title><description>Sometimes, we need to change header info for S3 objects. One solution is to download file locally and upload it again with new header information.&lt;br /&gt;&lt;br /&gt;Using &lt;a href=&quot;http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?CopyingObjectUsingREST.html&quot;&gt;Amazon API COPY functionality&lt;/a&gt;, it is possible to change headers on an S3 object without downloading the entire object. We need to set x-amz-metadata-directive as REPLACE to copy a S3 key to the same location.&lt;br /&gt;&lt;br /&gt;But if we do this using &lt;a href=&quot;http://rubygems.org/gems/right_aws&quot;&gt;right_aws ruby gem&lt;/a&gt;, ACL information is not preserved. For preserving ACL information as well, we need to preserve ACL permission before changing headers and then apply ACL again after changing headers.&lt;br /&gt;&lt;br /&gt;&lt;pre name=&quot;code&quot; class=&quot;ruby&quot;&gt;&lt;br /&gt;#!/usr/bin/env ruby&lt;br/&gt;&lt;br/&gt;require &#39;rubygems&#39;&lt;br/&gt;require &#39;right_aws&#39;&lt;br/&gt;&lt;br/&gt;@s3 = RightAws::S3Interface.new(&#39;AWS_ACESS_KEY&#39;, &#39;AWS_SECRET_KEY&#39;, :logger =&amp;gt; STDOUT)&lt;br/&gt;&lt;br/&gt;#In this example, I&#39;m changing the mime-type to image/png.&lt;br/&gt;#You can change whatever header you want.&lt;br/&gt;update_s3_object_headers(bucket, key, {&#39;Content-Type&#39; =&amp;gt; &#39;image/png&#39;})&lt;br/&gt;&lt;br/&gt;def update_s3_object_headers(bucket, key, headers)&lt;br/&gt;      #Saving current ACL&lt;br/&gt;      acl_xml = @s3.get_acl(bucket, key)[:object]&lt;br/&gt;      # Performing a copy with directive REPLACE&lt;br/&gt;      @s3.copy(bucket, key, bucket, key, :replace, headers)&lt;br/&gt;      #Restore ACL&lt;br/&gt;      @s3.put_acl(bucket, key, acl_xml)&lt;br/&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;</description><link>http://tech-queries.blogspot.com/2011/08/change-headers-of-s3-object.html</link><author>noreply@blogger.com (Akash)</author><thr:total>3</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-7448787157732141206</guid><pubDate>Mon, 22 Aug 2011 12:06:00 +0000</pubDate><atom:updated>2011-09-04T19:26:21.770+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Amazon S3</category><category domain="http://www.blogger.com/atom/ns#">Cloud Computing</category><title>Copy Files Between Separate AWS Accounts</title><description>Sometimes, we need to copy S3 data between separate AWS accounts. Though &lt;a href=&quot;http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?CopyingObjectUsingREST.html&quot;&gt;Amazon API provides COPY functionality&lt;/a&gt; but that is only for buckets under same account.&lt;br /&gt;&lt;br /&gt;It seems that if we want to copy data between buckets in different accounts, only option is to download the file to local system and then upload it to destination bucket.&lt;br /&gt;&lt;br /&gt;Since bucket names are unique across all S3, we can copy a &lt;span style=&quot;font-style: italic;&quot;&gt;public-read&lt;/span&gt; file to destination bucket (in different account) using COPY. I tested this and it works perfectly.&lt;br /&gt;&lt;br /&gt;For copying a private file, we need to temporarily give &lt;span style=&quot;font-style: italic;&quot;&gt;public-read&lt;/span&gt; permission on the file and then COPY it to different AWS accounts. Don’t forget to change permissions for file in source and destination bucket once copy is done.&lt;br /&gt;&lt;br /&gt;Also, we don&#39;t have to worry about bandwidth charges since COPY operation is internal to AWS. No download of the actual file required.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight:bold;&quot;&gt;Code:&lt;/span&gt;&lt;br /&gt;&lt;pre name=&quot;code&quot; class=&quot;ruby&quot;&gt;#!/usr/bin/env ruby&lt;br/&gt;&lt;br/&gt;require &#39;rubygems&#39;&lt;br/&gt;require &#39;right_aws&#39;&lt;br/&gt;&lt;br/&gt;srcBkt = &#39;SourceTest&#39;&lt;br/&gt;srcKey = &#39;test.ppt&#39;&lt;br/&gt;destBky = &#39;DestTest&#39;&lt;br/&gt;destKey = &#39;test.ppt&#39;&lt;br/&gt;&lt;br/&gt;# Put credentials of destination account&lt;br/&gt;s3 = RightAws::S3Interface.new(&#39;access_key&#39;, &#39;secret_key)  &lt;br/&gt;&lt;br/&gt;begin&lt;br/&gt;    #We can do a move operation as well if both the accounts are linked&lt;br/&gt;    s3.copy(srcBkt, srcKey, destBkt, destKey)&lt;br/&gt;rescue Exception =&gt; e&lt;br/&gt;    puts e.inspect&lt;br/&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Update:&lt;/span&gt; Please not that you will be able to COPY public content but can&#39;t MOVE (copy + delete) content across different accounts. If these accounts are linked with each other, you can MOVE as well.&lt;br /&gt;&lt;br /&gt;</description><link>http://tech-queries.blogspot.com/2011/08/copy-files-between-separate-s3-accounts.html</link><author>noreply@blogger.com (Akash)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-1712460953182458139</guid><pubDate>Sat, 13 Aug 2011 15:45:00 +0000</pubDate><atom:updated>2011-08-13T21:26:06.234+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">General</category><title>How To Add Facebook Comment Box To Blogger Blogs</title><description>Facebook comment box is one of the very useful tool for bloggers to increase engagement of readers. You may find many other blog posts teaching to add Facebook comment box to blogger blog. But still people are getting problem as I did. In this post, I will talk about how to integrate Facebook comment box to your blogger blog in very simple steps. &lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight:bold;&quot;&gt;Step 1:&lt;/span&gt; Setup an application at &lt;a href=&quot;https://developers.facebook.com/setup&quot;&gt;Facebook developer page&lt;/a&gt; and enter your blog name, URL. Save the APP-ID for future reference.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight:bold;&quot;&gt;Step2:&lt;/span&gt; Get your Facebook USER-ID. If you are using a custom username for your Facebook profile or page, you can get your profile Id from &lt;span style=&quot;font-weight:bold;&quot;&gt;http://graph.facebook.com/&amp;lt;your username&amp;gt;&lt;/span&gt;. &lt;a href=&quot;https://graph.facebook.com/ProgrammingInterviews&quot;&gt;Here&lt;/a&gt; is the same page for &lt;a href=&quot;https://facebook.com/ProgrammingInterviews&quot;&gt;Programming Interviews&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight:bold;&quot;&gt;Step 3:&lt;/span&gt; Login to you Blogger dashboard and navigate to Layout &amp;gt; Edit HTML and check on Expand Widget Templates. Search for &amp;lt;head&amp;gt; and add following lines just after it:&lt;br /&gt;&lt;br /&gt;To moderate comments across a site, all moderators must be added as admins of the app: &lt;br /&gt;&lt;br /&gt;&lt;pre name=&quot;code&quot; class=&quot;js&quot;&gt;&lt;br /&gt;&amp;lt;meta property=&amp;quot;fb:app_id&amp;quot; content=&amp;quot;{YOUR_APP_ID}&amp;quot;&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;To receive notifications on every comment posted to the Comment Box, add:&lt;br /&gt;&lt;br /&gt;&lt;pre name=&quot;code&quot; class=&quot;js&quot;&gt;&lt;br /&gt;&amp;lt;meta property=&amp;quot;fb:admins&amp;quot; content=&amp;quot;{YOUR_USER_ID}&amp;quot;&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Change {YOUR_APP_ID} and {YOUR_USER_ID} with earlier saved values.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight:bold;&quot;&gt;Step 4:&lt;/span&gt; Search for &amp;lt;data:post.body/&amp;gt; and add following lines just after it:&lt;br /&gt;&lt;br /&gt;&lt;pre name=&quot;code&quot; class=&quot;js&quot;&gt;&lt;br /&gt;&amp;lt;!-- Facebook comment start --&amp;gt;&lt;br/&gt;&amp;lt;b:if cond=&#39;data:blog.pageType == &amp;amp;quot;item&amp;amp;quot;&#39;&amp;gt;&lt;br/&gt;  &amp;lt;script src=&#39;http://connect.facebook.net/en_US/all.js#xfbml=1&#39;&amp;gt;&lt;br/&gt;  &amp;lt;/script&amp;gt;&lt;br/&gt;  &amp;lt;fb:comments expr:href=&#39;data:post.url&#39; num_posts=&#39;5&#39; width=&#39;600&#39;/&amp;gt;&lt;br/&gt;&amp;lt;/b:if&amp;gt;&lt;br/&gt;&amp;lt;!-- Facebook comment end --&amp;gt;&lt;br/&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Line 2 adds a check so that Facebook comment box doesn&#39;t appear on home page of your blog but only on the post pages. If you are familiar with blogger template you may want to add above code somewhere else. Please note to use expr:href in place of just href in line 5.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight:bold;&quot;&gt;Step 5:&lt;/span&gt; You may or may not want to hide your blogger comment box. If you want to hide Blogger comment box, navigate to Settings &amp;gt; Comments and select hide and save settings.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight:bold;&quot;&gt;PS:&lt;/span&gt; If you like this tutorial or have any question, please use below Facebook comment box to start conversation.&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;</description><link>http://tech-queries.blogspot.com/2011/08/how-to-add-facebook-comment-box-to.html</link><author>noreply@blogger.com (Akash)</author><thr:total>6</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-8682655850974907996</guid><pubDate>Thu, 11 Aug 2011 06:34:00 +0000</pubDate><atom:updated>2011-08-13T15:01:46.156+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Arrays/Strings</category><category domain="http://www.blogger.com/atom/ns#">Dynamic programming</category><title>Find optimal number of jumps to reach last element</title><description>&lt;b&gt;Question:&lt;/b&gt; Given an array, start from the first element and reach the last by jumping. The jump length can be at most the value at the current position in the array. Optimum result is when you reach the goal in minimum number of jumps.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Example:&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;Given array A = {2,3,1,1,4}&lt;br /&gt;&lt;br /&gt;Possible ways to reach the end (index list)&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt;0,2,3,4 (jump 2 to index 2, and then jump 1 to index 3 and then jump 1 to index 4)&lt;/li&gt;&lt;li&gt;0,1,4 (jump 1 to index 1, and then jump 3 to index 4)&lt;/li&gt;&lt;/ol&gt;Since second solution has only 2 jumps it is the optimum result.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Answer:&lt;/b&gt; This problem is a classic example of &lt;a href=&quot;http://tech-queries.blogspot.com/search/label/Dynamic%20programming&quot;&gt;Dynamic Programming&lt;/a&gt;. Though we can solve this by brute-force but complexity in that case will be horrendous. If you remember LIS problem or my &lt;a href=&quot;http://tech-queries.blogspot.com/2009/05/max-possible-sum-of-non-consecutive.html&quot;&gt;first post on dynamic programming&lt;/a&gt; then we can solve this by using same process.&lt;br /&gt;&lt;br /&gt;As soon as we traverse the array, we should find the minimum number of jumps for reaching that position (index) and update our result array. Once we reach at the end, we have the optimum solution at last index in result array.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;How to find optimum number of jump for every position (index)?&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;For first index, optimum number of jumps will be zero.  Please note that if value at first index is zero, we can’t jump to any element and return infinite.&lt;br /&gt;&lt;br /&gt;For (N+1)&lt;sup&gt;th&lt;/sup&gt; element, initialize result[N+1] as infinite. Then we should go through a loop from 0…N, and at every index (i), we should see if we are able to jump to (N+1) from there (i) or not. If possible then see if total number of jump (result[i]  + 1) is less than result[N+1], then update result[N+1] else just continue to next index.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Code:&lt;/b&gt; I skipped algorithm but commented code properly.&lt;br /&gt;&lt;br /&gt;&lt;pre name=&quot;code&quot; class=&quot;cpp&quot;&gt;&lt;br /&gt;//Define MAX 1 less so that adding 1 doesn&#39;t make it 0&lt;br/&gt;#define MAX 0xFFFFFFFE;&lt;br/&gt;&lt;br/&gt;unsigned int jump(int *array, int n)&lt;br/&gt;{&lt;br/&gt;  unsigned int&lt;br/&gt;*result = new unsigned int[n];&lt;br/&gt;  int i, j;&lt;br/&gt;  &lt;br/&gt;  //Boundry conditions&lt;br/&gt;  if (n==0 || array[0] == 0)&lt;br/&gt;    return MAX;&lt;br/&gt;    &lt;br/&gt;  result[0] = 0;  //no need to jump at first element&lt;br/&gt;  for (i = 1; i &amp;lt; n; i++)&lt;br/&gt;  {&lt;br/&gt;    result[i] = MAX; //Initialization of result[i]&lt;br/&gt;    for (j = 0; j &amp;lt; i; j++)&lt;br/&gt;    {&lt;br/&gt;      //check if jump is possible from j to is&lt;br/&gt;      if (array[j] &amp;gt;= (i-j))      {&lt;br/&gt;&lt;br/&gt;        //check if better solution available&lt;br/&gt;        if ((result[j] + 1) &amp;lt; result[i]) &lt;br/&gt;          result[i] = result[j] + 1;  //updating result[i]&lt;br/&gt;      }&lt;br/&gt;    }&lt;br/&gt;  }&lt;br/&gt;  &lt;br/&gt;  //return result[n-1]&lt;br/&gt;  unsigned int answer = result[n-1];&lt;br/&gt;  delete[] result;&lt;br/&gt;  &lt;br/&gt;  return answer;&lt;br/&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Above code will return optimum number of jumps only. If we want to have the jump indexes as well, we can very easily modify the code as per requirement.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Efficiency:&lt;/b&gt; Since we are running 2 loops here and iterating from 0 to I in every loop then total time takes will be 1 + 2 + 3 + 4 + …  + (N-1).&lt;br /&gt;&lt;br /&gt;So time efficiency O(n) = O(n*(n-1)/2) = O(n^2)&lt;br /&gt;&lt;br /&gt;We also need O(n) space for result array.&lt;br /&gt;</description><link>http://tech-queries.blogspot.com/2011/08/find-optimal-number-of-jumps-to-reach.html</link><author>noreply@blogger.com (Akash)</author><thr:total>5</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-6823365032905959835</guid><pubDate>Sun, 07 Aug 2011 11:14:00 +0000</pubDate><atom:updated>2011-08-24T21:56:12.076+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Arrays/Strings</category><category domain="http://www.blogger.com/atom/ns#">Mathematics</category><title>Matrix Madness - smallest non-negative number</title><description>&lt;span style=&quot;font-weight:bold;&quot;&gt;Question:&lt;/span&gt; There is an N x N matrix with the property that each entry in the matrix is the smallest non-negative number, which does not appear either above the entry or to its left. Write a method to find the entry in a &lt;span class=&quot;Apple-style-span&quot;&gt;particular&lt;/span&gt; row and column.&lt;br /&gt;&lt;br /&gt;For example, for N=8, we might have the matrix:&lt;br /&gt;&lt;blockquote&gt;&lt;pre&gt;&lt;div style=&quot;text-align: center;&quot;&gt;0    1    2    3    4    5    6    7&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;1    0    3    2    5    4    7    6&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;2    3    0    1    6    7    4    5&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;3    2    1    0    7    6    5    4&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;4    5    6    7    0    1    2    3&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;5    4    7    6    1    0    3    2&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;6    7    4    5    2    3    0    1&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;7    6    5    4    3    2    1    0&lt;/div&gt;&lt;/pre&gt;&lt;/blockquote&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight:bold;&quot;&gt;Answer:&lt;/span&gt; From the question statement, it is clear that the top left corner starts things off with 0 and the top row and the leftmost column are each completed with the positive integers 1,2,3,..., in order.&lt;br /&gt;&lt;br /&gt;Secondly, if every time we fill another cell, we use the smallest non-negative integers that have not so far appeared in the same column and the same row, then it is impossible to get a repeated integer in either the same column or the same row. Square matrix of order n, in which every symbol occurs exactly once in each row and column of the array, is called &lt;a href=&quot;http://en.wikipedia.org/wiki/Latin_square&quot;&gt;latin square&lt;/a&gt;. So we can say that above matrix is a latin square in different setting.&lt;br /&gt;&lt;br /&gt;Lets see if we can find some pattern in the sequence. If we write the matrix in binary number system an 8*8 matrix will look like below matrix:&lt;div&gt;&lt;br /&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFms7y3pEdPctVplegA-T6TF1vJyDiWG0lbaaZrXpxqPsWEwOSy-TrlTr2BpplqgeQN7j8FscbML7CPPQ8W2B8UV_ZnOj-dnbhCyL3QCysIpEeWEyIdM0ytAE0l5IXBX7iJx0XkhoEuRM/s1600/latin1.png&quot;&gt;&lt;img src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFms7y3pEdPctVplegA-T6TF1vJyDiWG0lbaaZrXpxqPsWEwOSy-TrlTr2BpplqgeQN7j8FscbML7CPPQ8W2B8UV_ZnOj-dnbhCyL3QCysIpEeWEyIdM0ytAE0l5IXBX7iJx0XkhoEuRM/s320/latin1.png&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5638074192416491282&quot; style=&quot;display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 320px; height: 204px; &quot; border=&quot;0&quot; /&gt;&lt;/a&gt;&lt;div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot;&gt;&lt;u&gt;&lt;br /&gt;&lt;/u&gt;&lt;/span&gt;&lt;/div&gt;If we split this 2&lt;sup&gt;n&lt;/sup&gt; square matrix in 4 parts of size 2&lt;sup&gt;n-1&lt;/sup&gt; and call them as M&lt;sub&gt;tl&lt;/sub&gt;, M&lt;sub&gt;tr&lt;/sub&gt;, M&lt;sub&gt;br&lt;/sub&gt;, M&lt;sub&gt;bl&lt;/sub&gt; (top-left, top-right, bottom-left, bottom-right respectively), each of these sub-matrixes is a latin square in itself.&lt;br /&gt;&lt;br /&gt;If we took the highest power of 2 from these values, we can also write this matrix as&lt;br /&gt;&lt;br /&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnFyMFK8m1xn8zgwtgrS1yEnSdDoQ9WUUDUsMRCdNIdofgpbGY25AgeXTI4V59FMzrKhNzVviC0DpxfMzGRn_UOlB1mPwHzFZCrnEYeIPxfQhd1a9gKE-cMgOGEYFuYazCweQT8uLuvqk/s1600/latin2.png&quot;&gt;&lt;img src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnFyMFK8m1xn8zgwtgrS1yEnSdDoQ9WUUDUsMRCdNIdofgpbGY25AgeXTI4V59FMzrKhNzVviC0DpxfMzGRn_UOlB1mPwHzFZCrnEYeIPxfQhd1a9gKE-cMgOGEYFuYazCweQT8uLuvqk/s320/latin2.png&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5638074220549494546&quot; style=&quot;display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 320px; height: 204px; &quot; border=&quot;0&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot;&gt;&lt;u&gt;&lt;br /&gt;&lt;/u&gt;&lt;/span&gt;&lt;/div&gt;Lets see how this works. First, fill the corner square of size 1x1 with the number 0. On the next step, we get a square of size 2x2. The latter consists of four squares (M&lt;sub&gt;tl&lt;/sub&gt;, M&lt;sub&gt;tr&lt;/sub&gt;, M&lt;sub&gt;br&lt;/sub&gt;, M&lt;sub&gt;bl&lt;/sub&gt; ) equal in size to the square on the previous step.  M&lt;sub&gt;tl&lt;/sub&gt; is the square from the previous step. Copy it into three other squares, and lastly add 1 (2&lt;sup&gt;o&lt;/sup&gt;) to every element of M&lt;sub&gt;tr&lt;/sub&gt; and M&lt;sub&gt;bl&lt;/sub&gt;.&lt;br /&gt;&lt;br /&gt;Now at every step for generating a square matrix of size 2&lt;sup&gt;n+1&lt;/sup&gt;, we can expand the matrix by assuming that a corner square of size 2&lt;sup&gt;n&lt;/sup&gt; (M&lt;sub&gt;tl) &lt;/sub&gt;has been filled. Copy it into adjacent squares M&lt;sub&gt;tr&lt;/sub&gt;, M&lt;sub&gt;br&lt;/sub&gt; and M&lt;sub&gt;bl&lt;/sub&gt; and add 2&lt;sup&gt;n&lt;/sup&gt; to every element of M&lt;sub&gt;tr&lt;/sub&gt; and M&lt;sub&gt;bl&lt;/sub&gt;. Final relationship will be like shown below:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjc8yFygE70qHOcCpBRl2CKSBM9Wew0dm_C6WvwMFvwt0ChqMyfJqAkdM-_h03fdTbScf7gziIkRf93_SwpsOYdszAWtG7AUEGDPHFsvCtScOUtuXfuQKoNw9JTz5KYBrzXROpMAAohLJ0/s1600/latin3.jpg&quot;&gt;&lt;img src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjc8yFygE70qHOcCpBRl2CKSBM9Wew0dm_C6WvwMFvwt0ChqMyfJqAkdM-_h03fdTbScf7gziIkRf93_SwpsOYdszAWtG7AUEGDPHFsvCtScOUtuXfuQKoNw9JTz5KYBrzXROpMAAohLJ0/s320/latin3.jpg&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5638074237749167858&quot; style=&quot;display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 243px; height: 108px; &quot; border=&quot;0&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot;&gt;&lt;u&gt;&lt;br /&gt;&lt;/u&gt;&lt;/span&gt;&lt;/div&gt;&lt;b&gt;How can we prove that resultant matrix has the required property?&lt;/b&gt; &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Lets prove it my using mathematical induction. We have seen that M&lt;sub&gt;0&lt;/sub&gt; adhere to the property. Now assume that M&lt;sub&gt;N-1&lt;/sub&gt; follow the property, lets show that M&lt;sub&gt;N&lt;/sub&gt; also follow the same:&lt;br /&gt;&lt;br /&gt;Since we assumed that M&lt;sub&gt;N-1&lt;/sub&gt; (i.e. M&lt;sub&gt;tl&lt;/sub&gt; for M&lt;sub&gt;N&lt;/sub&gt;) follows theis rule and entries of M&lt;sub&gt;tr&lt;/sub&gt; are formed by adding 2&lt;sup&gt;N-1&lt;/sup&gt; to M&lt;sub&gt;tl&lt;/sub&gt;. So M&lt;sub&gt;tr&lt;/sub&gt; is a latin square in itself. Also since elements from 0 to (2&lt;sup&gt;N-1&lt;/sup&gt; - 1) have already been used in M&lt;sub&gt;tl&lt;/sub&gt;, candidates for M&lt;sub&gt;tr&lt;/sub&gt; are only values greater than or equal to 2&lt;sup&gt;N-1&lt;/sup&gt;. So we can say that M&lt;sub&gt;tr&lt;/sub&gt; adheres to the given rule. Similar argument can be given for M&lt;sub&gt;bl&lt;/sub&gt;.&lt;br /&gt;&lt;br /&gt;For M&lt;sub&gt;br&lt;/sub&gt;, we see that value for 0..(2&lt;sup&gt;N-1&lt;/sup&gt; -1) are not used in these row and column yet, We can use them and we used M&lt;sub&gt;tl&lt;/sub&gt; as it is. Hence we prove that M&lt;sub&gt;N &lt;/sub&gt;the given conditions.&lt;br /&gt;&lt;br /&gt;Now we can calculate value at any row and column in O(logN) time as on every step we can reduce the matrix size by half.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Can we do it in constant time?&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;Assume that rows and columns starting with 0 as in C/C++. Let M&lt;sub&gt;(m,n)&lt;/sub&gt; denotes the number that appears in the (m, n) cell. Since we can denote any number with addition of power of 2, lets say&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;blockquote&gt;m = 2&lt;sup&gt;a&lt;/sup&gt; + 2&lt;sup&gt;b&lt;/sup&gt; + 2&lt;sup&gt;c&lt;/sup&gt; + ... where a &amp;gt; b &amp;gt; c...&lt;br /&gt;n = 2&lt;sup&gt;x&lt;/sup&gt; + 2&lt;sup&gt;y&lt;/sup&gt; + 2&lt;sup&gt;z&lt;/sup&gt; + ... where x &amp;gt; y &amp;gt; z...&lt;br /&gt;&lt;/blockquote&gt;&lt;br /&gt;&lt;b&gt;If a = x:&lt;/b&gt;  then (m, n) lies in the M&lt;sub&gt;br&lt;/sub&gt; square of the smallest square M&lt;sub&gt;N&lt;/sub&gt; that contains (m, n). By dropping 2&lt;sup&gt;a&lt;/sup&gt; from m and 2&lt;sup&gt;x&lt;/sup&gt; from n, the point is moved into M&lt;sub&gt;N-1&lt;/sub&gt;. So we don’t bother about a&lt;sup&gt;th&lt;/sup&gt; and x&lt;sup&gt;th&lt;/sup&gt; bit from m and n respectively.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;If a &amp;lt; x:&lt;/b&gt;  then (m, n) lies in the M&lt;sub&gt;tr&lt;/sub&gt; square of the smallest square M&lt;sub&gt;N&lt;/sub&gt; that contains (m, n). As we saw earlier, we can move it into M&lt;sub&gt;N-1&lt;/sub&gt; by dropping  2&lt;sup&gt;a&lt;/sup&gt; from m and add 2&lt;sup&gt;a&lt;/sup&gt; to result. So we don’t bother about a&lt;sup&gt;th&lt;/sup&gt; bit if it diffres.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;If a &amp;gt; x:&lt;/b&gt;  then (m, n) lies in the M&lt;sub&gt;bl&lt;/sub&gt; square of the smallest square M&lt;sub&gt;N&lt;/sub&gt; that contains (m, n). As we saw earlier, we can move it into M&lt;sub&gt;N-1&lt;/sub&gt; by dropping  2&lt;sup&gt;x&lt;/sup&gt; from n and add 2&lt;sup&gt;x&lt;/sup&gt; to result. So we don’t bother about x&lt;sup&gt;th&lt;/sup&gt; bit if it differs.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;The process will continue while either m or n are not zero. Every time one of them has a binary bit which is 0 in the other, this bit is removed from the number but added to result. So we see that whenever any bit of m and n differs, we need to add it to result and just drop it if it’s same. In Boolean mathematics, XOR operator does the same. At the end of the day, m = n = 0 whereas result contains (m XOR n) of the original m and n. So finally &lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;blockquote&gt;&lt;b&gt;M&lt;sub&gt;(m,n)&lt;/sub&gt; = m^n&lt;/b&gt;&lt;/blockquote&gt;&lt;/div&gt;&lt;/div&gt;Hence, we see that we can calculate the entry in a &lt;span class=&quot;Apple-style-span&quot;&gt;particular&lt;/span&gt; row and column in constant time and space.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;</description><link>http://tech-queries.blogspot.com/2011/08/matrix-madness-smallest-non-negative.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFms7y3pEdPctVplegA-T6TF1vJyDiWG0lbaaZrXpxqPsWEwOSy-TrlTr2BpplqgeQN7j8FscbML7CPPQ8W2B8UV_ZnOj-dnbhCyL3QCysIpEeWEyIdM0ytAE0l5IXBX7iJx0XkhoEuRM/s72-c/latin1.png" height="72" width="72"/><thr:total>4</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-834369811396203129</guid><pubDate>Wed, 03 Aug 2011 12:22:00 +0000</pubDate><atom:updated>2011-08-04T13:43:41.375+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Link List</category><category domain="http://www.blogger.com/atom/ns#">tree</category><title>Convert binary tree in circular doubly linked list</title><description>&lt;span style=&quot;font-weight: bold;&quot;&gt;Question:&lt;/span&gt; Take a binary tree and rearrange left and right pointers to make a circular doubly linked list.&lt;br /&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Or&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;Convert a BST to a sorted circular doubly-linked list in-place.&lt;br /&gt;&lt;br /&gt;You are supposed to play with pointers only. Assume left and right pointers of tree as previous and next pointers of doubly-linked list.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Answer:&lt;/span&gt; This is one of the most asked problems in programming interviews. &lt;a href=&quot;http://tech-queries.blogspot.com/search/label/MIcrosoft%20Interview&quot;&gt;Microsoft&lt;/a&gt; asks this question very frequently, I was asked the same when I rejected SDE-2 offer from Microsoft a few months ago. You can also find this problem at Stanford CS education library page as &lt;a href=&quot;http://cslibrary.stanford.edu/109/TreeListRecursion.html&quot;&gt;The Great Tree List Recursion Problem&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Below is original tree, which we have to convert in a circular doubly linked list.&lt;br /&gt;&lt;br /&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-XC3M3Phf3tRkjjon4sQ6Uy79JNt0alKEgR3ivuJMLXNqfrtAFN96yYyVuCM6jsW8bKA4MNY8YGvkUPsSF2xZtzhYakWMvo7CUEmJwm88DYqjor0owRpAhdKg9CR7tsuqY17vcFVkZ5k/s1600/treelist.png&quot;&gt;&lt;img style=&quot;display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 320px; height: 222px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-XC3M3Phf3tRkjjon4sQ6Uy79JNt0alKEgR3ivuJMLXNqfrtAFN96yYyVuCM6jsW8bKA4MNY8YGvkUPsSF2xZtzhYakWMvo7CUEmJwm88DYqjor0owRpAhdKg9CR7tsuqY17vcFVkZ5k/s320/treelist.png&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5636604929469537810&quot; border=&quot;0&quot; /&gt;&lt;/a&gt;&lt;br /&gt;And below is the original tree converted to circular doubly linked list with &quot;next&quot; and &quot;previous&quot; list arrows added.&lt;br /&gt;&lt;br /&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4gJLGuZP6Ws2RO5GZZohlJxJ4ix8Weu05vmKsmsubrXpfXLZnhN1lCv_a0uZz2f4P_IvLEnKkI6SgypAbTtSdqg78oiqBrhZwDm6dL6o13vMfKnjXCDm17NLD3O7x5xVTxZrQlyjkm8A/s1600/treelist2.gif&quot;&gt;&lt;img src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4gJLGuZP6Ws2RO5GZZohlJxJ4ix8Weu05vmKsmsubrXpfXLZnhN1lCv_a0uZz2f4P_IvLEnKkI6SgypAbTtSdqg78oiqBrhZwDm6dL6o13vMfKnjXCDm17NLD3O7x5xVTxZrQlyjkm8A/s320/treelist2.gif&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5636681958460436402&quot; style=&quot;display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 288px; height: 320px; &quot; border=&quot;0&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;Above drawing shows the all of the problem state -- the original tree is drawn with plain black lines and the desired next/previous pointers are added in as arrows. Notice that starting with the head pointer.&lt;br /&gt;&lt;br /&gt;Looking at the last figure, you might have already started thinking about in-order traversal. If not then please notice that in final linked list (shown below), all the nodes left to a node were actually the nodes from left-sub-tree in original tree. Similarly, all the nodes right to a node were actually the nodes from right-sub-tree in original tree. This is similar to in-order traversal of tree:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;process left sub tree&lt;/li&gt;&lt;li&gt;process current node&lt;/li&gt;&lt;li&gt;process right sub tree. &lt;/li&gt;&lt;/ol&gt;Here extra task is to modify pointers accordingly to create a link list.&lt;br /&gt;&lt;br /&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgNNQtbtk3mKeS6sdO2EpWqkrzsudVOo1P_0NCId1qZ7Ac1yGIwUjRJ2vDZS_PLWnxM-_HMv3nYq1zADo8MgcCEGtZTZnSQk8b_3rLFqw_dWsA889gccdMzlDo5NL9ckIjSmtVoPeGwKWk/s1600/doublylist.gif&quot;&gt;&lt;img style=&quot;display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 320px; height: 186px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgNNQtbtk3mKeS6sdO2EpWqkrzsudVOo1P_0NCId1qZ7Ac1yGIwUjRJ2vDZS_PLWnxM-_HMv3nYq1zADo8MgcCEGtZTZnSQk8b_3rLFqw_dWsA889gccdMzlDo5NL9ckIjSmtVoPeGwKWk/s320/doublylist.gif&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5636604926908607922&quot; border=&quot;0&quot; /&gt;&lt;/a&gt;&lt;br /&gt;As we traverse the tree in-order, we can modify a node’s left pointer to point to its predecessor. We also have to modify the predecessor’s right pointer to point to the current node to maintain the doubly linked list behavior.&lt;br /&gt;&lt;br /&gt;In this manner, we will be creating a list but that won’t be circular. We can solve this problem by creating a circular doubly linked list at every step in place of creating only doubly linked list. For this, we need to update the current node’s right pointer to point back to the head and the head’s left pointer to point to current node in each recursive call. As the recursion ends, the list’s head and tail would be automatically updated with the correct pointers.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Code:&lt;/span&gt;&lt;br /&gt;&lt;pre name=&quot;code&quot; class=&quot;cpp&quot;&gt;struct node {&lt;br /&gt;   int data;&lt;br /&gt;   struct node* left;&lt;br /&gt;   struct node* right;&lt;br /&gt;};&lt;br /&gt;typedef struct node* Node;&lt;br /&gt;&lt;br /&gt;//root: Current tree node&lt;br /&gt;//prev: this pointer should have the address of in-order predecessor of root&lt;br /&gt;//head: this denoted head of final link list&lt;br /&gt;void treeToDoublyList(Node root, Node &amp;amp; prev, Node &amp;amp; head)&lt;br /&gt;{&lt;br /&gt;   if (!root) return;&lt;br /&gt;   treeToDoublyList(root-&amp;gt;left, prev, head);&lt;br /&gt;&lt;br /&gt;   // current node&#39;s left points to previous node&lt;br /&gt;   root-&amp;gt;left = prev;&lt;br /&gt;   if (prev)&lt;br /&gt;       prev-&amp;gt;right = root; // previous node&#39;s right points to current node&lt;br /&gt;   else&lt;br /&gt;       head = root;        // if previous is NULL that current node is head&lt;br /&gt;&lt;br /&gt;   Node right = root-&amp;gt;right; //Saving right node&lt;br /&gt;&lt;br /&gt;   //Now we need to make list created till now as circular&lt;br /&gt;   head-&amp;gt;left = root;&lt;br /&gt;   root-&amp;gt;right = head;&lt;br /&gt;&lt;br /&gt;   //For right-subtree/parent, current node is in-order predecessor&lt;br /&gt;   prev = root;&lt;br /&gt;   treeToDoublyList(right, prev, head);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;//Wrapper function&lt;br /&gt;Node treeToDoublyList(Node root)&lt;br /&gt;{&lt;br /&gt;   Node prev = NULL;&lt;br /&gt;   Node head = NULL;&lt;br /&gt;   treeToDoublyList(root, prev, head);&lt;br /&gt;   return head;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Complexity:&lt;/span&gt; As this is nothing but in-order traversal with some extra steps at every node, we are traversing each node just once. Hence time complexity is O(n).&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Credits:&lt;/span&gt; All the images are copied from &lt;a href=&quot;http://cslibrary.stanford.edu/109/TreeListRecursion.html&quot;&gt;Stanford CS library page&lt;/a&gt;.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;</description><link>http://tech-queries.blogspot.com/2011/08/convert-binary-tree-in-circular-doubly.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-XC3M3Phf3tRkjjon4sQ6Uy79JNt0alKEgR3ivuJMLXNqfrtAFN96yYyVuCM6jsW8bKA4MNY8YGvkUPsSF2xZtzhYakWMvo7CUEmJwm88DYqjor0owRpAhdKg9CR7tsuqY17vcFVkZ5k/s72-c/treelist.png" height="72" width="72"/><thr:total>5</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-565965452157046964</guid><pubDate>Tue, 26 Jul 2011 12:25:00 +0000</pubDate><atom:updated>2011-07-26T18:16:44.075+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Brain Teasers</category><title>Truth or lie?</title><description>&lt;b&gt;Question:&lt;/b&gt; There are 100 people in a room. A person always speaks either lie or truth. When asked:&lt;br /&gt;&lt;blockquote&gt;1st person says =&amp;gt; all are liars&lt;br /&gt;2nd person says =&amp;gt; at most 1 speaks truth&lt;br /&gt;3rd person says =&amp;gt; at most 2 speak truth&lt;br /&gt;4th person says =&amp;gt; at most 3 speak truth&lt;br /&gt;.&lt;br /&gt;.&lt;br /&gt;.&lt;br /&gt;.&lt;br /&gt;100th person says =&amp;gt; at most 99 speak truth&lt;/blockquote&gt;&lt;br /&gt;How many people speak only truth?&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Answer:&lt;/b&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCOWmtBWqm-P3jh8aP1xQr-4zV54-P3ikWsMen_9qZWejFrOOrCF4vT4vH3nQ5B-bD6tgbOM25Z902cFVISQULStwA1ImI7GCP1nTQCe6UXURZn8hjXAWHIhqEOJhKDlSWy0W0TAdYycs/s1600/truth-lie.jpg&quot; onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot;&gt;&lt;img style=&quot;float:right; margin:0 0 10px 10px;cursor:pointer; cursor:hand;width: 166px; height: 200px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCOWmtBWqm-P3jh8aP1xQr-4zV54-P3ikWsMen_9qZWejFrOOrCF4vT4vH3nQ5B-bD6tgbOM25Z902cFVISQULStwA1ImI7GCP1nTQCe6UXURZn8hjXAWHIhqEOJhKDlSWy0W0TAdYycs/s200/truth-lie.jpg&quot; border=&quot;0&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5633637080748060354&quot; /&gt;&lt;/a&gt; Lets assume that person 1 speaks truth then all including him should be liar. It means he doesn’t speak truth.&lt;br /&gt;&lt;br /&gt;Before moving forward, we should make it clear what does “at most” mean? “at most N” means N or less.&lt;br /&gt;&lt;br /&gt;Lets assume that 2nd person speaks truth then he is the only person who speaks truth coz at most 1 means 1 or less. But if this statement is true then statements by all others are also true. Coz if “at most 1 person speaks truth” is true then “at most N speak truth” is also true, where N &amp;gt;= 1.  This contradicts his own statement, so person 2 is also a liar.&lt;br /&gt;&lt;br /&gt;Now lets say that 3rd person is speaking truth. But then the statements of person 4-100 are also true, which contradicts his own statement. It means that person 3 is also a liar.&lt;br /&gt;&lt;br /&gt;This process will continue since 50th person.  So 1-50 people are liars.&lt;br /&gt;&lt;br /&gt;51st person says “at most 50 speak truth”. Lets say he is speaking truth. “at most 50” means any number from 0-50. It means that statements like “at most 51 speak truth” and “at most 70 speak truth” are also true. It means that people from 51 to 100 are speaking truth.&lt;br /&gt;&lt;br /&gt;Hence, &lt;b&gt;50 people speak truth.&lt;/b&gt;&lt;div&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;</description><link>http://tech-queries.blogspot.com/2011/07/truth-or-lie.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCOWmtBWqm-P3jh8aP1xQr-4zV54-P3ikWsMen_9qZWejFrOOrCF4vT4vH3nQ5B-bD6tgbOM25Z902cFVISQULStwA1ImI7GCP1nTQCe6UXURZn8hjXAWHIhqEOJhKDlSWy0W0TAdYycs/s72-c/truth-lie.jpg" height="72" width="72"/><thr:total>6</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-3198457654974632142</guid><pubDate>Tue, 19 Jul 2011 05:11:00 +0000</pubDate><atom:updated>2011-07-27T00:44:24.293+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Arrays/Strings</category><category domain="http://www.blogger.com/atom/ns#">queue</category><title>Count Number of Blobs</title><description>&lt;b&gt;Question:&lt;/b&gt; You are given a 2D array like below:&lt;div style=&quot;text-align: center;&quot;&gt;&lt;/div&gt;&lt;blockquote&gt;&lt;div style=&quot;text-align: center;&quot;&gt;x o o o o x&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;x x x o o x&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;o o x o x o&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;o o x o o o&lt;/div&gt;&lt;/blockquote&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;/div&gt;&lt;br /&gt;A blob is defined as 1 or more adjacent (8 adjacent) Xs. Find the number of blobs in the most efficient manner.&lt;div&gt;&lt;br /&gt;&lt;b&gt;Example:&lt;/b&gt; Below 2D array has 2 blobs. One blob consists of cells which have red &#39;x&#39; and another consists of cells which have blue &#39;x&#39;.&lt;div&gt;&lt;br /&gt;&lt;img src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEvLIMuvudeMYxdzHGMxqd8jfUJ9XutkPVZFyKjn6W2SfoVMLrZHP54VrFzN0yJXQZCsIFk6dtREG95pxMSBpUlvUsDIyVsbcS4HAPK71lhIf3xg0jsuaC9AEdAMsNoXJnUK0qgcAG4Cc/s400/blob.png&quot; style=&quot;display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 244px;&quot; border=&quot;0&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5630927782414088738&quot; /&gt;&lt;br /&gt;&lt;b&gt;Extension:&lt;/b&gt; This question is also asked as to count the number of islands in an ocean where ocean is represented as a grid. Cells, having a part of any island, are marked as &#39;x&#39; otherwise &#39;o&#39;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;img src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsjxZCw9bvAtGJHBccUm_UHenR94Ie4FgWhs3U4Ctgkfqe_1JuLtMC-U7OLyIjqcuDko81E-gL8o9QBpChPg783harksQZKJjbzxHjLA8S_d3uLjsZPFzorqe2t2Z7wjcsziKvOzI7W20/s400/island.jpg&quot; style=&quot;display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 258px;&quot; border=&quot;0&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5630927780528782946&quot; /&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Answer:&lt;/b&gt; There is a recursive solution to check &#39;x&#39; cells every time you encounter &#39;x&#39; in any cell. But this solution is very inefficient coz you will be checking 8 cells for every &#39;x&#39; cell and will result in a number of recursive loops. Also keeping count of blobs in this case is a bit difficult.&lt;br /&gt;&lt;br /&gt;An efficient solution will be to mark all the cells in a single blob as used and increase the count by 1 for every blob. For this we need a data structure, which we can use to find cells in a single blob. This can be achieved by using a queue as described below.&lt;br /&gt;&lt;br /&gt;While traversing the array in row/column major order, as soon as you encounter an unused &#39;x&#39; cell, push it in queue. Also increment the count by 1 and mark this cell as used. Now pop front element from queue and check for its 8 neighbors, if they contain &#39;x&#39; and not used, put them in queue. Repeat this process until queue is empty.&lt;br /&gt;&lt;br /&gt;Using above method, you will be able to mark all cells of a blob as used. Now traverse array further and repeat the same process if you encounter any unused &#39;x&#39; cell.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Algorithm:&lt;/b&gt;&lt;br /&gt;&lt;pre name=&quot;code&quot; class=&quot;cpp&quot;&gt;count = 0&lt;br /&gt;while row &amp;lt; total rows&lt;br /&gt;while column &amp;lt; total columns&lt;br /&gt; if  cell[row][column] is unused&lt;br /&gt;  put in queue&lt;br /&gt;  increase count by 1&lt;br /&gt;  while queue is not empty&lt;br /&gt;   tmp = front element of queue&lt;br /&gt;   pop from queue&lt;br /&gt;   push unused &#39;x&#39; neighbors of tmp in queue&lt;br /&gt;  end while&lt;br /&gt; end if&lt;br /&gt;end while&lt;br /&gt;end while&lt;br /&gt;return count&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Code:&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;I have used MSB of every cell to use as a flag for used and unused cell. You can always use a different method.&lt;br /&gt;&lt;pre name=&quot;code&quot; class=&quot;cpp&quot;&gt;#define MAX 100&lt;br /&gt;#define USED 0x80&lt;br /&gt;&lt;br /&gt;struct point&lt;br /&gt;{&lt;br /&gt;    int x,y;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;void push_in_queue(int x, int y, queue&amp;lt;struct point&amp;gt; *q, char mat[MAX][MAX], int nrow, int ncol) &lt;br /&gt;{&lt;br /&gt;    if(x &amp;lt; 0 || x &amp;gt;= nrow || y &amp;lt; 0 || y &amp;gt;= ncol)&lt;br /&gt;      return;&lt;br /&gt;    struct point pnt;&lt;br /&gt;    if (mat[x][y] == &#39;X&#39; &amp;amp;&amp;amp; !(USED &amp;amp; mat[x][y]))&lt;br /&gt;    {        &lt;br /&gt;        mat[x][y] = USED | mat[x][y];&lt;br /&gt;        pnt.x = x;&lt;br /&gt;        pnt.y = y;&lt;br /&gt;        q-&amp;gt;push(pnt);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int count_blob(char mat[MAX][MAX], int nrow, int ncol)&lt;br /&gt;{   &lt;br /&gt;    queue&amp;lt;struct point&amp;gt; que;&lt;br /&gt;    int cnt = 0;&lt;br /&gt;    int x, y;&lt;br /&gt;    point pnt, tmp;&lt;br /&gt;    if (nrow == 0 &amp;amp;&amp;amp; ncol == 0)&lt;br /&gt;        return 0;&lt;br /&gt;        &lt;br /&gt;    for(x = 0; x &amp;lt; nrow; x++)&lt;br /&gt;    {&lt;br /&gt;        for(y = 0; y &amp;lt; ncol; y++)            &lt;br /&gt;        {&lt;br /&gt;            if (USED &amp;amp; mat[x][y])&lt;br /&gt;                continue;&lt;br /&gt;                &lt;br /&gt;            if (mat[x][y] == &#39;X&#39;)&lt;br /&gt;            {&lt;br /&gt;                cnt += 1;&lt;br /&gt;                mat[x][y] = USED | mat[x][y];&lt;br /&gt;                pnt.x = x;&lt;br /&gt;                pnt.y = y;&lt;br /&gt;                que.push(pnt);&lt;br /&gt;&lt;br /&gt;                while( !que.empty() )&lt;br /&gt;                {&lt;br /&gt;                    tmp = que.front();&lt;br /&gt;                    que.pop();                    &lt;br /&gt;                    push_in_queue(tmp.x - 1, tmp.y,     &amp;amp;que, mat, nrow, ncol);&lt;br /&gt;                    push_in_queue(tmp.x - 1, tmp.y - 1, &amp;amp;que, mat, nrow, ncol);&lt;br /&gt;                    push_in_queue(tmp.x - 1, tmp.y + 1, &amp;amp;que, mat, nrow, ncol);&lt;br /&gt;                    push_in_queue(tmp.x + 1, tmp.y,     &amp;amp;que, mat, nrow, ncol);&lt;br /&gt;                    push_in_queue(tmp.x + 1, tmp.y - 1, &amp;amp;que, mat, nrow, ncol);&lt;br /&gt;                    push_in_queue(tmp.x + 1, tmp.y + 1, &amp;amp;que, mat, nrow, ncol);&lt;br /&gt;                    push_in_queue(tmp.x,     tmp.y - 1, &amp;amp;que, mat, nrow, ncol);&lt;br /&gt;                    push_in_queue(tmp.x,     tmp.y + 1, &amp;amp;que, mat, nrow, ncol);                   &lt;br /&gt;                }                 &lt;br /&gt;            }                    &lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    return cnt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;b&gt;Complexity:&lt;/b&gt; Since every element of the matrix is processed at the most twice, once while putting in queue and once while normal 2D array traversal, time complexity is O(n) where n is total number of cells. You may argue that we are checking a few element more than 2 times while pushing in the queue, in that case also complexity will be O(n).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;b&gt;Space complexity:&lt;/b&gt; Extra space is occupied by queue. Please notice that queue size will never be more than &#39;n&#39;. You can also deduce that queue size will always be much lesser than &#39;n&#39; in worst case as well. So space complexity is of order &#39;n&#39; = O(n).&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;</description><link>http://tech-queries.blogspot.com/2011/07/count-number-of-blobs.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEvLIMuvudeMYxdzHGMxqd8jfUJ9XutkPVZFyKjn6W2SfoVMLrZHP54VrFzN0yJXQZCsIFk6dtREG95pxMSBpUlvUsDIyVsbcS4HAPK71lhIf3xg0jsuaC9AEdAMsNoXJnUK0qgcAG4Cc/s72-c/blob.png" height="72" width="72"/><thr:total>5</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6038272452605714757.post-374348279707613710</guid><pubDate>Fri, 15 Jul 2011 09:03:00 +0000</pubDate><atom:updated>2011-07-15T16:01:34.475+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Link List</category><title>Detect where the loop starts in a singly link list</title><description>In &lt;a href=&quot;http://tech-queries.blogspot.com/2011/07/find-loop-in-singly-linked-list.html&quot;&gt;last post&lt;/a&gt;, we found how to detect if there is a loop in singly &lt;a href=&quot;http://tech-queries.blogspot.com/search/label/Link%20List&quot;&gt;link list &lt;/a&gt;or not. Now we will see how to detect where the loop starts.&lt;img src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRwW3fnWwADyQTWbApKQlmlPjG2RpI7WNlX7r7Exv1hyFnPe0KuOnyy0EbQnCjAAPtvhj0-e3-9oMpBrx8FQwZCQB_iaTc2UuFGhvsvPXhOVH-ZO8x6uhk6rG7AdEzSzASrAuJw5k84Cg/s400/Screen+shot+2011-07-15+at+3.55.20+PM.png&quot; style=&quot;display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 211px;&quot; border=&quot;0&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5629523592155473970&quot; /&gt;In above figure, we see that loop starts at node (a) after length x and loop length is z. So the total length of link list is (x+z). Also as we saw in &lt;a href=&quot;http://tech-queries.blogspot.com/2011/07/find-loop-in-singly-linked-list.html&quot;&gt;last post&lt;/a&gt; that slow and fast iterator will meet at some node (b).&lt;br /&gt;&lt;br /&gt;Please note if we move a pointer (one node per iteration) from (b) and keep count of nodes until we visit (b)  again, we will be able to calculate z.&lt;br /&gt;&lt;br /&gt;After finding z, start an iterator itr1 form head and move it z nodes from head at (c). Take another iterator itr2 and start it from head. Now if you move itr1 and itr2 in parallel one node at a time, they will meet first at start of the loop (a).&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Explanation&lt;/b&gt; is based on following invariance:&lt;br /&gt;&lt;blockquote&gt;&quot;In a circle if we start from some point and move the distance equal to circumference along circle periphery, we will be at the same point again.&quot;&lt;/blockquote&gt;&lt;br /&gt;Both the iterators are meeting at (a) coz itr1 is z nodes ahead from itr2. Once itr1 is at (a), itr2 is z nodes behind (a). After z iterations, itr2 will reach (a) and itr1 also reaches (a) because of above invariant.&lt;br /&gt;&lt;br /&gt;This solution has been suggested by &lt;a href=&quot;http://www.blogger.com/profile/04320918945204019444&quot;&gt;Saket&lt;/a&gt; in &lt;a href=&quot;http://tech-queries.blogspot.com/2011/07/find-loop-in-singly-linked-list.html#comment-9217824841556636995&quot;&gt;comments to last post&lt;/a&gt;. Great solution Saket!&lt;div&gt;&lt;br /&gt;&lt;/div&gt;</description><link>http://tech-queries.blogspot.com/2011/07/detect-where-loop-start-in-singly-link.html</link><author>noreply@blogger.com (Akash)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRwW3fnWwADyQTWbApKQlmlPjG2RpI7WNlX7r7Exv1hyFnPe0KuOnyy0EbQnCjAAPtvhj0-e3-9oMpBrx8FQwZCQB_iaTc2UuFGhvsvPXhOVH-ZO8x6uhk6rG7AdEzSzASrAuJw5k84Cg/s72-c/Screen+shot+2011-07-15+at+3.55.20+PM.png" height="72" width="72"/><thr:total>9</thr:total></item></channel></rss>