<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Code and eventually Data]]></title><description><![CDATA[The purpose of this blog is mostly to document my algorithm practice and interesting things I learn. For the most part the content will be algorithms and data science.]]></description><link>https://rushil-patel.github.io</link><generator>RSS for Node</generator><lastBuildDate>Tue, 06 Sep 2016 22:08:27 GMT</lastBuildDate><atom:link href="https://rushil-patel.github.io/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Reverse a Singly Linked List]]></title><description><![CDATA[<div class="sect2">
<h3 id="_problem_description">Problem Description</h3>
<div class="paragraph">
<p>The task here is to write a function that will reverse a singly linked list.
The function will take a node, the head of the linked list. The function should return the head of the reversed linked list.</p>
</div>
</div>
<div class="sect2">
<h3 id="_process">Process</h3>
<div class="paragraph">
<p>Im only going focus on the iterative solution mainly because this is a relatively easy problem. The hardest part is executing the reversal in the correct order.</p>
</div>
<div class="paragraph">
<p>Here is a basic Node class I defined for this problem.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">public class Node {
   public int value;
   public Node next;

   public Node(int value) {
      this.value = value;
      next = null;
   }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>So the idea here is to traverse the linked list from head to tail and simultaneously reverse the links. In other words while we travel through the linked list we will switch the <code>next</code> pointers so that they point to the previous node rather than the next.</p>
</div>
<div class="paragraph">
<p>We have to be careful, if we set the next pointer of a node in the wrong order we will end up detaching the node from the rest of the list. To work around this, we can save the <code>current.next</code> node into our <code>next</code> node to hold onto the reference. Then we set <code>current.next</code> to the <code>previous node</code>, this is in effect reversing the links between the nodes. And then finally we advance the current node by setting the <code>current</code> node to <code>next</code>, remember we saved <code>current.next</code> into <code>next</code> so we are good.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">public Node reverse(Node head) {
   Node current = head;
   Node previous = null;
   Node next = null;

   while (current != null) {

      next = current.next;
      current.next = previous;

      previous = current;
      current = next;
   }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This solution will run in O(n) time and O(1) space.</p>
</div>
</div>]]></description><link>https://rushil-patel.github.io/2016/09/06/Reverse-a-Singly-Linked-List.html</link><guid isPermaLink="true">https://rushil-patel.github.io/2016/09/06/Reverse-a-Singly-Linked-List.html</guid><category><![CDATA[coding_problem]]></category><dc:creator><![CDATA[Rushil Patel]]></dc:creator><pubDate>Tue, 06 Sep 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Two Sum]]></title><description><![CDATA[<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>This is my breakdown of the <code>Two Sum</code> problem. It can be found here on <a href="https://leetcode.com/problems/two-sum-ii-input-array-is-sorted">leetcode</a> and a bunch of other websites.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_problem_description">Problem Description</h3>
<div class="paragraph">
<p>Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.</p>
</div>
<div class="paragraph">
<p>The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.</p>
</div>
<div class="paragraph">
<p>Note: Allowed to assume that each input has exactly one solution.</p>
</div>
</div>
<div class="sect2">
<h3 id="_process">Process</h3>
<div class="sect3">
<h4 id="_bruteforce">Bruteforce</h4>
<div class="paragraph">
<p>The obvious and naive way is to bruteforce. The general idea would be to keep generating a pair of numbers from the array until we get one that sums to our target value.</p>
</div>
<div class="paragraph">
<p>In code it would look something like this</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-python" data-lang="python">def two_sum(numbers, target):
   for i in range(0, len(numbers) - 1):
      for k in range(i + 1, len(numbers)):
         if numbers[i] + numbers[k] == target:
            return [i + 1, k + 1]
   return [None, None]</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the code above we start from the beginning of the list and check every pair of numbers moving towards the end of the list. Note, we are given a constraint <code>index1 &lt; index2</code> which is why the inner loop iterates from <code>i + 1</code>, this insures that one index is less than the other.</p>
</div>
<div class="paragraph">
<p>The code above will run in <code>O(n^2)</code> time with <code>O(1)</code> space. For a problem like this <code>O(n^2)</code> is pretty poor performance.</p>
</div>
<div class="paragraph">
<p>You may have noticed the code above doesn&#8217;t take advantage of the fact that the array is already sorted. We can do better!</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_optimization_1">Optimization #1</h3>
<div class="paragraph">
<p>We know that the array is already sorted, with this knowledge we can cut down the number of iterations executed. If we traverse the loops in the same fashion as above but we only continue incrementing if the sum of the numbers is less than the target. Once we reach a sum that is greater than the <code>target</code>, we can guarentee on the current iteration the other pair of numbers will also be greater than the sum because the array is ordered in increasing order. Thus, we have cut out some of the iterations.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-python" data-lang="python">def two_sum(numbers, target):
   current_sum = 0
   for i in range(0, len(numbers) - 1):
      for k in range(i + 1, len(numbers)):
         current_sum = 0
         if current_sum == target:
            return [i + 1, k + 1]
         elif current_sum &gt; target:
            break
         else:
            continue
   return [None, None]</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above code is still <code>O(n^2)</code> but because this code will run <code>N^2</code> times if the target is the sum of the last two numbers. But on average case this code will perform better than the bruteforce above.</p>
</div>
</div>
<div class="sect2">
<h3 id="_optimization_2">Optimization #2</h3>
<div class="paragraph">
<p>Let&#8217;s really make use of the fact that the array is sorted. In this approach we use two pointers starting on each end and step towards the middle of the array. Have any clues?
Hint: We can make the sum converge.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-python" data-lang="python">def two_sum(numbers, target):
   left = 0, right = len(numbers) - 1
   current_sum = 0
   while left &lt; right:
   	  current_sum = numbers[left] + numbers[right]
      if current_sum &gt; target:
         right -= 1
      elif current_sum &lt; target:
         left += 1
      else
         return [left + 1, right + 1]
   return [None, None]</code></pre>
</div>
</div>
<div class="paragraph">
<p>Since we we start on the ends of the array we begin by finding the sum of the maximun and minimum values of the array. Notice that as the right pointer moves from the end of the array towards the middle the values decrease.
In contrast as the left pointer moves from the beginning of the array to the middle the values increase. So if we find the sum of our two numbers to be greater than the target our only option is to move in a direction that would decrease the sum, thus we move the right pointer towards the middle of the array. Similarily, if we find the sum of the two numbers to be less than the target then we increase the sum, by moving the left pointer towards the middle.</p>
</div>
<div class="paragraph">
<p>This solution has <code>O(n)</code> time complexity and <code>O(1)</code> space complexity.</p>
</div>
</div>]]></description><link>https://rushil-patel.github.io/2016/09/05/Two-Sum.html</link><guid isPermaLink="true">https://rushil-patel.github.io/2016/09/05/Two-Sum.html</guid><category><![CDATA[coding_problem]]></category><category><![CDATA[ medium]]></category><dc:creator><![CDATA[Rushil Patel]]></dc:creator><pubDate>Mon, 05 Sep 2016 00:00:00 GMT</pubDate></item></channel></rss>