<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.9.3">Jekyll</generator><link href="/feed.xml" rel="self" type="application/atom+xml" /><link href="/" rel="alternate" type="text/html" /><updated>2023-10-31T02:04:14+00:00</updated><id>/feed.xml</id><title type="html">Musings</title><subtitle>Blogs and blah blahs by Asif Rehan</subtitle><entry><title type="html">Checking SHA256 Checksum One Line Command</title><link href="/checking-sha256-checksum-one-line-command/" rel="alternate" type="text/html" title="Checking SHA256 Checksum One Line Command" /><published>2022-02-22T17:18:00+00:00</published><updated>2022-02-22T17:18:00+00:00</updated><id>/checking-sha256-checksum-one-line-command</id><content type="html" xml:base="/checking-sha256-checksum-one-line-command/">&lt;p&gt;Just do the following&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;pre class=&quot;wp-block-code&quot;&amp;gt;```
cd /folder/path
echo &quot;known_sha_code  filename&quot;  | sha256 --check
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
yup, that’s it.

Example:

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;pre class=&quot;wp-block-code&quot;&gt;```
user@user-Linux:~$ echo &quot;4ee9c3aa53329cd7...d362b4 Miniconda3-py39_4.11.0-Linux-x86_64.sh&quot; | sha256sum --check
Miniconda3-py39_4.11.0-Linux-x86_64.sh: OK
```
```
&lt;/pre&gt;</content><author><name>Asif Rehan</name></author><category term="Linux" /><category term="System" /><category term="Checksum" /><category term="Linux" /><category term="SHA256" /><summary type="html">Just do the following</summary></entry><entry><title type="html">Union-Find (aka Disjoint Set) Data Structure</title><link href="/union-find-aka-disjoint-set-data-structure/" rel="alternate" type="text/html" title="Union-Find (aka Disjoint Set) Data Structure" /><published>2021-12-09T20:28:00+00:00</published><updated>2021-12-09T20:28:00+00:00</updated><id>/union-find-aka-disjoint-set-data-structure</id><content type="html" xml:base="/union-find-aka-disjoint-set-data-structure/">&lt;p&gt;If you are already not familiar with the Union-Find data structure, check out this &lt;a href=&quot;https://leetcode.com/discuss/general-discussion/1072418/Disjoint-Set-Union-(DSU)Union-Find-A-Complete-Guide&quot;&gt;simple tutorial&lt;/a&gt; to understand the data structure. The images help a lot.&lt;/p&gt;

&lt;h2 id=&quot;naive-implementation-without-optimizations&quot;&gt;Naive Implementation without Optimizations&lt;/h2&gt;

&lt;p&gt;The worst time complexity for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;find()&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;union()&lt;/code&gt; is O(n) since it may need to run through the whole chain of parents. So in the worst case, m operations can take O(mn) time.&lt;/p&gt;

&lt;h2 id=&quot;optimizations&quot;&gt;Optimizations&lt;/h2&gt;

&lt;h4 id=&quot;union-by-size&quot;&gt;&lt;strong&gt;Union-by-size&lt;/strong&gt;&lt;/h4&gt;

&lt;p&gt;Modify &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;union()&lt;/code&gt; to make the worst-case time of Θ(log n).&lt;/p&gt;

&lt;h4 id=&quot;path-compression&quot;&gt;&lt;strong&gt;Path compression&lt;/strong&gt;&lt;/h4&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;find()&lt;/code&gt; has an amortized time nearly Θ(1)&lt;/p&gt;

&lt;h4 id=&quot;with-both-union-by-size--path-compression&quot;&gt;&lt;strong&gt;With both Union-by-size + Path compression&lt;/strong&gt;&lt;/h4&gt;

&lt;p&gt;Worst-case time complexity is &lt;strong&gt;Θ(m α(m, n))&lt;/strong&gt;. for m&amp;gt;n operations, where n is the number of elements in the Union-Find tree.&lt;/p&gt;

&lt;p&gt;Now, &lt;strong&gt;α(m, n)&lt;/strong&gt; is constant when amortized over a big number of operations. So this turns the time complexity of m operations is just &lt;strong&gt;O(m)&lt;/strong&gt; so each union or find operation is just O(1) on average!&lt;/p&gt;</content><author><name>Asif Rehan</name></author><category term="Algorithms" /><category term="algorithms" /><category term="Data Structure" /><category term="Programming" /><summary type="html">Very quick summary of Union-Find or Disjoint Set data structure</summary></entry><entry><title type="html">Strongly Connected Component using Tarjan’s Algorithm</title><link href="/strongly-connected-component-using-tarjans-algorithm/" rel="alternate" type="text/html" title="Strongly Connected Component using Tarjan’s Algorithm" /><published>2021-10-13T03:57:31+00:00</published><updated>2021-10-13T03:57:31+00:00</updated><id>/strongly-connected-component-using-tarjans-algorithm</id><content type="html" xml:base="/strongly-connected-component-using-tarjans-algorithm/">&lt;h2 id=&quot;kosarajus-vs-tarjans&quot;&gt;Kosaraju’s vs Tarjan’s&lt;/h2&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Kosaraju’s algorithm finds the Topological Sorting of the original directed graph. For this, it uses DFS. Next it reverses the graph and runs DFS on the topologically sorted vertices. So it takes two DFS though the time complexity is O(&lt;/td&gt;
      &lt;td&gt;V&lt;/td&gt;
      &lt;td&gt;+&lt;/td&gt;
      &lt;td&gt;E&lt;/td&gt;
      &lt;td&gt;).&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Tarjan’s algorithm, on the other hand, only uses one DFS but uses some extra tracking variables to maintain a stack. This stack helps find loops which for SCC.&lt;/p&gt;

&lt;h2 id=&quot;tarjans-algorithm&quot;&gt;Tarjan’s Algorithm:&lt;/h2&gt;

&lt;p&gt;First, watch this video by &lt;a href=&quot;https://www.youtube.com/watch?v=wUgWX0nc4NY&quot;&gt;William Fiset&lt;/a&gt;. Then check out Wikipedia pseudocode &lt;a href=&quot;https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm#The_algorithm_in_pseudocode&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The following code implements it in Java.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;pre class=&quot;wp-block-code&quot;&amp;gt;```
import java.util.*;

