<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Umair&#039;s Blog &#187; Java</title>
	<atom:link href="http://umairsaeed.com/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://umairsaeed.com</link>
	<description></description>
	<lastBuildDate>Fri, 20 Jan 2012 16:28:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='umairsaeed.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Umair&#039;s Blog &#187; Java</title>
		<link>http://umairsaeed.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://umairsaeed.com/osd.xml" title="Umair&#039;s Blog" />
	<atom:link rel='hub' href='http://umairsaeed.com/?pushpress=hub'/>
		<item>
		<title>Finding the Start of a Loop in a Circular Linked List</title>
		<link>http://umairsaeed.com/2011/06/23/finding-the-start-of-a-loop-in-a-circular-linked-list/</link>
		<comments>http://umairsaeed.com/2011/06/23/finding-the-start-of-a-loop-in-a-circular-linked-list/#comments</comments>
		<pubDate>Thu, 23 Jun 2011 13:54:07 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Algos]]></category>

		<guid isPermaLink="false">https://umairsd.wordpress.com/?p=186</guid>
		<description><![CDATA[A lot of people are familiar with the problem of detecting a loop in a linked list. The problem goes as follows: “Given a linked list, what is the algorithm to determine if it has any cycles (loops)?” The algorithm &#8230; <a href="http://umairsaeed.com/2011/06/23/finding-the-start-of-a-loop-in-a-circular-linked-list/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&amp;blog=9333327&amp;post=186&amp;subd=umairsd&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A lot of people are familiar with the problem of detecting a loop in a linked list. The problem goes as follows: “Given a linked list, what is the algorithm to determine if it has any cycles (loops)?”</p>
<p>The algorithm is pretty straightforward:</p>
<ol>
<li>We start at the beginning of the linked list with two pointers.</li>
<li>The first pointer is incremented through each node of the list. The second pointer moves twice as fast, and skips every other node.</li>
<li>If the linked list contains a loop, these two pointers will eventually meet at the same node, thus indicating that the linked list contains a loop.</li>
</ol>
<p>The algorithm is straightforward and it is relatively easy to create a mental model and get an intuitive sense of why it works.</p>
<p>Now, a slight twist to the same question asks: “Given a circular linked list, what is the algorithm to find the first node of the loop.” For instance, in the circular list A-&gt;B-&gt;C-&gt;D-&gt;E-&gt;C, the first node of the loop is node C. The first part of the algorithm is identical to the algorithm for finding if there is a loop (above). Once a loop has been found, the following additional steps will give us the starting node of the loop:</p>
<ol>
<li>Once a loop as been detected (step-3 above), move one of the pointers to the beginning (head) of the linked list. The second pointer remains where it was at the end of step-3.</li>
<li>Increment both pointers one node at a time. The node at which the two pointers meet will be the starting node of the loop!</li>
</ol>
<p>This algorithm isn’t too difficult compared to the algorithm for detecting a loop. However, the mental model seems a bit trickier. Why and how does it always find the start of the loop?</p>
<p><strong><br />
</strong></p>
<h3>How does the Algorithm work? An intuitive explanation:</h3>
<p>Here’s some explanation which would hopefully help you intuitively understand why the algorithm works, without going into a lot of mathematical detail.</p>
<p><strong>First, meeting point of two pointers in a loop</strong></p>
<p>Consider two pointers: a slow pointer S that increments by one node at each step, and a fast pointer F that increments by two nodes at each step (i.e. it is twice as fast as S). Both pointers start at the same time from the beginning of an n-node loop. In the time S covers n nodes. F will have covered 2n nodes and they will both meet at the start of the loop.</p>
<p>Now, let us say that the slow pointer S starts at the beginning of the loop, and the fast pointer F starts at node k (where k &lt; n) of the loop. As these two pointers move along the loop, they will meet at node (n-x).</p>
<p>What we really need to do is figure out x, as it will give us the node at which the two pointers meet inside the loop.</p>
<ol>
<li>When S takes n/2 steps, it will be at node n/2. During the same time, F will have taken 2(n/2) = n steps, and it will be at node (k+n). Since the we are inside a loop, F will be effectively back at node k.</li>
<li>In order for the two pointers to meet at node (n-x), S needs to take a further (n-x-n/2)=(n/2-x) steps and it will end up at node n-x. During the same time, F will have taken 2*(n/2-x)=(n-2x) steps and will be at node k+(n-2x). Given our assumption that both S and F meet at the same node:</li>
</ol>
<pre>		n-x = k+n-2x
	=&gt;	  x = k</pre>
<p>This means that if S starts from the start of the loop, and F starts k nodes into the loop, both of them will meet at node (n-k), i.e k nodes from the end of the loop. This is a key insight.</p>
<p><strong>Circular Linked List</strong></p>
<p>Now, coming back to the linked list that contains a loop. Suppose the start of the loop is m (e.g. m=3) nodes from the start of the linked list. Both S and F start at the beginning of the linked list [Figure-1].</p>
<div class="image">
<p><img style="display:block;margin-left:0;margin-right:auto;" title="Figure-1.jpg" src="http://umairsd.files.wordpress.com/2011/06/figure-1.jpg?w=500&#038;h=338" alt="Figure-1: Circular linked list with S and F pointers at the start" width="500" height="338" border="0" /></p>
<div><small>Figure-1: Circular linked list with S and F pointers at the start</small></div>
</div>
<p>&nbsp;</p>
<p>By the time S gets to node m (i.e. start of loop), F will be at node 2m [Figure-2]. This means that S will be at the start of the loop and F will be m nodes <strong>*into the loop*</strong>.</p>
<div class="image">
<p><img style="display:block;margin-left:0;margin-right:auto;" title="Figure-2.jpg" src="http://umairsd.files.wordpress.com/2011/06/figure-2.jpg?w=500&#038;h=345" alt="Figure-2: Circular linked list, with S at the start of loop and F m nodes into the loop" width="500" height="345" border="0" /></p>
<div><small>Figure-2: Circular linked list, with S at the start of loop and F m nodes into the loop</small></div>
</div>
<p>&nbsp;</p>
<p>Based on the discussion above, we already know that if S begins from the start of the loop and F starts from node m, they will meet m nodes from the end of the loop (i.e. the orange-node in [Figure-3]).</p>
<div class="image">
<p><img style="display:block;margin-left:0;margin-right:auto;" title="Figure-3.jpg" src="http://umairsd.files.wordpress.com/2011/06/figure-3.jpg?w=500&#038;h=317" alt="Figure-3: Both F and S meet m nodes from the end of the loop" width="500" height="317" border="0" /></p>
<div><small>Figure-3: Both F and S meet m nodes from the end of the loop</small></div>
</div>
<p>&nbsp;</p>
<p>At this point, keep the pointer F at the orange-node where the two pointers met (i.e. m-nodes from the start of the loop), and move the pointer S to the beginning of the linked list [Figure-4]. Now, if we increment both S and F *one node at a time*, it is obvious that they will meet at &#8216;Node-m&#8217; (red-node) of the list, which is the start of the loop.</p>
<div class="image">
<p><img style="display:block;margin-left:0;margin-right:auto;" title="Figure-4.jpg" src="http://umairsd.files.wordpress.com/2011/06/figure-4.jpg?w=500&#038;h=325" alt="Figure-4: S at the start of linked list, F at the point they met. Both increment one at a time from here-on" width="500" height="325" border="0" /></p>
<div><small>Figure-4: S at the start of linked list, F at the point they met. Both increment one at a time from here-on</small></div>
</div>
<p>&nbsp;</p>
<p>For the curious, here’s the Java code snippets for detecting a loop in a linked list and finding the starting node. The complete source code for my linked list project is at my Github page (<a href="https://github.com/umairsd/LinkedList-Java">https://github.com/umairsd/LinkedList-Java</a>):</p>
<p><pre class="brush: java;">
	/**
	 * Checks if the given linked list is a circular linked list (i.e. it
	 * contains a loop). This means a list in which a node's next pointer points
	 * to an earlier node, so as to make a loop in the linked list. For
	 * instance:
	 * 			A -&gt; B -&gt; C -&gt; D -&gt; E -&gt; C
	 *
	 * @param linkedList
	 *            the linked list to be tested
	 * @return true if there is a loop, false if there isn't
	 */
	public static boolean hasLoop(LinkedList linkedList) {
		if (linkedList == null || linkedList.getHead() == null) {
			return false;
		}

		IntegerNode slow = linkedList.getHead();
		IntegerNode fast = linkedList.getHead();

		while (true) {
			slow = slow.getNext();

			if (fast.getNext() != null) {
				fast = fast.getNext().getNext();
			} else {
				return false;
			}

			if (slow == null || fast == null) {
				return false;
			}

			if (slow == fast) {
				return true;
			}
		}
	}
</pre></p>
<p>&nbsp;</p>
<p><pre class="brush: java;">

	/**
	 * Returns the node at the start of a loop in the given circular linked
	 * list. A circular list is one in which a node's next pointer points
	 * to an earlier node, so as to make a loop in the linked list. For
	 * instance:
	 *
	 * input: A -&gt; B -&gt; C -&gt; D -&gt; E -&gt; C [the same C as earlier]
	 * output: C
	 *
	 * (CCI_0205)
	 *
	 * @param linkedList
	 *            list to be tested
	 * @return the node at the start of the loop if there is a loop, null
	 * otherwise
	 */
	public static IntegerNode findLoopStart(LinkedList linkedList) {
		if (linkedList == null || linkedList.getHead() == null) {
			return null;
		}

		IntegerNode loopStartNode = null;
		IntegerNode slow = linkedList.getHead();
		IntegerNode fast = linkedList.getHead();

		while (slow != null &amp;&amp; fast != null) {
			slow = slow.getNext();
			if (fast.getNext() == null) {
				loopStartNode = null;
				break;
			}
			fast = fast.getNext().getNext();

			// If slow and fast point to the same node, it means that the
			// linkedList contains a loop.
			if (slow == fast) {

				slow = linkedList.getHead();

				while (slow != fast) {
					// Keep incrementing the two pointers until they both
					// meet again. When this happens, both the pointers will
					// point to the beginning of the loop
					slow = slow.getNext(); // Can't be null, as we have a loop
					fast = fast.getNext(); // Can't be null, as we have a loop
				}

				loopStartNode = slow;
				break;
			}
		}

		return loopStartNode;
	}

</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/186/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&amp;blog=9333327&amp;post=186&amp;subd=umairsd&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2011/06/23/finding-the-start-of-a-loop-in-a-circular-linked-list/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2011/06/figure-1.jpg" medium="image">
			<media:title type="html">Figure-1.jpg</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2011/06/figure-2.jpg" medium="image">
			<media:title type="html">Figure-2.jpg</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2011/06/figure-3.jpg" medium="image">
			<media:title type="html">Figure-3.jpg</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2011/06/figure-4.jpg" medium="image">
			<media:title type="html">Figure-4.jpg</media:title>
		</media:content>
	</item>
		<item>
		<title>Java Enum Puzzler</title>
		<link>http://umairsaeed.com/2009/09/29/java-enum-puzzler/</link>
		<comments>http://umairsaeed.com/2009/09/29/java-enum-puzzler/#comments</comments>
		<pubDate>Tue, 29 Sep 2009 22:31:33 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[enum]]></category>
		<category><![CDATA[puzzle]]></category>

		<guid isPermaLink="false">http://umairsd.wordpress.com/2009/09/29/java-enum-puzzler/</guid>
		<description><![CDATA[Recently, I ran into an interesting bit of code related to Java enumerations. Here’s a contrived minimal sample: When this code is run, an intuitive expectation is to see the following printed to the console: BRAVO CHARLIE ALPHA However, when &#8230; <a href="http://umairsaeed.com/2009/09/29/java-enum-puzzler/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&amp;blog=9333327&amp;post=27&amp;subd=umairsd&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Recently, I ran into an interesting bit of code related to Java enumerations. Here’s a contrived minimal sample:</p>
<pre><pre class="brush: java;">
/*
 * Some arbitrary resource type
 */
interface Resource {
	public Resource getResource();
}

enum A implements Resource{
	ALPHA (B.BRAVO);
	
	private Resource res;
	private A (Resource res){ this.res = res; }
	public Resource getResource(){ return res; }
}

enum B implements Resource{
	BRAVO (C.CHARLIE);

	private Resource res;
	private B (Resource res){ this.res = res; }
	public Resource getResource(){ return res; }

}

enum C implements Resource{
	CHARLIE (A.ALPHA);

	private Resource res;
	private C (Resource res){ this.res = res; }
	public Resource getResource(){ return res; }
}


class EnumTester{
	public static void main(String [] args){
		System.out.println(A.ALPHA.getResource());	
		System.out.println(B.BRAVO.getResource());	
		System.out.println(C.CHARLIE.getResource());
	}
}
</pre></pre>
<p>When this code is run, an intuitive expectation is to see the following printed to the console:</p>
<blockquote>
<table border="0" cellspacing="0" cellpadding="2" width="37">
<tbody>
<tr>
<td valign="top" width="35"><font face="Courier New">BRAVO</font></td>
</tr>
<tr>
<td valign="top" width="35"><font face="Courier New">CHARLIE</font></td>
</tr>
<tr>
<td valign="top" width="35"><font face="Courier New">ALPHA</font></td>
</tr>
</tbody>
</table>
</blockquote>
<p>However, when I actually run the code we see:</p>
<blockquote>
<table border="0" cellspacing="0" cellpadding="2" width="37">
<tbody>
<tr>
<td valign="top" width="35"><font face="Courier New">BRAVO</font></td>
</tr>
<tr>
<td valign="top" width="35"><font face="Courier New">CHARLIE</font></td>
</tr>
<tr>
<td valign="top" width="35"><font face="Courier New">null</font></td>
</tr>
</tbody>
</table>
</blockquote>
<p>While this may seem a bit funky, the key is to understand what enum constants mean in Java. The key question to address is: “when is the constructor for an enumerated type invoked”. To answer this, it is helpful to remember that enum constants are implicitly <font face="Courier New"><font size="2">public static final</font>.</font> Java guarantees that:</p>
<ul>
<li>Static variables in a class are initialized before any object of that class can be created </li>
<li>Static variables in a class are initialized before any static method of the class runs </li>
</ul>
<p>Knowing this, the behavior of the above code snippet becomes clearer. Here’s what happens in the main method:</p>
<ol>
<li>The fun happens at line 35, when we print&#160;&#160; <font face="Courier New">A.<em>ALPHA</em>.getResource()</font>. Behind the scene, the class loader loads enumeration A into memory (i.e. initializes A). </li>
<li>Once A is loaded into memory, the enum constant <em><font face="Courier New">ALPHA</font></em> gets created via call to the constructor where <font face="Courier New">B.<em>BRAVO</em></font> is passed in as the argument. </li>
<li>At this point, enumeration B is initialized and enum constant <em><font face="Courier New">BRAVO</font></em> gets created via a call to the constructor where <font face="Courier New">C.<em>CHARLIE</em></font> is passed in as the argument. </li>
<li>Same as before, now enumeration C is initialized (i.e. loaded into memory). Now here’s where things become interesting. </li>
<li>Immediately after the initialization of C, we create the enum constant <em><font face="Courier New">CHARLIE</font></em> via a call to the constructor and pass in <font face="Courier New">A.<em>ALPHA</em></font> as the argument. However, <font face="Courier New">A.<em>ALPHA</em></font> has not been instantiated yet, and therefore enum constant <em><font face="Courier New">CHARLIE</font></em> gets null as the value of its resource instance variable.&#160; </li>
</ol>
<p>This means that once the statement <font face="Courier New">A.<em>ALPHA</em>.getResource()</font> is evaluated, A, B and C are all loaded into memory and all the corresponding enum constants have already been instantiated. Lines 35-37 simply then print the corresponding resources for each enum constant. </p>
</p>
<p><strong></strong></p>
</p>
<p><strong><font size="4">A Possible Solution</font></strong></p>
<p>It is obvious that the entire problem stems from the cyclic dependency between A, B and C. Usually (but <a href="http://beust.com/weblog/archives/000208.html" target="_blank">not always</a>), this is an indication of a bad design choice and the fix is to simply get rid of the cyclic dependency. Assuming we want to keep the dependency, what are our options then?</p>
<p>Our solutions lies in Java&#8217;s ability to allow <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html" target="_blank">instance-specific methods on enumerations</a>. This is shown in the code below.</p>
<p>Running the following code with the EnumTester main method above will give us the results we wanted, without the problems caused by the previous approach.</p>
<pre><pre class="brush: java;">
enum A implements Resource{
	ALPHA { public Resource getResource() {return B.BRAVO; } };
	
	public abstract Resource getResource();
}

enum B implements Resource{
	BRAVO { public Resource getResource() { return C.CHARLIE; } };
	
	public abstract Resource getResource();
}

enum C implements Resource{
	CHARLIE { public Resource getResource() { return A.ALPHA; }};
	
	public abstract Resource getResource();
}
</pre></pre>
<p>What do you think? Do you know of any other ways to resolve the cyclic dependency? Have you seen any other weirdness related to Java’s Enums? </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/27/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&amp;blog=9333327&amp;post=27&amp;subd=umairsd&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2009/09/29/java-enum-puzzler/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>
	</item>
	</channel>
</rss>
