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

<channel>
	<title>Hash table &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/hash-table/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Computer Algorithms: Linked List</title>
		<link>/2012/06/14/computer-algorithms-linked-list-data-structure/</link>
		<comments>/2012/06/14/computer-algorithms-linked-list-data-structure/#comments</comments>
		<pubDate>Thu, 14 Jun 2012 12:12:47 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[B-tree]]></category>
		<category><![CDATA[Bin]]></category>
		<category><![CDATA[Data structures]]></category>
		<category><![CDATA[Data types]]></category>
		<category><![CDATA[Hash table]]></category>
		<category><![CDATA[HEAD]]></category>
		<category><![CDATA[Insert]]></category>
		<category><![CDATA[John]]></category>
		<category><![CDATA[Linked list]]></category>
		<category><![CDATA[List]]></category>
		<category><![CDATA[Null]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pointer]]></category>
		<category><![CDATA[public $head]]></category>
		<category><![CDATA[Smith]]></category>
		<category><![CDATA[SQL keywords]]></category>
		<category><![CDATA[Stack]]></category>

		<guid isPermaLink="false">/?p=3188</guid>
		<description><![CDATA[Introduction The linked list is a data structure in which the items are ordered in a linear way. Although modern programming languages support very flexible and rich libraries that works with arrays, which use arrays to represent lists, the principles of building a linked list remain very important. The way linked lists are implemented is &#8230; <a href="/2012/06/14/computer-algorithms-linked-list-data-structure/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Linked List</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/" rel="bookmark" title="Computer Algorithms: Detecting and Breaking a Loop in a Linked List">Computer Algorithms: Detecting and Breaking a Loop in a Linked List </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
<li><a href="/2012/07/24/php-arrays-or-linked-lists/" rel="bookmark" title="PHP: Arrays or Linked Lists?">PHP: Arrays or Linked Lists? </a></li>
<li><a href="/2012/06/05/computer-algorithms-stack-and-queue-data-structure/" rel="bookmark" title="Computer Algorithms: Stack and Queue">Computer Algorithms: Stack and Queue </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>The linked list is a data structure in which the items are ordered in a linear way. Although modern programming languages support very flexible and rich libraries that works with arrays, which use arrays to represent lists, the principles of building a linked list remain very important. The way linked lists are implemented is a ground level in order to build more complex data structures such as trees. </p>
<p>It&#8217;s true that almost every operation we can perform on a linked list can be done with an array. It&#8217;s also true that some operations can be faster on arrays compared to linked lists. </p>
<p>However understanding how to implement the basic operations of a linked list such as INSERT, DELETE, INSERT_AFTER, PRINT and so on is crucial in order to implement data structures as rooted trees, B-trees, red-black trees, etc.</p>
<h2>Overview</h2>
<p>Unlike arrays where we don’t have pointers to the next and the previous item, the linked list is designed to support such pointers. In some implementations there is only one pointer pointing to the successor of the item. This kind of data structures are called singly linked lists. In this case the the last element doesn’t have a successor, so the pointer to its next element usualy is NULL. However the most implemented version of a linked list supports two pointers. These are the so called doubly linked lists.</p>
<p><figure id="attachment_3197" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/0.-Arrays-vs.-linked-list.png"><img src="/wp-content/uploads/2012/06/0.-Arrays-vs.-linked-list.png" alt="Arrays vs. linked list" title="Arrays vs. linked list" width="621" height="333" class="size-full wp-image-3197" srcset="/wp-content/uploads/2012/06/0.-Arrays-vs.-linked-list.png 621w, /wp-content/uploads/2012/06/0.-Arrays-vs.-linked-list-300x160.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Arrays items are defined by their indices, while the linked list item contains a pointer to its predecessor and his successor!</figcaption></figure><span id="more-3188"></span></p>
<p>Let’s take a look at some examples. Here’s an array:</p>
<pre lang="PHP">
A[2, 'hello', 'world', 13, 31]
</pre>
<p>We know that A[0] contains the number 2, while A[1] contains the word (string) &#8220;hello&#8221;. This is the very basic array representation where the indices are consecutive and start from 0.</p>
<p>In that case we know that if we’re looking at the item with index <strong>i</strong>, its next element has an index <strong>i+1</strong>, while his predecessor&#8217;s index is <strong>i-1</strong>. Thus we can easily iterate over items. However if we have an array with only 5 elements A[5] doesn’t exists, and in most of the cases is NULL. In other words array items are defined by their indices, and can be accessed directly with their index.</p>
<p>In the other hand most of the programming languages support associative arrays also called hash maps.</p>
<p>An associative array in PHP can be something like this.</p>
<pre lang="PHP">
$a = array(
	'hello' => 'world',
	31	=> 12,
	'b7'	=> 144,
);
</pre>
<p>Now because the indices are not consecutive integers we don’t know the successor and the predecessor of the current item. Yes, there is some internal pointer that can give us the link to the previous and the next item, but explicitly we can&#8217;t refer them.</p>
<p>Of course some libraries may have functions that can point us to the next item, such a function is <a href="http://php.net/manual/en/function.next.php" target="_blank">next()</a> in <a href="/category/php/">PHP</a>.</p>
<p>As we see arrays can replace the typical pointer-like representation of a linked list, but as I said already this data structure is crucial in order to understand more complex data structures.</p>
<p>Typically the linked list is implemented with two classes. The first one describing the item and the other one containing the main operations of the list such as search, insert, delete, etc.</p>
<p>The first class, typically called <strong>Item</strong> is a normal class containing various info about an item. In terms of persons, for instance, this class can contain the first and last names of the person, his address, phone etc. However it’s very important that this class contains pointers to its previous and its next objects.</p>
<p>In our terms each object of class Person will contain a pointer to a next object of the same class Person.</p>
<pre lang="PHP">
class Person
{
	public $next = null;
	public $prev = null;
	
	protected $_firstName = '';
	protected $_lastName = '';
	protected $_phone = '';
	
	
	public function __construct($firstName, $lastName, $phone)
	{
		$this->_firstName = $firstName;
		$this->_lastName = $lastName;
		$this->_phone = $phone;
	}
	
	public function __toString()
	{
		return 'First name: ' . $this->_firstName 
			 . ', Last name: ' . $this->_lastName 
			 . ', Phone: ' . $this->_phone;
	}
}
</pre>
<p>So we must first design the structure of an item. </p>
<p>The following thing to do is to define a linked list as an abstraction over a real world list, just like the stack and the queue. We can implement various operations for a linked list like <strong>insert</strong>, <strong>delete</strong>, <strong>insertBefore</strong>, <strong>insertAfter</strong>, <strong>sort</strong>, <strong>search</strong>, <strong>insertSorted</strong> etc. It’s up to the developer to decide which operations he wants to use. And of course this depends on the application.</p>
<h2>Implementation</h2>
<h3>Operations</h3>
<p>We can perform and define as much operations as we need. For instance we can code a linked list only with the basic insert, delete and print, but we can also go for insertBefore, insertAfter, deleteBefore, deleteAfter, insertSorted, which are described on the diagrams below.</p>
<h4>Insert</h4>
<p>Inserting in the front of a list seems much like inserting into a queue. In this case the new item becomes the head of the list and its successor is the previous head of the list.</p>
<figure id="attachment_3204" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/1.-Insert-at-the-front-of-a-Linked-List.png"><img src="/wp-content/uploads/2012/06/1.-Insert-at-the-front-of-a-Linked-List.png" alt="Inserting at the front of a Linked List" title="Inserting at the front of a Linked List" width="619" height="346" class="size-full wp-image-3204" srcset="/wp-content/uploads/2012/06/1.-Insert-at-the-front-of-a-Linked-List.png 619w, /wp-content/uploads/2012/06/1.-Insert-at-the-front-of-a-Linked-List-300x167.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text">Inserting at the front of the list</figcaption></figure>
<pre lang="PHP">
class LList
{
	public $head;
	public $tail;
	
	public function insert($item) 
	{
		$item->next = $this->head;
		
		if ($this->head != null) {
			$this->head->prev = $item;
		}
		
		$this->head = $item;
	}

	public function __toString()
	{
		$cur = $this->head;
		
		$output = '';
		while ($cur) {
			$output .= $cur . ' ';
			
			$cur = $cur->next;
		}
		
		return $output . "\n";
	}
}

$ll = new LList();

$a = new Person('John', 'Smith', '555 9401');
$b = new Person('James', 'Johnes', '555 2454');

$ll->insert($a);
$ll->insert($b);

// James Johnes 555 2454
// John Smith 555 9401
echo $ll;
</pre>
<h4>Delete</h4>
<p>Delete the head of the list is much like deleting an item from a queue. However we can implement also deleting a custom element that&#8217;s inside the list.</p>
<figure id="attachment_3206" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/4.-Delete-an-item.png"><img src="/wp-content/uploads/2012/06/4.-Delete-an-item.png" alt="Delete an item" title="Delete an item" width="618" height="362" class="size-full wp-image-3206" srcset="/wp-content/uploads/2012/06/4.-Delete-an-item.png 618w, /wp-content/uploads/2012/06/4.-Delete-an-item-300x175.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">Deleting an item from the inside of the list!</figcaption></figure>
<pre lang="PHP">
class LList
{
	public $head;
	public $tail;
	
	public function insert($item) 
	{
		$item->next = $this->head;
		
		if ($this->head != null) {
			$this->head->prev = $item;
		}
		
		$this->head = $item;
	}
	
	public function delete($item) 
	{
		$cur = $this->head;
		
		while ($cur) {
			
			if ($cur == $item) {
				$prev = $cur->prev;
				$next = $cur->next;
				
				if ($prev != null) {
					$prev->next = $next;
				} else {
					// because head points to the first item
					$this->head = $next;
				}
				
				if ($next != null) {
					$next->prev = $prev;
				}
				
				return $cur;
			}
		
			$cur = $cur->next;
		}
	}

	public function __toString()
	{
		$cur = $this->head;
		
		$output = '';
		while ($cur) {
			$output .= $cur . ' ';
			
			$cur = $cur->next;
		}
		
		return $output . "\n";
	}
}

$ll = new LList();

$a = new Person('John', 'Smith', '555 9401');
$b = new Person('James', 'Johnes', '555 2454');
$c = new Person('Jeanne', 'Francois', '333 2323');

$ll->insert($a);
$ll->insert($b);
$ll->insert($c);

// prints objects $c, $b, $a:
// Jeanne Francois 333 2323
// James Johnes 555 2454
// John Smith 555 9401
echo $ll;

$ll->delete($b);

// prints objects $c, $a:
// Jeanne Francois 333 2323
// John Smith 555 9401
echo $ll;
</pre>
<h4>Insert before &#038; insert after</h4>
<p>Inserting before and after needs a reference to an already existing list item. After that the new object is inserted into it right place, as shown on the images below.</p>
<figure id="attachment_3208" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/2.-Insert-after-a-given-item-of-a-Linked-List.png"><img src="/wp-content/uploads/2012/06/2.-Insert-after-a-given-item-of-a-Linked-List.png" alt="Insert after a given item of a Linked List" title="Insert after a given item of a Linked List" width="618" height="362" class="size-full wp-image-3208" srcset="/wp-content/uploads/2012/06/2.-Insert-after-a-given-item-of-a-Linked-List.png 618w, /wp-content/uploads/2012/06/2.-Insert-after-a-given-item-of-a-Linked-List-300x175.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">Insert after splits the list after the pointed item and inserts the new object there!</figcaption></figure>
<pre lang="PHP">
class LList
{
	public $head;
	public $tail;
	
	public function insert($item) 
	{
		$item->next = $this->head;
		
		if ($this->head != null) {
			$this->head->prev = $item;
		}
		
		$this->head = $item;
	}
	
	public function insertAfter($newItem, $item) 
	{
		$cur = $this->head;
		while ($cur) {
			if ($cur == $item) {
				$next = $cur->next;
				
				$cur->next = $newItem;
				$newItem->prev = $cur;
				
				if ($next != null) {
					$newItem->next = $next;
					$next->prev = $newItem;
				}
				return;
			}
			$cur = $cur->next;
		}
		
		$this->head = $this->tail = $item;
	}

	public function __toString()
	{
		$cur = $this->head;
		
		$output = '';
		while ($cur) {
			$output .= $cur . ' ';
			
			$cur = $cur->next;
		}
		
		return $output . "\n";
	}
}

$ll = new LList();

$a = new Person('John', 'Smith', '555 9401');
$b = new Person('James', 'Johnes', '555 2454');
$c = new Person('Jeanne', 'Francois', '333 2323');

$ll->insert($a);
$ll->insert($c);

// inserts $b after $a
$ll->insertAfter($b, $c);

// Jeanne Francois 333 2323
// James Johnes 555 2454
// John Smith 555 9401
echo $ll;
</pre>
<p>Insert a new object before an item is the same as insert after, but instead of splitting the list after the given item, we split it before it.</p>
<figure id="attachment_3209" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/3.-Insert-before-a-given-item-of-a-Linked-List.png"><img src="/wp-content/uploads/2012/06/3.-Insert-before-a-given-item-of-a-Linked-List.png" alt="Insert before a given item of a Linked List" title="Insert before a given item of a Linked List" width="618" height="362" class="size-full wp-image-3209" srcset="/wp-content/uploads/2012/06/3.-Insert-before-a-given-item-of-a-Linked-List.png 618w, /wp-content/uploads/2012/06/3.-Insert-before-a-given-item-of-a-Linked-List-300x175.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">Insert before and insert after are very similar operations!</figcaption></figure>
<h4>Search</h4>
<p>Searching into a list can be modified depending on the application needs. Here we just compare the searched object with a list item.</p>
<a href="/wp-content/uploads/2012/06/5.-Search-for-an-item.png"><img src="/wp-content/uploads/2012/06/5.-Search-for-an-item.png" alt="Search for an item" title="Search for an item" width="620" height="258" class="size-full wp-image-3210" srcset="/wp-content/uploads/2012/06/5.-Search-for-an-item.png 620w, /wp-content/uploads/2012/06/5.-Search-for-an-item-300x124.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a>
<pre lang="PHP">
class LList
{
	public $head;
	public $tail;
	
	public function insert($item) 
	{
		$item->next = $this->head;
		
		if ($this->head != null) {
			$this->head->prev = $item;
		}
		
		$this->head = $item;
	}
	
	public function insertAfter($item, $key) 
	{
		$cur = $this->head;
		while ($cur) {
			if ($cur->data == $key) {
				$next = $cur->next;
				
				$cur->next = $item;
				$item->prev = $cur;
				
				if ($next != null) {
					$item->next = $next;
					$next->prev = $item;
				}
				return;
			}
			$cur = $cur->next;
		}
		
		$this->head = $this->tail = $item;
	}

	public function search($item)
	{
		$cur = $this->head;
		
		while ($cur) {
			if ($cur == $item) {
				return 1;
			}
			
			$cur = $cur->next;
		}
		
		return 0;
	}
	
	public function __toString()
	{
		$cur = $this->head;
		
		$output = '';
		while ($cur) {
			$output .= $cur . ' ';
			
			$cur = $cur->next;
		}
		
		return $output . "\n";
	}
}

$ll = new LList();

$a = new Person('John', 'Smith', '555 9401');
$b = new Person('James', 'Johnes', '555 2454');
$c = new Person('Jeanne', 'Francois', '333 2323');

$ll->insert($a);
$ll->insert($b);

// 1, because $b is in the list
echo $ll->search($b);

// 0, cause $c isn't in the list
echo $ll->search($c);
</pre>
<p>The operations here are only one sub-set of all possible operations you can implement on a linked list. It all depends on our needs. However the principles are important, so we can implement more complex data structures.</p>
<h2>Application</h2>
<p>It&#8217;s true that linked list are a very basic data structure. Someone may wonder why we should code and implement linked list since we can do the same (with almost every modern programming language/library) with arrays. The answer is that data structures as trees are difficult to implement with arrays, so it&#8217;s easy to code them using pointers. Thus linked lists is a ground level for understanding them. Indeed each linked list is a tree with only one branch as shown on the image below.</p>
<figure id="attachment_3213" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/6.-Linked-List-Trees.png"><img src="/wp-content/uploads/2012/06/6.-Linked-List-Trees.png" alt="Linked List &amp; Trees" title="Linked List &amp; Trees" width="620" height="399" class="size-full wp-image-3213" srcset="/wp-content/uploads/2012/06/6.-Linked-List-Trees.png 620w, /wp-content/uploads/2012/06/6.-Linked-List-Trees-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Each linked list is a single branch tree!</figcaption></figure>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/" rel="bookmark" title="Computer Algorithms: Detecting and Breaking a Loop in a Linked List">Computer Algorithms: Detecting and Breaking a Loop in a Linked List </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
<li><a href="/2012/07/24/php-arrays-or-linked-lists/" rel="bookmark" title="PHP: Arrays or Linked Lists?">PHP: Arrays or Linked Lists? </a></li>
<li><a href="/2012/06/05/computer-algorithms-stack-and-queue-data-structure/" rel="bookmark" title="Computer Algorithms: Stack and Queue">Computer Algorithms: Stack and Queue </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/06/14/computer-algorithms-linked-list-data-structure/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Rabin-Karp String Searching</title>
		<link>/2012/04/02/computer-algorithms-rabin-karp-string-searching/</link>
		<comments>/2012/04/02/computer-algorithms-rabin-karp-string-searching/#comments</comments>
		<pubDate>Mon, 02 Apr 2012 19:48:15 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[ASCII]]></category>
		<category><![CDATA[basic sub-string matching algorithm]]></category>
		<category><![CDATA[Boyer–Moore string search algorithm]]></category>
		<category><![CDATA[Complexity The Rabin-Karp algorithm]]></category>
		<category><![CDATA[Cryptographic hash function]]></category>
		<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Hash function]]></category>
		<category><![CDATA[Hash table]]></category>
		<category><![CDATA[Hashing]]></category>
		<category><![CDATA[Michael O. Rabin]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Rabin-Karp algorithm]]></category>
		<category><![CDATA[Rabin-Karp string search algorithm]]></category>
		<category><![CDATA[Richard M. Karp]]></category>
		<category><![CDATA[Rolling hash]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[string matching algorithms]]></category>
		<category><![CDATA[String searching algorithm]]></category>
		<category><![CDATA[string searching algorithms]]></category>
		<category><![CDATA[sub-string matching algorithms]]></category>
		<category><![CDATA[This algorithm]]></category>

		<guid isPermaLink="false">/?p=2991</guid>
		<description><![CDATA[Introduction Brute force string matching is the a very basic sub-string matching algorithm, but it’s good for some reasons. For example it doesn’t require preprocessing of the text or the pattern. The problem is that it’s very slow. That is why in many cases brute force matching can’t be very useful. For pattern matching we &#8230; <a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Rabin-Karp String Searching</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" rel="bookmark" title="Computer Algorithms: Morris-Pratt String Searching">Computer Algorithms: Morris-Pratt String Searching </a></li>
<li><a href="/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/" rel="bookmark" title="Computer Algorithms: Boyer-Moore String Searching">Computer Algorithms: Boyer-Moore String Searching </a></li>
<li><a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" rel="bookmark" title="Computer Algorithms: Brute Force String Matching">Computer Algorithms: Brute Force String Matching </a></li>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p><a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" title="Computer Algorithms: Brute Force String Searching">Brute force string matching</a> is the a very basic sub-string matching algorithm, but it’s good for some reasons. For example it doesn’t require preprocessing of the text or the pattern. The problem is that it’s very slow. That is why in many cases brute force matching can’t be very useful. For pattern matching we need something faster, but to understand other sub-string matching algorithms let’s take a look once again on brute force matching. </p>
<p>In brute force sub-string matching we checked every single character from the text with the first character of the pattern. Once we have a match between them we shift the comparison between the second character of the pattern with the next character of the text, as shown on the picture below.</p>
<p><figure id="attachment_3002" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Rabin-Karp-Brute-Froce-Principles.png"><img src="/wp-content/uploads/2012/04/Rabin-Karp-Brute-Froce-Principles.png" alt="Brute Froce Principles" title="Brute Froce Principles" width="618" height="242" class="size-full wp-image-3002" srcset="/wp-content/uploads/2012/04/Rabin-Karp-Brute-Froce-Principles.png 618w, /wp-content/uploads/2012/04/Rabin-Karp-Brute-Froce-Principles-300x117.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">Brute force string matching is slow because it compares every single character from the pattern and the text!</figcaption></figure><span id="more-2991"></span></p>
<p>This algorithm is slow for mainly two reasons. First we have to check every single character from the text. On the other hand even if we find a match between a text character and the first character of the pattern we continue to check step by step (character by character) every single symbol of the pattern in order to find whether it is in the text. So is there any other approach to find whether the text contains the pattern?</p>
<p>In fact there is a “faster” approach. In this case in order to avoid the comparison between the pattern and the text character by character, we’ll try to compare them at once, so we need a good hash function. With its help we can hash the pattern and check against hashed sub-strings of the text. We must be sure that the hash function is returning “small” hash codes for larger sub-strings. Another problem is that for larger patterns we can’t expect to have short hashes. But besides this the approach should be quite effective compared to the brute force string matching. </p>
<p>That approach is known as Rabin-Karp algorithm.</p>
<h2>Overview</h2>
<p><a href="http://en.wikipedia.org/wiki/Michael_O._Rabin" title="Michael O. Rabin" target="_blank">Michael O. Rabin</a> and <a href="http://en.wikipedia.org/wiki/Richard_M._Karp" title="Richard M. Karp" target="_blank">Richard M. Karp</a> came up with the idea of hashing the pattern and to check it against a hashed sub-string from the text in 1987. In general the idea seems quite simple, the only thing is that we need a hash function that gives different hashes for different sub-strings. Such hash function, for instance, may use the ASCII codes for every character, but we must be careful for multi-lingual support.</p>
<figure id="attachment_3003" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Rabin-Karp-Basic-Principles.png"><img src="/wp-content/uploads/2012/04/Rabin-Karp-Basic-Principles.png" alt="Rabin-Karp Basic Principles" title="Rabin-Karp Basic Principles" width="621" height="299" class="size-full wp-image-3003" srcset="/wp-content/uploads/2012/04/Rabin-Karp-Basic-Principles.png 621w, /wp-content/uploads/2012/04/Rabin-Karp-Basic-Principles-300x144.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Rabin-Karp hashes the pattern and the sub-string in order to compare them quickly!</figcaption></figure>
<p>The hash function may vary depending on many things, so it may consist of ASCII char to number converting, but it can be also anything else. The only thing we need is to convert a string (pattern) into some hash that is faster to compare. Let’s say we have the string “hello world”, and let’s assume that its hash is hash(‘hello world’) = 12345. So if hash(‘he’) = 1 we can say that the pattern “he” is contained in the text “hello world”. Thus on every step we take from the text a sub-string with the length of m, where m is the pattern length. Thus we hash this sub-string and we can directly compare it to the hashed pattern, as on the picture above.</p>
<h2>Implementation</h2>
<p>So far we saw some diagrams explaining the Rabin-Karp algorithm, but let’s take a look on its implementation. Here in this very basic example where a simple hash table is used in order to convert the characters into integers. The code is PHP and it&#8217;s used only to illustrate the principles of this algorithm.</p>
<pre lang="PHP">
function hash_string($str, $len)
{
	$hash = '';
 
	$hash_table = array(
		'h' => 1,
		'e' => 2,
		'l' => 3,
		'o' => 4,
		'w' => 5,
		'r' => 6,
		'd' => 7,
	);
 
	for ($i = 0; $i < $len; $i++) {
		$hash .= $hash_table[$str{$i}];
	}
 
	return (int)$hash;
}
 
function rabin_karp($text, $pattern)
{
	$n = strlen($text);
	$m = strlen($pattern);
 
	$text_hash = hash_string(substr($text, 0, $m), $m);
	$pattern_hash = hash_string($pattern, $m);
 
	for ($i = 0; $i < $n-$m+1; $i++) {
		if ($text_hash == $pattern_hash) {
			return $i;
		}
 
		$text_hash = hash_string(substr($text, $i, $m), $m);
	}
 
	return -1;
}
 
// 2
echo rabin_karp('hello world', 'ello');
</pre>
<h3>Multiple Pattern Match</h3>
<p>It’s great to say that the Rabin-Karp algorithm is great for multiple pattern match. Indeed its nature is supposed to support such functionality, which is its advantage in compare to other string searching algorithms.</p>
<h2>Complexity</h2>
<p>The Rabin-Karp algorithm has the complexity of O(nm) where <strong>n</strong>, of course, is the length of the text, while <strong>m</strong> is the length of the pattern. So where it is compared to brute-force matching? Well, brute force matching complexity is O(nm), so as it seems there’s no much gain in performance. However it’s considered that Rabin-Karp’s complexity is O(n+m) in practice, and that makes it a bit faster, as shown on the chart below.</p>
<figure id="attachment_3001" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Rabin-Karp-Complexity.png"><img src="/wp-content/uploads/2012/04/Rabin-Karp-Complexity.png" alt="Rabin-Karp Complexity" title="Rabin-Karp Complexity" width="600" height="371" class="size-full wp-image-3001" srcset="/wp-content/uploads/2012/04/Rabin-Karp-Complexity.png 600w, /wp-content/uploads/2012/04/Rabin-Karp-Complexity-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">Rabin-Karp&#039;s complexity is O(nm), but in practice it&#039;s O(n+m)!</figcaption></figure>
<p>Note that the Rabin-Karp algorithm also needs O(m) preprocessing time.</p>
<h2>Application</h2>
<p>As we saw Rabin-Karp is not so faster than brute force matching. So where we should use it?</p>
<h3>3 Reasons Why Rabin-Karp is Cool</h3>
<p>1. Good for plagiarism, because it can deal with multiple pattern matching!<br />
<figure id="attachment_3000" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Application-of-Rabin-Karp.png"><img src="/wp-content/uploads/2012/04/Application-of-Rabin-Karp.png" alt="Application of Rabin-Karp" title="Application of Rabin-Karp" width="620" height="399" class="size-full wp-image-3000" srcset="/wp-content/uploads/2012/04/Application-of-Rabin-Karp.png 620w, /wp-content/uploads/2012/04/Application-of-Rabin-Karp-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Rabin-Karp can detect plagiarism efficiently!</figcaption></figure></p>
<p>2. Not faster than brute force matching in theory, but in practice its complexity is O(n+m)!<br />
3. With a good hashing function it can be quite effective and it's easy to implement!</p>
<h3>2 Reasons Why Rabin-Karp is Not Cool</h3>
<p>1. There are lots of string matching algorithms that are faster than O(n+m)<br />
2. It’s practically as slow as brute force matching and it requires additional space</p>
<h2>Final Words</h2>
<p>Rabin-Karp is a great algorithm for one simple reason - it can be used to match against multiple pattern. This makes it perfect to detect plagiarism even for larger phrases. </p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" rel="bookmark" title="Computer Algorithms: Morris-Pratt String Searching">Computer Algorithms: Morris-Pratt String Searching </a></li>
<li><a href="/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/" rel="bookmark" title="Computer Algorithms: Boyer-Moore String Searching">Computer Algorithms: Boyer-Moore String Searching </a></li>
<li><a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" rel="bookmark" title="Computer Algorithms: Brute Force String Matching">Computer Algorithms: Brute Force String Matching </a></li>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/04/02/computer-algorithms-rabin-karp-string-searching/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Make your own link shortener</title>
		<link>/2010/01/28/make-your-own-link-shortener/</link>
		<comments>/2010/01/28/make-your-own-link-shortener/#respond</comments>
		<pubDate>Thu, 28 Jan 2010 08:09:44 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Hash table]]></category>
		<category><![CDATA[Twitter Inc]]></category>
		<category><![CDATA[URL]]></category>
		<category><![CDATA[URL shortening]]></category>

		<guid isPermaLink="false">/?p=968</guid>
		<description><![CDATA[Why you should do that? First of all what’s a link shortener? Such online software exists and it’s widely used by the customers. Sites like bit.ly became extremely popular because of the growth of web apps like Facebook and especially Twitter. The simple goal that they achieve is to convert a long website uri into &#8230; <a href="/2010/01/28/make-your-own-link-shortener/" class="more-link">Continue reading <span class="screen-reader-text">Make your own link shortener</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/01/26/prevent-link-default-action-when-mousedown-and-mouseup-fires/" rel="bookmark" title="Prevent link default action when mousedown and mouseup fires!">Prevent link default action when mousedown and mouseup fires! </a></li>
<li><a href="/2010/06/04/one-form-multiple-db-records/" rel="bookmark" title="One Form &#8211; Multiple DB Records">One Form &#8211; Multiple DB Records </a></li>
<li><a href="/2010/03/09/what-make-javascript-closures-work/" rel="bookmark" title="What make JavaScript closures work?">What make JavaScript closures work? </a></li>
<li><a href="/2010/11/12/how-to-make-mp4-progressive-with-qt-faststart/" rel="bookmark" title="How to Make MP4 Progressive with qt-faststart">How to Make MP4 Progressive with qt-faststart </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Why you should do that?</h2>
<p>First of all what’s a link shortener? Such online software exists and it’s widely used by the customers. Sites like bit.ly became extremely popular because of the growth of web apps like Facebook and especially Twitter. The simple goal that they achieve is to convert a long website uri into a short unique one. Beside that they give more information about who clicked that link and some useful stats along with that.</p>
<p>The question is why to make your own link shortener? One of the main reasons why is to paste links containing in plaintext your domain. In the case of <strong>http://stoimen.com/</strong> instead of using <strong>http://bit.ly/xxxxx</strong> it will be great if the link was something like <strong>http://stoimen.com/xxxx</strong> than pasting it into Twitter or wherever I get the primary impression of my domain.</p>
<h2>How to &#8230;</h2>
<p>It should be no mystery how to make your own. In fact you’ll need only one more table into the database, as this is the most common way to achieve it. Of course you can do that with no database using the file system to store the hash table in whatever format you’d like.</p>
<p>In the case of the DB solution you can simply make a table with three columns containing the unique id of the row, the short and the full link. Thus requesting some short link the db will return the “real” full uri. You can simply drop the short column if you’d like more efficient solution. Thus the unique identifier may become short link. That may be really fast if you’ve an index on the full link column.</p>
<p><strong>See the example below:</strong></p>
<blockquote>
<pre>id | short_link | full_link
1  | qwrt 	| /blog/2010/01/27/theory-of-caching-zend_cache-zend-optimizer</pre>
</blockquote>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/01/26/prevent-link-default-action-when-mousedown-and-mouseup-fires/" rel="bookmark" title="Prevent link default action when mousedown and mouseup fires!">Prevent link default action when mousedown and mouseup fires! </a></li>
<li><a href="/2010/06/04/one-form-multiple-db-records/" rel="bookmark" title="One Form &#8211; Multiple DB Records">One Form &#8211; Multiple DB Records </a></li>
<li><a href="/2010/03/09/what-make-javascript-closures-work/" rel="bookmark" title="What make JavaScript closures work?">What make JavaScript closures work? </a></li>
<li><a href="/2010/11/12/how-to-make-mp4-progressive-with-qt-faststart/" rel="bookmark" title="How to Make MP4 Progressive with qt-faststart">How to Make MP4 Progressive with qt-faststart </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/01/28/make-your-own-link-shortener/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