public class TarjanSCC {
    List&amp;lt;Integer&amp;gt;[] g;
    boolean[] visited;
    int[] low;
    int[] index;
    Stack&amp;lt;Integer&amp;gt; stack;
    boolean[] onStack;
    private int count;
    List&amp;lt;List&amp;lt;Integer&amp;gt;&amp;gt; allSCC;

    private List&amp;lt;List&amp;lt;Integer&amp;gt;&amp;gt; SCC(List&amp;lt;Integer&amp;gt;[] graph){
        this.g = graph;
        allSCC = new ArrayList&amp;lt;&amp;gt;();
        low = new int[graph.length];
        index = new int[graph.length];
        stack = new Stack&amp;lt;&amp;gt;();
        onStack = new boolean[graph.length];
        visited = new boolean[graph.length];

        for (int i=0; i&amp;lt;graph.length; i++) {
            if (!visited[i]) {
                DFS(i);
            }
        }
        return allSCC;

    }
    void DFS(int v) {
        low[v] = index[v] = count++;
        visited[v] = true;
        onStack[v] = true;
        stack.push(v);
        for (Integer w: g[v]) {
            if (!visited[w]) {
                DFS(w);
                low[v] = Math.min(low[v], low[w]);
            } else if (onStack[w]) {
                low[v] = Math.min(low[v], index[w]);
            }
        }
        if (low[v] == index[v]) {
            List&amp;lt;Integer&amp;gt; scc = new ArrayList&amp;lt;&amp;gt;();
            int x;
            do {
                x =  stack.pop();
                onStack[x] = false;
                scc.add(x);
            } while (x != v);
            System.out.println(scc);
            this.allSCC.add(scc);
        }
    }
    public static void main(String[] args) {
        List&amp;lt;Integer&amp;gt;[] g = new List[8];
        g[0] = Arrays.asList(new Integer[]{1});
        g[1] = Arrays.asList(new Integer[]{2});
        g[2] = Arrays.asList(new Integer[]{0});
        g[3] = Arrays.asList(new Integer[]{4,7});
        g[4] = Arrays.asList(new Integer[]{5});
        g[5] = Arrays.asList(new Integer[]{0,6});
        g[6] = Arrays.asList(new Integer[]{0,2,4});
        g[7] = Arrays.asList(new Integer[]{3,5});
        TarjanSCC tarjanSCC = new TarjanSCC();
        System.out.println(tarjanSCC.SCC(g));

    }

}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
## Result: 

