<?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: codechunker</title>
    <description>The latest articles on DEV Community by codechunker (@codechunker).</description>
    <link>https://dev.to/codechunker</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%2F312383%2F21246835-4bd3-4a7f-a4e4-2f5c5da0b8b2.png</url>
      <title>DEV Community: codechunker</title>
      <link>https://dev.to/codechunker</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/codechunker"/>
    <language>en</language>
    <item>
      <title>I didn’t know how to solve this Leetcode Problem!😭😭😭</title>
      <dc:creator>codechunker</dc:creator>
      <pubDate>Wed, 13 May 2020 23:27:58 +0000</pubDate>
      <link>https://dev.to/codechunker/i-didn-t-know-how-to-solve-this-leetcode-problem-476o</link>
      <guid>https://dev.to/codechunker/i-didn-t-know-how-to-solve-this-leetcode-problem-476o</guid>
      <description>&lt;p&gt;This is a medium &lt;a href="https://leetcode.com/problems/remove-k-digits/" rel="noopener noreferrer"&gt;Leetcode 402&lt;/a&gt; question where you are asked to remove k digits from a number to make that number the smallest possible number. See problem description below:&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%2Fmiro.medium.com%2Fmax%2F1400%2F1%2Aonau0Cc28whWvAy4eNvtAg.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%2Fmiro.medium.com%2Fmax%2F1400%2F1%2Aonau0Cc28whWvAy4eNvtAg.png" alt="problem description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The question is quite understandable and straight forward but the issue is with knowing the numbers to remove. At first, I thought that sorting the numbers and keeping track of the positions and then removing the largest numbers would work but apparently that didn’t work.&lt;/p&gt;

&lt;p&gt;After trying to no avail, I had to seek for solution online and came across two algorithms:&lt;/p&gt;

