R@M3$H.NTech Blog.
/
Sun, 28 Feb 2016 13:57:40 +0000Sun, 28 Feb 2016 13:57:40 +0000Jekyll v3.0.3Call Base class method through base class pointer pointing to derived class<p>class Base<br />
{<br />
public:<br />
virtual void foo()<br />
{}<br />
};</p>
<p>class Derived: public Base<br />
{<br />
public:<br />
virtual void foo()<br />
{}<br />
};</p>
<p>int main()<br />
{<br />
Base *pBase = NULL;<br />
Base objBase;<br />
Derived objDerived;</p>
<p> pBase = &objDerived;<br />
pBase->foo();</p>
<p> /*Here Derived class foo will be called, but i want this to call<br />
a base class foo. Is there any way for this to happen? i.e. through<br />
casting or something? */<br />
}</p>
<p>You can do it through scope resolution operator ::</p>
<p>Something like this:</p>
<p>pBase->Base::foo()</p>
Mon, 02 Nov 2015 10:33:14 +0000
/cpp/2015/11/02/call-base-class-method-through-base-class-pointer-pointing-to-derived-class-2.html
/cpp/2015/11/02/call-base-class-method-through-base-class-pointer-pointing-to-derived-class-2.htmlCPPJson & XML Formating on Mac CommandLine<p> print formatted JSON, XML from osx command line<br />
Working with various interfaces that output json or xml results in lots of situations where you have a single-line, unformatted output. Here's a quick way to format json, xml from the CLI.</p>
<p>via the command line:</p>
<p>format json</p>
<p>cat unformatted.json | python -m json.tool<br />
format json from clipboard</p>
<p>pbpaste | python -m json.tool<br />
format xml from clipboard</p>
<p>pbpaste | xmllint --format -<br />
xmllint is part of libxml2 and installed by default on OSX. Be aware that xmllint cleans up XML as well as formatting it, ocassionally modifying the output.<br />
for all above examples, you can pipe back to the clipboard with | pbcopy at the end of the command, or output to a file with > output.json or > output.xml.</p>
Wed, 14 Oct 2015 10:27:01 +0000
/linux/2015/10/14/json-xml-formating-on-mac-commandline.html
/linux/2015/10/14/json-xml-formating-on-mac-commandline.htmlLinuxConstructing Bridges<p>Problem:<br />
A River that cuts through a set of cities above and below it. Each city above the river is matched with a city below the river.<br />
Construct as many Non-Crossing Bridges as possible.<br />
Input:<br />
Above Bank >> 7 4 3 6 2 1 5<br />
Below Bank >> 5 3 2 4 6 1 7<br />
are given in pairs: (7,5) (4,3) (3,2) (6,4) (2,6) (1,1) (5,7)<br />
Output:<br />
(1,1) (3,2) (4,3) (6,4) (7,5)</p>
<p>Solution:<br />
Its an Longest Increasing Sub-Sequence Dynamic programming Problem with O(N log N) solution.</p>
<p>Above Bank >> 7 4 3 6 2 1 5<br />
Below Bank >> 5 3 2 4 6 1 7<br />
Pairs >> (7,5) (4,3) (3,2) (6,4) (2,6) (1,1) (5,7)</p>
<p>Sort the pairs based on Lower Bank Cities as Below:<br />
Above Bank >> 1 3 4 6 7 2 5<br />
Below Bank >> 1 2 3 4 5 6 7</p>
<p>Now the Problem reduces to finding the LIS from the Cities in Above Bank >> 1 3 4 6 7 2 5<br />
which is 1 3 4 6 7</p>
<p>So, the Output with corresponding Lower Bank Cities will be<br />
(1,1) (3,2) (4,3) (6,4) (7,5)</p>
<p>EDIT:<br />
If we have the elements sorted by their Below Bank, then we can tell if two pairs are orderable by <=, by just looking at their positions in the Above Bank.<br />
If the first pair(1,1) is to the left of the second pair(3,2), we immediately know that the second elements of the first pair(1) is less than the second element of the second pair(2), since we've sorted them by the second coordinate.<br />
We then have this pair of elements can have Bridge built together if and only if the first element of the first pair(1) is less than the first element of the second pair(3).</p>
<p>Consequently, if we want to find a set of Bridges that can be built together, we're looking for an Increasing Sub-Sequence of the Cities in Above Bank, since in that case both the first and second elements of the pairs are increasing as we move from the left to the right.</p>
<p>Finding the longest increasing subsequence then solves this problem.</p>
<p>Complexity:<br />
Sort the pairs by their Below Bank = O(N log N)<br />
Find the LIS in O(N log N)<br />
So, this is an O(N log N) solution.</p>
Thu, 01 Jan 2015 13:07:25 +0000
/algos/2015/01/01/constructing-bridges.html
/algos/2015/01/01/constructing-bridges.htmlAlgosDesign a Tiny URl Service<p>Redirect Part:</p>
<p>When you click on a link of any tiny url, an HTTP Request is sent to their server with the full URL, like http // bit.ly / b9 (not a real one).</p>
<p>They read the path part (here b9), which maps to their Database.</p>
<p>In the Database, they find the real URL. Then they issue a redirect, which is a HTTP 302 response and the target URL in the header.</p>
<p>Encoding Part:</p>
<p>One of the most popular URL shortening services simply take the ID in the database of the URL and then convert it to Base 62[a-zA-Z0-9].</p>
<p>import static org.testing.AssertJUnit.assertEquals ;</p>
<p>public class TinyURL {<br />
private static final String ALPHABET_MAP = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ;<br />
private static final int BASE = ALPHABET_MAP.length() ;</p>
<p>public static String encode ( int IndexNum ) {<br />
StringBuilder sb = new StringBuilder() ;</p>
<p>while ( IndexNum > 0 ) {<br />
sb.append ( ALPHABET_MAP.charAt ( IndexNum % BASE ) ) ;<br />
IndexNum /= BASE ;<br />
}<br />
return sb.reverse().toString() ;<br />
}</p>
<p>public static int decode ( String str ) {<br />
int Num = 0 ;</p>
<p>for ( int i = 0, len = str.length(); i < len; i++ ) {<br />
Num = Num * BASE + ALPHABET_MAP.indexOf ( str.charAt(i) ) ;<br />
}<br />
return Num ;<br />
}</p>
<p>public static void main ( String[] args ) {<br />
//System.out.println ( "Encoding for 123 is " + encode(123) ) ;<br />
//System.out.println ( "Decoding for b9 is " + decode ("b9" ) ) ;</p>
<p>assertEquals ( "b9", encode(123) ) ;<br />
assertEquals ( 123, decode("b9") ) ;<br />
}<br />
}</p>
<p>I think this is more of a design question than a coding one.</p>
<p>We can think about<br />
- reducing the response time of the server<br />
---- by using a distributed system to share the load based on geography<br />
---- by using a central server but many caching servers at various geographical locations<br />
---- what would be the right database design</p>
<p>- reducing the storage space<br />
---- database design</p>
<p>- backup and failover</p>
<p>- security issues<br />
---- prevent people from creating links to ---whatever---</p>
<p>- handling old/obsolete urls<br />
---- may be, while creating the url we can say to the user that it will be deleted if the url is never used for more than say 3 years<br />
---- may be allow the user to login and delete unused ones</p>
<p>- how a company like bit.ly is going to make profit out of this service! how can that be improved</p>
<p>- user friendly things<br />
---- browser plugins to speed up creating links (youtube sharing has an option to create short urls)<br />
---- giving report to user about the usage statistics<br />
---- mobile app to create urls quickly</p>
<p>.....</p>
Thu, 01 Jan 2015 13:04:54 +0000
/design/2015/01/01/design-a-tiny-url-service.html
/design/2015/01/01/design-a-tiny-url-service.htmlDesignCreating an Array of Objects<p>I have a class A for example -</p>
<p>A[] arr = new A[4];<br />
But this is only creating pointers (references) to A and not 4 objects. Is this correct? I see that when I try to access functions/variables in the objects created I get a null pointer exception. To be able to manipulate/access the objects I had to do this --</p>
<p>A[] arr = new A[4];<br />
for( int i=0; i<4; i++ )<br />
arr[i] = new A();</p>
<p>I find this odd because in C++ you just say new A[4] and it creates the four objects.</p>
<p>This is correct.</p>
<p>A[] a = new A[4];<br />
creates 4 A variables, similar to doing this</p>
<p>A a1;<br />
A a2;<br />
A a3;<br />
A a4;<br />
now you couldn't do a1.someMethod() without allocating a1 as</p>
<p>a1 = new A();<br />
similarly, with the array you need to do</p>
<p>a[0] = new A();<br />
before using it.</p>
<p>The reason int works, but MyClass doesn't:</p>
<p>From here:</p>
<p>Data Type Default Value (for fields)<br />
byte 0<br />
short 0<br />
int 0<br />
long 0L<br />
float 0.0f<br />
double 0.0d<br />
char '\u0000'<br />
String (or any object) null<br />
boolean false<br />
When you initialize an array, all elements take on the default value.</p>
<p>So, when you initialize an int[], all elements are 0, so no problem using that or assigning a new value to it.</p>
<p>But, when you initialize an MyClass[], all elements are null, which is a problem when you try to access a member of one of the elements.</p>
<p>If you don't know why accessing a null object's members won't work, you probably need to take 2 steps back and read a Java book.</p>
<p>Additional Note:</p>
<p>Technically, this:</p>
<p>int[] foo = new int[1];<br />
foo[0] = 0;<br />
is actually more like this:</p>
<p>MyClass[] foo = new MyClass[10];<br />
foo[0] = new MyClass();<br />
not:</p>
<p>MyClass[] foo = new MyClass[10];<br />
foo[0].bar = 0;<br />
since you're assigning a new value to an element, rather than accessing a member of an element.</p>
<p>No enclosing instance of type Test is accessible:</p>
<p>The other answers cover that pretty well, and here are 3 related questions:</p>
<p>No enclosing instance of type is accessible.</p>
<p>No enclosing instance of type Server is accessible</p>
<p>"No enclosing instance of type" error while calling method from another class in Android</p>
Wed, 19 Nov 2014 16:11:12 +0000
/java/2014/11/19/creating-an-array-of-objects.html
/java/2014/11/19/creating-an-array-of-objects.htmlJava[ALGO] Median of Integer Stream<div id="stcpDiv">
<p>Given a stream of unsorted integers, find the median element in sorted order at any given time. So, we will be receiving a continuous stream of numbers in some random order and we don’t know the stream length in advance. Write a function that finds the median of the already received numbers efficiently at any time. We will be asked to find the median multiple times. Just to recall, median is the middle element in an odd length sorted array, and in the even case it’s the average of the middle elements.</p>
<p>This is a data structure question. We will insert the received numbers into such a data structure that we’ll be able to find the median very efficiently. Let’s analyse the possible options.</p>
<p>We can insert the integers to an unsorted array, so we’ll just append the numbers to the array one by one as we receive. Insertion complexity is O(1) but finding the median will take O(N) time, if we use the <a href="http://www.ardendertat.com/2011/10/27/programming-interview-questions-10-kth-largest-element-in-array/">Median of Medians</a> algorithm that I described in my previous post. However, our goal is to find the median most efficiently, we don’t care that much about insertion performance. But this algorithm does the exact opposite, so unsorted array is not a feasible solution.</p>
<p>What about using a sorted array? We can find the position to insert the received number in O(logN) time using binary search. And at any time if we’re asked for the median we can just return the middle element if the array length is odd, or the average of middle elements if the length is even. This can be done in O(1) time, which is exactly what we’re looking for. But there’s a major drawback of using a sorted array. To keep the array sorted after inserting an element, we may need to shift the elements to the right, which will take O(N) time. So, even if finding the position to insert the number takes O(logN) time, the overall insertion complexity is O(N) due to shifting. But finding the median is still extremely efficient, constant time. However, linear time insertion is pretty inefficient and we would prefer a better performance.</p>
<p>Let’s try linked lists. First unsorted linked list. Insertion is O(1), we can insert either to the head or tail but we suffer from the same problem of unsorted array. Finding the median is O(N). What if we keep the linked list sorted? We can find the median in O(1) time if we keep track of the middle elements. Insertion to a particular location is also O(1) in any linked list, so it seems great thus far. But, finding the right location to insert is not O(logN) as in sorted array, it’s instead O(N) because we can’t perform binary search in a linked list even if it is sorted. So, using a sorted linked list doesn’t worth the effort, insertion is O(N) and finding median is O(1), same as the sorted array. In sorted array insertion is linear due to shifting, here it’s linear because we can’t do binary search in a linked list. This is a very fundamental data structure knowledge that we should keep at the top of our heads all the time.</p>
<p>Using a stack or queue wouldn’t help as well. Insertion would be O(1) but finding the median would be O(N), very inefficient.</p>
<p>What if we use trees? Let’s use a binary search tree with additional information at each node, number of children on the left and right subtrees. We also keep the number of total nodes in the tree. Using this additional information we can find the median in O(logN) time, taking the appropriate branch in the tree based on number of children on the left and right of the current node. However, the insertion complexity is O(N) because a standard binary search tree can degenerate into a linked list if we happen to receive the numbers in sorted order.</p>
<p>So, let’s use a balanced binary search tree to avoid worst case behaviour of standard binary search trees. In a height balanced binary search tree (i.e. AVL tree) the balance factor is the difference between the heights of left and right subtrees. A node with balance factor 0, +1, or -1 is considered to be balanced. However, in our tree the balance factor won’t be height, it is the number of nodes in the left subtree minus the number of nodes in the right subtree. And only the nodes with balance factor of +1 or 0 are considered to be balanced. So, the number of nodes on the left subtree is either equal to or 1 more than the number of nodes on the right subtree, but not less. If we ensure this balance factor on every node in the tree, then the root of the tree is the median, if the number of elements is odd. In the even case, the median is the average of the root and its inorder successor, which is the leftmost descendent of its right subtree. So, complexity of insertion maintaining balance condition is O(logN) and find median operation is O(1) assuming we calculate the inorder successor of the root at every insertion if the number of nodes is even. Insertion and balancing is very similar to AVL trees. Instead of updating the heights, we update the number of nodes information.</p>
<p>Balanced binary search trees seem to be the most optimal solution, insertion is O(logN) and find median is O(1). Can we do better? We can achieve the same complexity with a simpler and more elegant solution. We will use 2 heaps simultaneously, a max-heap and a min-heap with 2 requirements. The first requirement is that the max-heap contains the smallest half of the numbers and min-heap contains the largest half. So, the numbers in max-heap are always less than or equal to the numbers in min-heap. Let’s call this the order requirement. The second requirement is that, the number of elements in max-heap is either equal to or 1 more than the number of elements in the min-heap. So, if we received 2N elements (even) up to now, max-heap and min-heap will both contain N elements. Otherwise, if we have received 2N+1 elements (odd), max-heap will contain N+1 and min-heap N. Let’s call this the size requirement.</p>
<p>The heaps are constructed considering the two requirements above. Then once we’re asked for the median, if the total number of received elements is odd, the median is the root of the max-heap. If it’s even, then the median is the average of the roots of the max-heap and min-heap. Let’s now analyse why this approach works, and how we construct the heaps.</p>
<p>We will have two methods, insert a new received number to the heaps and find median. The insertion procedure takes the two requirements into account, and it’s executed every time we receive a new element. We take two different approaches depending on whether the total number of elements is even or odd before insertion.</p>
<p>Let’s first analyze the size requirement during insertion. In both cases we insert the new element to the max-heap, but perform different actions afterwards. In the first case, if the total number of elements in the heaps is even before insertion, then there are N elements both in max-heap and min-heap because of the size requirement. After inserting the new element to the max-heap, it contains N+1 elements but this doesn’t violate the size requirement. Max-heap can contain 1 more element than min-heap. In the second case, if the number of elements is odd before insertion, then there are N+1 elements in max-heap and N in min-heap. After we insert the new element to the max-heap, it contains N+2 elements. But this violates the size constraint, max-heap can contain at most 1 more element than min-heap. So we pop an element from max-heap and push it to min-heap. The details will be described soon.</p>
<p>Now let’s analyse the order requirement. This requirement forces every element in the max-heap to be less than or equal to all the elements in min-heap. So the max-heap contains the smaller half of the numbers and the min-heap contains the larger half. Note that by design the root of the max-heap is the maximum of the lower half, and root of the min-heap is the minimum of the upper half. Keeping these in mind, we again take two different actions depending on whether the total number of elements is even or odd before insertion. In the even case we just inserted the new element to the max-heap. If the new element is less than all the elements in the min-heap, then the order constraint is satisfied and we’re done. We can perform this check by comparing the new element to the root of the min-heap in O(1) time since the root of the min-heap is the minimum. But if the new element is larger than the root of min-heap then we should exchange those elements to satisfy the order requirement. Note that in this case the root of the max-heap is the new element. So we pop the the root of min-heap and insert it to max-heap. Also pop the root of max-heap and insert it to min-heap. In second case, where the total number of elements before insertion is odd, we inserted the new element to max-heap, then we popped an element and pushed it to the min-heap. To satisfy the order constraint, we pop the maximum element of the max-heap, the root, and insert it to the min-heap. Insertion complexity is O(logN), which is the insertion complexity of a heap.</p>
<p>That is exactly how the insertion procedure works. We ensured that both size and order requirements are satisfied during insertion. Find median function works as follows. At any time we will be queried for the median element. If the total number of elements at that time is odd, then the median is the root of the max-heap. Let’s visualize this with an example. Assume that we have received 7 elements up to now, so the median is the 4th number in sorted order. Currently, max-heap contains 4 smallest elements and min-heap contains 3 largest because of the requirements described above. And since the root of the max-heap is the maximum of the smallest four elements, it’s the 4th element in sorted order, which is the median. Else if the total number of elements is even, then the median is the average of the roots of max-heap and min-heap. Let’s say we have 8 elements, so the median is the average of 4th and 5th elements in sorted order. Currently, both the max-heap and min-heap contain 4 numbers. Root of the max-heap is the maximum of the smallest numbers, which is 4th in sorted order. And root of the min-heap is the minimum of the largest numbers, which is 5th in sorted order. So, the median is the average of the roots. In both cases we can find the median in O(1) time because we only access the roots of the heaps, neither insertion nor removal is performed. Therefore, overall this solution provides O(1) find heap and O(logN) insert.</p>
<p>A code is worth a thousand words, here is the code of the 2-heaps solution. As you can see, it’s much less complicated than it’s described. We can use the heapq module in python, which provides an implementation of min-heap only. But we need a max-heap as well, so we can make a min-heap behave like a max-heap by multiplying the number to be inserted by -1 and then inserting. So, every time we insert or access an element from the max-heap, we multiply the value by -1 to get the original number:</p>
<div class="wp_syntax">
<table>
<tbody>
<tr>
<td class="code">
<pre class="python">class streamMedian:
def __init__(self):
self.minHeap, self.maxHeap = [], []
self.N=0
def insert(self, num):
if self.N%2==0:
heapq.heappush(self.maxHeap, -1*num)
self.N+=1
if len(self.minHeap)==0:
return
if -1*self.maxHeap[0]>self.minHeap[0]:
toMin=-1*heapq.heappop(self.maxHeap)
toMax=heapq.heappop(self.minHeap)
heapq.heappush(self.maxHeap, -1*toMax)
heapq.heappush(self.minHeap, toMin)
else:
toMin=-1*heapq.heappushpop(self.maxHeap, -1*num)
heapq.heappush(self.minHeap, toMin)
self.N+=1
def getMedian(self):
if self.N%2==0:
return (-1*self.maxHeap[0]+self.minHeap[0])/2.0
else:
return -1*self.maxHeap[0]</pre>
</td>
</tr>
</tbody>
</table>
</div>
<p>We have a class streamMedian, and every time we receive an element, insert function is called. The median is returned using the getMedian function.</p>
<p>This is a great interview question that tests data structure fundamentals in a subtle way.</p>
<p>- See more at: http://www.ardendertat.com/2011/11/03/programming-interview-questions-13-median-of-integer-stream/#sthash.dvIFZG2G.dpuf</p></div>
Wed, 08 Oct 2014 16:38:00 +0000
/algos/2014/10/08/algo-median-of-integer-stream.html
/algos/2014/10/08/algo-median-of-integer-stream.htmlAlgosHow to make a method thread-safe in Java?<p>Interview Question:</p>
<p>Is the following method thread-safe? How to make it thread-safe?</p>
<div class="wp_syntax">
<table>
<tbody>
<tr>
<td class="code">
<pre class="java">class MyCounter {
private static int counter = 0;
public static int getCount() {
return counter++;
}
}</pre>
</td>
</tr>
</tbody>
</table>
</div>
<p>This post explains a general interview question that has been asked by Google and a lot of companies. It's low-level and not about how to design concurrent program.</p>
<p>First of all, the answer is NO. The method is not thread-safe, because the <em>counter++</em> operation is not atomic, which means it consists more than one atomic operations. In this case, one is accessing value and the other is increasing the value by one.</p>
<p><img class="alignnone size-full wp-image-11967" src="/assets/thread-safe-method1.png" alt="thread-safe method" width="400" height="280" /></p>
<p>When Thread 1 accesses the method at t1, Thread 2 may not be done with the method. So the value returned to Thread 1 is the value that has not been increased.</p>
<p><strong>Make a method thread-safe - Method 1</strong></p>
<p>Adding synchronized to this method will makes it thread-safe. When <em>synchronized</em> is added to a static method, the <em>Class</em> object is the object which is locked.</p>
<p>Is marking it synchronized enough? The answer is YES.</p>
<div class="wp_syntax">
<table>
<tbody>
<tr>
<td class="code">
<pre class="java">class MyCounter {
private static int counter = 0;
public static synchronized int getCount() {
return counter++;
}
}</pre>
</td>
</tr>
</tbody>
</table>
</div>
<p>If the method is not static, then adding <em>synchronized</em> keyword willsynchronize the instance of the class, not the <em>Class</em> object.</p>
<p><strong>Make a method thread-safe - Method 2</strong></p>
<p>In this particular counter example, we actually can make <em>count++</em> atomic by using AtomicInteger from the package "java.util.concurrent.atomic".</p>
<div class="wp_syntax">
<table>
<tbody>
<tr>
<td class="code">
<pre class="java">import java.util.concurrent.atomic.AtomicInteger;
public class MyCounter {
private static AtomicInteger counter = new AtomicInteger(0);
public static int getCount() {
return counter.getAndIncrement();
}
}</pre>
</td>
</tr>
</tbody>
</table>
</div>
<p><strong>Some other useful facts about thread-safe</strong></p>
<p>Local variables are thread safe in Java.</p>
<p>Each thread has its own stack. Two different threads never shares the same stack. All local variables defined in a method will be allocated memory in stack. As soon as method execution is completed by the current thread, stack frame will be removed.</p>
<p>http://www.programcreek.com/2014/02/how-to-make-a-method-thread-safe-in-java/</p>
Sun, 14 Sep 2014 04:19:59 +0000
/java/2014/09/14/how-to-make-a-method-thread-safe-in-java-2.html
/java/2014/09/14/how-to-make-a-method-thread-safe-in-java-2.htmlJava[TREE] Inorder successor and predecessor of a BST without parent pointer<p>Problem:<br />
Find inorder successor/predecessor of given node in binary search tree.</p>
<p>In-order successor of a node is the node which will come after the given node in in-order traversal of binary search tree. In other words, it would be the next larger element in BST.</p>
<p>There are four cases:</p>
<p>1. If there is a right child of the given node. In this case the smallest element in the right sub tree would be the in-order successor.<br />
2. If node does not have right sub tree and if last turn was right, then the node where we took the last left turn will be the in-order successor.<br />
3. If node does not have right sub tree and if last turn was left turn, parent of the node is inorder successor.<br />
4. If the node is the right most node, then there is no in-order successor.</p>
<p>It is clear from the analysis that we need to change the candidate only when we are moving towards left and not when moving right.</p>
<p>Algorithm<br />
1. Start with root.<br />
2. If the node is given has less than root, then search on left side and update successor.<br />
3. If the node is greater than root, then search in right part, don't update successor.<br />
4. If we find the node and if the node has right sub tree, then the minimum node on the right sub tree of node is the in-order successor.<br />
5. Return successor</p>
<p>The Algorithm is divided into two cases on the basis of right subtree of the input node being empty or not.</p>
<p>Input: node, root // node is the node whose Inorder successor is needed.<br />
output: succ // succ is Inorder successor of node.</p>
<p>1) If right subtree of node is not NULL, then succ lies in right subtree. Do following.<br />
Go to right subtree and return the node with minimum key value in right subtree.<br />
2) If right sbtree of node is NULL, then start from root and us search like technique. Do following.<br />
Travel down the tree, if a node’s data is greater than root’s data then go right side, otherwise go to left side.</p>
<p>struct node * inOrderSuccessor(struct node *root, struct node *n)<br />
{<br />
// step 1 of the above algorithm<br />
if( n->right != NULL )<br />
return minValue(n->right);</p>
<p> struct node *succ = NULL;</p>
<p> // Start from root and search for successor down the tree<br />
while (root != NULL)<br />
{<br />
if (n->data data)<br />
{<br />
succ = root;<br />
root = root->left;<br />
}<br />
else if (n->data > root->data)<br />
root = root->right;<br />
else<br />
break;<br />
}</p>
<p> return succ;<br />
}</p>
<p>OR<br />
Node * find_minimum(Node *root){<br />
if(!root)<br />
return NULL;</p>
<p> while(root->left){<br />
root = root->left;</p>
<p> }<br />
return root;<br />
}</p>
<p>Node *inorder_success(Node *root, int K){</p>
<p> Node * successor = NULL;<br />
Node *current = root;<br />
if(!root)<br />
return NULL;</p>
<p> while(current->value != K){<br />
if(current->value >K){<br />
successor = current;<br />
current= current->left;<br />
}<br />
else<br />
current = current->right;<br />
}<br />
if(current && current->right){<br />
successor = find_minimum(current->right);<br />
}</p>
<p> return successor;<br />
}</p>
<p>Time Complexity: O(h) where h is height of tree.<br />
Complexity of this algorithm will be O(logN) in almost balanced binary tree. If tree is skewed, then we have worst case complexity of O(N).</p>
<p>Inorder Predecessor:<br />
Case 1: Node has left sub tree.<br />
In this case the right most node in the left sub-tree would be the in-order predecessor.</p>
<p>Case 2: Node has no left sub-tree.<br />
In this case in-order predecessor will be the node where we took the latest right turn.</p>
<p>Case 3 : Node is left most node of BST.<br />
There is no in-order predecessor in this case and In this case there won't be any right turn.i.e. return NULL</p>
<p>Node * find_maximum(Node *root){<br />
if(!root)<br />
return NULL;</p>
<p> while(root->right){<br />
root = root->right;</p>
<p> }<br />
return root;<br />
}</p>
<p>Node *inorder_preced(Node *root, int K){</p>
<p> Node * successor = NULL;<br />
Node *current = root;<br />
if(!root)<br />
return NULL;</p>
<p> while(current && current->value != K){<br />
if(current->value >K){<br />
current= current->left;<br />
}<br />
else{<br />
successor = current;<br />
current = current->right;<br />
}<br />
}<br />
if(current && current->left){<br />
successor = find_maximum(current->left);<br />
}</p>
<p> return successor;</p>
<p>}</p>
<p>Complexity analysis<br />
Complexity of finding in-order predecessor would be same as successor i.e. O(logN).</p>
<p>PS<br />
Method 1 (Uses Parent Pointer)<br />
In this method, we assume that every node has parent pointer.</p>
<p>The Algorithm is divided into two cases on the basis of right subtree of the input node being empty or not.</p>
<p>Input: node, root // node is the node whose Inorder successor is needed.<br />
output: succ // succ is Inorder successor of node.</p>
<p>1) If right subtree of node is not NULL, then succ lies in right subtree. Do following.<br />
Go to right subtree and return the node with minimum key value in right subtree.<br />
2) If right sbtree of node is NULL, then succ is one of the ancestors. Do following.<br />
Travel up using the parent pointer until you see a node which is left child of it’s parent. The parent of such a node is the succ.</p>
<p>Implementation<br />
Note that the function to find InOrder Successor is highlighted (with gray background) in below code.</p>
<p>#include<br />
#include </p>
<p>/* A binary tree node has data, pointer to left child<br />
and a pointer to right child */<br />
struct node<br />
{<br />
int data;<br />
struct node* left;<br />
struct node* right;<br />
struct node* parent;<br />
};</p>
<p>struct node * minValue(struct node* node); </p>
<p>struct node * inOrderSuccessor(struct node *root, struct node *n)<br />
{<br />
// step 1 of the above algorithm<br />
if( n->right != NULL )<br />
return minValue(n->right);</p>
<p> // step 2 of the above algorithm<br />
struct node *p = n->parent;<br />
while(p != NULL && n == p->right)<br />
{<br />
n = p;<br />
p = p->parent;<br />
}<br />
return p;<br />
}</p>
<p>/* Given a non-empty binary search tree, return the minimum data<br />
value found in that tree. Note that the entire tree does not need<br />
to be searched. */<br />
struct node * minValue(struct node* node) {<br />
struct node* current = node;</p>
<p> /* loop down to find the leftmost leaf */<br />
while (current->left != NULL) {<br />
current = current->left;<br />
}<br />
return current;<br />
}</p>
<p>-------------------------------------------------------------------------------------------------------<br />
Here is a non-recursive version of finding the successor. There are two cases: (i) the right child of node is not NULL. In this case, we can find the successor by finding the minimum element of the right substree. (ii) If the right child of node is NULL, the successor must either be NULL, or the lowest node on the path from root to node whose value is larger than node's value.</p>
<p>/*<br />
* We assume that 'node' is in the tree<br />
*/<br />
Node * find_successor(Node * root, Node * node)<br />
{<br />
Node * y = root, * c = NULL;</p>
<p> if (node->right != NULL){<br />
y = node->right;<br />
while (y->left != NULL) y = y->left;<br />
return y;<br />
}</p>
<p> while ( y != node && y != NULL ){<br />
if ( node->data data ){<br />
c = y;<br />
y = y->left;<br />
}<br />
else{<br />
y = y->right;<br />
}<br />
}<br />
return c;<br />
}</p>
<p>Node * find_predecessor(Node * root, Node * node)<br />
{<br />
Node * y = root, *c = NULL;<br />
if (node->left != NULL){<br />
y = node->left;<br />
while (y->right != NULL) y = y->right;<br />
return y;<br />
}</p>
<p> while ( y != node ){<br />
if (node->data data){<br />
y = y->left;<br />
}<br />
else {<br />
c = y;<br />
y = y->right;<br />
}<br />
}<br />
return c;<br />
}</p>
Mon, 24 Mar 2014 16:50:24 +0000
/algos/2014/03/24/tree-inorder-successor-and-predecessor-of-a-bst-without-parent-pointer.html
/algos/2014/03/24/tree-inorder-successor-and-predecessor-of-a-bst-without-parent-pointer.htmlAlgos[ARRAY] Relocate arr[I] = arr[arr[I]]<p>WAP to modify the array such that arr[I] = arr[arr[I]].<br />
Do this in place i.e. with out using additional memory. </p>
<p>example : if a = {2,3,1,0}<br />
o/p = a = {1,0,3,2} </p>
<p>Note : The array contains 0 to n-1 integers.</p>
<p>void relocate(int *arr,int size) {<br />
for(int i=0;i<size;i++) {<br />
arr[i] += (arr[arr[i]]%size)*size;<br />
}<br />
for(int i=0;i<size;i++) {<br />
arr[i] /= size;<br />
}<br />
}</p>
<p>It is simple maths:</p>
<p>(x + y*z)/z = y provided x and y is less than z.<br />
(x + y*z)%z = x provided x and y is less than z.<br />
This is the concept used here.<br />
Example:<br />
(3 + 4*5)/5 = 4<br />
(3 + 4*5)%5 = 3</p>
<p>arr[i] = arr[i] + arr[arr[i]]*size<br />
so arr[i]/size = arr[arr[i]]</p>
<p>In the code you see the author has used % below; this is done just to make sure arr[i] and arr[arr[i]] is less than size as explained earlier.<br />
arr[i] += (arr[arr[i]]%size)*size;</p>
<p>When he multiplies the arr[arr[i]] by size and add the current value to it, you get a new value. This new value can use division to get the final result or modulo to obtain the current value.<br />
When he does the division, the current value(remainder) just falls off and you get the final value.</p>
<p>In the first loop, I add (size * "OLD arr[arr[i]]") to arr[i] so that, when doing integer division by size, I get old arr[arr[i]], when doing %size, I get old arr[i]. However I add arr[arr[i]]%size to get old arr[arr[i]], in case it was already modified in the loop. The second loop simply replaces each arr[i] with old arr[arr[i]], as mentioned above.</p>
<p>FAQ:<br />
Do we really need (arr[arr[i]] % size) why cant we directly put the arr[arr[i]] which i guess will yield the same result.since the values of array cannot be more than the size...<br />
--- I think you need the %size because you can potentially retrieve the new final value from arr[arr[i]]. And that would mess up the calculation. You can try it with the input from the question:<br />
{2,3,1,0} will become:<br />
{1,0,3,6}</p>
Mon, 03 Mar 2014 10:58:36 +0000
/algos/2014/03/03/array-relocate-arri-arrarri.html
/algos/2014/03/03/array-relocate-arri-arrarri.htmlAlgosMelbourne --- AUSTRALIAN GRAND PRIX<p>
Why go?</p>
<p>The Australian Grand Prix Corporation coined the phrase 'a great place for the race' and Melbourne is just that. Australia's second largest city is one of the most vibrant and cosmopolitan on earth, with plenty to do both day and night. The climate in late summer is perfect, the people are friendly and, to top it all, the Grand Prix is one of the most well organised of the year.</p>
<p>"Melburnians are sports-mad," says local hero Mark Webber. "The climate allows for a very outdoor lifestyle, so people are always doing something."</p>
<p>Albert Park staged a non-championship Grand Prix between 1956 and '58, but only in 1996 did it appear on the world championship calendar. Until 2005 the race had always been the season-opener, but that changed for 2006 due to the Commonwealth Games being staged in Melbourne until mid-March.</p>
<p>"You're totally spoilt for choice when it comes to restaurants, so you could spend the whole time eating if you wanted," adds Webber. "I take a look at the Melbourne Cricket Ground and tootle down the Great Ocean Road, which is an easy drive away."</p>
<p>Did you know? Melbourne is said to be the fox capital of the western world, with an estimated six foxes per square kilometre in the metropolitan area.<br />
Transport</p>
<p>International flights arrive at Melbourne's Tullamarine Airport, 22 kilometres north west of the city. A taxi from there to the city centre is inexpensive. Alternatively, there is a regular bus service.</p>
<p>Melbourne's parks, beaches and open spaces make it pleasurable city to walk around. Everything is quite spread out, but the city's cheap and convenient tram system makes getting about easy. There are several stops near the Albert Park circuit, which is two kilometres south of the city centre.</p>
<p>If hiring a car, don't forget to pay the automatic motorway toll, and have plenty of coins handy as most inner city parking is metered.<br />
Useful tips</p>
<p>Set in mown parkland, the circuit is easy to walk around. That makes general admission an appealing ticket to have on race day. But there are lots of grandstands too, particularly at the beginning and end of the lap, divided into three basic ticket prices. Remember to take sun cream and a hat. Even in March, the days are long and the rays are strong.<br />
Book Tickets</p>
<p>In the evenings, don't book early for dinner. Melbourne's bustling nightlife doesn't kick off until around 9pm, and don't go clubbing until gone midnight - unless you suffer from claustrophobia and like an empty dance floor...</p>
<p>Another bit of advice - and one well worth heeding - comes direct from the state department's traffic agency, which has the following slogan visible at various points around Albert Park: 'If you drink and drive, you're a bl**dy idiot!'<br />
Where to go?</p>
<p>There's something for everyone in Melbourne, as you'd expect from a city known for being the arts, culinary and sporting capital of Australia. To name just a few daytime attractions: the Aquarium, the old Gaol, Melbourne Zoo, Melbourne Cricket Ground, the Ian Potter Centre and Chinatown.</p>
<p>"This might sound a bit weird," says Webber, "but a lot of young Aussies are getting into lawn bowls. They have a few beers and have a good laugh doing that. Don't knock it until you've tried it!"<br />
Where to stay?</p>
<p>Since the Grand Prix came to Albert Park, the south Melbourne area has benefited from a lot of regeneration and there are now plenty of places to stay within walking distance of the track.</p>
<p>St Kilda is a popular destination for the F1 media because of its mix of street restaurants, clubs and stunning views of Port Phillip Bay. Drivers and senior team members tend to stay more centrally, usually at the Crown Towers.<br />
Extended stay</p>
<p>There are plenty of things to do in Victoria, but if you'd prefer to get away from it all, jump on a plane, head north and visit the Great Barrier Reef.</p>
<p>"Victoria is not my home state," says Webber, "but I always fancy a road trip up the Great Ocean Road to check out some of the beaches. You've got to go to Lorne, Torquay or Bell's Beach, where they filmed the movie Point Break. If you plan to surf, that place isn't for boys, let me tell you. Elsewhere, I'd head to the snowfields to the north or to some of the vineyards."<br />
Enthusiasts only</p>
<p>Phillip Island, home of the Australian Motorcycle Grand Prix is 140 kilometres south east of Melbourne. The bikers are often testing at around the time of the Formula One Grand Prix, so you might get to see some action.</p>
<p>For those in search of some Grand Prix nostalgia, go to Adelaide and drive the old Grand Prix track, which hosted the Australian race from 1985 to 1995.<br />
Circuit address</p>
<p>Albert Park<br />
220 Albert Road<br />
South Melbourne<br />
Victoria 3205<br />
Australia</p>
Tue, 11 Feb 2014 06:48:16 +0000
/travel/2014/02/11/melbourne-australian-grand-prix.html
/travel/2014/02/11/melbourne-australian-grand-prix.htmlTravel