There are three SCC’s as below:

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;pre class=&quot;wp-block-code&quot;&gt;```
[[2, 1, 0], [6, 5, 4], [7, 3]]
```
```
&lt;/pre&gt;</content><author><name>Asif Rehan</name></author><category term="Algorithms" /><category term="algorithms" /><category term="directed graph" /><category term="graph" /><category term="Java" /><category term="strongly connected component" /><summary type="html">Kosaraju’s vs Tarjan’s</summary></entry><entry><title type="html">Hacker Rank: Caesar Cipher aka Rotational Cipher</title><link href="/hacker-rank-caesar-cipher-aka-rotational-cipher/" rel="alternate" type="text/html" title="Hacker Rank: Caesar Cipher aka Rotational Cipher" /><published>2021-10-09T14:54:00+00:00</published><updated>2021-10-09T14:54:00+00:00</updated><id>/hacker-rank-caesar-cipher-aka-rotational-cipher</id><content type="html" xml:base="/hacker-rank-caesar-cipher-aka-rotational-cipher/">&lt;p&gt;This is a array/string problem and you can look up this problem on &lt;a href=&quot;https://www.hackerrank.com/challenges/caesar-cipher-1&quot;&gt;HackerRank&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;To solve this one, it can not theoretically be any better than O(n) time complexity. Here I convert the string to character array, then for each character and if this is a small ASCII character between a-z, then subtract the value of a, and add the offset values, take modulus of 26 and add back the value of 26. This primitive integer value has to be cast to char value before replacing the original character.&lt;/p&gt;

&lt;p&gt;Similar logic applies for capital case characters, A-Z. At this point, it deviates from the HackerRank problem as I consider numbers as well for encryption, where the modulus of 10 is taken.&lt;/p&gt;

&lt;p&gt;The solution below is pretty self-explanatory.&lt;/p&gt;

&lt;h2 id=&quot;java-solution&quot;&gt;Java Solution&lt;/h2&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;pre class=&quot;wp-block-code&quot; title=&quot;Rotational Cipher&quot;&amp;gt;```
class Main {

  // Add any helper functions you may need here
  

  String rotationalCipher(String input, int rotationFactor) {
    char[] chars = input.toCharArray();
    for (int i=0; i&amp;lt;chars.length; i++) {
      rotate(i, chars, rotationFactor);
    }
    
    return String.valueOf(chars);
  }