&lt;h3&gt;&lt;b&gt;FIRST ALGORITHM&lt;/b&gt;&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static String removeKdigits(String num, int k) {
    Stack&amp;lt;Character&amp;gt; stack = new Stack&amp;lt;&amp;gt;();
    StringBuilder answer = new StringBuilder();
    if (num.length() == k) return "0";

  for (int i = 0; i &amp;lt; num.length(); i++) {
   while (k &amp;gt; 0 &amp;amp;&amp;amp; !stack.isEmpty() &amp;amp;&amp;amp; stack.peek() &amp;gt; num.charAt(i)) {
            stack.pop();
            k = k - 1;
        }
        stack.push(num.charAt(i));
    }

    while (!stack.isEmpty()) {
        answer.append(stack.pop());
    }

    if (!answer.toString().isEmpty()) {
        answer = answer.reverse();
        String s = answer.toString().replaceFirst("^0+(?!$)", "");
        if (k != 0)
            s = s.substring(0, answer.length() - k);
        return s;
    } else
        return "0";
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To understand the algorithm above, please check &lt;a href="https://www.youtube.com/watch?v=HXvxIth510g" rel="noopener noreferrer"&gt;thecodingworld&lt;/a&gt; on YouTube. He did a good job to explain the algorithm. His code was written in Python, so I had to translate to Java.&lt;/p&gt;

&lt;h3&gt;&lt;b&gt;SECOND ALGORITHM&lt;/b&gt;&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static String  removeKdigits(String num, int k) {
    Stack&amp;lt;Character&amp;gt; stack =  new Stack&amp;lt;&amp;gt;();
    int length = num.length();
  for (int i = 0; i &amp;lt; length; i++) {
   while (!stack.isEmpty() &amp;amp;&amp;amp; k &amp;gt; 0 &amp;amp;&amp;amp; stack.peek() &amp;gt; num.charAt(i)) {
            stack.pop();
            k -= 1;
        }

        if (!stack.isEmpty() || num.charAt(i) != '0')
            stack.push(num.charAt(i));
    }

    //Now remove the largest values from the top of the stack
    while (!stack.empty() &amp;amp;&amp;amp; k != 0) {
        stack.pop();
        k--;
    }


    if (stack.isEmpty())
        return "0";

    //now retrieve the number from stack into a string
    StringBuilder result = new StringBuilder();
    while (!stack.isEmpty()) {
        result.append(stack.pop());
    }
    return result.reverse().toString();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also to understand the second algorithm above, please check &lt;a href="https://www.youtube.com/watch?v=3QJzHqNAEXs" rel="noopener noreferrer"&gt;Tech Dose&lt;/a&gt; for the explanation. I also translated the code to Java.&lt;/p&gt;

&lt;h3&gt;&lt;b&gt;OBSERVATION&lt;/b&gt;&lt;/h3&gt;

&lt;p&gt;I have learnt a lot from these algorithms especially from the way people think and I think that’s the fun of solving algorithm questions.&lt;br&gt;
Thank you for reading. Please leave a comment or suggestion below.&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>algorithms</category>
      <category>codenewbie</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>The Good, The Bad and The Ugly Solutions to Leetcode’s Single Element in a Sorted Array</title>
      <dc:creator>codechunker</dc:creator>
      <pubDate>Tue, 12 May 2020 20:20:30 +0000</pubDate>
      <link>https://dev.to/codechunker/the-good-the-bad-and-the-ugly-solutions-to-leetcode-s-single-element-in-a-sorted-array-1d5m</link>
      <guid>https://dev.to/codechunker/the-good-the-bad-and-the-ugly-solutions-to-leetcode-s-single-element-in-a-sorted-array-1d5m</guid>
      <description>&lt;p&gt;This is a medium &lt;a href="https://leetcode.com/problems/single-element-in-a-sorted-array/"&gt;Leetcode 543&lt;/a&gt; question. You are given an array of integers of which all elements in the array appear twice except one. The question is to get the one that does not have any duplicate (i.e appeared just once). See problem description below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--4qYsV5V7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/875/1%2AoadmmztTutxcu0zZ_e2Mkg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4qYsV5V7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/875/1%2AoadmmztTutxcu0zZ_e2Mkg.png" alt="problem description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;NOTE: The solution should be in O(log n) and O(1) space.&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
The above problems can be solved in so many ways but I will talk about three ways to solve it in decreasing order of performance.&lt;/p&gt;

&lt;h3&gt;&lt;b&gt;FIRST ALGORITHM (THE UGLY)&lt;/b&gt;&lt;/h3&gt;

&lt;p&gt;The first solution that came to my mind was to use a HashMap. There is a saying that goes thus;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;For every question you encounter, always think HashMaps, there is a probability that you will solve the problem with HasMap 😂😂😂.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The idea is to store the count of elements in the array inside a HashMap with the element as the key and the count as the value.&lt;/p&gt;

&lt;p&gt;Then next step is to loop through return the key that its value is 1 because if the value is 1, definitely that’s the odd one. The code is shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public int singleNonDuplicateUsingHashMap(int[] nums) {
    HashMap&amp;lt;Integer, Integer&amp;gt; map = new HashMap&amp;lt;&amp;gt;();

    //store the count of each element in the map
    for (int i = 0; i &amp;lt; nums.length; i++) {
        if (!map.containsKey(nums[i])) {
            //if the key doesn't exist, create a new one
            map.put(nums[i], 1);
        }else {
          //update the count of the existing by incrementing it by 1
            map.put(nums[i], map.get(nums[i]) + 1);
        }
    }

    //loop through map and get the one that has the value of 1
    for (Map.Entry&amp;lt;Integer, Integer&amp;gt; entry : map.entrySet()) {
        if (entry.getValue() == 1) {
            return entry.getKey();
        }
    }

    return -1;

}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The above code works just fine but the runtime is &lt;strong&gt;O(n)&lt;/strong&gt; for each of the loops which translates to &lt;strong&gt;O(n) + O(n)&lt;/strong&gt; which is equal to &lt;strong&gt;2O(n)&lt;/strong&gt;. &lt;strong&gt;2O(n)&lt;/strong&gt; is the same as &lt;strong&gt;O(n)&lt;/strong&gt; because we don’t consider constants in calculating runtime. To make this slightly better, let’s look at another algorithm.&lt;/p&gt;

&lt;h3&gt;&lt;b&gt;SECOND ALGORITHM (THE BAD)&lt;/b&gt;&lt;/h3&gt;

&lt;p&gt;1.Loop through the array by incrementing the count by two (2);&lt;/p&gt;

&lt;p&gt;2.check if the current element is equal to the next element;&lt;/p&gt;

&lt;p&gt;3.if they are not, that means that current element is the odd one without a duplicate. See the steps in the image below;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1v_vMX-M--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/875/1%2ABJyqskPBxOXW6kWRNlrAcw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1v_vMX-M--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/875/1%2ABJyqskPBxOXW6kWRNlrAcw.png" alt="steps for hashmap"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;&lt;b&gt;STEPS&lt;/b&gt;&lt;/h3&gt;

&lt;p&gt;The first step starts from element at index 0(i=0), checks if the next element at index(i+1) is the same. Since they are the same, it increments the index (i) by 2. It follows the same process for Step 2.&lt;br&gt;
For step 3 which is at index 4, it checks and finds out they are not the same, so it returns value at the current index (i=4)which is 10. The code is shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public int singleNonDuplicateLinearly(int[] nums) {
    if (nums.length == 1) return nums[0];
    for (int i = 0; i &amp;lt; nums.length; i+=2) {
        if (i == nums.length - 1) return nums[i];
        if (i+1 &amp;lt; nums.length &amp;amp;&amp;amp; nums[i] != nums[i+1]) {
            return nums[i];
        }
    }
    return -1;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;THIRD ALGORITHM (THE GOOD😎😎😎)&lt;/h3&gt;

&lt;p&gt;If you look at the problem description, it says that the runtime should be O(log n) and space complexity of O(1).&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Whenever you see a question that says runtime should be O(log n) and space complexity of O(1), just know that the solution would probably involve Binary Search.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--gVlPzv8K--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1400/1%2Aioj79lYbWwXTLCGE72VLnQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--gVlPzv8K--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1400/1%2Aioj79lYbWwXTLCGE72VLnQ.png" alt="solving with binary search"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;As with every binary search, it starts from the middle (divide the array into two halves);&lt;/li&gt;
&lt;li&gt;checks the right half elements to know if they are even number of elements left. if they are even (stores the state in a variable (isEven)), there is no way the odd number would be in the second half if they are even.&lt;/li&gt;
&lt;li&gt;From the element at middle, it checks the element before it to know if they are equal.&lt;/li&gt;
&lt;li&gt;If they are equal and the variable isEven is true, it moves the right arrow to be at two elements before the middle element (mid-2). if the variable isEven is false, it moves the left arrow to start from an element after the middle element (mid+1).&lt;/li&gt;
&lt;li&gt;If they are not equal, and isEven is true, it moves the left arrow to two elements after the middle element. If they are not equal, it right arrow to an element before the middle element.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static int singleNonDuplicateUsingBinarySearch(int[] nums) {
   int lowLeft = 0;
   int highRight = nums.length-1;
   boolean isEven;

   while (highRight &amp;gt; lowLeft) {
       int mid = lowLeft + (highRight - lowLeft) /2;
       //check if the right side is even
       isEven = (highRight - mid) % 2 == 0;

       if (nums[mid] == nums[mid-1]) {
           if (isEven) {
               highRight = mid - 2;
           }else {
               lowLeft = mid + 1;
           }
       }else if (nums[mid] == nums[mid + 1]){
           if (isEven) {
               lowLeft = mid + 2;
           }else {
               highRight = mid - 1;
           }

       }else  {
           return nums[mid];
       }

   }
   return nums[lowLeft];
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Thank you for reading. Please drop a comment.&lt;/p&gt;

</description>
      <category>tutorial</category>
      <category>algorithms</category>
      <category>codenewbie</category>
      <category>leetcode</category>
    </item>
    <item>
      <title>Solution to Leetcode's Flood Fill Question (interesting Question) </title>
      <dc:creator>codechunker</dc:creator>
      <pubDate>Tue, 12 May 2020 01:14:32 +0000</pubDate>
      <link>https://dev.to/codechunker/solution-to-leetcode-s-flood-fill-question-interesting-question-1f0j</link>
      <guid>https://dev.to/codechunker/solution-to-leetcode-s-flood-fill-question-interesting-question-1f0j</guid>
      <description>&lt;p&gt;This is an easy &lt;a href="https://leetcode.com/problems/flood-fill/"&gt;Leetcode 733&lt;/a&gt; problem. See problem description below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--31jG5okK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1400/1%2AkgiIrNpaapSP94fIZTuU7w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--31jG5okK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1400/1%2AkgiIrNpaapSP94fIZTuU7w.png" alt="problem description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;&lt;b&gt;Question Explanation&lt;/b&gt;&lt;/h3&gt;

&lt;p&gt;To get a clearer picture of what the question wants us to do, first, it will be better to break the multidimensional array elements to form a square-like structure e.g the picture below shows the break down of &lt;strong&gt;[[1,1,1], [1,1,0], [1,0,1]]&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--oscl9whD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/966/1%2ApFLU8Vf5QrykCJObBYjuBg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oscl9whD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/966/1%2ApFLU8Vf5QrykCJObBYjuBg.png" alt="splitting array elements"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now that we have broken the elements into rows and columns as shown in the figure above, the explanation of the question is this; given a particular starting row (&lt;strong&gt;&lt;em&gt;sr&lt;/em&gt;&lt;/strong&gt;) and a starting column(&lt;strong&gt;&lt;em&gt;sc&lt;/em&gt;&lt;/strong&gt;) which is suppose to be the starting pixel and given a new color (&lt;strong&gt;&lt;em&gt;newColor&lt;/em&gt;&lt;/strong&gt;) which is to be used to replace, change that starting pixel (sr, sc) to the new color (&lt;strong&gt;&lt;em&gt;newColor&lt;/em&gt;&lt;/strong&gt;) and also change its neigbours (4-directional to the starting pixel which is of the same colour).&lt;/p&gt;

&lt;p&gt;For example, assuming the circled number in the image above is the starting index, the image below shows exactly the steps that will be taken to flood fill:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--o2fHvbWe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1206/1%2Aa9XO_frwfRNsVnuiEygP4A.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--o2fHvbWe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1206/1%2Aa9XO_frwfRNsVnuiEygP4A.png" alt="flood fill transition steps"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;NOTE: The colored numbers/pixels are the neigbours (4-directional)of the circled numbers/pixels.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;&lt;b&gt;STEPS&lt;/b&gt;&lt;/h3&gt;

&lt;p&gt;So Step 1 starts from the middle as the starting pixel, changes itself to the new colour which is ‘2’ in this case. It checks its neighbours (left, right, top, bottom), replaces those that had the same number as the one the starting pixel had (which is 1)before it changed to the new colour (2). So it changes all the 1s to 2s as long as they are neighbours. it then moves the ‘batton’ to its left neighbour (1st column)to go through the same process.&lt;/p&gt;

&lt;p&gt;Step 2, changes its top and bottom neigbours to 2 because those neighbours had the same number as its initial before itself was changed. &lt;strong&gt;&lt;em&gt;NOTE that step 2 does not have a left neighbour.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Step 3 and 4 go through the same process.&lt;/p&gt;

&lt;p&gt;if you noticed, the left and right neigbours can be considered as the columns while the top and bottom can be considered as the rows.&lt;br&gt;
ALGORITHM&lt;br&gt;
The first idea that comes to the mind in this kind of problem is &lt;strong&gt;Recursion&lt;/strong&gt;.&lt;br&gt;
We need to keep a track of the initial colour and then use recursion to go through all the paths.&lt;/p&gt;

&lt;p&gt;The source code is shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        if (image[sr][sc] == newColor) return image;

        flood(image, image[sr][sc], newColor, sr, sc);

        return image;
    }

public void flood(int[][] image, int color, int newColor, int sr, int sc) {
        if (sr &amp;lt; 0 || sc &amp;lt; 0 ||  sr &amp;gt;= image.length || sc &amp;gt;= image[0].length || image[sr][sc] != color) {
            return;
        }

        image[sr][sc] = newColor;

        int topRowNeighbour = sr - 1;
        int bottomRowNeighbour = sr + 1;
        int leftColumnNeigbour = sc - 1;
        int rightColumnNeighbour = sc + 1;

        flood(image, color, newColor, topRowNeighbour, sc );
        flood(image, color, newColor, bottomRowNeighbour, sc );
        flood(image, color, newColor, sr, leftColumnNeigbour );
        flood(image, color, newColor, sr, rightColumnNeighbour );
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Thank you very much for reading. Please leave a comment or suggestion.&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>tutorial</category>
      <category>algorithms</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Took a while to solve this Leetcode problem. Remove Duplicates From Sorted Array II</title>
      <dc:creator>codechunker</dc:creator>
      <pubDate>Sun, 10 May 2020 21:55:21 +0000</pubDate>
      <link>https://dev.to/codechunker/took-a-while-to-solve-this-leetcode-problem-remove-duplicates-from-sorted-array-ii-3aji</link>
      <guid>https://dev.to/codechunker/took-a-while-to-solve-this-leetcode-problem-remove-duplicates-from-sorted-array-ii-3aji</guid>
      <description>&lt;p&gt;I must confess this question took me a while as a beginner. This is a medium &lt;a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/"&gt;Leetcode 80&lt;/a&gt; question. This is similar to &lt;a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array"&gt;Leetcode 26&lt;/a&gt; where you are simply asked to remove all duplicates in an array. The tweak in Leetcode 80 is that the highest duplicate a number in array can have is two e.g &lt;strong&gt;[1,1,1,2,2,3]&lt;/strong&gt; should turn to &lt;strong&gt;[1,1,2,2,3]&lt;/strong&gt;. See problem description below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--dSrOr_10--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1400/1%2AMycigMpBfUepc-B1IVf5bA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--dSrOr_10--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1400/1%2AMycigMpBfUepc-B1IVf5bA.png" alt="problem description"&gt;&lt;/a&gt;&lt;br&gt;
This problem took me a while not because i could not solve it with any method I wanted, but I wanted to solve it the way it was described in the question i.e solving it in-place in O(1) space complexity.&lt;/p&gt;

&lt;p&gt;See below the rubbish I was trying to do🤣🤣🤣. &lt;strong&gt;PLEASE DON’T TRY THIS AT HOME.&lt;/strong&gt; I won't even bother trying to explain what i was trying to do but if you can understand it, fine and good.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static int removeDuplicates(int[] nums) {
    //111223 =&amp;gt; 11223
    int count = 0;
    int elementCount = 1;

    for (int i = 0; i &amp;lt; nums.length; i++) {
        if (i + 1 &amp;lt; nums.length) {

            if (nums[i] == nums[i + 1] &amp;amp;&amp;amp; elementCount &amp;lt; 3) {
                elementCount++;
                nums[count] = nums[i];
                count++;
            }else if (nums[i] == nums[i+1] &amp;amp;&amp;amp; elementCount &amp;gt;= 3){
                elementCount++;
                continue;
            }else if (nums[i] != nums[i+1] &amp;amp;&amp;amp; elementCount &amp;gt;=3){
                elementCount = 1;
                int temp = nums[i+1];
                nums[count] = temp;
                nums[i+1] = -1;
                count++;
            }else if (nums[i] != nums[i+1] &amp;amp;&amp;amp; elementCount &amp;lt; 3){
                elementCount = 1;

                if (nums[i] == -1){
                    nums[count] = nums[i+1];
                    elementCount = 3;
                }

                else nums[count] = nums[i];
                count++;
            }
        }

    }

    return count;

}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;&lt;b&gt;THE CORRECT CONCEPT&lt;/b&gt;&lt;/h3&gt;

&lt;p&gt;Since the problem says the maximum duplicates you can have for a number is two (2) and the problem must be solve in-place i.e don’t create a new array rather manipulate the given array. The concept is as follows;&lt;/p&gt;

&lt;p&gt;Keep a counter index(&lt;strong&gt;indexCount&lt;/strong&gt;)from the third index (3) this is to be incremented. You do this because no matter what, the first two indices will always be correct. it doesn’t matter if they are the same or different.&lt;/p&gt;

&lt;p&gt;From the third index, start comparing the current index to two indices before it. If they are not equal, put the current element (&lt;strong&gt;nums[i]&lt;/strong&gt;) into the current &lt;strong&gt;indexCount&lt;/strong&gt; value and then increment &lt;strong&gt;indexCount&lt;/strong&gt;. Remember, if they are equal, that means the current element is now 3 which violates condition that the maximum duplicate should be 2. The code is shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static int removeDuplicates(int[] nums) {
    int indexCount = 2;
    for (int i = 2; i &amp;lt; nums.length; i++) {
        if (nums[i] != nums[indexCount-2]) {
            nums[indexCount] = nums[i];
            indexCount++;
        }
    }
    return indexCount;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The runtime of the algorithm above is O(n) and the space complexity is O(1) which makes it very efficient especially in terms of space complexity.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Remember always think outside the box&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
Thank you for reading. Please leave a comment or suggestion.&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>tutorial</category>
      <category>codenewbie</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>Solution to Leetcode’s Valid Perfect Square</title>
      <dc:creator>codechunker</dc:creator>
      <pubDate>Sat, 09 May 2020 23:34:28 +0000</pubDate>
      <link>https://dev.to/codechunker/solution-to-leetcode-s-valid-perfect-square-5gd</link>
      <guid>https://dev.to/codechunker/solution-to-leetcode-s-valid-perfect-square-5gd</guid>
      <description>&lt;p&gt;This is an easy &lt;a href="https://leetcode.com/problems/valid-perfect-square/"&gt;Leetcode problem 367&lt;/a&gt;. The question gives a number and you are to write a function to determine if it is a perfect square. See the image below for description.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--RGzAespI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1400/1%2AP5i0IPr8UqObEFFcpMIZlQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RGzAespI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1400/1%2AP5i0IPr8UqObEFFcpMIZlQ.png" alt="problem description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;According to &lt;a href="https://en.wikipedia.org/wiki/Square_number"&gt;wikipedia&lt;/a&gt;, a perfect square is the product of a number with itself. in this context, a perfect square is a number when multiplied by itself will give you the number in question.&lt;br&gt;
There are many ways in solving this problem but I will talk about three in this article.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NOTE: Do not use any library functions like Math.sqrt().&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;&lt;b&gt;THE NAIVE APPROACH&lt;/b&gt;&lt;/h3&gt;

&lt;p&gt;Of course the naive or brute force approach would be to loop through from 1 to the number, multiplying a number by itself and checking if the product equals the number you are looking for. if it does, then return true, else return false.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static boolean isPerfectSquareWithBruteForce(int num) {
    if (num == 1) return true;
    for (int i = 1; i &amp;lt; num; i++) {
        if (i*i == num) return true;
    }
    return false;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The code above works but can be very slow. its runtime is O(n).&lt;br&gt;
To make this better, we may decide to loop from 1 to half of the number because there is no way you can get the number in question by multiplying number greater than half (i.e num/2) by itself. e.g to determine if 9 is a perfect square, there is no way a number between 4 to 9 would give you 9. So in other words, to know if a number is a perfect square, the number that will multiply itself will have to be in the first half (between 1–3).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt; public static boolean isPerfectSquareWithHalfNumber(int num) {
        if (num ==  1 || num ==  0) return true;
        for (int i = num/2; i &amp;gt;= 0; i-- ) {
            if (i*i == num) return true;
        }

        return false;
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Technically speaking, it may seem that the above code would make it faster but the truth is , the runtime of this is O(n/2) which still translates to O(n) because in computer science, we don’t consider constants when dealing with runtime.&lt;/p&gt;

&lt;h3&gt;&lt;b&gt;A FASTER SOLUTION&lt;/b&gt;&lt;/h3&gt;

&lt;p&gt;A better way to solve this problem would be to use Binary Search. This solves the problem by using the divide and conquer methodology. It keeps splitting the number into half and checking if number is found.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static boolean isPerfectSquareWithBinarySearch(int num) {

    double start = 1;
    double end = num/2;

    if (num == 1) return true;

    while (start &amp;lt;= end) {
        double mid = Math.floor((end - start)/2) + start;

        if (mid * mid ==  num) {
            return true;
        }else if (mid * mid &amp;lt; num) {
            start = mid + 1;
        }else {
            end = mid - 1;
        }
    }
    return false;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The runtime of the above is O(log n) which is faster than O(n) linear time.&lt;/p&gt;

&lt;p&gt;Thank you for reading and please leave a comment or suggestion.&lt;/p&gt;

</description>
      <category>tutorial</category>
      <category>codenewbie</category>
      <category>leetcode</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>INTRODUCTION TO REGEX EXPRESSIONS FOR JAVA DEVELOPERS</title>
      <dc:creator>codechunker</dc:creator>
      <pubDate>Wed, 29 Apr 2020 17:39:07 +0000</pubDate>
      <link>https://dev.to/codechunker/introduction-to-regex-expressions-for-java-developers-chd</link>
      <guid>https://dev.to/codechunker/introduction-to-regex-expressions-for-java-developers-chd</guid>
      <description>&lt;p&gt;According to &lt;a href="https://docs.oracle.com/javase/tutorial/essential/regex/intro.html"&gt;oracle doc&lt;/a&gt;, &lt;br&gt;
Regular Expressions popularly called Regex are  ways to describe a set of strings based on common characteristics shared by each string in the set. They can be used to search, edit, or manipulate text and data.&lt;/p&gt;

&lt;p&gt;In layman’s term, Regular Expressions are ways that help you to validate or match strings according to a particular format. In other words, you can use it to check if a particular input by a user is correct or use it to retrieve or extract values that match a particular sequence.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;IMPORTANCE/USAGES OF REGEX&lt;/strong&gt;&lt;br&gt;
• Validate a user’s input.&lt;br&gt;
• Search text in a given data. (can be used in Text Editors)&lt;br&gt;
• Parser in compilers&lt;br&gt;
• Syntax highlighting, packet sniffers etc.&lt;/p&gt;

&lt;p&gt;To have a thorough basic understanding of Regex we need to understand the following concepts:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;QUANTIFIERS ( * + ? {n} . )&lt;/strong&gt;&lt;br&gt;
The quantifiers in Java ( and in  most programming languages) consists of  &lt;em&gt;,  +,  ?, {} . &lt;br&gt;
a)   * matches zero or more instances of its preceding pattern. e.g. abc* means the text must match 'ab' followed by zero or more of 'c' i.e. the text may not have ‘c’ attached to it and the text may also have one or more ‘c’ . The preceding pattern in this case is ‘ab’. *&lt;/em&gt;&lt;a href="https://regex101.com/r/S1ejep/3"&gt;TRY IT&lt;/a&gt;** &lt;/p&gt;

&lt;p&gt;b)  + matches one or more instances of its preceding pattern e.g abc+ means that the text must have ‘ab’ followed by &lt;strong&gt;one or more&lt;/strong&gt; ‘c’. so abc is the least you can have that is correct, abcc is also correct. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/4"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;c)  ? matches zero or one occurrences of the pattern e.g abc? Means the text can either be abc or ab. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/5"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;d)  {n} matches the exact number (n) specified in the expression. e.g a{2}bc means that you can only have two ‘a’ followed by one ‘b’ and one ‘c’. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/6"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;e)  {n, } matches at least the number specified. That means you must have n number or more  of the preceding expression  e.g ab{2,}c means you must have a, followed by two or more ‘b’ and then c. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/7"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;f)  {n,m} matches between n and m (inclusive) of the pattern. This means you can have between to m occurrences of the preceding pattern. e.g ab{2,5}c means abbc, abbbc, abbbbc, abbbbbc are all correct. Anything out of these is wrong. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/8"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;g)  ‘.’ matches all non-white space characters&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;OPERATORS(| [] ^ )&lt;/strong&gt;&lt;br&gt;
Pipe (|) is used as ‘OR’. So it matches the expression on the left or the expression on the right. e.g abc|abd means the text should be either abc or abd. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/11"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;[] means the text should match any of the characters in the angle brackets e.g a[bc] means the text should be ‘a’ followed by either ‘b’ or ‘c’.&lt;br&gt;
[0-9]% means the text should be any number from 0 to 9 followed by ‘%’&lt;br&gt;
[a-zA-Z] means any character as long as it between a-z or A-Z. &lt;br&gt;
[abc] means the text or string should be either a, or b or c.&lt;br&gt;
Adding ‘^’ to any of the expressions negates the meaning of that expression e.g [^abc] means the string should be any character as long as it is not a or b or c. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/12"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GROUPING AND BACK REFERENCES&lt;/strong&gt;&lt;br&gt;
Another interesting thing about regex is that you can group your expressions and probably reuse them when necessary. To group elements in expressions, use round brackets e.g ().&lt;br&gt;
A Back Reference stores the part of the string that matched the group. You can reference a particular group by using the sign $. $1, $2…represent group 1, group 2 etc. the default group is $0 which is the actual text itself. For example, lets remove all the spaces in a sentence .The regex for this example would be the code snippet below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private static String backReference(String text) {
    String pattern = "(\\w+)([\\s])";
    return text.replaceAll(pattern, "$1");
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The expression in the code above has 2 groups: (\w+) and (\s). So we are saying the text has to be a bunch of words(\w+) and spaces(\s+). After that, we replace the whole text with just group 1($1) which will just remove the spaces because all we need now is just words. Referencing $1 in the back referencing. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NOTE: In java, we need to escape the character class (\w and \s) with another slash otherwise you would have a syntax error.&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LOOK AHEAD/LOOK BEHIND&lt;/strong&gt;&lt;br&gt;
This is a way to exclude a pattern. So you can say a string should be valid only if it doesn’t come before a particular string and vice versa. e.g. abc(?=d) will match ‘abc’ as long as it follows a ‘d’.  but note that ‘d’ will be excluded. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/14"&gt;TRY IT&lt;/a&gt;.&lt;/strong&gt; &lt;br&gt;
A good real life application of this would be to get the value in any HTML tag e.g &amp;lt;h1&amp;gt;Hello World&amp;lt;/h1&amp;gt;. The expression would be (?i)(&amp;lt;h1.*?&amp;gt;)(.*(?=&amp;lt;))()  &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/15"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;. This returns Hello World&lt;br&gt;
You can also use (?!pattern) as a negative look ahead e.g ab(?!c) will match ab if ‘ab’  is not followed by ‘b’.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GREEDY AND LAZY&lt;/strong&gt; &lt;br&gt;
The quantifiers above are said to be &lt;strong&gt;greedy&lt;/strong&gt; in the sense that they’ll match as many occurrences as long as the match is still successful. e.g for the regex a.+c, you would expect it to mean the text should be ‘a’ followed by one or more non-white space character. So you would expect a possible match to be ‘abcccd’ or ‘abcc’ or ‘abbc’ as &lt;strong&gt;individual&lt;/strong&gt; results. This is meant to be true but because of the greedy attitude, it will grab all the texts (abcccd abcc  abbc) as one and return ‘abcccd abcc  abbc’ as one result because if you notice, the first character is ‘a’ followed by one or more of any other character and it now ends with c which matches exactly &lt;strong&gt;a.+c&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In order to restrict this “greedy attitude”, just add question mark (?) in front of the quantifier, this makes the quantifier a bit reluctant which means it will match as few occurrences as possible as long as the match is successful. So ab.+?c would return the results individually instead of grabbing the whole string and processing them as one. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/9"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;A better application of this would be this: Assuming you want to get just the tags &amp;lt;h1&amp;gt; and &amp;lt;/h1&amp;gt; seperately from  &amp;lt;h1&amp;gt;Hello World&amp;lt;/h1&amp;gt;, you would expect that the regex for it would be &amp;lt;.+&amp;gt; but in reality, it is going to grab the whole text (&amp;lt;h1&amp;gt;Hello World&amp;lt;/h1&amp;gt;) and process it as one and still return the same text to you because it actually matches the expression you provided (the text should start with ‘&amp;lt;’, followed by one or more of any other character and then end ‘&amp;gt;’ ) which the text satisfies &lt;a href="https://regex101.com/r/S1ejep/10"&gt;TRY IT&lt;/a&gt;. &lt;br&gt;
&lt;strong&gt;Adding ‘?’ in front of the quantifier is sometimes called lazy&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In a nutshell, ‘Greedy’ means match longest possible string while ‘lazy’ means match shortest possible string.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NOTE: Be careful when using these quantifiers especially period(.) in expressions.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CHARACTER CLASSES&lt;/strong&gt;&lt;br&gt;
A character class is an escape sequence that represents a group of characters. Some predefined characters in java are listed below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rewjJZAM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AxBF8iwuoXgcfVhmPytS6bA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rewjJZAM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AxBF8iwuoXgcfVhmPytS6bA.png" alt="character classes"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you notice from the above table, the Uppercase letters negate the functions of the lowercase letters vice versa&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NOW OVER TO THE WORLD OF JAVA&lt;/strong&gt;&lt;br&gt;
String class in Java comes with an inbuilt boolean method called matches that matches a string against a regex.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static void main(String[] args) {
    String value = "12345";
    System.out.println("The Result is: "+value.matches("\\d{5}"));
}

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



&lt;p&gt;The code snippet above would return ‘The Result is: true’ because the value (12345) matches exactly 5 characters. Any thing other than 5 would return ‘The Result is: false’.&lt;/p&gt;

&lt;p&gt;Apart from matches method of the String class, most of the classes you would need for regex are found in java.util.regex package. They consist of three classes:&lt;br&gt;
• &lt;strong&gt;Pattern&lt;/strong&gt;: this is the compiled representation of of a regular expression. To use this, you must first call the static method (compile) in the pattern class which returns a Pattern object.&lt;br&gt;
• &lt;strong&gt;Matcher&lt;/strong&gt;: This is the engine that that interprets the pattern and performs match operations against an input string. To get an object, you have to invoke the matcher method on a Pattern object.&lt;br&gt;
• &lt;strong&gt;PatternSyntaxException&lt;/strong&gt;: this indicates error in a regular expression pattern&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;To Match a string using Pattern/Matcher Classes&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static void main(String[] args) {
    String value = "12345";
    String regex = "\\d{5}";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(value);
    System.out.println("The Result is: "+matcher.matches());
}

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



&lt;p&gt;Now the question is why would I go through the stress of using Pattern/Matcher when I can just match the string against the regex &lt;strong&gt;(value.matches(regex))&lt;/strong&gt;. &lt;br&gt;
Well the truth is the implementation of method matches in class String using Pattern/Matcher under the hood. So, for every string you match, it creates a Pattern object before matching.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When to use Pattern/Matcher VS String.matches(String text)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class PatternMatcher {
    public static void main(String[] args) {
        String [] texts = {"nozzle","punjabi","waterlogged","imprison","crux","numismatlogists","sultans","rambles","deprecating","aware","outfield","marlborough","guardrooms","roast","wattage","shortcuts","confidential","reprint","foxtrot","disposseslogsion","floodgate","unfriendliest","semimonthlies","dwellers","walkways","wastrels","dippers","engrlogossing","undertakings"};
         List&amp;lt;String&amp;gt; resultStringMatches = matchUsingStringMatches(texts);
        List&amp;lt;String&amp;gt; resultsPatternMatcher = matchUsingPatternMatcher(texts);
        System.out.println("The Result for String matches is: "+resultStringMatches.toString());
        System.out.println("The Result for pattern/matcher is: "+resultStringMatches.toString());
    }

    private static List&amp;lt;String&amp;gt; matchUsingPatternMatcher(String[] texts) {
        List&amp;lt;String&amp;gt; matchedList = new ArrayList&amp;lt;&amp;gt;();
        String pattern = "[a-zA-Z]*log[a-zA-Z]*";
        Pattern regexPattern = Pattern.compile(pattern);
        Matcher matcher;
        for (int i = 0; i &amp;lt; texts.length; i++) {
             matcher = regexPattern.matcher(texts[i]);
            if (matcher.matches()) {
                matchedList.add(texts[i]);
            }
        }
        return matchedList;
    }

    private static List&amp;lt;String&amp;gt; matchUsingStringMatches(String[] texts) {
        String pattern = "[a-zA-Z]*log[a-zA-Z]*";
        List&amp;lt;String&amp;gt; matchedList = new ArrayList&amp;lt;&amp;gt;();

        for (int i = 0; i &amp;lt; texts.length; i++) {
            //for each time it calls matches(pattern), it creates a pattern object
            if (texts[i].matches(pattern)) {
                matchedList.add(texts[i]);
            }
        }
        return matchedList;
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The code above matches all the elements in an array against a particular regex ([a-zA-Z]&lt;em&gt;log[a-zA-Z]&lt;/em&gt;). The regex is meant to get all texts that have the word “log”. Before a match against a regex, that expression must be compiled (Pattern.compile);&lt;br&gt;
The first method &lt;strong&gt;&lt;em&gt;matchUsingPatternMatcher()&lt;/em&gt;&lt;/strong&gt; compiles the pattern first before looking for matches while the second method &lt;strong&gt;&lt;em&gt;matchUsingStringMatches()&lt;/em&gt;&lt;/strong&gt; creates a new Pattern Object &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;(Pattern.compile())&lt;/strong&gt; for every element in the array which is expensive/costly and may cause memory leakage especially then the data/texts are too many. &lt;br&gt;
So if you care about performance when dealing with large set of data, use the Pattern/Matcher class to compile first and use the instance to match the texts.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Thank you very much for reading. Please you can leave a comment, suggestion or correction on the comment section below.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>java</category>
      <category>tutorial</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>INTRODUCTION TO REGEX EXPRESSIONS FOR JAVA DEVELOPERS</title>
      <dc:creator>codechunker</dc:creator>
      <pubDate>Tue, 28 Apr 2020 10:54:56 +0000</pubDate>
      <link>https://dev.to/codechunker/introduction-to-regex-expressions-for-java-developers-11jn</link>
      <guid>https://dev.to/codechunker/introduction-to-regex-expressions-for-java-developers-11jn</guid>
      <description>&lt;p&gt;According to &lt;a href="https://docs.oracle.com/javase/tutorial/essential/regex/intro.html"&gt;oracle doc&lt;/a&gt;, &lt;br&gt;
Regular Expressions popularly called Regex are  ways to describe a set of strings based on common characteristics shared by each string in the set. They can be used to search, edit, or manipulate text and data.&lt;/p&gt;

&lt;p&gt;In layman’s term, Regular Expressions are ways that help you to validate or match strings according to a particular format. In other words, you can use it to check if a particular input by a user is correct or use it to retrieve or extract values that match a particular sequence.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;IMPORTANCE/USAGES OF REGEX&lt;/strong&gt;&lt;br&gt;
• Validate a user’s input.&lt;br&gt;
• Search text in a given data. (can be used in Text Editors)&lt;br&gt;
• Parser in compilers&lt;br&gt;
• Syntax highlighting, packet sniffers etc.&lt;/p&gt;

&lt;p&gt;To have a thorough basic understanding of Regex we need to understand the following concepts:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;QUANTIFIERS ( * + ? {n} . )&lt;/strong&gt;&lt;br&gt;
The quantifiers in Java ( and in  most programming languages) consists of  &lt;em&gt;,  +,  ?, {} . &lt;br&gt;
a)   * matches zero or more instances of its preceding pattern. e.g. abc* means the text must match 'ab' followed by zero or more of 'c' i.e. the text may not have ‘c’ attached to it and the text may also have one or more ‘c’ . The preceding pattern in this case is ‘ab’. *&lt;/em&gt;&lt;a href="https://regex101.com/r/S1ejep/3"&gt;TRY IT&lt;/a&gt;** &lt;/p&gt;

&lt;p&gt;b)  + matches one or more instances of its preceding pattern e.g abc+ means that the text must have ‘ab’ followed by &lt;strong&gt;one or more&lt;/strong&gt; ‘c’. so abc is the least you can have that is correct, abcc is also correct. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/4"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;c)  ? matches zero or one occurrences of the pattern e.g abc? Means the text can either be abc or ab. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/5"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;d)  {n} matches the exact number (n) specified in the expression. e.g a{2}bc means that you can only have two ‘a’ followed by one ‘b’ and one ‘c’. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/6"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;e)  {n, } matches at least the number specified. That means you must have n number or more  of the preceding expression  e.g ab{2,}c means you must have a, followed by two or more ‘b’ and then c. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/7"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;f)  {n,m} matches between n and m (inclusive) of the pattern. This means you can have between to m occurrences of the preceding pattern. e.g ab{2,5}c means abbc, abbbc, abbbbc, abbbbbc are all correct. Anything out of these is wrong. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/8"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;g)  ‘.’ matches all non-white space characters&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;OPERATORS(| [] ^ )&lt;/strong&gt;&lt;br&gt;
Pipe (|) is used as ‘OR’. So it matches the expression on the left or the expression on the right. e.g abc|abd means the text should be either abc or abd. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/11"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;[] means the text should match any of the characters in the angle brackets e.g a[bc] means the text should be ‘a’ followed by either ‘b’ or ‘c’.&lt;br&gt;
[0-9]% means the text should be any number from 0 to 9 followed by ‘%’&lt;br&gt;
[a-zA-Z] means any character as long as it between a-z or A-Z. &lt;br&gt;
[abc] means the text or string should be either a, or b or c.&lt;br&gt;
Adding ‘^’ to any of the expressions negates the meaning of that expression e.g [^abc] means the strinf should be any character as long as it is not a or b or c. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/12"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GROUPING AND BACK REFERENCES&lt;/strong&gt;&lt;br&gt;
Another interesting thing about regex is that you can group your expressions and probably reuse them when necessary. To group elements in expressions, use round brackets e.g ().&lt;br&gt;
A Back Reference stores the part of the string that matched the group. You can reference a particular group by using the sign $. $1, $2…represent group 1, group 2 etc. the default group is $0 which is the actual text itself. For example, lets remove all the spaces in a sentence .The regex for this example would be the code snippet below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private static String backReference(String text) {
    String pattern = "(\\w+)([\\s])";
    return text.replaceAll(pattern, "$1");
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The expression in the code above has 2 groups: (\w+) and (\s). So we are saying the text has to be a bunch of words(\w+) and spaces(\s+). After that, we replace the whole text with just group 1($1) which will just remove the spaces because all we need now is just words. Referencing $1 in the back referencing. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NOTE: In java, we need to escape the character class (\w and \s) with another slash otherwise you would have a syntax error.&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LOOK AHEAD/LOOK BEHIND&lt;/strong&gt;&lt;br&gt;
This is a way to exclude a pattern. So you can say a string should be valid only if it doesn’t come before a particular string and vice versa. e.g. abc(?=d) will match ‘abc’ as long as it follows a ‘d’.  but note that ‘d’ will be excluded. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/14"&gt;TRY IT&lt;/a&gt;.&lt;/strong&gt; &lt;br&gt;
A good real life application of this would be to get the value in any HTML tag e.g &amp;lt;h1&amp;gt;Hello World&amp;lt;/h1&amp;gt;. The expression would be (?i)(&amp;lt;h1.*?&amp;gt;)(.*(?=&amp;lt;))()  &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/15"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;. This returns Hello World&lt;br&gt;
You can also use (?!pattern) as a negative look ahead e.g ab(?!c) will match ab if ‘ab’  is not followed by ‘b’.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GREEDY AND LAZY&lt;/strong&gt; &lt;br&gt;
The quantifiers above are said to be &lt;strong&gt;greedy&lt;/strong&gt; in the sense that they’ll match as many occurrences as long as the match is still successful. e.g for the regex a.+c, you would expect it to mean the text should be ‘a’ followed by one or more non-white space character. So you would expect a possible match to be ‘abcccd’ or ‘abcc’ or ‘abbc’ as &lt;strong&gt;individual&lt;/strong&gt; results. This is meant to be true but because of the greedy attitude, it will grab all the texts (abcccd abcc  abbc) as one and return ‘abcccd abcc  abbc’ as one result because if you notice, the first character is ‘a’ followed by one or more of any other character and it now ends with c which matches exactly &lt;strong&gt;a.+c&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In order to restrict this “greedy attitude”, just add question mark (?) in front of the quantifier, this makes the quantifier a bit reluctant which means it will match as few occurrences as possible as long as the match is successful. So ab.+?c would return the results individually instead of grabbing the whole string and processing them as one. &lt;strong&gt;&lt;a href="https://regex101.com/r/S1ejep/9"&gt;TRY IT&lt;/a&gt;&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;A better application of this would be this: Assuming you want to get just the tags &amp;lt;h1&amp;gt; and &amp;lt;/h1&amp;gt; seperately from  &amp;lt;h1&amp;gt;Hello World&amp;lt;/h1&amp;gt;, you would expect that the regex for it would be &amp;lt;.+&amp;gt; but in reality, it is going to grab the whole text (&amp;lt;h1&amp;gt;Hello World&amp;lt;/h1&amp;gt;) and process it as one and still return the same text to you because it actually matches the expression you provided (the text should start with ‘&amp;lt;’, followed by one or more of any other character and then end ‘&amp;gt;’ ) which the text satisfies &lt;a href="https://regex101.com/r/S1ejep/10"&gt;TRY IT&lt;/a&gt;. &lt;br&gt;
&lt;strong&gt;Adding ‘?’ in front of the quantifier is sometimes called lazy&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In a nutshell, ‘Greedy’ means match longest possible string while ‘lazy’ means match shortest possible string.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NOTE: Be careful when using these quantifiers especially period(.) in expressions.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CHARACTER CLASSES&lt;/strong&gt;&lt;br&gt;
A character class is an escape sequence that represents a group of characters. Some predefined characters in java are listed below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rewjJZAM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AxBF8iwuoXgcfVhmPytS6bA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rewjJZAM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AxBF8iwuoXgcfVhmPytS6bA.png" alt="character classes"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you notice from the above table, the Uppercase letters negate the functions of the lowercase letters vice versa&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NOW OVER TO THE WORLD OF JAVA&lt;/strong&gt;&lt;br&gt;
String class in Java comes with an inbuilt boolean method called matches that matches a string against a regex.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static void main(String[] args) {
    String value = "12345";
    System.out.println("The Result is: "+value.matches("\\d{5}"));
}

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



&lt;p&gt;The code snippet above would return ‘The Result is: true’ because the value (12345) matches exactly 5 characters. Any thing other than 5 would return ‘The Result is: false’.&lt;/p&gt;

&lt;p&gt;Apart from matches method of the String class, most of the classes you would need for regex are found in java.util.regex package. They consist of three classes:&lt;br&gt;
• &lt;strong&gt;Pattern&lt;/strong&gt;: this is the compiled representation of of a regular expression. To use this, you must first call the static method (compile) in the pattern class which returns a Pattern object.&lt;br&gt;
• &lt;strong&gt;Matcher&lt;/strong&gt;: This is the engine that that interprets the pattern and performs match operations against an input string. To get an object, you have to invoke the matcher method on a Pattern object.&lt;br&gt;
• &lt;strong&gt;PatternSyntaxException&lt;/strong&gt;: this indicates error in a regular expression pattern&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;To Match a string using Pattern/Matcher Classes&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static void main(String[] args) {
    String value = "12345";
    String regex = "\\d{5}";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(value);
    System.out.println("The Result is: "+matcher.matches());
}

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



&lt;p&gt;Now the question is why would I go through the stress of using Pattern/Matcher when I can just match the string against the regex &lt;strong&gt;(value.matches(regex))&lt;/strong&gt;. &lt;br&gt;
Well the truth is the implementation of method matches in class String using Pattern/Matcher under the hood. So, for every string you match, it creates a Pattern object before matching.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When to use Pattern/Matcher VS String.matches(String text)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class PatternMatcher {
    public static void main(String[] args) {
        String [] texts = {"nozzle","punjabi","waterlogged","imprison","crux","numismatlogists","sultans","rambles","deprecating","aware","outfield","marlborough","guardrooms","roast","wattage","shortcuts","confidential","reprint","foxtrot","disposseslogsion","floodgate","unfriendliest","semimonthlies","dwellers","walkways","wastrels","dippers","engrlogossing","undertakings"};
         List&amp;lt;String&amp;gt; resultStringMatches = matchUsingStringMatches(texts);
        List&amp;lt;String&amp;gt; resultsPatternMatcher = matchUsingPatternMatcher(texts);
        System.out.println("The Result for String matches is: "+resultStringMatches.toString());
        System.out.println("The Result for pattern/matcher is: "+resultStringMatches.toString());
    }

    private static List&amp;lt;String&amp;gt; matchUsingPatternMatcher(String[] texts) {
        List&amp;lt;String&amp;gt; matchedList = new ArrayList&amp;lt;&amp;gt;();
        String pattern = "[a-zA-Z]*log[a-zA-Z]*";
        Pattern regexPattern = Pattern.compile(pattern);
        Matcher matcher;
        for (int i = 0; i &amp;lt; texts.length; i++) {
             matcher = regexPattern.matcher(texts[i]);
            if (matcher.matches()) {
                matchedList.add(texts[i]);
            }
        }
        return matchedList;
    }

    private static List&amp;lt;String&amp;gt; matchUsingStringMatches(String[] texts) {
        String pattern = "[a-zA-Z]*log[a-zA-Z]*";
        List&amp;lt;String&amp;gt; matchedList = new ArrayList&amp;lt;&amp;gt;();

        for (int i = 0; i &amp;lt; texts.length; i++) {
            //for each time it calls matches(pattern), it creates a pattern object
            if (texts[i].matches(pattern)) {
                matchedList.add(texts[i]);
            }
        }
        return matchedList;
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The code above matches all the elements in an array against a particular regex ([a-zA-Z]&lt;em&gt;log[a-zA-Z]&lt;/em&gt;). The regex is meant to get all texts that have the word “log”. Before a match against a regex, that expression must be compiled (Pattern.compile);&lt;br&gt;
The first method &lt;strong&gt;&lt;em&gt;matchUsingPatternMatcher()&lt;/em&gt;&lt;/strong&gt; compiles the pattern first before looking for matches while the second method &lt;strong&gt;&lt;em&gt;matchUsingStringMatches()&lt;/em&gt;&lt;/strong&gt; creates a new Pattern Object &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;(Pattern.compile())&lt;/strong&gt; for every element in the array which is expensive/costly and may cause memory leakage especially then the data/texts are too many. &lt;br&gt;
So if you care about performance when dealing with large set of data, use the Pattern/Matcher class to compile first and use the instance to match the texts.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Thank you very much for reading. Please you can leave a comment, suggestion or correction on the comment section below.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>codenewbie</category>
      <category>tutorial</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Solution to Leetcode's Contiguous Array</title>
      <dc:creator>codechunker</dc:creator>
      <pubDate>Sat, 18 Apr 2020 23:20:20 +0000</pubDate>
      <link>https://dev.to/codechunker/solution-to-leetcode-s-contiguous-array-3800</link>
      <guid>https://dev.to/codechunker/solution-to-leetcode-s-contiguous-array-3800</guid>
      <description>&lt;p&gt;This is a medium &lt;a href="https://leetcode.com/problems/contiguous-array/"&gt;Leetcode problem 525&lt;/a&gt;. See below image for description:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--VMBLx7aL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res.cloudinary.com/chunks/image/upload/v1587251961/Chunks%2520Blog/Images/contiguous-array_ou9pyc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--VMBLx7aL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res.cloudinary.com/chunks/image/upload/v1587251961/Chunks%2520Blog/Images/contiguous-array_ou9pyc.png" alt="problem description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;ALGORITHM&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;Create a map that stores the current count to the index.&lt;/li&gt;
&lt;li&gt;Loop through the array, if the current value is 0, subtract 1 from count. if it is 1, add 1 to count.&lt;/li&gt;
&lt;li&gt;if the map does not have the current value of count as a key, put the new value in map with key as the current count and the value as the index.&lt;/li&gt;
&lt;li&gt;if the map has the current count as key, get the maximum between the current max and (index - value of the key).&lt;/li&gt;
&lt;li&gt;return max.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;CODE&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt; public int findMaxLength(int[] nums) {
        int count = 0;
        int max = 0;
        HashMap&amp;lt;Integer, Integer&amp;gt; map = new HashMap&amp;lt;&amp;gt;();
        map.put(0, -1);

        for (int i = 0; i &amp;lt; nums.length; i++) {
            if (nums[i] == 0)
                count += -1;
            else
                count += 1;

            if (map.containsKey(count))
                max = Math.max(max, i - map.get(count));
            else
                map.put(count, i);

        }

        return max;
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Solution to Leetcode’s Maximum Subarray</title>
      <dc:creator>codechunker</dc:creator>
      <pubDate>Mon, 23 Mar 2020 11:11:20 +0000</pubDate>
      <link>https://dev.to/codechunker/solution-to-leetcode-s-maximum-subarray-4gdf</link>
      <guid>https://dev.to/codechunker/solution-to-leetcode-s-maximum-subarray-4gdf</guid>
      <description>&lt;p&gt;This is an easy &lt;a href="https://leetcode.com/problems/maximum-subarray/"&gt;Leetcode problem 53&lt;/a&gt;. See below image for description:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--tehyygLg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/860/1%2A3ymjM19wozTRYha9sJHOEQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--tehyygLg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/860/1%2A3ymjM19wozTRYha9sJHOEQ.png" alt="problem description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;ALGORITHM&lt;/h1&gt;

&lt;p&gt;1.Have a global variable currentSum;&lt;/p&gt;

&lt;p&gt;2.Have a global variable max that will also be the return value;&lt;/p&gt;

&lt;p&gt;3.Loop through the array, check if the current element (nums[i]) is greater than the current sum and current element put together (i.e currentSum + nums[i]);&lt;/p&gt;

&lt;p&gt;4.if it is greater, reassign the currentSum variable to be the current element, nums[i];&lt;/p&gt;

&lt;p&gt;5.if it is not, reassign the currentSum variable to be the summation of both the existing current sum and the current array element (currentSum = currentSum + nums[i])&lt;/p&gt;

&lt;p&gt;6.finally, check if the currentSum is greater than the current maximum. if it is, reassign the current max to be equal to currentSum.&lt;/p&gt;

&lt;p&gt;7.Then return max.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CODE&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static int maxSubArray(int[] nums) {

    int currentSum = nums[0];
    int max = nums[0];

    for (int i = 1; i &amp;lt; nums.length; i++) {
        if (nums[i] &amp;gt; (currentSum + nums[i]))
            currentSum = nums[i];
        else
            currentSum = currentSum + nums[i];

        if (currentSum &amp;gt; max) {
            max = currentSum;
        }
    }
    return max;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;OUTCOME&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--A20T_6BW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1018/1%2A3c6cW3x0mSStQBqTFe9xog.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--A20T_6BW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1018/1%2A3c6cW3x0mSStQBqTFe9xog.png" alt="outcome image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;IMPROVEMENT&lt;/strong&gt;&lt;br&gt;
Math.max checks the maximum/bigger value between two numbers. So we can replace those if statements with Math.max(). Cleaner code is shown below:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;IMPROVED CODE&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt; public static int maxSubArray(int[] nums) {

        int currentSum = nums[0];
        int max = nums[0];

        for (int i = 1; i &amp;lt; nums.length; i++) {

            //cleaner and simple
            currentSum = Math.max(nums[i], currentSum + nums[i]);

            max = Math.max(currentSum, max);
        }
        return max;
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;LESSONS&lt;/strong&gt;&lt;br&gt;
1.Don’t always be in the box of a particular algorithm you thought would work, just the way i thought Sliding window would work.&lt;/p&gt;

&lt;p&gt;2.Using library functions where and when needed.&lt;/p&gt;

&lt;p&gt;Thank you for reading. Please leave a comment.&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>datastructure</category>
      <category>algorithms</category>
      <category>problemsolving</category>
    </item>
    <item>
      <title>Solution to Leetcode's ZigZag Conversion: My thought process as a beginner</title>
      <dc:creator>codechunker</dc:creator>
      <pubDate>Tue, 28 Jan 2020 03:17:14 +0000</pubDate>
      <link>https://dev.to/codechunker/solution-to-leetcode-s-zigzag-conversion-my-thought-process-as-a-beginner-1m6j</link>
      <guid>https://dev.to/codechunker/solution-to-leetcode-s-zigzag-conversion-my-thought-process-as-a-beginner-1m6j</guid>
      <description>&lt;p&gt;This is a medium &lt;a href="https://leetcode.com/problems/zigzag-conversion"&gt;Leetcode Problem&lt;/a&gt;. See below image for description:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--iCGVU70F--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/901/1%2AtEh6Z-j3-mC63L8MORnMbg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--iCGVU70F--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/901/1%2AtEh6Z-j3-mC63L8MORnMbg.png" alt="problem description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;ALGORITHM&lt;/h1&gt;

&lt;p&gt;1.Have a map of a row to a StringBuilder of the characters for that row;&lt;br&gt;
2.Have a global counter (row): the current count of the row as you loop through;&lt;br&gt;
3.boolean variable to know when to increment or decrement the row variable in step 2 above;&lt;br&gt;
4.loop through the string, check if the current count of the global variable row is equal to the number of row; if it is, it should set the increment variable to false; else, it should set the increment variable to true;&lt;br&gt;
5.increment/decrement row variable depending on the current value of the increment variable;&lt;br&gt;
6.check the map for availability of the current row value. if it is not found, put the row with a new StringBuilder object;&lt;br&gt;
7.Get the the value of the current row and append the current character to it;&lt;br&gt;
8.loop through the map, append values to stringbuilder, then return string value of the stringbuilder.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;OUTCOME&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EEvyBbN---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1635/1%2AAUfBaBzpJ5uwyr4-l-isOw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EEvyBbN---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1635/1%2AAUfBaBzpJ5uwyr4-l-isOw.png" alt="outcome image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LESSONS&lt;/strong&gt;&lt;br&gt;
After checking discussion section on Leetcode, I discovered that there was pattern to use. Learnt a lot from reading other people’s solutions.&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>algorithms</category>
      <category>problemsolving</category>
      <category>datastructures</category>
    </item>
    <item>
      <title>What you need to know about Leetcode’s Count and Say: My thought process as a beginner.</title>
      <dc:creator>codechunker</dc:creator>
      <pubDate>Mon, 20 Jan 2020 02:02:07 +0000</pubDate>
      <link>https://dev.to/codechunker/what-you-need-to-know-about-leetcode-s-count-and-say-my-thought-process-as-a-beginner-4e0d</link>
      <guid>https://dev.to/codechunker/what-you-need-to-know-about-leetcode-s-count-and-say-my-thought-process-as-a-beginner-4e0d</guid>
      <description>&lt;p&gt;This is another &lt;a href="https://medium.com/@codechunkers/what-you-need-to-know-about-leetcodes-count-and-say-my-thought-process-as-a-beginner-9d531fb1639b"&gt;Leetcode Problem&lt;/a&gt;: You are given an integer to generate the nth term of its count and say.The count and say is a way of reading off digits from the previous member. So 1 would read as “One 1” or 11 and 11 would read as “Two 1s” or 21 etc.&lt;/p&gt;

&lt;h1&gt;ALGORITHM&lt;/h1&gt;

&lt;p&gt;1.Get the first character of the string. This would serve as the previous;&lt;br&gt;
2.Loop through every other character (i.e from the next character after step 1). This would serve as the next character.&lt;br&gt;
3.Compare if step 1 and 2 (previous and next) are equal.&lt;br&gt;
4.If they are equal, increment the global counter.&lt;br&gt;
5.If they are not equal, append the current value of global counter and the previous character (in that order) into a global result StringBuilder. The previous character now becomes the current next character (previous = next). Then reset global counter (count = 1).&lt;br&gt;
6.Outside the loop, append the global counter and previous to the global result.This is majorly for edge cases.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;MY CODE&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Solution {
    public String countAndSay(int n) {
          if (n == 1)
            return "1";
        else {
            return doCounting(countAndSay(n - 1));
        }
    }

    private String doCounting(String value) {
        int length = value.length();
        int count = 1;
        StringBuilder result = new StringBuilder();
        int i;
        char previous = value.charAt(0);//initial
        for (i  = 1; i &amp;lt; length; i++) {
            char next = value.charAt(i);
            if (previous == next) {
                count++;
            }else {
                result.append(count).append(previous);
                previous = next;
                count = 1;//reset
            }
        }
        result.append(count).append(previous);

        return result.toString();
    }
}

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



&lt;p&gt;&lt;strong&gt;OUTCOME&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--AOvDAt3o--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1040/1%2AWSgEFt5g1xnbfDA0SCo4Eg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--AOvDAt3o--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/1040/1%2AWSgEFt5g1xnbfDA0SCo4Eg.png" alt="outcome image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;IMPROVEMENT&lt;/strong&gt;&lt;br&gt;
At first, the solution was a bit slower so I had to scan through to look for a way to make my solution a bit faster. Found out where I got it wrong: For every loop, I was calling value.length(). This should be reusable, so I initialized it to a variable. Did the same thing for charAt(i).&lt;br&gt;
After the cleanups, I got the above scores, which I feel is very OK.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LESSONS&lt;/strong&gt;&lt;br&gt;
Always initialize some library functions to variable to prevent calling it multiple times e.g, value.length(), value.charAt(i) etc. I’m sure you get the point. This also applies to Object creations or instances.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CONCLUSION&lt;/strong&gt;&lt;br&gt;
I hope you keep solving problems by chunking them. Please leave a comment, correction or suggestion (I'd really love that). Thank you.&lt;/p&gt;

</description>
      <category>algorithms</category>
      <category>tutorial</category>
      <category>datastructures</category>
      <category>codenewbie</category>
    </item>
  </channel>
</rss>
