<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Pankaj Tanwar</title>
    <description>The latest articles on DEV Community by Pankaj Tanwar (@pankajtanwarbanna).</description>
    <link>https://dev.to/pankajtanwarbanna</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F390171%2Fb20c7eb3-3529-4b74-95d2-4cec85f966f0.jpeg</url>
      <title>DEV Community: Pankaj Tanwar</title>
      <link>https://dev.to/pankajtanwarbanna</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/pankajtanwarbanna"/>
    <language>en</language>
    <item>
      <title>Challenge of day #21 - Split a String in Balanced Strings</title>
      <dc:creator>Pankaj Tanwar</dc:creator>
      <pubDate>Sat, 09 Oct 2021 06:53:31 +0000</pubDate>
      <link>https://dev.to/pankajtanwarbanna/challenge-of-day-21-split-a-string-in-balanced-strings-2p05</link>
      <guid>https://dev.to/pankajtanwarbanna/challenge-of-day-21-split-a-string-in-balanced-strings-2p05</guid>
      <description>&lt;p&gt;Hello!&lt;/p&gt;

&lt;p&gt;It's day 21 of &lt;a href="https://pankajtanwar.in"&gt;my coding diary&lt;/a&gt;. Yesterday, &lt;a href="https://vercel.com/"&gt;vercel&lt;/a&gt; was having some issues with their build system. Well, it's up and working smooth now. Let's directly move to the problem of the day.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem of the day&lt;/strong&gt; - &lt;a href="https://leetcode.com/problems/split-a-string-in-balanced-strings/"&gt;Split a String in Balanced Strings&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tag&lt;/strong&gt; - Easy &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Balanced&lt;/strong&gt; strings are those that have an equal quantity of &lt;code&gt;'L'&lt;/code&gt; and &lt;code&gt;'R'&lt;/code&gt; characters.&lt;/p&gt;

&lt;p&gt;Given a &lt;strong&gt;balanced&lt;/strong&gt; string &lt;code&gt;s&lt;/code&gt;, split it in the maximum amount of balanced strings.&lt;/p&gt;

&lt;p&gt;Return &lt;em&gt;the maximum amount of split &lt;strong&gt;balanced&lt;/strong&gt; strings&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Input:&lt;/strong&gt; s = "RLRRLLRLRL"&lt;br&gt;
&lt;strong&gt;Output:&lt;/strong&gt; 4&lt;/p&gt;




&lt;p&gt;This is the worst problem statement, I have ever seen. It's really confusing man, all the example test cases are not clear. I spent time unnecessarily, building some dynamic programming logic for this dumb question.&lt;/p&gt;