  void rotate(int i, char[] chars, int rf) {
    char c = chars[i];
    char newCh;
    
    if (c &amp;gt;= 'a' &amp;amp;&amp;amp; c &amp;lt;= 'z') {
      newCh = (char)((c-'a' + rf) % 26 + 'a');
    } else if (c &amp;gt;= 'A' &amp;amp;&amp;amp; c &amp;lt;= 'Z') {
      newCh = (char)((c-'A' + rf) % 26 + 'A');
    } else if (c &amp;gt;= '0' &amp;amp;&amp;amp; c &amp;lt;= '9') {
      newCh = (char)((c-'0' + rf) % 10 + '0');
    } else {
      return;
    }  
    chars[i] = newCh;
    
    return;
  }

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;```&lt;/p&gt;</content><author><name>Asif Rehan</name></author><category term="Algorithms" /><category term="algorithms" /><category term="HackerRank" /><category term="Problem Solving" /><summary type="html">This is a array/string problem and you can look up this problem on HackerRank.</summary></entry><entry><title type="html">Spring Boot and Angular JS Application Development</title><link href="/spring-boot-and-angular-js-application-development/" rel="alternate" type="text/html" title="Spring Boot and Angular JS Application Development" /><published>2021-08-29T21:19:08+00:00</published><updated>2021-08-29T21:19:08+00:00</updated><id>/spring-boot-and-angular-js-application-development</id><content type="html" xml:base="/spring-boot-and-angular-js-application-development/">&lt;h2 id=&quot;installing-environment&quot;&gt;Installing Environment&lt;/h2&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;pre class=&quot;wp-block-code&quot;&amp;gt;```
sudo apt update
sudo apt install snapd

sudo apt install -y default-jdk
sudo snap install node --classic
sudo npm install -g @angular/cli --unsafe-perm=true --allow-root

sudo snap install intellij-idea-ultimate --classic --edge
sudo snap install --classic code 
sudo snap install postman

sudo snap install http
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
&amp;lt;figure class=&quot;wp-block-embed&quot;&amp;gt;&amp;lt;div class=&quot;wp-block-embed__wrapper&quot;&amp;gt;https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart &amp;lt;/div&amp;gt;&amp;lt;/figure&amp;gt;## Setup PostgreSQL Database Server

We are going to show how to install PostgreSQL database on a Debian Linux system.

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;pre class=&quot;wp-block-preformatted&quot;&gt;$ sudo apt-get install postgresql  
```

Check status

```
&lt;pre class=&quot;wp-block-preformatted&quot;&gt;$ /etc/init.d/postgresql status
```

Add password for the postgress account

```
&lt;pre class=&quot;wp-block-preformatted&quot;&gt;$ sudo -u postgres psql postgres
psql (9.5.10)
Type &quot;help&quot; for help.

postgres=# \password postgres
Enter new password: 
Enter it again: 
```

Create a new user with a password

```
&lt;pre class=&quot;wp-block-preformatted&quot;&gt;$ sudo -u postgres createuser --interactive --password usertest
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) y
Shall the new role be allowed to create more new roles? (y/n) n
Password: 
```

Create a new database test\_db with the new role as the owner

```
&lt;pre class=&quot;wp-block-preformatted&quot;&gt;$ sudo -u postgres createdb test_db -O usertest
```

Now edit the `pg_hba.conf` file to enable connection

```
&lt;pre class=&quot;wp-block-preformatted&quot;&gt;$ sudo vi /etc/postgresql/12/main/pg_hba.conf
```

By changing the lines below with **trust**

```
&lt;pre class=&quot;wp-block-preformatted&quot;&gt;# &quot;local&quot; is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
```

Restart the server

```
&lt;pre class=&quot;wp-block-preformatted&quot;&gt;$ sudo service postgresql restart
```

Check if the new role can access the new database

```
&lt;pre class=&quot;wp-block-preformatted&quot;&gt;$ psql -U user_test -d test_db -W 
```
&lt;/pre&gt;&lt;/pre&gt;&lt;/pre&gt;&lt;/pre&gt;&lt;/pre&gt;&lt;/pre&gt;&lt;/pre&gt;&lt;/pre&gt;&lt;/pre&gt;</content><author><name>Asif Rehan</name></author><category term="System" /><category term="Full stack" /><category term="Java" /><category term="Postgres" /><category term="PostgreSQL" /><category term="REST" /><category term="Software Engineering" /><category term="Spring Boot" /><summary type="html">Installing Environment</summary></entry><entry><title type="html">Reading List</title><link href="/reading-list/" rel="alternate" type="text/html" title="Reading List" /><published>2021-08-08T19:10:00+00:00</published><updated>2021-08-08T19:10:00+00:00</updated><id>/reading-list</id><content type="html" xml:base="/reading-list/">&lt;ol&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.amazon.com/Good-Great-Some-Companies-Others/dp/0066620996&quot;&gt;Good to Great – Jim Collins&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.amazon.com/Signal-Noise-Many-Predictions-Fail-but-ebook/dp/B007V65R54/ref=sr_1_1?crid=LMPF6M0ZC15V&amp;amp;dchild=1&amp;amp;keywords=signal+and+the+noise&amp;amp;qid=1587913186&amp;amp;s=books&amp;amp;sprefix=signal+and+%2Cstripbooks%2C-1&amp;amp;sr=1-1&quot;&gt;Signal and Noise by Nate Silver&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.amazon.com/Security-Analysis-Foreword-Buffett-Editions/dp/0071592539&quot;&gt;Security Analysis by Graham and Dodd&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;</content><author><name>Asif Rehan</name></author><category term="Uncategorized" /><summary type="html">Good to Great – Jim Collins Signal and Noise by Nate Silver Security Analysis by Graham and Dodd</summary></entry><entry><title type="html">LeetCode#34: Find First and Last Position of Element in Sorted Array</title><link href="/leetcode34-34-find-first-and-last-position-of-element-in-sorted-array/" rel="alternate" type="text/html" title="LeetCode#34: Find First and Last Position of Element in Sorted Array" /><published>2021-04-29T03:30:22+00:00</published><updated>2021-04-29T03:30:22+00:00</updated><id>/leetcode34-34-find-first-and-last-position-of-element-in-sorted-array</id><content type="html" xml:base="/leetcode34-34-find-first-and-last-position-of-element-in-sorted-array/">&lt;p&gt;This &lt;a href=&quot;https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/802/&quot;&gt;LeetCode problem&lt;/a&gt; is a great practice problem to implement a binary search for a value in a sorted array with duplicate values. It asks to find the indices of the first and start the occurrence of a value in the sorted array with possibly duplicate values.&lt;/p&gt;

&lt;p&gt;It can be solved in a naive manner to search for the start and end in a linear runtime O(n). But a better solution is to use Binary Search which runs in O(logn) time.&lt;/p&gt;

&lt;p&gt;A typical binary search method looks like this if the array has unique and sorted numbers.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;pre class=&quot;wp-block-code&quot;&amp;gt;```
private int binarySearch(int[] nums, int target, int l, int r) {
        int result = -1;
        while (l&amp;lt;=r){
            int mid = (l+r)/2;
            if(nums[mid]==target){
                return mid;
            } else if (nums[mid] &amp;lt; target) {
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        return result;
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
But for this problem, the Binary Search requires a little modification because of the duplicates and also that we can design it in a way to look for not only the target value but also specifically search for the starting and ending occurrence. So check out the solution below.

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;pre class=&quot;wp-block-code&quot;&gt;```java
public class SearchForARange {
    public int[] searchRange(int[] nums, int target) {
        int[] res = new int[]{-1,-1};
        if (nums.length==0) return res;
        res[0] = binarySearchLeft(nums, target, 0, nums.length-1);
        if (res[0]&amp;gt;=0) {
            res[1] = binarySearchRight(nums, target, res[0], nums.length-1);
        }    
        return res;
    }

    private int binarySearchLeft(int[] nums, int target, int l, int r) {
        int result = -1;
        while(l&amp;lt;=r){
            int mid = (l+r)/2;
            if (nums[mid] == target){
                result = mid;
                r = mid-1;

            } else if (nums[mid] &amp;gt; target){
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        } 
        return result;
    }

    private int binarySearchRight(int[] nums, int target, int l, int r) {
        int result = -1;
        while (l&amp;lt;=r){
            int mid = (l+r)/2;
            if(nums[mid]==target){
                result = mid;
                l = mid + 1;
            } else if (nums[mid] &amp;gt; target) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return result;
    }
}
```
```

For understanding the logic, check out [this post](https://www.techiedelight.com/find-first-or-last-occurrence-of-a-given-number-sorted-array/).
&lt;/pre&gt;</content><author><name>Asif Rehan</name></author><category term="Algorithms" /><category term="algorithms" /><category term="Binary Search" /><category term="LeetCode" /><summary type="html">This LeetCode problem is a great practice problem to implement a binary search for a value in a sorted array with duplicate values. It asks to find the indices of the first and start the occurrence of a value in the sorted array with possibly duplicate values.</summary></entry><entry><title type="html">LeetCode#75: Sort Color using Three-way Partitioning</title><link href="/three-way-partion-sort-an-array/" rel="alternate" type="text/html" title="LeetCode#75: Sort Color using Three-way Partitioning" /><published>2021-04-28T20:15:00+00:00</published><updated>2021-04-28T20:15:00+00:00</updated><id>/three-way-partion-sort-an-array</id><content type="html" xml:base="/three-way-partion-sort-an-array/">&lt;p&gt;The Sort Color problem expects to sort the array with values {0, 1, 2}. This can be done in a typical sorting algorithm in O(nlogn) time. &lt;br /&gt;
A better approach is to use three-way partitioning of the array.&lt;/p&gt;

&lt;h2 id=&quot;generic-three-way-partitioning&quot;&gt;Generic three-way partitioning&lt;/h2&gt;

&lt;p&gt;Below the threeWayPartitionSort() method splits the given an array, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[3,2,0,2,1,1,0,-1]&lt;/code&gt;, into three parts, where values equal to or 0 come first, in the last part, values equal to or greater than 2 show up. Anything in between stays in between. So the final result is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[-1,0,0,   1,1,   2,2,3]&lt;/code&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;pre class=&quot;wp-block-code&quot;&amp;gt;```
public class threeWayPartitionSort{
    public void threeWayPartitionSort(int[] nums, int a, int b) {
        int l = 0;
        int r = nums.length - 1;
        int i = 0;
        while(i&amp;lt;=r){
            if (nums[i]&amp;lt;=a) {
                swap(nums, i++, l++);
            } else if (nums[i]&amp;gt;=b){
                swap(nums, i, r--);
            } else {
                i++;
            }
        
        }
    }
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
    public static void main(String[] args) {
        nums = new int[]{3,2,0,2,1,1,0,-1};
        sortColors.sortColors(nums, 0, 2);
        System.out.println(Arrays.toString(nums));
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;pre class=&quot;wp-block-code&quot;&gt;```java
Output: [-1, 0, 0, 1, 1, 2, 2, 3]
```
```

Notice, that there are three pointers, `i` for looping through the the array until it hits the right side marker `r`, and the left side marker `l`. Until `i` hits `r`, we keep looping, and each time a value below a is met it is swapped with left marker and both `l` and `i` are incremented. If a value greater than or equal to b is found, value at`r` and `i` are swapped, but only `r` is decremented, showing that the ride side is already partitioned. For value in between, just increment `i`. This expects, that if we move the larger values to the right region and smaller values in the left region, then every value in between should fall in the right middle region.

## Solution for Sort Color

Using the above approach the solution for the [Sort Color](https://leetcode.com/problems/sort-colors/) problem is below. This approach takes O(n) times.

```
&lt;pre class=&quot;wp-block-code&quot;&gt;```
class Solution {
        public void sortColors(int[] nums) {
        int l = 0;
        int r = nums.length - 1;
        int i = 0;
        while(i&amp;lt;=r){
            if (nums[i]==0) {
                swap(nums, i++, l++);
            } else if (nums[i]==2){
                swap(nums, i, r--);
            } else {
                i++;
            }
        
        }
    }
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
```
```
&lt;/pre&gt;&lt;/pre&gt;</content><author><name>Asif Rehan</name></author><category term="Algorithms" /><category term="algorithms" /><category term="Java" /><category term="LeetCode" /><summary type="html">The Sort Color problem expects to sort the array with values {0, 1, 2}. This can be done in a typical sorting algorithm in O(nlogn) time. A better approach is to use three-way partitioning of the array.</summary></entry><entry><title type="html">Stock Prediction Using Deep Learning</title><link href="/stock-prediction-using-deep-learning/" rel="alternate" type="text/html" title="Stock Prediction Using Deep Learning" /><published>2021-04-23T07:04:00+00:00</published><updated>2021-04-23T07:04:00+00:00</updated><id>/stock-prediction-using-deep-learning</id><content type="html" xml:base="/stock-prediction-using-deep-learning/">&lt;p&gt;Recently have been looking into some stock market prediction libraries and repositories for our group project for &lt;a href=&quot;https://www.cc.gatech.edu/classes/AY2020/cs7643_fall/&quot;&gt;CS7643 Deep Learning&lt;/a&gt; at Georgia Tech. Previously I worked on traditional Machine Learning algorithms and Q-Learning algorithm from Reinforcement Learning for &lt;a href=&quot;https://omscs.gatech.edu/cs-7646-machine-learning-trading&quot;&gt;CS7646: Machine Learning for Trading&lt;/a&gt; commonly known as the “ML4T course”. My codes for ML4T is locked in this &lt;a href=&quot;https://github.com/asif-rehan/ML4T_Spring2020&quot;&gt;private GitHub repo&lt;/a&gt;. But here I am sharing the research findings for applications of Deep Learning for stock prediction.&lt;/p&gt;

&lt;h2 id=&quot;approaches&quot;&gt;Approaches&lt;/h2&gt;

&lt;p&gt;Traditional stock prediction can be seen as a time series regression problem where many many algorithms already exist. A naive approach could be classification/regression but time series is more robust approach.&lt;/p&gt;

&lt;p&gt;However, for a regression stock prediction model, one needs to map the predicted stock price to BUY / SELL / HOLD action space. So classification probably makes more sense. But Reinforcement Learning really helps a lot because it can optimize the total gains.&lt;/p&gt;

&lt;h2 id=&quot;pytorch-implementations&quot;&gt;PyTorch Implementations&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Generic RNN, LSTM:&lt;/strong&gt; many resources available online&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Transformer+Attention:&lt;/strong&gt; This &lt;a href=&quot;https://towardsdatascience.com/stock-predictions-with-state-of-the-art-transformer-and-time-embeddings-3a4485237de6&quot;&gt;Medium article&lt;/a&gt; and its corresponding &lt;a href=&quot;https://github.com/JanSchm/CapMarket/blob/master/bot_experiments/IBM_Transformer%2BTimeEmbedding.ipynb&quot;&gt;GitHub repo&lt;/a&gt; applies Transformer and time embeddings which seems quite interesting&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dual-stage Attention -RNN (DA-RNN):&lt;/strong&gt; The paper is here &lt;a href=&quot;https://arxiv.org/pdf/1704.02971.pdf&quot;&gt;https://arxiv.org/pdf/1704.02971.pdf&lt;/a&gt; and the implemented model is available here in &lt;a href=&quot;https://github.com/ysn2233/attentioned-dual-stage-stock-prediction&quot;&gt;this GitHub&lt;/a&gt;. A similar implementation in PyTorch is available here by &lt;a href=&quot;https://github.com/KurochkinAlexey/DA-RNN/blob/master/DARNN_NASDAQ.ipynb&quot;&gt;KurochkinAlexey&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Deep Reinforcement Learning:&lt;/strong&gt; Finally, this &lt;a href=&quot;http://finrl.org/guide/overview.html&quot;&gt;FinRL&lt;/a&gt; is an excellent library for applying Deep RL on stock prediction with demo and code examples to help you get started.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is a work-in-progress note. So will update this as needed.&lt;/p&gt;</content><author><name>Asif Rehan</name></author><category term="Algorithms" /><category term="Data Science" /><category term="CS7643" /><category term="Deep Learning" /><category term="Finance" /><category term="Financial Modeling" /><category term="GATECH" /><category term="Georgia Tech" /><category term="OMSCS" /><category term="PyTorch" /><category term="Stock Prediction" /><summary type="html">Recently have been looking into some stock market prediction libraries and repositories for our group project for CS7643 Deep Learning at Georgia Tech. Previously I worked on traditional Machine Learning algorithms and Q-Learning algorithm from Reinforcement Learning for CS7646: Machine Learning for Trading commonly known as the “ML4T course”. My codes for ML4T is locked in this private GitHub repo. But here I am sharing the research findings for applications of Deep Learning for stock prediction.</summary></entry><entry><title type="html">LeetCode: Find Peak Element Solution</title><link href="/leetcode-find-peak-element-solution/" rel="alternate" type="text/html" title="LeetCode: Find Peak Element Solution" /><published>2021-04-21T19:57:13+00:00</published><updated>2021-04-21T19:57:13+00:00</updated><id>/leetcode-find-peak-element-solution</id><content type="html" xml:base="/leetcode-find-peak-element-solution/">&lt;p&gt;The Find Peak Element problem can be solved using a linear search in O(n) time and O(1) space. but it can be even better to solve it by binary search in O(log n) time complexity. But there can be two cases for binary search solution, the recursive solution creates stacks for each call and thus takes O(log n) space. On the other hand, the iterative solution takes O(1) space. So the iterative binary search solution is the best approach.&lt;/p&gt;

&lt;h2 id=&quot;recursive-solution&quot;&gt;Recursive Solution&lt;/h2&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;pre class=&quot;wp-block-code&quot;&amp;gt;```java
public class FindPeakElement {
    int[] nums;
    public int findPeakElement(int[] nums){
        this.nums = nums;
        return search(0, this.nums.length-1);

    }
    private int search(int l, int r) {
        if(l==r) return l;
        int mid = (l+r)/2;
        if (nums[mid]&amp;gt;nums[mid+1]){
            return search(l, mid);
        } else return search(mid+1, r);
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
## Iterative Solution

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;pre class=&quot;wp-block-code&quot;&gt;```java
public class FindPeakElement {
    int[] nums;
    public int findPeakElement(int[] nums){
        this.nums = nums;
        return searchIterative(0, this.nums.length-1);
    }

    private int searchIterative(int l, int r){
        while(l&amp;lt;r){
            int mid = (l+r)/2;
            if (nums[mid]&amp;gt;nums[mid+1]){
                r = mid;
            } else {
                l = mid+1;
            }
        }
        return l;
    }
```
```
&lt;/pre&gt;</content><author><name>Asif Rehan</name></author><category term="Algorithms" /><category term="100%" /><category term="Binary Search" /><category term="Complexity" /><category term="Find Peak Element" /><category term="Iterative" /><category term="Java" /><category term="LeetCode" /><category term="Linear" /><category term="Logarithmic" /><category term="Programming" /><category term="Programming Solution" /><category term="Recursive" /><category term="Runtime" /><category term="Space" /><category term="Time" /><summary type="html">The Find Peak Element problem can be solved using a linear search in O(n) time and O(1) space. but it can be even better to solve it by binary search in O(log n) time complexity. But there can be two cases for binary search solution, the recursive solution creates stacks for each call and thus takes O(log n) space. On the other hand, the iterative solution takes O(1) space. So the iterative binary search solution is the best approach.</summary></entry></feed>