<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Algorithm on Kailun's Blog</title><link>https://elated-hopper-5c0cb3.netlify.app/tags/algorithm/</link><description>Recent content in Algorithm on Kailun's Blog</description><generator>Hugo</generator><language>en-us</language><lastBuildDate>Sat, 02 May 2020 23:40:40 -0700</lastBuildDate><atom:link href="https://elated-hopper-5c0cb3.netlify.app/tags/algorithm/index.xml" rel="self" type="application/rss+xml"/><item><title>Quick Review of KMP Algorithm</title><link>https://elated-hopper-5c0cb3.netlify.app/posts/kmp/</link><pubDate>Sat, 02 May 2020 23:40:40 -0700</pubDate><guid>https://elated-hopper-5c0cb3.netlify.app/posts/kmp/</guid><description>&lt;p&gt;Published in 1977, the Knuth-Morris-Pratt algorithm can search substring pattern in time linear to the total string length. Recently I encountered 2 Leetcode questions (1367, 1392) that can be effectively solved by KMP, and therefore want to use this post as a quick refresher and go through the basic mechanism and some concrete examples of this algorithm. (A nice video explanation of KMP can be found &lt;a href="https://www.youtube.com/watch?v=uKr9qIZMtzw&amp;amp;t=764s"&gt;here&lt;/a&gt;&lt;/p&gt;
&lt;h1 id="intuition"&gt;Intuition&lt;/h1&gt;
&lt;p&gt;In a naive substring search approach, when we find a mismatch between the pattern and the string, we shift the pattern by 1 character to start a new round of comparison (in the example below, we shift the starting &lt;code&gt;B&lt;/code&gt; to index 1 after we detect the mismatch at index 4). But we already know the portion before &lt;code&gt;C&lt;/code&gt; in the pattern, and we know that we&amp;rsquo;re gonna compare &lt;code&gt;BAAAA&lt;/code&gt; against &lt;code&gt;AAACB...&lt;/code&gt;. This means we are doing some kind of &amp;ldquo;backup&amp;rdquo; after a mismatch. KMP avoids this backup by using deterministic finite state machine, which will be shown in detail in next section.&lt;/p&gt;</description></item></channel></rss>