&lt;p&gt;So, the problem says, to find the maximum amount of split balanced strings. It does not clearly talk about the order of &lt;code&gt;L&lt;/code&gt; &amp;amp; &lt;code&gt;R&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Mentioning `splitting gives an idea of considering one sub-string having multiple balanced sub-strings as one only.  but still, initially, I got confused with logic for considering all corner cases.&lt;/p&gt;

&lt;p&gt;It turned out to be the simplest problem with just tracking count of &lt;code&gt;L&lt;/code&gt; &amp;amp; &lt;code&gt;R&lt;/code&gt;, that's it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Here is my solution&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;`cpp&lt;br&gt;
class Solution {&lt;br&gt;
public:&lt;br&gt;
    int balancedStringSplit(string s) {&lt;br&gt;
        int res = 0;&lt;br&gt;
        int balance = 0;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    for(int i=0;i&amp;lt;s.length();i++) {
        balance += s[i] == 'L' ? 1 : -1;
        if(balance == 0) res++;
    }
    return res;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;};&lt;br&gt;
`&lt;code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Not to mention, run time 0ms and faster than 100%. Honestly, I am not happy. Such uncleared problems make me less excited about solving more problems.&lt;/p&gt;

&lt;p&gt;Well, I will try some good medium problems tomorrow!&lt;/p&gt;




&lt;p&gt;Thanks for being part of my daily-code-workout journey. As always, if you have any thoughts about anything shared above, don't hesitate to &lt;a href="https://twitter.com/the2ndfloorguy"&gt;reach out&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;You might like previous editions of &lt;a href="https://pankajtanwar.in/coding-diary"&gt;my coding diary&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://pankajtanwar.in/code/to-lower-case/"&gt;Day #20 - To Lower Case.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://pankajtanwar.in/code/n-repeated-element-in-size-2n-array/"&gt;Day #19 - N-Repeated Element in Size 2N Array.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://pankajtanwar.in/code/count-negative-numbers-in-a-sorted-matrix/"&gt;Day #18 - Count Negative Numbers in a Sorted Matrix.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://pankajtanwar.in/code/sum-of-unique-elements/"&gt;Day #17 - Sum of Unique Elements.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://pankajtanwar.in/code/best-time-to-buy-and-sell-stock/"&gt;Day #16 - Best Time to Buy and Sell Stock.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://pankajtanwar.in/code/count-number-of-pairs-with-absolute-difference-k/"&gt;Day #15 - Count Number of Pairs With Absolute Difference K.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://pankajtanwar.in/code/minimum-number-of-operations-to-move-all-balls-to-each-box/"&gt;Day #14 - Minimum Number of Operations to Move All Balls to Each Box.&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>beginners</category>
      <category>programming</category>
      <category>tutorial</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Challenge of the day #20 - To Lower Case.</title>
      <dc:creator>Pankaj Tanwar</dc:creator>
      <pubDate>Fri, 08 Oct 2021 05:28:23 +0000</pubDate>
      <link>https://dev.to/pankajtanwarbanna/challenge-of-the-day-20-to-lower-case-3foh</link>
      <guid>https://dev.to/pankajtanwarbanna/challenge-of-the-day-20-to-lower-case-3foh</guid>
      <description>&lt;p&gt;Hey-yo people!&lt;/p&gt;

&lt;p&gt;Welcome to yet another edition (day 20) of &lt;a href="https://www.pankajtanwar.in/coding-diary"&gt;my coding diary&lt;/a&gt;. I am sure, you might be having some thoughts about what I do here. So, every day I solve a challenge, sharing some interesting approaches + my learning.&lt;/p&gt;

&lt;p&gt;Well, let's jump straight to the problem statement for the day!&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Problem of the day&lt;/strong&gt; -  &lt;a href="https://leetcode.com/problems/to-lower-case/"&gt;To Lower Case&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tag&lt;/strong&gt; - Easy&lt;/p&gt;

&lt;p&gt;Given a string &lt;code&gt;s&lt;/code&gt;, return the string after replacing every uppercase letter with the same lowercase letter.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Input:&lt;/strong&gt; s = "Hello"&lt;br&gt;
&lt;strong&gt;Output:&lt;/strong&gt; "hello"&lt;/p&gt;



&lt;p&gt;I don't even need to re-iterate the problem. It's the simple challenge one can ever get. Hold on, I know it can be solved within seconds but trust me, we are going to discuss some really cool insights.&lt;/p&gt;

&lt;p&gt;I have a couple of solutions for this problem -&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The very first, simplest solution&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;toLowerCase&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;length&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;tolower&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I am sorry, don't punish me for using the built-in function. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ASCII comes to rescue&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;toLowerCase&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;length&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mi"&gt;65&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;90&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;32&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pretty straightforward! &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Tip for C++ beginners: Use int() to convert char to decimal and use char() to convert, a number to ASCII Char.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I usually, struggle to remember the exact ASCII code of &lt;code&gt;A&lt;/code&gt;, &lt;code&gt;Z&lt;/code&gt;,&lt;code&gt;a&lt;/code&gt;,&lt;code&gt;z&lt;/code&gt;. So, I did this -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;toLowerCase&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;length&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="sc"&gt;'A'&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="sc"&gt;'Z'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;32&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ahh, Some times I don't even remember the difference is &lt;code&gt;32&lt;/code&gt;. So,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="sc"&gt;'A'&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="sc"&gt;'Z'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="sc"&gt;'A'&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="sc"&gt;'a'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;Here is the hilarious approach to optimize it further. &lt;/p&gt;

&lt;p&gt;As, to optimize the comparison, instead of using -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="sc"&gt;'A'&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="sc"&gt;'Z'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;we can do,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="sc"&gt;'Z'&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="sc"&gt;'A'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, the thought is, for every lower case letter, it will get rejected in the first check itself, of the &lt;code&gt;if&lt;/code&gt; condition. One comparison saved! (drum rolls please)&lt;/p&gt;

&lt;p&gt;I know I am being too picky here but that's how I optimized it further. Not to mention, my runtime beats 100% of the submissions. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;One guy solved it using &lt;a href="https://leetcode.com/problems/to-lower-case/discuss/348186/C%2B%2B-Using-bit-manipulation"&gt;bit manipulation&lt;/a&gt;. Insane!&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;You might like previous editions of &lt;a href="https://www.pankajtanwar.in/coding-diary"&gt;my coding diary&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/n-repeated-element-in-size-2n-array/"&gt;Day #19 - N-Repeated Element in Size 2N Array.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/count-negative-numbers-in-a-sorted-matrix/"&gt;Day #18 - Count Negative Numbers in a Sorted Matrix.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/sum-of-unique-elements/"&gt;Day #17 - Sum of Unique Elements.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/best-time-to-buy-and-sell-stock/"&gt;Day #16 - Best Time to Buy and Sell Stock.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/count-number-of-pairs-with-absolute-difference-k/"&gt;Day #15 - Count Number of Pairs With Absolute Difference K.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/minimum-number-of-operations-to-move-all-balls-to-each-box/"&gt;Day #14 - Minimum Number of Operations to Move All Balls to Each Box.&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>beginners</category>
      <category>tutorial</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Challenge #19 - N-Repeated Element in Size 2N Array.</title>
      <dc:creator>Pankaj Tanwar</dc:creator>
      <pubDate>Thu, 07 Oct 2021 06:19:47 +0000</pubDate>
      <link>https://dev.to/pankajtanwarbanna/challenge-19-n-repeated-element-in-size-2n-array-3l6o</link>
      <guid>https://dev.to/pankajtanwarbanna/challenge-19-n-repeated-element-in-size-2n-array-3l6o</guid>
      <description>&lt;p&gt;Howdy!&lt;/p&gt;

&lt;p&gt;This is day 19 of &lt;a href="https://www.pankajtanwar.in/coding-diary"&gt;my coding diary&lt;/a&gt; and I am pretty excited to share today's challenge with you guys! &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Spoiler Alert&lt;/strong&gt; - This is one of the interesting problems I have ever encountered. I feel every easy problem has a really smart hidden approach. &lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Problem of the day&lt;/strong&gt; - &lt;a href="https://leetcode.com/problems/n-repeated-element-in-size-2n-array/"&gt;N-Repeated Element in Size 2N Array&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tag&lt;/strong&gt; - Easy&lt;/p&gt;

&lt;p&gt;You are given an integer array &lt;code&gt;nums&lt;/code&gt; with the following properties:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;nums.length == 2 * n&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;nums&lt;/code&gt; contains &lt;code&gt;n + 1&lt;/code&gt; &lt;strong&gt;unique&lt;/strong&gt; elements.&lt;/li&gt;
&lt;li&gt;  Exactly one element of &lt;code&gt;nums&lt;/code&gt; is repeated &lt;code&gt;n&lt;/code&gt; times.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Return &lt;em&gt;the element that is repeated&lt;/em&gt; &lt;code&gt;n&lt;/code&gt; &lt;em&gt;times&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Input:&lt;/strong&gt; nums = [1,2,3,3]&lt;br&gt;
&lt;strong&gt;Output:&lt;/strong&gt; 3&lt;/p&gt;



&lt;p&gt;Ahh, very basic problem. Just use a hashmap, store the count and return a result that has more than one reputation.&lt;/p&gt;

&lt;p&gt;But wait, I could smell the trap here. Leetcode didn't seem happy with my old school hashmap approach &lt;code&gt;(O(n) time and O(n) space)&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;repeatedNTimes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;second&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;first&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Is it even possible to optimize it further?&lt;/p&gt;

&lt;p&gt;Let's find out!&lt;/p&gt;




&lt;p&gt;So, if we observe more closely, we can see that, if a number is repeated n times, in an array of length &lt;code&gt;2 * n&lt;/code&gt;, the repeated number will have to appear either next to each other (&lt;code&gt;nums[i] and nums[i+1]&lt;/code&gt;) or after another (&lt;code&gt;nums[i] and nums[i+2]&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;I know it was tough, read it again. It took even, me some time to digest. &lt;/p&gt;

&lt;p&gt;I was literally, blown away with the intuition. It comes with practice and solving problems of different - different patterns.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The edge case is [1,2,3,1]. In this case, we just return the last element.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Here is the code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;repeatedNTimes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This solution has the &lt;code&gt;O(n)&lt;/code&gt; runtime.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Learning&lt;/strong&gt; &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Never settle for the first approach getting accepted, check out how others have done it. It's a great learning experience.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Thanks for being part of my daily-code-workout journey. As always, if you have any thoughts about anything shared above, don't hesitate to &lt;a href="https://twitter.com/the2ndfloorguy"&gt;reach out&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;You might like previous editions of &lt;a href="https://dev.to/coding-diary"&gt;my coding diary&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/count-negative-numbers-in-a-sorted-matrix/"&gt;Day #18 - Count Negative Numbers in a Sorted Matrix.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/sum-of-unique-elements/"&gt;Day #17 - Sum of Unique Elements.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/best-time-to-buy-and-sell-stock/"&gt;Day #16 - Best Time to Buy and Sell Stock.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/count-number-of-pairs-with-absolute-difference-k/"&gt;Day #15 - Count Number of Pairs With Absolute Difference K.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/minimum-number-of-operations-to-move-all-balls-to-each-box/"&gt;Day #14 - Minimum Number of Operations to Move All Balls to Each Box.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/number-of-rectangles-that-can-form-the-largest-square/"&gt;Day #13 - Number Of Rectangles That Can Form The Largest Square.&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>computerscience</category>
      <category>codenewbie</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Challenge #18 - Count Negative Numbers in a Sorted Matrix</title>
      <dc:creator>Pankaj Tanwar</dc:creator>
      <pubDate>Wed, 06 Oct 2021 06:13:44 +0000</pubDate>
      <link>https://dev.to/pankajtanwarbanna/challenge-18-count-negative-numbers-in-a-sorted-matrix-1ja8</link>
      <guid>https://dev.to/pankajtanwarbanna/challenge-18-count-negative-numbers-in-a-sorted-matrix-1ja8</guid>
      <description>&lt;p&gt;Hey-yo!&lt;/p&gt;

&lt;p&gt;Welcome to day #18 of &lt;a href="https://www.pankajtanwar.in//coding-diary"&gt;my coding diary&lt;/a&gt;. It has been a great journey so far, a really good daily-code-workout. It's too much fun, trust me.&lt;/p&gt;

&lt;h3&gt;
  
  
  TLDR;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Problem seemed pretty easy to me at first but it turned out be a gem when I tried to optimize the solution. &lt;/li&gt;
&lt;li&gt;This is one of the cleverest problems I have ever seen.&lt;/li&gt;
&lt;li&gt;One can just slap on the brute force approach and get on with his life BUT I would recommend everyone to just solve this problem once.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;Problem of the day&lt;/strong&gt; - &lt;a href="https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/"&gt;Count Negative Numbers in a Sorted Matrix&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tag&lt;/strong&gt; - Easy&lt;/p&gt;

&lt;p&gt;Given a &lt;code&gt;m x n&lt;/code&gt; matrix &lt;code&gt;grid&lt;/code&gt; which is sorted in non-increasing order both row-wise and column-wise, return &lt;em&gt;the number of &lt;strong&gt;negative&lt;/strong&gt; numbers in&lt;/em&gt; &lt;code&gt;grid&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Input:&lt;/strong&gt; grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]&lt;br&gt;
&lt;strong&gt;Output:&lt;/strong&gt; 8&lt;br&gt;
&lt;strong&gt;Explanation:&lt;/strong&gt; There are 8 negatives number in the matrix.&lt;/p&gt;



&lt;p&gt;Ahhmmm, calm down, calm down! I know this seems pretty easy. I could not stop my hands, coding the brute force &lt;code&gt;O(n2)&lt;/code&gt;solution for it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;countNegatives&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Quite straightforward. 30 seconds of code! haha. But pretty bad from an optimization point of view. Let's think of a good approach.&lt;/p&gt;




&lt;p&gt;When I see something sorted, I call my dearest friend, &lt;code&gt;binary search&lt;/code&gt;. Let's reduce the time complexity from &lt;code&gt;O(n2)&lt;/code&gt; to &lt;code&gt;O(n log m)&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Here is the code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;getIndex&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;low&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;high&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;low&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="n"&gt;high&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;low&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;high&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;low&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="n"&gt;high&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;low&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 
            &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;high&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;low&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;low&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;countNegatives&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;index&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;getIndex&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;index&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pardon my ugly code style. &lt;/p&gt;

&lt;p&gt;I hit submit and was about to celebrate my small achievement BUT a small text below the problem statement shattered all my hopes.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Follow up:&lt;/strong&gt; Could you find an &lt;code&gt;O(n + m)&lt;/code&gt; solution?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Oh man, I thought I cracked the best solution for this. Ah shit, here we go again.&lt;/p&gt;




&lt;p&gt;No worries, let's try to find it can be done in &lt;code&gt;O(n + m)&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;I am not gonna lie. I tried my best but could not find any approach to solving it in the given time complexity. I can just think of something, checking for negative element, if found, based on that, just tick mark the index for new rows also. &lt;/p&gt;

&lt;p&gt;After checking out the discussion tab, I was blown away by the approach. It was so clever. &lt;/p&gt;

&lt;p&gt;So, We start from the upper right, check if one positive element is found, we just jump to the next row, for the same index (as we know columns are also in a sorted manner). &lt;/p&gt;

&lt;p&gt;I know, it's complex to understand. This guy has written &lt;a href="https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/discuss/510217/C%2B%2B-Three-Methods"&gt;an excellent explanation&lt;/a&gt;. Check it out.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Here is the smartest approach&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;countNegatives&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;col&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;col&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;col&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I am in love with this problem. The way, it's designed is commendable. It was fun solving it.&lt;/p&gt;

&lt;p&gt;As always, if you have any thoughts about anything shared above, don't hesitate to &lt;a href="https://twitter.com/the2ndfloorguy"&gt;reach out&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Do let me know if you are also solving problems. &lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;You might like previous editions of &lt;a href="https://dev.to/coding-diary"&gt;my coding diary&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in//code/sum-of-unique-elements/"&gt;Day #17 - Sum of Unique Elements.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://pankajtanwar.in/code/best-time-to-buy-and-sell-stock/"&gt;Day #16 - Best Time to Buy and Sell Stock.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://pankajtanwar.in/code/count-number-of-pairs-with-absolute-difference-k/"&gt;Day #15 - Count Number of Pairs With Absolute Difference K.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://pankajtanwar.in/code/minimum-number-of-operations-to-move-all-balls-to-each-box/"&gt;Day #14 - Minimum Number of Operations to Move All Balls to Each Box.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in//code/number-of-rectangles-that-can-form-the-largest-square/"&gt;Day #13 - Number Of Rectangles That Can Form The Largest Square.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in//code/unique-morse-code-words/"&gt;Day #12 - Unique Morse Code Words.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in//code/count-the-number-of-consistent-strings/"&gt;Day #11 - Count the Number of Consistent Strings.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in//code/find-greatest-common-divisor-of-array/"&gt;Day #10 - Find Greatest Common Divisor of Array.&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>javascript</category>
      <category>codenewbie</category>
      <category>leetcode</category>
    </item>
    <item>
      <title>Challenge #17 - Sum of Unique Elements.</title>
      <dc:creator>Pankaj Tanwar</dc:creator>
      <pubDate>Tue, 05 Oct 2021 07:04:31 +0000</pubDate>
      <link>https://dev.to/pankajtanwarbanna/challenge-17-sum-of-unique-elements-4bde</link>
      <guid>https://dev.to/pankajtanwarbanna/challenge-17-sum-of-unique-elements-4bde</guid>
      <description>&lt;p&gt;Helllllooooo!&lt;/p&gt;

&lt;p&gt;Pretty much excited about today's problem (No, 17 is not my lucky number.) Cool, let's directly jump to the challenge for Day #17 of &lt;a href="https://www.pankajtanwar.in/coding-diary"&gt;my coding diary&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Problem of the day&lt;/strong&gt; - &lt;a href="https://leetcode.com/problems/sum-of-unique-elements/"&gt;Sum of Unique Elements&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tag&lt;/strong&gt; - Easy &lt;/p&gt;

&lt;p&gt;You are given an integer array &lt;code&gt;nums&lt;/code&gt;. The unique elements of an array are the elements that appear &lt;strong&gt;exactly once&lt;/strong&gt; in the array.&lt;/p&gt;

&lt;p&gt;Return &lt;em&gt;the &lt;strong&gt;sum&lt;/strong&gt; of all the unique elements of&lt;/em&gt; &lt;code&gt;nums&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Input:&lt;/strong&gt; nums = [1,2,3,2]&lt;br&gt;
&lt;strong&gt;Output:&lt;/strong&gt; 4&lt;br&gt;
&lt;strong&gt;Explanation:&lt;/strong&gt; The unique elements are [1,3], and the sum is 4.&lt;/p&gt;



&lt;p&gt;The problem is quite easy to understand. Now, after solving some good number of problems, I feel, multiple approaches are striking to my mind instantly, after reading the problem statement (or may be the problems are easy!)&lt;/p&gt;



&lt;p&gt;So, we need to find the sum of only unique elements in the array. Ummm, as of now I can think of three approaches. &lt;/p&gt;
&lt;h3&gt;
  
  
  1. My all-time savior best friend, Hashmap
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Loop over the list, save the count of each element in the hashmap&lt;/li&gt;
&lt;li&gt;Loop over the list again, if the count is 1, add else tata-bye-bye&lt;/li&gt;
&lt;li&gt;just return the final result&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Here is the code&lt;/strong&gt; -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;sumOfUnique&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;hash&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;        
        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;hash&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hash&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pretty nice solution. &lt;/p&gt;

&lt;h3&gt;
  
  
  2. Using sort
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Sort the list&lt;/li&gt;
&lt;li&gt;Loop over the list and just check if the previous element is the same (means element is duplicated), skip that&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ahh, please don't be angry with me for not coding the solution for this. It would be a too slow approach, &lt;code&gt;O(n log n)&lt;/code&gt;. And I don't like leetcode rewarding me for the slowest submission ever!&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Using a constant array
&lt;/h3&gt;

&lt;p&gt;Whenever I see the constraints are too small, my mind automatically starts thinking of having a constant array. We can replace the hashmap with a constant array here.&lt;/p&gt;

&lt;p&gt;Ummm, can I do it one pass only?  let's try!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;sumOfUnique&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;101&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
                &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
                &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, what I am doing here?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Keep a constant array of length 101&lt;/li&gt;
&lt;li&gt;If, number is not repeated, add it to final result and increase the count &lt;/li&gt;
&lt;li&gt;If number is repeated, I deduct that number and assign the count of that number to -1 (means I don't want to see this again in my life)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Pretty simple right? &lt;/p&gt;

&lt;p&gt;Oh man, I just checked this guy has &lt;a href="https://leetcode.com/problems/sum-of-unique-elements/discuss/1052455/C%2B%2B-7-Solutions"&gt;7 solutions for this problem&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;As always, if you have any thoughts about anything shared above, don't hesitate to &lt;a href="https://twitter.com/the2ndfloorguy"&gt;reach out&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;You might like previous editions of &lt;a href="https://dev.to/coding-diary"&gt;my coding diary&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/best-time-to-buy-and-sell-stock/"&gt;Day #16 - Best Time to Buy and Sell Stock.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/count-number-of-pairs-with-absolute-difference-k/"&gt;Day #15 - Count Number of Pairs With Absolute Difference K.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/minimum-number-of-operations-to-move-all-balls-to-each-box/"&gt;Day #14 - Minimum Number of Operations to Move All Balls to Each Box.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/number-of-rectangles-that-can-form-the-largest-square/"&gt;Day #13 - Number Of Rectangles That Can Form The Largest Square.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/unique-morse-code-words/"&gt;Day #12 - Unique Morse Code Words.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/count-the-number-of-consistent-strings/"&gt;Day #11 - Count the Number of Consistent Strings.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/find-greatest-common-divisor-of-array/"&gt;Day #10 - Find Greatest Common Divisor of Array.&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>codenewbie</category>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title> Challenge #16 - Best Time to Buy and Sell Stock </title>
      <dc:creator>Pankaj Tanwar</dc:creator>
      <pubDate>Mon, 04 Oct 2021 07:18:23 +0000</pubDate>
      <link>https://dev.to/pankajtanwarbanna/challenge-16-best-time-to-buy-and-sell-stock-13al</link>
      <guid>https://dev.to/pankajtanwarbanna/challenge-16-best-time-to-buy-and-sell-stock-13al</guid>
      <description>&lt;p&gt;Hello!&lt;/p&gt;

&lt;p&gt;I hope you had a lovely weekend. Here is my today's journal (btw it's day 16) of &lt;a href="https://www.pankajtanwar.in/coding-diary"&gt;my coding diary&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Problem of the day&lt;/strong&gt; - &lt;a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/"&gt;Best Time to Buy and Sell Stock&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tag&lt;/strong&gt; - Easy &lt;/p&gt;

&lt;p&gt;You are given an array &lt;code&gt;prices&lt;/code&gt; where &lt;code&gt;prices[i]&lt;/code&gt; is the price of a given stock on the &lt;code&gt;ith&lt;/code&gt; day.&lt;/p&gt;

&lt;p&gt;You want to maximize your profit by choosing a &lt;strong&gt;single day&lt;/strong&gt; to buy one stock and choosing a &lt;strong&gt;different day in the future&lt;/strong&gt; to sell that stock.&lt;/p&gt;

&lt;p&gt;Return &lt;em&gt;the maximum profit you can achieve from this transaction&lt;/em&gt;. If you cannot achieve any profit, return &lt;code&gt;0&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Input:&lt;/strong&gt; prices = [7,1,5,3,6,4] &lt;br&gt;&lt;br&gt;
&lt;strong&gt;Output:&lt;/strong&gt; 5 &lt;br&gt;&lt;br&gt;
&lt;strong&gt;Explanation:&lt;/strong&gt; Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;em&gt;Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;Ahh, quite a famous problem. It's the most favorite interview challenge of every interviewer for an entry-level job. Let's try and see if I am a good fit for an entry level job🤭.&lt;/p&gt;

&lt;p&gt;So, the problem is pretty straightforward. I just need to find the maximum possible difference between two numbers (in increasing order only). &lt;/p&gt;

&lt;p&gt;Well, I welcome my dearest friend, &lt;strong&gt;brute force approach&lt;/strong&gt;. Directly coded the solution within seconds.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;maxProfit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;prices&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;ans&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;prices&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;prices&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;ans&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ans&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;prices&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;prices&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;ans&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hit submit and ....... Leetcode shattered all my hopes, with a beautiful &lt;strong&gt;Time Limit Exceeded&lt;/strong&gt; message.&lt;/p&gt;

&lt;p&gt;Well, I need to find some optimized way, brute force doesn't work always. &lt;/p&gt;




&lt;p&gt;So, I need to find the maximum difference between a number with all numbers next to him. For that, I just need to know what is the maximum number among all those numbers.&lt;/p&gt;

&lt;p&gt;Oh man, pretty easy peasy. I will iterate from backward and keep on tracking the maximum number till date and with each number, I will calculate the difference and see if it's the maximum or not.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Don't worry, here is the code&lt;/strong&gt; -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;maxProfit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;prices&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;ans&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;max_val&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;INT_MIN&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;prices&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;max_val&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;max_val&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;prices&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
            &lt;span class="n"&gt;ans&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ans&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;max_val&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;prices&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;ans&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Woohoo, all ticks green. No pain full &lt;strong&gt;TLE&lt;/strong&gt; this time. Ummm, it was a nice problem. Interesting thing was, test cases were designed so beautiful that one can't celebrate his brute approach submission.&lt;/p&gt;

&lt;p&gt;As always, if you have any thoughts about anything shared above, don't hesitate to &lt;a href="https://twitter.com/the2ndfloorguy"&gt;reach out to me&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;You might like previous editions of &lt;a href="https://dev.to/coding-diary"&gt;my coding diary&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/count-number-of-pairs-with-absolute-difference-k/"&gt;Day #15 - Count Number of Pairs With Absolute Difference K.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/minimum-number-of-operations-to-move-all-balls-to-each-box/"&gt;Day #14 - Minimum Number of Operations to Move All Balls to Each Box.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/number-of-rectangles-that-can-form-the-largest-square/"&gt;Day #13 - Number Of Rectangles That Can Form The Largest Square.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/unique-morse-code-words/"&gt;Day #12 - Unique Morse Code Words.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/count-the-number-of-consistent-strings/"&gt;Day #11 - Count the Number of Consistent Strings.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/find-greatest-common-divisor-of-array/"&gt;Day #10 - Find Greatest Common Divisor of Array.&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>javascript</category>
      <category>programming</category>
      <category>codenewbie</category>
      <category>computerscience</category>
    </item>
    <item>
      <title>Challenge #15 - Count Number of Pairs With Absolute Difference K</title>
      <dc:creator>Pankaj Tanwar</dc:creator>
      <pubDate>Sun, 03 Oct 2021 06:36:40 +0000</pubDate>
      <link>https://dev.to/pankajtanwarbanna/challenge-15-count-number-of-pairs-with-absolute-difference-k-2798</link>
      <guid>https://dev.to/pankajtanwarbanna/challenge-15-count-number-of-pairs-with-absolute-difference-k-2798</guid>
      <description>&lt;p&gt;Bonjour!&lt;/p&gt;

&lt;p&gt;Thanks for sticking along, it's day 15 of &lt;a href="https://www.pankajtanwar.in/coding-diary"&gt;my coding diary&lt;/a&gt;. Well, I started this journey to discipline my self and I feel, now I am literally enjoying it. Let's jump to the problem statement for today.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;TLDR; &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Never settle down by just seeing green tick with brute force approach. Think harder to reach the optimized one. (I found 3 approaches for the problem)&lt;/li&gt;
&lt;li&gt;Easy problems might have interesting hidden challenges&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;




&lt;p&gt;&lt;strong&gt;Problem of the day&lt;/strong&gt; - &lt;a href="https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/"&gt;Count Number of Pairs With Absolute Difference K&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tag&lt;/strong&gt; - Easy&lt;/p&gt;

&lt;p&gt;Given an integer array &lt;code&gt;nums&lt;/code&gt; and an integer &lt;code&gt;k&lt;/code&gt;, return &lt;em&gt;the number of pairs&lt;/em&gt; &lt;code&gt;(i, j)&lt;/code&gt; &lt;em&gt;where&lt;/em&gt; &lt;code&gt;i &amp;lt; j&lt;/code&gt; &lt;em&gt;such that&lt;/em&gt; &lt;code&gt;|nums[i] - nums[j]| == k&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The value of &lt;code&gt;|x|&lt;/code&gt; is defined as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;x&lt;/code&gt; if &lt;code&gt;x &amp;gt;= 0&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;-x&lt;/code&gt; if &lt;code&gt;x &amp;lt; 0&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Input:&lt;/strong&gt; nums = [1,2,2,1], k = 1&lt;br&gt;
&lt;strong&gt;Output:&lt;/strong&gt; 4&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Just after reading the problem statement carefully, like any other dev, a brute force, O(n2), the slowest approach came to my mind and I just started typing without wasting a second.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;countKDifference&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;abs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As expected, the worst approach. It took 39ms, faster than 7%, Arghhhh. I knew it. &lt;/p&gt;




&lt;p&gt;I again read the problem statement. A quick thought came to my mind, why not store count for each value and check count of &lt;code&gt;val + k&lt;/code&gt; and &lt;code&gt;val - k&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;countKDifference&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Approach&lt;/strong&gt; -&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Store count of each value&lt;/li&gt;
&lt;li&gt;Iterate over the &lt;code&gt;nums&lt;/code&gt; array&lt;/li&gt;
&lt;li&gt;For each element, reduce the count for the current value first, and check the count of &lt;code&gt;val - k&lt;/code&gt; and &lt;code&gt;val + k&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;return the final value, that's the answer&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I hit submit in the excitement of O(n) approach, BUT leetcode said, Ummm, it's a good try but still slower than 60% submission, think harder. WTH, I thought I cracked it.&lt;/p&gt;




&lt;p&gt;I kept on digging more. I again read the problem statement, no luck! Suddenly, I looked at the constraints. It was a light bulb moment.....&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Constraints:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;1 &amp;lt;= nums.length &amp;lt;= 200&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;1 &amp;lt;= nums[i] &amp;lt;= 100&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;1 &amp;lt;= k &amp;lt;= 99&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's remove the sluggish hashmap and use an array of length 200.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;countKDifference&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;201&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
            &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hit submit, and boom! It's 9ms, faster than 90% of solutions. Oh man, that was fun. I am gradually recognizing the patterns. &lt;/p&gt;




&lt;p&gt;You might like previous editions of &lt;a href="https://www.pankajtanwar.in/coding-diary"&gt;my coding diary&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/minimum-number-of-operations-to-move-all-balls-to-each-box/"&gt;Day #14 - Minimum Number of Operations to Move All Balls to Each Box.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/number-of-rectangles-that-can-form-the-largest-square/"&gt;Day #13 - Number Of Rectangles That Can Form The Largest Square.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/unique-morse-code-words/"&gt;Day #12 - Unique Morse Code Words.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/count-the-number-of-consistent-strings/"&gt;Day #11 - Count the Number of Consistent Strings.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pankajtanwar.in/code/find-greatest-common-divisor-of-array/"&gt;Day #10 - Find Greatest Common Divisor of Array.&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>javascript</category>
      <category>programming</category>
      <category>codenewbie</category>
      <category>leetcode</category>
    </item>
    <item>
      <title>Prevent duplicate cron job running.</title>
      <dc:creator>Pankaj Tanwar</dc:creator>
      <pubDate>Fri, 03 Sep 2021 15:23:04 +0000</pubDate>
      <link>https://dev.to/pankajtanwarbanna/prevent-duplicate-cron-job-running-3i1e</link>
      <guid>https://dev.to/pankajtanwarbanna/prevent-duplicate-cron-job-running-3i1e</guid>
      <description>&lt;p&gt;Today, while working on an in-house project, I encountered a really interesting problem. I needed a python script, running every 30 minutes, pulling some information from a third party, processing the data, updating on my local database &amp;amp; take a rest till the next round. I wrote the script and set-up the cron.&lt;/p&gt;

&lt;p&gt;Smooth right!&lt;/p&gt;

&lt;p&gt;But, my happiness didn't last long. Sometimes, my script took more than 30 minutes to execute. This presented me with a beautiful issue of cron jobs overlapping &amp;amp; data duplication. I didn't want the jobs to start stacking up over each other.&lt;/p&gt;

&lt;p&gt;Ahh. Cute &lt;a href="https://en.wikipedia.org/wiki/Concurrency_(computer_science)"&gt;concurrency&lt;/a&gt; problem.&lt;/p&gt;

&lt;p&gt;To fix this, like any other developer, a couple of thoughts popped up in my mind. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Modify my python script, use some internal package to list down all running processes &amp;amp; grep if the same cron is already running. If yes, maybe it's not a good time to run it.&lt;/li&gt;
&lt;li&gt;Why not look for the existence of a particular file &lt;code&gt;mylock.txt&lt;/code&gt; and exit if it exists or create it if it doesn't?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both solutions seemed pretty lousy &amp;amp; unsafe. And touching a working code is my biggest nightmare.&lt;/p&gt;

&lt;p&gt;Our internal discussion, headed me over to a beautiful tool, &lt;a href="https://linux.die.net/man/1/flock"&gt;Flock&lt;/a&gt;. &lt;/p&gt;

&lt;h1&gt;
  
  
  So, What's flock?
&lt;/h1&gt;

&lt;p&gt;&lt;a href="https://linux.die.net/man/1/flock"&gt;Flock&lt;/a&gt; is a very easy &amp;amp; simple tool. This tiny utility comes by default with the &lt;code&gt;util-linux&lt;/code&gt; package.&lt;/p&gt;

&lt;p&gt;Its mechanism is pretty neat and simple. For execution, it takes a &lt;code&gt;lock file&lt;/code&gt; &amp;amp; &lt;code&gt;command&lt;/code&gt; to run as input. It puts a lock on a given lock file and releases the lock when the script is executed. Lock on the file helps the tool decide, whether to run the script or not, in the next round. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Just to add here, &lt;a href="https://en.wikipedia.org/wiki/File_locking"&gt;file locking&lt;/a&gt; is a mechanism to restrict access to a file among multiple processes. It allows only one process to access the file at a specific time.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  How to setup a cron job, using flock ?
&lt;/h2&gt;

&lt;p&gt;Setting up a cron using flock is pretty simple. &lt;/p&gt;

&lt;h3&gt;
  
  
  Step 1 - Install flock, if not available in your system
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yum install -y util-linux
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;You can verify if flock has been installed by &lt;code&gt;whereis flock&lt;/code&gt; in linux system. It should show &lt;code&gt;/usr/bin/flock&lt;/code&gt; as a path.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Step 2 - Open up cron tab
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;crontab -e
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 3 - Install your new cron
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; */30 * * * * /usr/bin/flock -w 0 /home/myfolder/my-file.lock python my_script.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And you are done.&lt;/p&gt;

&lt;p&gt;The moment flock starts, it locks the &lt;code&gt;my-file.lock&lt;/code&gt; file &amp;amp; if in next round, the previous cron is already running, it will not the script again.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Don't worry about &lt;code&gt;my-file.lock&lt;/code&gt; , flock will create it for you if it doesn't exist.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To verify the lock, try -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fuser -v /home/myfolder/my-file.lock
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, my crontab entry looked like this -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; */30 * * * * /usr/bin/flock -w 0 /home/myfolder/my-file.lock python my_script.py &amp;gt; /home/myfolder/mylog.log 2&amp;gt;&amp;amp;1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Well, calm down. I know, I have added some random texts to my cron. Let's decode the meaning of &lt;code&gt;&amp;gt;/home/myfolder/mylog.log 2&amp;gt;&amp;amp;1&lt;/code&gt; one by one.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;&amp;gt;&lt;/code&gt; is standard I/O redirection.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;/home/myfolder/mylog.log&lt;/code&gt; is a black hole where any data is sent&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;2&lt;/code&gt; is the file descriptor for standard error (STDERR)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;&amp;gt;&lt;/code&gt; , again for redirect&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;&amp;amp;&lt;/code&gt; symbol for file descriptor &lt;/li&gt;
&lt;li&gt;
&lt;code&gt;1&lt;/code&gt; is file descriptor for standard output (STDOUT)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;2&amp;gt;&amp;amp;1&lt;/code&gt; means a redirection of channel 2 (STDERR) to channel 1 (STDOUT) so both outputs are now on the same channel 1. &lt;code&gt;&amp;gt;/home/myfolder/mylog.log&lt;/code&gt; means, output from channel 1 will be sent to this black hole. &lt;/p&gt;

&lt;p&gt;To sum it up, output &amp;amp; errors are generated while the execution of your script will go to this file.&lt;/p&gt;

&lt;h2&gt;
  
  
  The unfortunate truths of flock
&lt;/h2&gt;

&lt;h3&gt;
  
  
  How to run multiple commands with flock
&lt;/h3&gt;

&lt;p&gt;I had an interesting use case. Due to some system absolute path-related stuff inside my python script, I had to run the script as a combination of two commands. &lt;/p&gt;

&lt;p&gt;Instead of -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python /home/myfolder/script.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I needed to do -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd /home/myfolder/ &amp;amp;&amp;amp; python script.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Running multiple commands with the help of flock, is a bit tricky. After a bit of struggle, this one worked for me.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;*/30 * * * * cd /home/myfolder/ /usr/bin/flock -w 0 /home/myfolder/my-file.lock &amp;amp;&amp;amp; python my_script.py &amp;gt; /home/myfolder/mylog.log 2&amp;gt;&amp;amp;1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  flock doesn't always seem to be working.
&lt;/h3&gt;

&lt;p&gt;Flock does &lt;a href="https://www.baeldung.com/linux/file-locking#1-advisory-locking"&gt;advisory locking&lt;/a&gt;, which is a cooperative locking scheme which means you will be able to override the lock if you don't cooperate. &lt;/p&gt;

&lt;p&gt;It has been raised many times that if, the flock is used to invoke a command in a subshell, other programs seem to be able to read/write to the locked file. &lt;a href="https://unix.stackexchange.com/questions/388026/flock-doesnt-seem-to-be-working"&gt;This issue on stackoverflow&lt;/a&gt; talks about this in detail. &lt;/p&gt;

</description>
      <category>linux</category>
      <category>programming</category>
      <category>devops</category>
      <category>computerscience</category>
    </item>
    <item>
      <title>What is the sorting algorithm behind ORDER BY query in MySQL?</title>
      <dc:creator>Pankaj Tanwar</dc:creator>
      <pubDate>Wed, 21 Jul 2021 17:15:55 +0000</pubDate>
      <link>https://dev.to/pankajtanwarbanna/what-is-the-sorting-algorithm-behind-order-by-query-in-mysql-1cl3</link>
      <guid>https://dev.to/pankajtanwarbanna/what-is-the-sorting-algorithm-behind-order-by-query-in-mysql-1cl3</guid>
      <description>&lt;p&gt;Since the last couple of weeks, I have been working on MySQL more closely. MySQL is a brilliant piece of software. I remember reading about all the sorting algorithms in college so I was curious to know which algorithm MySQL uses and how ORDER BY query works internally in such an efficient manner. &lt;/p&gt;

&lt;p&gt;I started exploring &amp;amp; digging deeper into its &lt;a href="https://github.com/mysql/mysql-server/blob/8.0/sql/filesort.cc" rel="noopener noreferrer"&gt;open source code&lt;/a&gt; and I was amazed with its implementation.&lt;/p&gt;

&lt;p&gt;MySQL is canny. It’s sorting algorithm depends on a couple of factors -&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Available Indexes &lt;/li&gt;
&lt;li&gt;Expected size of result&lt;/li&gt;
&lt;li&gt;MySQL version&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;MySQL has two methods to produce sorted/ordered streams of data. &lt;/p&gt;

&lt;h2&gt;
  
  
  1. Smart use of Indexes
&lt;/h2&gt;

&lt;p&gt;Firstly MySQL optimiser analyses the query and figures out if it can just take advantage of sorted indexes available. If yes, it naturally returns records in index order. (The exception is NDB engine, which needs to perform a merge sort once it gets data from all storage nodes)&lt;/p&gt;

&lt;p&gt;Hands down to the MySQL optimiser, who smartly figures out if the index access method is cheaper than other access methods.&lt;/p&gt;

&lt;p&gt;Really interesting thing to see here is- &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The index may also be used even if ORDER BY doesn’t match the index exactly, as long as other columns in ORDER BY are constant.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Sometimes, the optimizer probably may not use Index if it finds indexes expensive as compared to scanning through the table. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;For example -&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Assume, we have an index on userId and mobileNumber in the user table and we run below query -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT * FROM USER
ORDER BY userId , mobileNumber;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, you might feel Indexes on userId and mobileNumber enables optimizer to use index BUT this query has “ *&lt;em&gt;SELECT *&lt;/em&gt;* ”, which is selecting more columns than just userId and mobileNumber. &lt;/p&gt;

&lt;p&gt;In this case, scanning through an entire index, to find columns which are not in the index, is more expensive than scanning the table and sorting the results. Here, the optimizer probably does not use the index.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1626851688432%2Fc5N_1cLt8.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1626851688432%2Fc5N_1cLt8.jpeg" alt="IMG-20210721-WA0007.jpg"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Filesort Algorithm
&lt;/h2&gt;

&lt;p&gt;If Indexes can not be used to satisfy an &lt;strong&gt;ORDER BY&lt;/strong&gt; clause, &lt;strong&gt;MySQL&lt;/strong&gt; utilises filesort algorithm. This is a really interesting algorithm. In a nutshell, It works like this -&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It scans through the table and finds the rows which matches the &lt;strong&gt;WHERE&lt;/strong&gt; condition&lt;/li&gt;
&lt;li&gt;It maintains a buffer and stores a couple of values (sort key value, row pointer and columns required in the query) from each row in it. The size of this chunk is system variable &lt;a href="https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_sort_buffer_size" rel="noopener noreferrer"&gt;sort_buffer_size&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;When, buffer is full, it runs a quick sort on it based on the sort key and stores it safely to the temp file on disk and remembers a pointer to it.&lt;/li&gt;
&lt;li&gt;It will repeat the same step on chunks of data until there are no more rows left.&lt;/li&gt;
&lt;li&gt;Now, it has a couple of chunks which are sorted. &lt;/li&gt;
&lt;li&gt;Finally, it applies merge sort on all sorted chunks and puts it in one result file.&lt;/li&gt;
&lt;li&gt;In the end, it will fetch the rows from the sorted result&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If the expected result fits in one chunk, the data never hits disk, but remains in RAM.&lt;/p&gt;

&lt;p&gt;To your surprise, suppose, if we have 1 Billion rows in our user table and if we run below two queries -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT * FROM users ORDER BY userId ;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT * FROM users ORDER BY userId LIMIT 5;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;MySQL optimizer is smart enough to understand, it's not worth using merge sort. So, It uses heap sort if we just want a set of results, not the entire data. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Ordering by multiple columns does not require scanning the database twice! In MySQL (&amp;lt;v4.1), it used to read the data twice, once to match rows in WHERE clause and one, in the end to prepare the result from row pointers. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  TL;DR
&lt;/h2&gt;

&lt;h2&gt;
  
  
  Smart algorithm behind MySQL ORDER BY -
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;External merge sort (quick sort + merge sort) if data doesn’t fits into the memory&lt;/li&gt;
&lt;li&gt;Quick sort, if data fits into the memory and we want all of it&lt;/li&gt;
&lt;li&gt;Heap sort, if data fits into the memory but we are using LIMIT to fetch only some results &lt;/li&gt;
&lt;li&gt;Index lookup (not exactly a sorting algorithm, just a pre-calculated binary tree) &lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;With the help of EXPLAIN statement, we can see if query is making use of filesort or indexes.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  References -
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://dev.mysql.com/doc/refman/8.0/en/order-by-optimization.html" rel="noopener noreferrer"&gt;MySQL Official Website&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/mysql/mysql-server/blob/8.0/sql/filesort.cc" rel="noopener noreferrer"&gt;MySQL filesort : Github&lt;/a&gt;&lt;/p&gt;



&lt;br&gt;
If you enjoyed reading it, you might like -

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://blog.pankajtanwar.in/how-instagram-computes-real-time-trending-hashtags" rel="noopener noreferrer"&gt;How Instagram computes real-time trending hashtags ?&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://blog.pankajtanwar.in/how-database-indexing-actually-works-internally" rel="noopener noreferrer"&gt;How database indexing actually works internally?&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://blog.pankajtanwar.in/proxy-vs-reverse-proxy-using-a-real-life-example" rel="noopener noreferrer"&gt;Proxy vs Reverse Proxy - using a real life example!&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://twitter.com/the2ndfloorguy" rel="noopener noreferrer"&gt;@the2ndfloorguy&lt;/a&gt; on twitter!&lt;/p&gt;

</description>
      <category>mysql</category>
      <category>algorithms</category>
      <category>programming</category>
      <category>database</category>
    </item>
    <item>
      <title>🎉 Launching Bestresources.co : Share &amp; explore personal resources at one place!</title>
      <dc:creator>Pankaj Tanwar</dc:creator>
      <pubDate>Wed, 30 Jun 2021 13:43:42 +0000</pubDate>
      <link>https://dev.to/pankajtanwarbanna/launching-bestresources-co-share-explore-personal-resources-at-one-place-50h8</link>
      <guid>https://dev.to/pankajtanwarbanna/launching-bestresources-co-share-explore-personal-resources-at-one-place-50h8</guid>
      <description>&lt;p&gt;Namaste 🙏&lt;/p&gt;

&lt;p&gt;I am Pankaj, a self taught software developer passionate about exploring tech. Today, I feel extremely proud to launch &lt;a href="https://bestresources.co"&gt;https://bestresources.co&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Motivation
&lt;/h2&gt;

&lt;p&gt;One fine day, I was having a technical discussion on a Linkedin comment thread.  I had written a blog post on &lt;a href="https://blog.pankajtanwar.in/the-basics-you-need-to-know-about-kafka-graphic-explanation-ahead"&gt;Apache Kafka&lt;/a&gt; so I was asked if I could share some good resources available on the same. &lt;/p&gt;

&lt;p&gt;This was my moment of inspiration to build a solution for the tiring, cumbersome job of finding the relevant resources. How do you actually learn something new in today’s life? &lt;/p&gt;

&lt;p&gt;Suppose you want to learn JavaScript. There are plenty of resources available on the web. You hit a search on google, and you start reading. You waste a plenty of time to find some perfect resources for you. &lt;/p&gt;

&lt;p&gt;But here is the catch! When someone else starts learning JavaScript, he too repeats the same cycle. How can the process be expedited?&lt;/p&gt;

&lt;p&gt;What if you could share your personal resources with the guy? What if you had access to the resources used by seniors engineers at the first place? It would have saved a tons of time.&lt;/p&gt;

&lt;p&gt;Well, there are a couple of ways, some of the devs post a blog sharing your resources. BUT this is not scalable. Not everyone can find their blogs on the internet. &lt;/p&gt;

&lt;p&gt;One, will have to dig deeper. It takes a lot of time to find something worthy. &lt;/p&gt;

&lt;p&gt;I felt the need of a dedicated platform, where people can share their resources, personally used by them.&lt;/p&gt;

&lt;p&gt;Introducing Bestresources.co - a free platform for the community to share &amp;amp; get direct access to the personal resources of the community.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--dGAbfnzB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1625025068685/32JUdUgrg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--dGAbfnzB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1625025068685/32JUdUgrg.png" alt="Screenshot from 2021-06-30 09-20-00.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://bestresources.co"&gt;https://bestresources.co&lt;/a&gt; is now live with curated resources by senior developers from Google, Amazon, Uber etc and so many self taught developers &amp;amp;  freelancers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Our Story
&lt;/h2&gt;

&lt;p&gt;Story of &lt;a href="https://bestresources.co"&gt;https://bestresources.co&lt;/a&gt; started with a comment. Initially, I didn’t pay much attention to this idea and put it aside (like every other dev). But on 19 June, I got to know about the HarperDB hackathon by Hashnode &amp;amp; it motivated me to work on it. &lt;/p&gt;

&lt;p&gt;I had a very limited time but I decided to finish the development and launch it anyhow. &lt;/p&gt;

&lt;p&gt;I had to manage my regular job, my freelancing projects and other work. I enjoyed working late at night . I continued to ship features as much as possible. I had already made up my mind that I will not keep it as a demo project, whatever it takes, I will launch it.&lt;/p&gt;

&lt;p&gt;And within 1.5 week, I was able to launch bestresoures.co 🎉&lt;/p&gt;

&lt;h2&gt;
  
  
  Features -
&lt;/h2&gt;

&lt;p&gt;I am very very sensitive to code quality. 😛 While maintaining the code quality, (as much as possible), &lt;a href="https://bestresources.co"&gt;https://bestresources.co&lt;/a&gt; is live with below features -&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;1. Listing of interesting resources *&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;As you head over to bestresources.co, it brings you  interesting resources. Explore the hidden gem of the web.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Create &amp;amp; Manage&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;Add &amp;amp; share your resources with the community at a single click. Easy and beautiful UI will make it easier for you to do so.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Express gratitude to the author&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Who does not like appreciation? Express your gratitude to the author author for taking out time and sharing his resources. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Bookmark&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Save the resource for later use at just one tap. We always remember what you save!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Social Share&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;Loved the resource? Share socially and spread some love at a single click.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Search&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;Just type what you are looking to learn, we bring the best curated resources to you.  &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. Sort&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;Sort the resources by interest, trend and time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;8. Magic Link - One tap authentication&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Arrghhh. Remembering passwords is tough. Just type in your email and we will send you a secure  magic link to login on a click.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;9. Featured&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;Every week, we feature one resource to the home page, loved by the community. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;10. The world of tags&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;Create and search &amp;amp; filter resources by popular tags. Suggest new tags!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;11. Weekly newsletter&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Every week, we send you some really exciting &amp;amp; interesting resources direct to your inbox. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;12. Profile&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;We love author recognition. Update your profile and let your audience find you on social media. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;13. Notifications&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;We notify you when something interesting comes up related to you. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;14. Responsive and mobile friendly&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Access &lt;a href="https://bestresources.co"&gt;https://bestresources.co&lt;/a&gt; from any device and spread love.&lt;/p&gt;

&lt;h2&gt;
  
  
  Technology Stack
&lt;/h2&gt;

&lt;p&gt;Bestresources.co is baked by the latest tech stack. Here is the list -&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;NodeJs&lt;/strong&gt; - Best backend JavaScript run time environment &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;HarperDB&lt;/strong&gt; - Oh gosh! Fastest and the most flexible data storage. Single node, handling upto 100000 requests per second seamlessly. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Express&lt;/strong&gt; - Super simple, backend application framework for NodeJs&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Angular&lt;/strong&gt; - JavaScript based frontend framework built by Google.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Nginx&lt;/strong&gt; - Used as high performance load balancer, web server and reverse proxy. Very handy when it comes to caching.  &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;AWS EC2&lt;/strong&gt; - Secure and resizable compute capacity in the cloud, deployed the application over there&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Cloudflare&lt;/strong&gt; - For SSL, client side caching &amp;amp; internet security&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Mailgun&lt;/strong&gt; - For email delivery &lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;P.S.&lt;/strong&gt; I personally send a thank you email to everyone who signs up, for showing trust!&lt;/p&gt;

&lt;h2&gt;
  
  
  What's next?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://bestresources.co"&gt;https://bestresources.co&lt;/a&gt; is ready to roll out some really exciting features in a couple of weeks.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Dark mode, of-course [first priority] &lt;/li&gt;
&lt;li&gt;Personalised content in a more optimised manner &lt;/li&gt;
&lt;li&gt;Mobile App &lt;/li&gt;
&lt;li&gt;Auto detection of bad content and links &lt;/li&gt;
&lt;li&gt;Comment thread for the resource&lt;/li&gt;
&lt;li&gt;Thank the author with a note.&lt;/li&gt;
&lt;li&gt;Hall of Fame (a separate page including most loved authors with their social media handles)&lt;/li&gt;
&lt;li&gt;Idea Box (Request community for resources - inspired from hashnode)&lt;/li&gt;
&lt;li&gt;Public APIs for developers to play with&lt;/li&gt;
&lt;li&gt;Google, Github authentication&lt;/li&gt;
&lt;li&gt;A more improved notifications &lt;/li&gt;
&lt;li&gt;Improve trending section&lt;/li&gt;
&lt;li&gt;High performance server side caching and a lot more&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Would love to hear your valuable feedback or new feature requests.&lt;/p&gt;

&lt;p&gt;Well, there were a lot of challenges on the way to bringing this project to life. It was fun, I will cover it in a separate post in detail. &lt;/p&gt;

&lt;h2&gt;
  
  
  Github
&lt;/h2&gt;

&lt;p&gt;The complete source code is available on github. Feel free to &lt;a href="https://twitter.com/the2ndfloorguy"&gt;DM me on twitter&lt;/a&gt; if you need more details. Would love to help.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;a href="https://github.com/Pankajtanwarbanna/bestresources.co"&gt;Bestresources.co Github Link&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you feel like contributing to the platform, feel free to raise a PR. Let's give something back to the community. &lt;/p&gt;

&lt;h2&gt;
  
  
  Try Bestresources.co
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;a href="https://bestresources.co"&gt;Bestresources.co&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;There are many others, who have guided and helped this project come to life - friends, family, @&lt;a href="https://dev.to@hashnode"&gt;Hashnode&lt;/a&gt;, internet strangers!&lt;/p&gt;

&lt;p&gt;I am most grateful for everyone’s kindness ❤️&lt;/p&gt;

&lt;h2&gt;
  
  
  Support
&lt;/h2&gt;

&lt;p&gt;If you feel, my little initiative &lt;a href="https://bestresourcse.co"&gt;https://bestresourcse.co&lt;/a&gt; adds value to you, please share it with your friends. Drop me a message on &lt;a href="https://twitter.com/the2ndfloorguy"&gt;twitter&lt;/a&gt;, It's the real motivation for me. &lt;/p&gt;

</description>
      <category>programming</category>
      <category>showdev</category>
      <category>discuss</category>
    </item>
    <item>
      <title>What is latency? Let’s deep dive &amp; understand possible ways to optimise it.</title>
      <dc:creator>Pankaj Tanwar</dc:creator>
      <pubDate>Fri, 18 Jun 2021 07:00:49 +0000</pubDate>
      <link>https://dev.to/pankajtanwarbanna/what-is-latency-let-s-deep-dive-understand-possible-ways-to-optimise-it-4bh3</link>
      <guid>https://dev.to/pankajtanwarbanna/what-is-latency-let-s-deep-dive-understand-possible-ways-to-optimise-it-4bh3</guid>
      <description>&lt;p&gt;Hi 👋,&lt;/p&gt;

&lt;p&gt;Latency is yet another, a very important topic when we talk about backend engineering or networking. In this article, we will be discussing latency, it's importance and ways to optimise it in order to improve application performance.&lt;/p&gt;

&lt;h3&gt;
  
  
  Table of Contents
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;What is latency?&lt;/li&gt;
&lt;li&gt;Why is it important?&lt;/li&gt;
&lt;li&gt;What causes latency?&lt;/li&gt;
&lt;li&gt;How to measure latency?&lt;/li&gt;
&lt;li&gt;How to optimise the latency?&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  1. What is latency?
&lt;/h2&gt;

&lt;p&gt;Latency is the total time between a client’s action and the server’s response to that action. It’s simply a round trip time between browser &amp;amp; server. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1623948399459%2FZyY_dleHx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1623948399459%2FZyY_dleHx.png" alt="Latency Image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Network latency is measured in milliseconds (ms).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  2. Why is it important?
&lt;/h2&gt;

&lt;p&gt;Latency is directly related to the performance of the application. High latency means a slow network and no one likes to be on a slow website. At a large scale, latency plays a very critical role.&lt;/p&gt;

&lt;p&gt;Let’s understand with a simple example by emulating a GET request in a browser. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1623936262250%2Fvj3kFHHB-.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1623936262250%2Fvj3kFHHB-.png" alt="Browser Network Timing"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Blocking&lt;/strong&gt; : The time for which request was in queue. (A chrome browser can only make at max 6 HTTP request at a time to the server) &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;DNS Resolution&lt;/strong&gt; : Time taken in DNS lookup&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Connecting&lt;/strong&gt; : Time taken in a TCP handshake &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;TLS Setup&lt;/strong&gt; : Time taken in establishing a secure TLS connection&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Sending&lt;/strong&gt; : Time taken to send the HTTP request to the server&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Waiting&lt;/strong&gt; : Time taken by the server to prepare the response&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Receiving&lt;/strong&gt; : Time taken to receive the response from server&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;For the very first request, for the first 14KB data, latency is longer due to DNS lookup, a TCP handshake and the secure TLS negotiation. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  3. What causes latency?
&lt;/h2&gt;

&lt;p&gt;Latency plays a vital role in system performance. It depends on various factors -&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Distance&lt;/strong&gt; &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One of the principal causes of network latency is distance between client (who is making request) and the server (responding to the request). &lt;/p&gt;

&lt;p&gt;&lt;em&gt;For example&lt;/em&gt; - Suppose, my website (&lt;a href="https://pankajtanwar.in/" rel="noopener noreferrer"&gt;https://pankajtanwar.in/&lt;/a&gt;) is hosted in a data center in Delhi. So, for a user accessing from Jaipur (~200KM from Delhi), it is likely to respond within 20-30ms but for a user accessing from New York (~11000 KM from Delhi), it might face a latency close to 70ms. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Transmission Medium&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The type of transmission medium being used for data packet transmission also impacts the latency. Modern optic fiber is ~200 times faster than old copper cable-based networks.  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Multiple Routers&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We should not ignore the fact that routers play a very important role in latency. Routers take some time and analyse the headers of each data package passing thought, which adds to network latency. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Poorly optimized server&lt;/strong&gt; &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Several factors on the backend server, such as slow database queries, low memory space, slow data processing and un-optimized code also impacts the latency. &lt;/p&gt;

&lt;h2&gt;
  
  
  4. How to measure latency?
&lt;/h2&gt;

&lt;p&gt;There are several standard metrics to measure latency. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Time to First Byte (TTFB)&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is one of the widely accepted matrices to measure latency. As the name itself explains, TTFB is the time (in milliseconds) for a browser to receive the first byte of response from the server.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Ping&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ping is the most common utility to measure latency. It sends a 32 bytes packet to the server &amp;amp; measures the time it took to reach the destination and come back with response to the client.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Round Trip Time (RTT)&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It’s a pretty common and simple matrix. It is the total time taken by the data packet, travelling from source to the destination and back. &lt;/p&gt;

&lt;h2&gt;
  
  
  5. How to optimize the latency?
&lt;/h2&gt;

&lt;p&gt;In terms of application performance optimization, It is very important to reduce the causes of high latency. Here are major methods, which can help us reduce the latency.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;CDN&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Using CDN (Content Delivery Network) is a major step towards reducing the latency. CDN, caches content, serves it from the nearest data centre &amp;amp; provides an efficient path for data packets to travel on, which drastically reduces the round trip time and so latency. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;HTTP/2&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;HTTP/2 is a highly efficient protocol which reduces the latency by enabling parallelised data transfers, response multiplexing, requests prioritisation, minimised protocol overhead by efficient compression of HTTP headers, reduced round trips and many more.  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Client Side Caching&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Browsers can cache some of the resources which reduces the calls to the server and improves the latency. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Server Side Optimisations&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Server side optimisations such as less disk I/O, caching, efficient algorithms, smart database layer &amp;amp; asynchronous programming can help in optimising the latency.&lt;/p&gt;



&lt;h2&gt;
  
  
  6. Conclusion
&lt;/h2&gt;

&lt;p&gt;Latency might seem a very simple concept but it plays a very crucial role when we build high scale systems like trading or gaming software. For such systems, even a double digit millisecond latency affects the performance.  &lt;/p&gt;

&lt;p&gt;In the next article, we will discuss how to system design a real time multiplayer game &lt;strong&gt;counter-strike&lt;/strong&gt; (CS-Go) which is highly sensitive to latency (or ‘lag’).  &lt;/p&gt;

&lt;p&gt;Let’s connect &lt;a href="https://twitter.com/the2ndfloorguy" rel="noopener noreferrer"&gt;https://twitter.com/the2ndfloorguy&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Originally published at&lt;/strong&gt; : &lt;a href="https://blog.pankajtanwar.in/what-is-latency-lets-deep-dive-and-understand-possible-ways-to-optimise-it" rel="noopener noreferrer"&gt;https://blog.pankajtanwar.in/what-is-latency-lets-deep-dive-and-understand-possible-ways-to-optimise-it&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;References&lt;/strong&gt; &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/Performance/Understanding_latency" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/Performance/Understanding_latency&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.cloudflare.com/en-gb/learning/performance/glossary/what-is-latency/" rel="noopener noreferrer"&gt;https://www.cloudflare.com/en-gb/learning/performance/glossary/what-is-latency/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Latency_(engineering)" rel="noopener noreferrer"&gt;https://en.wikipedia.org/wiki/Latency_(engineering)&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>programming</category>
      <category>systems</category>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Have you ever thought, how ‘nodemon’ works internally? Let’s build our own ‘nodemon’ in under 10 minutes!
</title>
      <dc:creator>Pankaj Tanwar</dc:creator>
      <pubDate>Wed, 02 Jun 2021 12:04:45 +0000</pubDate>
      <link>https://dev.to/pankajtanwarbanna/have-you-ever-thought-how-nodemon-works-internally-let-s-build-our-own-nodemon-in-under-10-minutes-5fkm</link>
      <guid>https://dev.to/pankajtanwarbanna/have-you-ever-thought-how-nodemon-works-internally-let-s-build-our-own-nodemon-in-under-10-minutes-5fkm</guid>
      <description>&lt;p&gt;Hey 👋,&lt;/p&gt;

&lt;p&gt;If you have ever worked with Node.Js, you must have used a package called &lt;code&gt;nodemon&lt;/code&gt; for development. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;For those who are not aware of it, &lt;a href="https://www.npmjs.com/package/nodemon" rel="noopener noreferrer"&gt;nodemon&lt;/a&gt; is a tool that helps develop NodeJs based applications by automatically restarting the node application when file changes in the directory are detected. We can simply install it globally and use it throughout our system without making any additional changes to the code.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;But, have you ever thought about how it works internally? How would you proceed if you are asked to build a nodemon clone?&lt;/p&gt;

&lt;p&gt;This is a really interesting Node and JavaScript developer interview question. It helps the interviewer to test your basics such as NodeJs stream, child process, events, debouncing etc. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Github Repo Link - &lt;a href="https://github.com/Pankajtanwarbanna/nodekeeper" rel="noopener noreferrer"&gt;Nodekeeper&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In this article, we will create a simple Node.Js CLI (command line application) tool named as &lt;code&gt;nodekeeper&lt;/code&gt;, similar to &lt;code&gt;nodemon&lt;/code&gt;. So, let’s get started. &lt;/p&gt;

&lt;h3&gt;
  
  
  Requirements
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;We should be able to run any JS file using &lt;code&gt;nodekeeper &amp;lt;filename&amp;gt;&lt;/code&gt; command&lt;/li&gt;
&lt;li&gt;Automatically restart the node application when changes are detected in files&lt;/li&gt;
&lt;li&gt;Manually restart the server when user enters &lt;code&gt;rs&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On a high level, the problem might seem very difficult to implement but it’s not. The main idea behind it is to create a CLI tool which will create a node child process for the given file and keep eyes on the files in the repo. If new changes are detected, just kill the child process and again create a new process.&lt;/p&gt;

&lt;p&gt;Ok, some of the terms might seem very technical. Let’s get more into details. &lt;/p&gt;

&lt;h3&gt;
  
  
  Let’s first understand how to create a NodeJs CLI tool.
&lt;/h3&gt;

&lt;p&gt;So first, what is a CLI tool? CLI stands for ‘command line application’. It helps us run any command on the terminal which will do some magic with our system. For example - to run any JavaScript file NodeJs provides us with &lt;code&gt;node&lt;/code&gt; CLI. We just have &lt;code&gt;node index.js&lt;/code&gt; from the command line(terminal) and it executes the file. We can give commands just from the terminal.&lt;/p&gt;

&lt;p&gt;In our use case also, we want to run a JavaScript file using &lt;code&gt;nodekeeper index.js&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Let’s start. First, we create a new folder named &lt;code&gt;nodekeeper&lt;/code&gt; and do &lt;code&gt;npm init&lt;/code&gt; inside it to set up the node project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir nodekeeper 
cd nodekeeper
npm init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After it, a package.json file would be generated. Which will look something like this -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "name": "nodekeeper",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" &amp;amp;&amp;amp; exit 1"
    },
    "keywords": [],
    "author": "Pankaj Tanwar",
    "license": "ISC",
    "dependencies": {
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s create a new javascript file &lt;code&gt;index.js&lt;/code&gt; and paste the following code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#!/usr/bin/env node
console.log(‘Hey! Welcome to nodekeeper’);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here the first line which starts with &lt;strong&gt;#!&lt;/strong&gt; is called ‘shebang’. Its main purpose is to inform the system what type of script is included in the rest of the file. Here, we have included a path to node binary which tells the system that our file is a file which can we executed by node. &lt;/p&gt;

&lt;p&gt;To run a JavaScript file using &lt;code&gt;nodekeeper index.js&lt;/code&gt; instead of &lt;code&gt;node index.js&lt;/code&gt; we need to create a duplicate node binary. &lt;/p&gt;

&lt;p&gt;For this, we add a new key “bin” inside our package.json file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "name": "nodekeeper",
    "version": "1.0.0",
    "description": "A lightweight alertnative to nodemon.",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" &amp;amp;&amp;amp; exit 1"
    },
    "bin": {
        "nodekeeper": "./index.js"
    },
    "keywords": [],
    "author": "Pankaj Tanwar",
    "license": "ISC",
    "dependencies": {
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, to install this tool to run globally in our system we run -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm link
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, anywhere in our system we can run any JavaScript file like this ‘nodekeeper ’. Really cool right?&lt;/p&gt;

&lt;p&gt;Let’s understand now, what child processes are. As we all know, NodeJs is single threaded but still we can take advantage of the child processes with the help of the &lt;code&gt;child_process&lt;/code&gt; module. To scale our node app, It helps us to leverage parallel processing on multi-core CPUs. &lt;/p&gt;

&lt;p&gt;In simple terms, a child process allows us to run any system command. &lt;/p&gt;

&lt;h3&gt;
  
  
  Let’s understand child process with an analogy
&lt;/h3&gt;

&lt;p&gt;Today, my father was working on something and he wanted to drink water. As I was sitting doing nothing (as usual), so, he asked me to bring a glass of water for him. Here, my father is the main process who is performing some work. He could also go and get the glass of water but it would impact his work so he has a child process (which is me), and assigned a task to it. This is called parallel computing. Now, my father can continue working on his task and when I (child process) completes my task, I will let the main process know.  &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1622352428805%2Fxup9EMtvX.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1622352428805%2Fxup9EMtvX.png" alt="Father Child Analogy"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So, when we want to run a JavaScript, in the terminal we run &lt;code&gt;node index.js&lt;/code&gt; and we get the output. In a similar way, we can create a child process and tell it to run the &lt;code&gt;node index.js&lt;/code&gt; command, and give us the output. &lt;/p&gt;

&lt;p&gt;There are 4 ways to create a child process in Node.Js, spawn(), fork(), exec() and execFile(). For running a system command, spawn() and exec() are useful. &lt;/p&gt;

&lt;h3&gt;
  
  
  Syntax for spawn()
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const spawn = require(‘child_process’).spawn;
let nodeServer = spawn(‘node’ , [ ‘index.js‘ ])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Syntax for exec()
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const exec = require(‘child_process’).exec;
let nodeServer = exec(‘node index.js’, function(data) {
    console.log(data);
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Both of them will run &lt;code&gt;node index.js&lt;/code&gt; command on the terminal. To view the output, we need to pipe this child process to the main process. To do so,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let nodeServer = spawn(‘node’ , [ ‘index.js’ ], { stdio: [ process.stdin, process.stdout, process.stderr ]})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It has piped the child process to the main process. So, we can log it’s output on the terminal.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;BUT here is a catch in the working of spawn() and exec(). *&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;spawn() gives output in streams but exec() gives out after the whole data is received. Suppose, in the file index.js we have -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(‘Hey Hashnode’)
setTimeout(function() {
    console.log(‘Timer completed’);
}, 5000)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we run this file using both methods. We see that spawn child process, immediately logs ‘Hey Hashnode’ and after 5 seconds it logs ‘Timer completed’ but exec child process will log both lines after 5 seconds. So, it explains spawn gives output in streams, it does not wait for the file to execute completely. &lt;/p&gt;

&lt;p&gt;For our use case, we need to spawn the child process.  &lt;/p&gt;

&lt;p&gt;For watching files to new changes, we can make use of NodeJs inbuilt module, &lt;strong&gt;fs&lt;/strong&gt;. It exposes a function called &lt;strong&gt;fs.watchFile&lt;/strong&gt; but there have been a lot of issues reported by the community saying it’s not reliable. It fires multiple events sometimes for a single file change which results in high CPU utilization. So, to overcome this problem we can use the &lt;a href="https://www.npmjs.com/package/chokidar" rel="noopener noreferrer"&gt;chokidar&lt;/a&gt; package. &lt;/p&gt;

&lt;p&gt;We can pass in watch paths and other paths, we want to be ignored and we can listen to it’s events to get notified when there is a new change.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const chokidar = require(‘chokidar’);

chokidar.watch([
    "/**/*/*js"
], {
    ignored : “**/node_modules/**”
}).on(‘all’, () =&amp;gt; {
    console.log(‘File changes detected’);
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, whenever we detect changes, we can kill the current node child process and start a new process again. &lt;/p&gt;

&lt;p&gt;To kill a process -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nodeServer.kill(‘SIGTERM’) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;SIGTERM is just one of the signals which is used to kill any process. There are many types of signals. More Info can we found &lt;a href="https://nodejs.org/api/process.html#process_process_kill_pid_signal" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If we structure our code a bit, our final index.js for this would look like this -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#!/usr/bin/env node
const spawn         = require('child_process').spawn;
const chokidar      = require('chokidar');
const path          = require('path');

class Nodekeeper {
    constructor() {
        this.__init__();
    }

    __init__        = () =&amp;gt; {
        this.args               = process.argv;
        this.fileName           = this.args[2];
        this.cwd                = process.cwd();
        this.watchPaths         = [
            path.join(this.cwd, "/**/*.js")
        ];
        this.ignoredPaths       = "**/node_modules/*";

        this.reload();
        this.startWatching();
        this.listeningEvents();
    }

    reload          = () =&amp;gt; {
        if(this.nodeServer) this.nodeServer.kill('SIGTERM');

        this.nodeServer     = spawn('node', [ this.fileName ], { stdio: [ process.stdin, process.stdout, process.stderr ]});
    }

    startWatching   = () =&amp;gt; {
        chokidar.watch(this.watchPaths, {
            ignored         : this.ignoredPaths,
            ignoreInitial   : true
        }).on('all', (event, path) =&amp;gt; {
            this.reload();
        });
    }

    listeningEvents    = () =&amp;gt; {
        // listening on CLI input
        process.stdin.on("data", (chunk) =&amp;gt; {
            let cliInput = chunk.toString();

            switch(cliInput) {
                case 'rs\n':
                    this.reload();
                    break
            }
        });
    }
}

new Nodekeeper();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we can see, if we create a new express server, go to that folder and run it using &lt;code&gt;nodekeeper server.js&lt;/code&gt; , upon file changes, it will automatically restart the server. &lt;/p&gt;

&lt;p&gt;We put everything in a &lt;code&gt;nodekeeper&lt;/code&gt; class and export it as a module. &lt;/p&gt;

&lt;p&gt;We have one more requirement which is when a user enters &lt;code&gt;rs&lt;/code&gt;, we need to manually restart the server. It’s very simple as we have already implemented logic for restarting the server. To capture what user entered we just need to put an event on the main process.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;process.stdin.on("data", (chunk) =&amp;gt; {
    let cliInput = chunk.toString();

   switch(cliInput) {
        case 'rs\n':
             this.reload();
             break;
   }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It works great but there are still some issues. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;What if we save multiple files at the same time or we press Ctrl+S multiple times. Chokidar would fire change events multiple times. So, it will kill the on-going node process and start a new one which is CPU extensive. To overcome this problem, we use a concept called ‘debounce’. We delay the execution for a time period and execute it once the user stops saving. (This concept is used in search bar suggestions, it will not fetch data on every keystroke, it will affect the performance, Instead of it, we typically fetch the data when user stops typing)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hope you have a got a decent idea of what how to proceed to build a nodemon clone.&lt;/p&gt;

&lt;p&gt;I have published with a modified version &lt;code&gt;nodekeeper&lt;/code&gt; - a lightweight nodemon alternative. Package can be found &lt;a href="https://github.com/Pankajtanwarbanna/nodekeeper" rel="noopener noreferrer"&gt;here&lt;/a&gt;. If you are willing to contribute, pull requests are welcome. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;References -&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://nodejs.org/" rel="noopener noreferrer"&gt;https://nodejs.org/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Show some love. Originally Published at &lt;a href="https://www.pankajtanwar.in/blog/have-you-ever-thought-how-nodemon-works-internally-lets-build-our-own-nodemon-in-under-10-minutes" rel="noopener noreferrer"&gt;https://www.pankajtanwar.in/blog/have-you-ever-thought-how-nodemon-works-internally-lets-build-our-own-nodemon-in-under-10-minutes&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let's connect - &lt;a href="https://twitter.com/the2ndfloorguy" rel="noopener noreferrer"&gt;https://twitter.com/the2ndfloorguy&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>node</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
