<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Samyak Moon on Medium]]></title>
        <description><![CDATA[Stories by Samyak Moon on Medium]]></description>
        <link>https://medium.com/@samyakmoon855?source=rss-dcfb410276f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JF6M-2hEkIYhDq2IlcGRmA.png</url>
            <title>Stories by Samyak Moon on Medium</title>
            <link>https://medium.com/@samyakmoon855?source=rss-dcfb410276f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:15:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samyakmoon855/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Comprehensive Revision Guide for Binary Search]]></title>
            <link>https://medium.com/@samyakmoon855/a-comprehensive-revision-guide-for-binary-search-1da6cf245528?source=rss-dcfb410276f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1da6cf245528</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[searching]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Samyak Moon]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 08:11:35 GMT</pubDate>
            <atom:updated>2024-09-01T08:13:05.104Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p><strong>Binary search</strong> is a fundamental algorithm that efficiently finds the position of a target value within a sorted array. Unlike a linear search that checks each element one by one, binary search leverages the sorted nature of the array to eliminate half of the remaining elements with each step, leading to a much faster search time.</p><p>In this blog, we will dive deep into the concept of binary search, understand why it’s an essential tool in a programmer’s toolkit, and learn how to apply it correctly. We’ll explore the different scenarios where binary search is applicable, discuss the critical aspects of implementing the algorithm, and cover common pitfalls, such as boundary conditions and overflow issues. By the end of this blog, you’ll have a solid understanding of how binary search works and how to use it effectively in your coding endeavors.</p><h3>What is Binary Search?</h3><p>Binary search is an algorithm that finds the position of a target value within a sorted array by repeatedly dividing the search interval in half.</p><ol><li>If the target value is less than the midpoint of the interval, the search continues in the left half</li><li>If it’s greater, the search continues in the right half.</li></ol><p>This halving process continues until the target value is found or the search interval is empty.</p><h3>Why Binary Search is Needed</h3><p>In computer science, efficiency is crucial, especially when dealing with large datasets. A linear search on an unsorted array requires <strong>O(n)</strong> time complexity, meaning the time it takes to find an element grows linearly with the size of the array. In contrast, binary search operates with <strong>O(logn)</strong> time complexity, making it significantly faster for large datasets. This efficiency makes binary search a preferred choice in scenarios where fast data retrieval is essential.</p><h3>Criteria for Using Binary Search</h3><p>To apply binary search effectively, certain criteria must be met:</p><ol><li><strong>Sorted Data:</strong> The array or list must be sorted. Binary search relies on the fact that you can discard half of the elements based on comparisons.</li><li><strong>Random Access:</strong> The data structure must allow direct access to elements using indices. Arrays are ideal for binary search, whereas linked lists are not.</li><li><strong>Deterministic Order:</strong> The elements must follow a deterministic order, meaning they should be comparable.</li></ol><h3>How to Apply Binary Search</h3><p>Applying binary search involves setting up pointers (low and high) to the beginning and end of the array and repeatedly narrowing down the search range based on comparisons with the midpoint (mid). Here&#39;s a step-by-step explanation of the binary search algorithm:</p><ol><li><strong>Initialization:</strong> Set low to 0 and high to the last index of the array.</li><li><strong>Midpoint Calculation:</strong> Calculate the midpoint index as mid = low + (high - low) / 2.</li><li><strong>Comparison:</strong> Compare the target value with the element at mid.</li></ol><ul><li>If the target is equal to nums[mid], return mid.</li><li>If the target is less than nums[mid], update high to mid - 1 (search the left half).</li><li>If the target is greater than nums[mid], update low to mid + 1 (search the right half).</li></ul><p>4.<strong> Loop:</strong> Repeat the process until low exceeds high. If the target is not found, return -1.</p><h3>When to Use low &lt;= high and When to Use low &lt; high</h3><ul><li><strong>Use </strong><strong>low &lt;= high:</strong> When you want to ensure that every possible element in the search range is considered, including when low equals high. This is typically used when searching for an exact match or when you&#39;re sure the target exists within the search range.</li><li><strong>Use </strong><strong>low &lt; high:</strong> When you want the loop to stop as soon as the search space is reduced to a single element. This approach is often used in optimization problems, such as finding boundaries or conditions where you don&#39;t need to check the final element explicitly.</li></ul><p>The choice between using &lt;= or &lt; in the condition of a binary search loop is closely related to how you define the search interval during the algorithm.</p><h4>Understanding the Search Interval</h4><ol><li><strong>Closed Interval [low, high]:</strong></li></ol><ul><li>When you use low &lt;= high, you&#39;re working within a closed interval, meaning both low and high are valid search indices. The interval includes both endpoints.</li><li>This ensures that every possible index within the range, including the last index where low == high, is considered during the search.</li></ul><p>2.<strong> Half-Open Interval [left, right):</strong></p><ul><li>When you use low &lt; high, you&#39;re working within a half-open interval, meaning left is inclusive, but high is exclusive. The interval does not include the high endpoint.</li><li>This approach may lead to the scenario where the search space narrows down to a single element, but the loop stops just before considering it.</li></ul><h3>Why We Should Use mid = low + (high - low) / 2 and Not mid = (low + high) / 2</h3><p>The formula mid = (low + high) / 2 can lead to overflow errors in languages where the maximum integer size is limited. For instance, if low and high are large values, their sum could exceed the maximum value an integer can hold, leading to incorrect results or runtime errors.</p><p>To avoid this, we use mid = low + (high - low) / 2. This formula effectively calculates the midpoint without the risk of overflow, ensuring that the binary search operates correctly even with large input sizes.</p><p>Consider the situation where you are performing a binary search on a sorted array, and you need to calculate the midpoint (mid) of the search range. The formula you&#39;re using to calculate mid is:</p><pre>mid = (low + high) / 2;</pre><h4>Potential Overflow Issue</h4><p>Imagine that low and high are large integers. For example:</p><ul><li>low = 2,000,000,000</li><li>high = 2,000,000,001</li></ul><p>Now, let’s calculate the midpoint using the formula mid = (low + high) / 2.</p><ol><li><strong>First Calculation: </strong>low + high = 2,000,000,000 + 2,000,000,001 = 4,000,000,001</li><li><strong>Division: </strong>mid = 4,000,000,001 / 2 = 2,000,000,000.5</li></ol><p>Since mid is supposed to be an integer, it would be truncated to 2,000,000,000.</p><p>But the real problem here isn’t the truncation; it’s that low + high might exceed the maximum value an integer can hold, depending on the programming language you’re using.</p><h4>Integer Overflow Example</h4><p>In languages like Java, the maximum value for an integer is 2,147,483,647 (Integer.MAX_VALUE). If the sum of low and high exceeds this value, an overflow occurs, leading to incorrect calculations.</p><p>In example:</p><ul><li>4,000,000,001 &gt; 2,147,483,647</li></ul><p>This would cause an overflow, meaning that low + high does not store 4,000,000,001 but instead wraps around to a negative number or another incorrect value, leading to unpredictable results.</p><p><strong>Safe Calculation Using </strong><strong>mid = low + (high - low) / 2</strong></p><p>To avoid overflow, we use:</p><pre>mid = low + (high - low) / 2;</pre><p>Let’s break it down with our previous values:</p><ol><li><strong>First Calculation: </strong>high - low = 2,000,000,001 - 2,000,000,000 = 1</li><li><strong>Division: </strong>(high - low) / 2 = 1 / 2 = 0 (since we’re dealing with integer division)</li><li><strong>Final Calculation: </strong>mid = 2,000,000,000 + 0 = 2,000,000,000</li></ol><p>In this case, the calculation doesn’t involve adding two large numbers, so there’s no risk of overflow. The formula safely computes the midpoint without exceeding the integer limits, ensuring the binary search operates correctly.</p><h3>Binary Search Variants: Code Examples and Explanation</h3><h4>1. Binary Search (Iterative)</h4><p><strong>Problem Introduction</strong>:<br>The iterative binary search is a classic method to find the index of a target value in a sorted array. It reduces the search space by half in each iteration.</p><p><strong>Code Implementation</strong>:</p><pre>public int binarySearchIterative(int[] nums, int target) {<br>    int low = 0, high = nums.length - 1;<br>    while (low &lt;= high) {<br>        int mid = low + (high - low) / 2;<br>        if (nums[mid] == target)<br>            return mid;<br>        if (nums[mid] &gt; target) {<br>            high = mid - 1;<br>        } else {<br>            low = mid + 1;<br>        }<br>    }<br>    return -1;<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>The algorithm starts by initializing low and high to represent the search range.</li><li>The midpoint mid is calculated to split the array.</li><li>If nums[mid] equals the target, the index mid is returned.</li><li>If the target is less than nums[mid], the search space is reduced to the left half; otherwise, the right half is explored.</li><li>The loop continues until low exceeds high, indicating the target is not present in the array, and -1 is returned.</li></ul><p><strong>Time Complexity:</strong> O(logN)<br><strong>Space Complexity:</strong> O(1)</p><h4>2. Binary Search (Recursive)</h4><p><strong>Problem Introduction</strong>:<br>The recursive version of binary search works similarly to the iterative one, but it uses function calls to handle the repeated halving of the search space.</p><p><strong>Code Implementation</strong>:</p><pre>public int binarySearchRecursive(int[] nums, int low, int high, int target) {<br>    if (low &gt; high)<br>        return -1;<br>    int mid = low + (high - low) / 2;<br>    if (nums[mid] == target)<br>        return mid;<br>    else if (nums[mid] &gt; target)<br>        return binarySearchRecursive(nums, low, mid - 1, target);<br>    else<br>        return binarySearchRecursive(nums, mid + 1, high, target);<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>The base case is when low exceeds high, indicating the target is not found.</li><li>The midpoint mid is calculated, and the function checks if nums[mid] is the target.</li><li>If the target is smaller, the function recursively searches the left half; otherwise, it searches the right half.</li><li>The recursion continues until the target is found or the search space is exhausted.</li></ul><p><strong>Time Complexity:</strong> O(logN)<br><strong>Space Complexity:</strong> O(logN)</p><h4>3. Binary Search for First Occurrence</h4><p><strong>Problem Introduction</strong>:<br>This variant of binary search finds the first occurrence of a target element in a sorted array, even if the target appears multiple times.</p><p><strong>Code Implementation</strong>:</p><pre>public int firstOccurrence(int[] nums, int target) {<br>    int low = 0, high = nums.length - 1;<br>    int result = -1;<br>    while (low &lt;= high) {<br>        int mid = low + (high - low) / 2;<br>        if (nums[mid] == target) {<br>            result = mid;<br>            high = mid - 1; // Search in left half to find First Occurrence<br>        } else if (nums[mid] &gt; target) {<br>            high = mid - 1;<br>        } else {<br>            low = mid + 1;<br>        }<br>    }<br>    return result;<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>The search starts like a typical binary search, but when the target is found at mid, it records mid as the potential first occurrence.</li><li>To ensure it’s the first occurrence, the search continues in the left half by adjusting high.</li><li>The process repeats until all possible positions are checked, and the first occurrence is returned.</li></ul><p><strong>Time Complexity:</strong> O(logN)<br><strong>Space Complexity:</strong> O(1)</p><h3>4. Binary Search for Last Occurrence</h3><p><strong>Problem Introduction</strong>:<br>This binary search variant finds the last occurrence of a target element in a sorted array where the target may appear multiple times.</p><p><strong>Code Implementation</strong>:</p><pre>public int lastOccurrence(int[] nums, int target) {<br>    int low = 0, high = nums.length - 1;<br>    int result = -1;<br>    while (low &lt;= high) {<br>        int mid = low + (high - low) / 2;<br>        if (nums[mid] == target) {<br>            result = mid;<br>            low = mid + 1; // Search in right half to find Last Occurrence<br>        } else if (nums[mid] &gt; target) {<br>            high = mid - 1;<br>        } else {<br>            low = mid + 1;<br>        }<br>    }<br>    return result;<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The algorithm works similarly to the first occurrence search but focuses on finding the last occurrence.</li><li>When the target is found at mid, the result is updated, and the search continues in the right half by adjusting low.</li><li>The process continues until the last occurrence is found and returned.</li></ul><p><strong>Time Complexity:</strong> O(logN)<br><strong>Space Complexity:</strong> O(1)</p><h4>5. Binary Search for Smallest Element Greater than Target (Lower Bound)</h4><p><strong>Problem Introduction</strong>:<br>This problem involves finding the smallest element in a sorted array that is greater than a given target value.</p><p><strong>Code Implementation</strong>:</p><pre>public int smallestElementGreaterThanTarget(int[] nums, int target) {<br>    int low = 0, high = nums.length - 1;<br>    int result = -1;<br>    while (low &lt;= high) {<br>        int mid = low + (high - low) / 2;<br>        if (nums[mid] &lt;= target) {<br>            low = mid + 1; // Search the right half<br>        } else {<br>            result = mid; // Potential answer found<br>            high = mid - 1; // Continue searching in the left half<br>        }<br>    }<br>    return result;<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>The algorithm searches for the smallest element greater than the target by checking the midpoint.</li><li>If nums[mid] is less than or equal to the target, the search space moves to the right.</li><li><strong>If </strong><strong>nums[mid] is greater than the target, it could be the answer, but the search continues in the left half to find the smallest possible value.</strong></li></ul><p><strong>Time Complexity:</strong> O(logN)<br><strong>Space Complexity:</strong> O(1)</p><h4>6. Binary Search for Largest Element Less than Target (Upper Bound)</h4><p><strong>Problem Introduction</strong>:<br>This problem involves finding the largest element in a sorted array that is less than a given target value.</p><p><strong>Code Implementation</strong>:</p><pre>public int largestElementSmallerThanTarget(int[] nums, int target) {<br>    int low = 0, high = nums.length - 1;<br>        int result = -1;<br><br>        while (low &lt;= high) {<br>            int mid = low + (high - low) / 2;<br>            if (nums[mid] &lt;= target) {<br>                result = mid;<br>                low = mid + 1;<br>            } else {<br>                high = mid - 1;<br>            }<br>        }<br>        return result;<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>The algorithm searches for the largest element smaller than the target by evaluating the midpoint.</li><li><strong>If </strong><strong>nums[mid] is less than equal to the target, it might be the answer, and the search continues to the right to find the largest possible value</strong>.</li><li>If nums[mid] is greater than or equal to the target, the search space moves to the left.</li></ul><p><strong>Time Complexity:</strong> O(logN)<br><strong>Space Complexity:</strong> O(1)</p><h4>7. Binary Search on a Rotated Sorted Array</h4><p><strong>Problem Introduction</strong>:<br>This variant is used to find an element in a rotated sorted array, where the rotation disrupts the typical increasing order.</p><p><strong>Code Implementation</strong>:</p><pre>public int rotatedSearch(int[] nums, int target) {<br>    int start = 0, end = nums.length - 1;<br>        while (start &lt;= end) {<br>            int mid = start + (end - start) / 2;<br>            if (nums[mid] == target)<br>                return mid;<br>            if (nums[start] &lt;= nums[mid]) {<br>                if (nums[start] &lt;= target &amp;&amp; nums[mid] &gt; target) {<br>                    end = mid - 1;<br>                } else {<br>                    start = mid + 1;<br>                }<br>            } else {<br>                if (nums[mid] &lt; target &amp;&amp; nums[end] &gt;= target) {<br>                    start = mid + 1;<br>                } else {<br>                    end = mid - 1;<br>                }<br>            }<br>        }<br>        return -1;<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>The array is divided into two parts by the rotation point, so the algorithm first checks which part is sorted.</li><li>If the left side is sorted and the target lies within its range, the search space is reduced to the left side.</li><li>If the right side is sorted and the target lies within its range, the search space is reduced to the right side.</li><li>The process continues until the target is found or the search space is exhausted.</li></ul><p><strong>Time Complexity:</strong> O(logN)<br><strong>Space Complexity:</strong> O(1)</p><h4>8. Binary Search in a 2D Matrix</h4><h4><strong>Variation 1: Fully Sorted Rows</strong></h4><p><strong>Problem Introduction</strong>:<br>In this problem, each row of a 2D matrix is sorted, and the first integer of each row is greater than the last integer of the previous row.</p><p>Ex: [[1,3,5,7],[10,11,16,20],[23,30,34,60]]</p><p><strong>Code Implementation</strong>:</p><pre>boolean bs(int[] nums,int target){<br>        int start = 0, end = nums.length-1;<br>        while(start&lt;=end){<br>            int mid = start+(end-start)/2;<br>            if(nums[mid]==target)<br>                return true;<br>            else if(nums[mid]&gt;target)<br>                end = mid -1;<br>            else<br>                start = mid+1;<br>        }<br>        return false;<br>    }<br><br>    public boolean searchMatrix(int[][] matrix, int target) {<br>        int top = 0, bottom = matrix.length-1;<br>        System.out.println(top+&quot; &quot;+bottom);<br>        int n = matrix[0].length;<br>        while(top&lt;=bottom){<br>            int mid = top+(bottom-top)/2;<br>            if(matrix[mid][0]&lt;=target &amp;&amp; matrix[mid][n-1]&gt;=target){<br>                System.out.println(mid);<br>                return bs(matrix[mid],target);<br>            }else if(matrix[mid][0]&gt;target)<br>                bottom = mid - 1;<br>            else<br>                top = mid+1;<br>        }<br><br>        return false;<br>    }</pre><p><strong>Explanation</strong>:</p><p><strong>Row Selection:</strong></p><ul><li>We start by defining top and bottom pointers to represent the first and last rows.</li><li>Using binary search, we narrow down the row where the target might reside. This is done by comparing the target with the first and last elements of the middle row (mid).</li></ul><p><strong>Element Search:</strong></p><ul><li>After identifying the row, we apply a standard binary search on this row to locate the target.</li></ul><p><strong>Time Complexity:</strong> O(log m) + O(log n)<br><strong>Space Complexity:</strong> O(1)</p><h4>Variation 2: Each Row Independently Sorted</h4><p><strong>Problem Introduction</strong>:<br>In this problem, each row of a 2D matrix is sorted, but the first integer of each row is not necessarily greater than the last integer of the previous row.</p><p>Ex: [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]]</p><p><strong>Code Implementation</strong>:</p><pre>public boolean searchMatrix2D(int[][] matrix, int target) {<br>    int row = matrix.length,col = matrix[0].length;<br>        int low = 0, high = col-1;<br>        while(low&lt;row &amp;&amp; high&gt;=0){<br>            if(matrix[low][high]==target)<br>                return true;<br>            else if(matrix[low][high]&gt;target)<br>                high--;<br>            else <br>                low++;<br>        }<br>     return false;<br>}<br></pre><p><strong>Explanation</strong>:</p><ul><li>Treat the 2D matrix as a flattened array where each index in the 1D array maps to a specific element in the 2D matrix.</li><li>The midElement is calculated using matrix[mid / col][mid % col].</li><li>Binary search is then applied as usual, adjusting low and high based on comparisons with midElement.</li><li>If the target is found, true is returned; otherwise, false is returned.</li></ul><p><strong>Time Complexity:</strong> O(logN)<br><strong>Space Complexity:</strong> O(1)</p><h4>9. Binary Search for Peak Element in Unimodal Array</h4><p><strong>Problem Introduction: <br></strong>Given a <strong>unimodal array</strong> (also known as a <strong>mountain array</strong>) where elements first strictly increase to a peak element and then strictly decrease, find and return the index of the peak element.</p><pre>public int peakIndexInMountainArray(int[] arr) {<br>        int low = 0, high = arr.length -1;<br>        <br>        while(low&lt;=high){<br>            int mid = low+(high-low)/2;<br>            if((mid-1&gt;=0 &amp;&amp; arr[mid]&gt;arr[mid-1]) &amp;&amp; (mid+1&lt;arr.length &amp;&amp; arr[mid]&gt;arr[mid+1])){<br>                return mid;<br>            }<br>            else if(arr[mid]&lt;arr[mid+1])<br>                low = mid+1;<br>            else<br>                high = mid-1;<br>        }<br>        return -1;<br>    }</pre><p><strong>Explanation:<br></strong>To find the peak element in a unimodal array, we use binary search:</p><p>If arr[mid] is greater than both its neighbors (arr[mid - 1] and arr[mid + 1]), mid is the peak.</p><p>If arr[mid] &lt; arr[mid + 1], move low to mid + 1. Otherwise, move high to mid - 1.</p><p><strong>Time Complexity:</strong> O(logN)<br><strong>Space Complexity:</strong> O(1)</p><h4><strong>10. Binary Search on Unbounded Array</strong></h4><p><strong>Steps to Implement Binary Search on an Unbounded Array</strong></p><ol><li><strong>Find the Range:</strong></li></ol><ul><li>Start with a small range, e.g., start = 0 and end = 1.</li><li>Double the range until end is greater than or equal to the target or you’ve reached the end of the array.</li></ul><p><strong>2. Perform Binary Search:</strong></p><ul><li>Once the range is determined, apply the standard binary search within this range.</li></ul><h3><strong>Problems to Practice</strong></h3><h4>Easy</h4><ul><li><a href="https://leetcode.com/problems/binary-search/">Search in a sorted array</a></li><li><a href="https://leetcode.com/problems/search-insert-position/">Search Insert postion</a></li><li><a href="https://leetcode.com/problems/search-a-2d-matrix/">Search A 2D Matrix</a></li><li><a href="https://leetcode.com/problems/sqrtx/">Sqrt(x)</a></li><li><a href="https://leetcode.com/problems/first-bad-version/">First Bad Version</a></li><li><a href="https://leetcode.com/problems/find-smallest-letter-greater-than-target/">Find Smallest Letter Greater Than Target</a></li><li><a href="https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/">Find Minimum in Rotated Sorted Array</a></li><li><a href="https://leetcode.com/problems/arranging-coins/">Arranging Coins</a></li></ul><h4>Medium</h4><ul><li><a href="https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/">Find First and Last Position of Element in Sorted Array</a></li><li><a href="https://leetcode.com/problems/peak-index-in-a-mountain-array/">Peak Index in a Mountain Array</a></li><li><a href="https://leetcode.com/problems/find-peak-element/">Find Peak Element</a></li><li><a href="https://leetcode.com/problems/minimum-speed-to-arrive-on-time/">Minimum Speed to Arrive on Time</a></li><li><a href="https://leetcode.com/problems/kth-missing-positive-number/">Kth Missing Positive Number</a></li><li><a href="https://leetcode.com/problems/search-in-rotated-sorted-array/">Search in Rotated Sorted Array</a></li><li><a href="https://leetcode.com/problems/nth-digit/">Nth Digit</a></li><li><a href="https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/">Find Minimum in Rotated Sorted Array</a></li><li><a href="https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/submissions/">Find Minimum in Rotated Sorted Array II</a></li><li><a href="https://leetcode.com/problems/koko-eating-bananas/">Koko Eating Bananas</a></li><li><a href="https://leetcode.com/problems/minimum-time-to-complete-trips/description/">Minimum Time to Complete Trips</a></li><li><a href="https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/description/">Kth Smallest element in a sorted matrix</a></li><li><a href="https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/">Minimum number of days to Make m bouquets</a></li><li><a href="https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/">Sum of mutated array closest to target</a></li><li><a href="https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/">Find the smallest Divisor given a threshold</a></li><li><a href="https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/">Capacity to ship packages within d days</a></li></ul><h4>Hard</h4><ul><li><a href="https://leetcode.com/problems/find-in-mountain-array/">Find in Mountain Array</a></li><li><a href="https://leetcode.com/problems/find-a-peak-element-ii/">Find a Peak Element II</a></li><li><a href="https://leetcode.com/problems/search-in-rotated-sorted-array-ii/">Search in Rotated Sorted Array II</a></li><li><a href="https://leetcode.com/problems/median-of-two-sorted-arrays/">Median of Two Sorted Arrays</a></li></ul><h3>Conclusion</h3><p>Binary search is a powerful algorithm that, when applied correctly, can drastically reduce the time complexity of search operations. Understanding the nuances of binary search, including when to use different loop conditions and how to calculate the midpoint safely, is crucial for any programmer looking to write efficient code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1da6cf245528" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup QA Server inVirtual Machine for Springboot Application]]></title>
            <link>https://medium.com/@samyakmoon855/setup-qa-server-invirtual-machine-for-springboot-application-82a5c57701a9?source=rss-dcfb410276f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/82a5c57701a9</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[ssh-keygen]]></category>
            <category><![CDATA[sonarqube]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Samyak Moon]]></dc:creator>
            <pubDate>Sun, 14 Jul 2024 10:54:23 GMT</pubDate>
            <atom:updated>2024-07-14T13:41:30.421Z</atom:updated>
            <content:encoded><![CDATA[<h3>Setup QA Server in Virtual Machine for Springboot Application</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45FH4i01jCUll5TTgyu6tQ.jpeg" /><figcaption>Deploy Springboot Application</figcaption></figure><h3>Introduction</h3><p>In today’s fast-paced software development environment, having a dedicated QA (Quality Assurance) server is crucial for testing applications before they go live. This guide demonstrates how to set up a QA server in an Ubuntu VM on a local machine for a Spring Boot application. By automating the deployment process using Jenkins, you can ensure consistent and reliable delivery of your application, making your development workflow more efficient and robust.</p><p>In this project, we will cover how to deploy a Spring Boot application onto an Ubuntu VM installed in UTM from your local machine via Jenkins. This will give you an insight on how you can setup an environment.</p><p>Setting up a QA server allows developers to test their applications in an environment that mimics the production server, ensuring that any issues can be identified and resolved before the application goes live. Automating the deployment process has several benefits:</p><ul><li><strong>Efficiency</strong>: Streamlines repetitive tasks, saving time and reducing manual errors.</li><li><strong>Consistency</strong>: Ensures that every deployment is carried out in the same way, reducing the risk of configuration discrepancies.</li><li><strong>Continuous Integration/Continuous Deployment (CI/CD)</strong>: Facilitates automatic testing and deployment of code changes.</li><li><strong>Code Quality</strong>: Integrates tools like SonarQube to maintain high code quality standards.</li><li><strong>Scalability</strong>: Allows for consistent deployments across different environments.</li></ul><p>These practices are essential for modern development workflows, promoting efficiency, reliability, and high-quality software delivery.</p><h3>Prerequisites</h3><p>Before diving into the setup, ensure you have the following:</p><ol><li><strong>Jenkins</strong>: Installed and configured on your local machine.</li><li><strong>Ubuntu VM</strong>: Running on UTM or any other virtualization tool.</li><li><strong>SonarQube</strong>: Installed for code quality checks.</li><li><strong>GitHub Repository</strong>: Hosting your Spring Boot application code.</li><li><strong>Jenkins Plugins</strong>: Git, Maven, SonarQube Scanner, SSH Agent.</li></ol><p><strong>Note</strong>: The installation commands in this guide for some operations are for macOS. For other operating systems, please search for the equivalent commands online.</p><h3>Step-by-Step Guide</h3><h4>Setting Up Jenkins</h4><ol><li>Install Jenkins</li></ol><pre>#Install Jenkins<br>$brew install jenkins-lts<br>#Start the service<br>$brew services start jenkins-lts<br><br>#Run jenkins<br>$jenkins-lts</pre><p>If jenkins-lts gives an error, manually start Jenkins with the following command:</p><pre>$java -Dmail.smtp.starttls.enable=true -jar /opt/homebrew/Cellar/jenkins-lts/2.452.3/libexec/jenkins.war --httpListenAddress=0.0.0.0 --httpPort=8080</pre><p>2. Install Required Plugins</p><ul><li>Navigate to Jenkins Dashboard &gt; Manage Jenkins &gt; Manage Plugins.</li><li>Install Git, Maven Integration, SonarQube Scanner, and SSH Agent plugins.</li></ul><h4>Setting up SonarQube</h4><h4>1. Download and Setup SonarQube</h4><ol><li>Download SonarQube from the official website.</li><li>Unzip the downloaded file.</li><li>Navigate to the bin directory specific to your OS and run the appropriate script to start SonarQube (.sh for Linux/Mac, StartSonar.bat for Windows).</li><li>Open your browser and go to <a href="http://localhost:9000.">http://localhost:9000.</a></li><li>Enter the default username/password (admin/admin) and create a new password.</li><li>Create a project and follow the prompts.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yvJBigWY3TwG0dIDW-mISg.png" /><figcaption>Create a local Project in SonarQube</figcaption></figure><h4>2. Generate a Project Token</h4><ol><li>In the project setup, choose “Use the global setting” and create the project.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QoxQS4DCWYgSibd3sV-nQ.png" /><figcaption>Choose Use the global setting</figcaption></figure><p>2. Generate a project token and click on Create project</p><p>3. Once, project is created you will see a page as below from there choose locally</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vvdqFlsp7ZAsWo4wGUZzJA.png" /><figcaption>Choose Locally</figcaption></figure><p>4. Next, Once you click locally you will come to this page, where you will generate a project token. Generate the token and copy it somewhere</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*verPHhPAaOsiuplpPszmdQ.png" /><figcaption>Generate Project Token</figcaption></figure><h4>3. Configure Jenkins for SonarQube</h4><ol><li>Go to Jenkins &gt; Manage Jenkins &gt; Credentials.</li><li>Create SonarQube credentials by adding the generated token in the “Secret” field.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKH8UqFpDDYYfBwYpVlI6A.png" /></figure><p>3. Go to Jenkins &gt; Manage Jenkins &gt; Configure System.</p><p>4. Fill in the name, Server URL (e.g., http://localhost:9000), and choose the credentials you created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqbcSknQit4hCfcUK40dWA.png" /></figure><p>5. Click Save and Apply.</p><h4><strong>Configure the Pipeline</strong></h4><p>Create a new Pipeline job in Jenkins:</p><ol><li><strong>Create a New Pipeline</strong>:</li></ol><ul><li>Go to Jenkins Dashboard &gt; New Item.</li><li>Enter the name (e.g., UserApp) and select Pipeline. Click OK.</li></ul><p><strong>2. Pipeline Script</strong>:</p><ul><li>Copy the following script into the Pipeline section:</li></ul><pre>pipeline {<br>    agent any<br>    environment {<br>        JAVA_HOME = &#39;/opt/homebrew/Cellar/openjdk@17/17.0.11&#39;<br>        SONARQUBE_TOKEN = credentials(&#39;sonar-token&#39;)<br>    }<br>    stages {<br>        stage(&#39;Clone Repository&#39;) {<br>            steps {<br>                git branch: &#39;main&#39;, url: &#39;https://github.com/samyak2405/Springboot-Application-Deployed-via-Jenkins-on-VM.git&#39;<br>            }<br>        }<br>        stage(&#39;Build&#39;) {<br>            steps {<br>                sh &#39;echo $JAVA_HOME&#39;<br>                dir(&#39;UserApp&#39;) {  <br>                    sh &#39;mvn clean install&#39;<br>                }<br>            }<br>        }<br>        stage(&#39;SonarQube Analysis&#39;) {<br>            steps {<br>                dir(&#39;UserApp&#39;) {<br>                    withSonarQubeEnv(&#39;SonarQube&#39;) { <br>                        sh &quot;mvn sonar:sonar -Dsonar.projectKey=UserApp -Dsonar.projectName=&#39;UserApp&#39; -Dsonar.host.url=http://localhost:9000 -Dsonar.login=${SONARQUBE_TOKEN}&quot;<br>                    }<br>                }<br>            }<br>        }<br>        stage(&#39;Deploy&#39;) {<br>            steps {<br>                sshagent([&#39;ubuntu&#39;]) {<br>                    sh &#39;&#39;&#39;<br>                    scp UserApp/target/UserApp-0.0.1-SNAPSHOT.jar ubuntu@192.168.64.2:/home/ubuntu/UserApplication/<br>                    ssh ubuntu@192.168.64.2 &#39;bash /home/ubuntu/UserApplication/start.sh&#39;<br>                    &#39;&#39;&#39;<br>                }<br>            }<br>        }<br>    }<br>    post {<br>        always {<br>            cleanWs()  // Clean workspace after the build<br>        }<br>    }<br>}</pre><p>This script automates the process of cloning the repository, building the project, performing code analysis, and deploying the application, ensuring a streamlined and repeatable CI/CD pipeline.</p><ul><li><strong>agent any</strong>: This tells Jenkins to run the pipeline on any available agent (node).</li><li><strong>environment</strong>: Defines environment variables for the pipeline.</li><li><strong>JAVA_HOME</strong>: Specifies the path to the JDK installation in your local environment.</li><li><strong>SONARQUBE_TOKEN</strong>: Retrieves the SonarQube token from Jenkins credentials, which is used for authenticating with the SonarQube server.</li></ul><h4>Stages</h4><p>The pipeline has several stages, each defining a specific part of the build and deployment process.</p><p><strong>Stage 1: Clone Repository</strong></p><ul><li><strong>stage(&#39;Clone Repository&#39;)</strong>: This stage checks out the source code from the Git repository.</li><li><strong>git</strong>: Uses the git step to clone the specified branch (&#39;main&#39;) from the given repository URL.</li></ul><p><strong>Stage 2: Build</strong></p><ul><li><strong>stage(&#39;Build&#39;)</strong>: This stage builds the project.</li><li><strong>sh &#39;echo $JAVA_HOME&#39;</strong>: Prints the JAVA_HOME environment variable to ensure it&#39;s set correctly.</li><li><strong>dir(&#39;UserApp&#39;)</strong>: Changes the current directory to UserApp.</li><li><strong>sh &#39;mvn clean install&#39;</strong>: Runs the Maven command to clean the project and install dependencies, compiling the project and packaging it into a JAR file.</li></ul><p><strong>Stage 3: SonarQube Analysis</strong></p><ul><li><strong>stage(&#39;SonarQube Analysis&#39;)</strong>: This stage performs static code analysis using SonarQube.</li><li><strong>dir(&#39;UserApp&#39;)</strong>: Changes the current directory to UserApp.</li><li><strong>withSonarQubeEnv(&#39;SonarQube&#39;)</strong>: Sets up the environment for SonarQube analysis.</li><li><strong>sh &quot;mvn sonar:sonar -Dsonar.projectKey=UserApp -Dsonar.projectName=&#39;UserApp&#39; -Dsonar.host.url=http://localhost:9000 -Dsonar.login=${SONARQUBE_TOKEN}&quot;</strong>: Runs the SonarQube analysis using Maven with the specified project key, project name, SonarQube server URL, and authentication token.</li></ul><p><strong>Stage 4: Deploy</strong></p><ul><li><strong>stage(&#39;Deploy&#39;)</strong>: This stage handles the deployment of the application.</li><li><strong>sshagent([&#39;ubuntu&#39;])</strong>: Uses SSH agent with credentials labeled &#39;ubuntu&#39; for secure SSH operations.</li><li><strong>sh</strong>: Executes shell commands to deploy the application.</li><li><strong>scp UserApp/target/UserApp-0.0.1-SNAPSHOT.jar ubuntu@192.168.64.2:/home/ubuntu/UserApplication/</strong>: Copies the generated JAR file to the remote server.</li><li><strong>ssh ubuntu@192.168.64.2 &#39;bash /home/ubuntu/UserApplication/start.sh&#39;</strong>: Connects to the remote server and executes a script to start the application.</li></ul><h4>Post Actions</h4><ul><li><strong>post { always { cleanWs() } }</strong>: This section defines actions to be taken after the stages are completed.</li><li><strong>always</strong>: Ensures the action is executed regardless of the build result (success, failure, or unstable).</li><li><strong>cleanWs()</strong>: Cleans up the workspace, removing all files generated during the build process to free up space.</li></ul><h3>SSH Access to the Ubuntu Server</h3><p>To deploy your application, you need to securely access your Ubuntu server from your local machine. Here’s how to set up and use SSH to connect to your Ubuntu server.</p><ol><li><strong>Generate SSH Key Pair</strong>: Open a terminal on your local machine and run:</li></ol><pre>$ssh-keygen -t rsa -b 4096 -C &quot;your_email@example.com&quot;</pre><ul><li>Replace your_email@example.com with your mail id.</li><li>When prompted, choose a file location (default is ~/.ssh/id_rsa) and enter a passphrase if desired.</li></ul><p><strong>2. Add SSH Key to SSH Agent</strong>: Start the SSH agent in the background:</p><pre>eval &quot;$(ssh-agent -s)&quot;</pre><ul><li>Add your SSH private key to the SSH agent:</li></ul><pre>ssh-add ~/.ssh/id_rsa</pre><p><strong>3. Copy SSH Key to Ubuntu Server</strong>: Use the ssh-copy-id command to copy your public key to the Ubuntu server:</p><pre>ssh-copy-id ubuntu@192.168.64.2</pre><p>Enter the password for the ubuntu user when prompted.</p><ol><li><strong>Verify SSH Access</strong>: To ensure that the setup is successful, try SSH’ing into the Ubuntu server without a password prompt:</li></ol><pre>$ssh ubuntu@192.168.64.2</pre><ul><li>You should be logged in to the server without being asked for a password.</li></ul><ol><li><strong>Add SSH Credentials in Jenkins</strong>:</li></ol><ul><li>Go to Jenkins Dashboard &gt; Manage Jenkins &gt; Manage Credentials.</li><li>Add a new SSH Username with private key.</li><li>Enter the ID (e.g., ubuntu), Username (e.g., ubuntu), and paste the content of your private key (~/.ssh/id_rsa).</li></ul><p><strong>Note</strong>: Ensure you paste the entire content of the private key starting from the start tag till the end tag.</p><h4>Ubuntu Setup to run the Springboot application</h4><ol><li>Setup Ubuntu on Mac using UTM or any other virtualization software</li></ol><p>2. Install Java using below command (for Ubuntu)</p><pre>$sudo apt update<br>$sudo apt install <br>#Install Java<br>$apt install openjdk-17-jdk openjdk-17-jre<br>#Verify Java Installation<br>$java -version</pre><p>3. Install and configure MySQL</p><pre>$ sudo apt update<br>$ sudo apt install mysql-server<br>$ sudo systemctl start mysql.service<br>$ sudo systemctl status mysql.service</pre><p>If the status is inactive, resolve the error and try again:</p><pre>$ sudo mysql<br>$ mysql&gt; CREATE USER &#39;your_username&#39;@&#39;localhost&#39; IDENTIFIED WITH mysql_native_password BY &#39;your_password&#39;;<br>$ mysql&gt; GRANT ALL PRIVILEGES ON *.* TO &#39;sammy&#39;@&#39;localhost&#39; WITH GRANT OPTION;<br>$ mysql&gt; FLUSH PRIVILEGES;<br>$ mysql&gt; exit<br>$ sudo mysql -u root -p</pre><p>To allow remote connections, add the below line in the mysqld.conf file present in the MySQL installation directory (/etc/mysql/):</p><pre>bind-address = 0.0.0.0</pre><p>4. Get the IP of Ubuntu machine using below command</p><pre>$ifconfig</pre><h3>Create Project Deployment Folder</h3><ol><li>Create a folder (here UserApplication) which contains the start.sh script and application-qa.yml file.</li><li>When we trigger a build and if it’s successful, the jar will be deployed in this folder and the application will run with the help of the start.sh file and configurations as specified in application-qa.yml.</li><li>In the Springboot application, keep the application.yml file outside of the src folder. Externalizing the application.yml file enhances security and flexibility by separating configuration from code, allowing for environment-specific settings and dynamic updates without redeployment. This approach supports efficient and secure CI/CD pipelines, ensuring consistent and reliable application delivery.</li></ol><h4>Project Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4pYUYXXWuvuaJxpQ0h5Kg.png" /></figure><h4>application-qa.yml File</h4><p>Place this file by creating a config directory in the UserApplication folder of Ubuntu Server:</p><pre>spring:<br>  application:<br>  name: UserApp<br>  datasource:<br>    url: jdbc:mysql://{UBUNTU_VM_IP}:3306/userdb?allowPublicKeyRetrieval=true&amp;useSSL=false<br>    username: {MYSQL_USERNAME}<br>    password: {MYSQL_PASSWORD}<br>  jpa:<br>    hibernate:<br>      ddl-auto: update<br><br>    properties:<br>      hibernate:<br>        dialect: org.hibernate.dialect.MySQL8Dialect<br>        naming:<br>          physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl<br>        format-sql: true<br>    show-sql: true<br><br>server:<br>  port: 8090<br><br></pre><p>Replace the IP of mysql db with the IP of your Ubuntu VM.</p><p><strong>start.sh file: </strong>place this file in UserApplication folder</p><pre>#!/bin/bash<br><br># Path to the JAR file<br>JAR_PATH=&quot;/home/ubuntu/UserApplication/UserApp-0.0.1-SNAPSHOT.jar&quot;<br><br># Path to the log file<br>LOG_FILE=&quot;/home/ubuntu/UserApplication/application.log&quot;<br><br>CONFIG_PATH=&quot;/home/ubuntu/UserApplication/config/application-qa.yml&quot;<br><br># Java options (you can add JVM options here)<br>JAVA_OPTS=&quot;-Xms512m -Xmx1024m&quot;<br><br># Start the Spring Boot application<br>echo &quot;Starting the Spring Boot application...&quot;<br>nohup java $JAVA_OPTS -jar $JAR_PATH --spring.config.location=$CONFIG_PATH &gt; $LOG_FILE 2&gt;&amp;1 &amp;<br># Print the process ID<br>echo &quot;Spring Boot application started with PID $!&quot;</pre><h3><strong>Trigger the Build</strong></h3><p>Once you click on “Build Now” in Jenkins(Inside your created pipeline), your build will be triggered and go through stages that you have configured in script. If every stage is successful, the application will be deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fTTUoe1al-Nv9PJRkBGrA.png" /></figure><p>You can access your application URL from the QA Server(Ubuntu VM)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gn7EOLQNXbcdc4Nz2J3M8g.png" /><figcaption>Application URL from QA Server</figcaption></figure><p>To see your SonarQube report, go to http://localhost:9000 and select the project that you have configured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6o3Xvu3wRZNo_zw4MMbU3w.png" /><figcaption>SonarQube Report</figcaption></figure><h3><strong>Conclusion</strong></h3><p>By following this guide, you have set up a dedicated QA server for your Spring Boot application in an Ubuntu VM, automated the deployment process using Jenkins, and integrated code quality checks using SonarQube. This setup ensures a streamlined, consistent, and reliable CI/CD pipeline, enhancing your development workflow’s efficiency and reliability.</p><p>You can further enhance your CI/CD pipeline by adding more stages such as:</p><ul><li><strong>Unit Testing</strong>: Automatically run unit tests to ensure code quality and functionality before deployment.</li><li><strong>Integration Testing</strong>: Verify that different parts of the application work together as expected.</li><li><strong>Performance Testing</strong>: Ensure that the application performs well under load and meets performance requirements.</li><li><strong>Security Scanning</strong>: Check for vulnerabilities and security issues in the codebase.</li><li><strong>Deployment to Staging</strong>: Deploy the application to a staging environment for further testing before production.</li><li><strong>Notification</strong>: Send notifications (e.g., via email or Slack) to the team about the build and deployment status.</li><li><strong>Rollback</strong>: Implement a rollback mechanism in case the deployment fails or issues are detected.</li></ul><p>By incorporating these additional stages, you can further improve the robustness and quality of your deployment pipeline.</p><p><strong>You can find code, scripts and configuration files in the Github Repo: </strong><a href="https://github.com/samyak2405/Springboot-Application-Deployed-via-Jenkins-on-VM"><strong>here</strong></a></p><blockquote><strong><em>If you have any doubts or any suggestion please feel free to comment, and if you liked it please do clap and follow for more</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82a5c57701a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Packaging Explained: Choosing the Right Format for Application]]></title>
            <link>https://medium.com/@samyakmoon855/java-packaging-explained-choosing-the-right-format-for-application-bccbb33d3673?source=rss-dcfb410276f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bccbb33d3673</guid>
            <category><![CDATA[package]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[core-java]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <dc:creator><![CDATA[Samyak Moon]]></dc:creator>
            <pubDate>Fri, 31 May 2024 19:37:28 GMT</pubDate>
            <atom:updated>2024-05-31T19:37:28.609Z</atom:updated>
            <content:encoded><![CDATA[<p>Packaging your Java application correctly is a crucial step to ensure smooth deployment and distribution. Java offers several packaging formats, each tailored to specific types of applications and use cases. In this blog, we’ll look into the main types of Java packaging services: JAR, WAR, EAR, and JMOD, explaining their purposes, use cases, structures, creation methods, and deployment processes.</p><h3>1. JAR (Java Archive)</h3><h4>Purpose:</h4><p>A JAR (Java Archive) file is designed to bundle Java classes, metadata, and resources like text files and images into a single, compressed file. This simplifies the distribution and deployment of Java applications and libraries.</p><h4>Use Case:</h4><p>JAR files are widely used for both libraries and standalone Java applications. They can encapsulate a set of reusable classes or a complete application.</p><h4>Structure:</h4><p>A typical JAR file includes:</p><ul><li>META-INF directory: Contains the MANIFEST.MF file, which can specify the entry point (main class) and classpath dependencies.</li><li>Java class files and resources.</li></ul><h4>Creation:</h4><p>JAR files are created using the jar tool included in the JDK. For example:</p><pre>jar cf myApp.jar -C bin .</pre><p>This command creates a JAR file named myApp.jar from the contents of the bin directory.</p><h4>Execution:</h4><p>Executable JAR files can be run directly if they specify a main class in the manifest:</p><pre>java -jar myApp.jar</pre><h3>2. WAR (Web Application Archive)</h3><h4>Purpose:</h4><p>A WAR (Web Application Archive) file packages web applications to be deployed on a servlet container or application server. It is tailored for web-based Java applications.</p><h4>Use Case:</h4><p>WAR files are used for Java web applications built using servlets and JSPs (JavaServer Pages).</p><h4>Structure:</h4><p>A typical WAR file includes:</p><ul><li>WEB-INF directory: Contains the web.xml deployment descriptor, classes, libraries (in the lib folder), and other resources.</li><li>Static resources: HTML, CSS, and JavaScript files in the root directory.</li></ul><h4>Creation:</h4><p>WAR files are often created using build tools like Maven or Gradle:</p><ul><li>Maven</li></ul><pre>mvn package</pre><ul><li>Gradle</li></ul><pre>gradle assemble</pre><h4>Deployment:</h4><p>WAR files are deployed on web servers such as Apache Tomcat, Jetty, or on application servers like GlassFish and JBoss. Simply copy the WAR file to the deployment directory of the server.</p><h3>3. EAR (Enterprise Archive)</h3><h4>Purpose:</h4><p>An EAR (Enterprise Archive) file is designed for large-scale enterprise applications. It can bundle multiple modules, such as EJB (Enterprise JavaBeans) and web modules, into a single file for unified deployment.</p><h4>Use Case:</h4><p>EAR files are ideal for complex enterprise applications that combine various components (EJBs, web modules, etc.) and need centralized management.</p><h4>Structure:</h4><p>A typical EAR file includes:</p><ul><li>META-INF directory: Contains the application.xml deployment descriptor.</li><li>JAR files: For EJB modules.</li><li>WAR files: For web modules.</li><li>Additional resources.</li></ul><h4>Creation:</h4><p>EAR files are created using build tools with special plugins for handling enterprise archives:</p><ul><li>Maven</li></ul><pre>mvn package</pre><ul><li>Gradle</li></ul><pre>gradle assemble</pre><h4>Deployment:</h4><p>EAR files are deployed on application servers like JBoss, WebSphere, or WebLogic. These servers provide comprehensive support for managing and running enterprise applications.</p><h3>4. JMOD (Java Module)</h3><h4>Purpose:</h4><p>JMOD files are used to package modules in the Java Platform Module System, introduced in Java 9. They are part of the modularization effort in Java to improve application maintainability and scalability.</p><h4>Use Case:</h4><p>JMOD files are suitable for modular Java applications where you need to package module definitions, classes, native libraries, and other resources in a modular fashion.</p><h4>Structure:</h4><p>A typical JMOD file includes:</p><ul><li>module-info.class: Contains module metadata.</li><li>Class files: Java bytecode.</li><li>Native libraries: Platform-specific code.</li><li>Configuration files and other resources.</li></ul><h4>Creation:</h4><p>JMOD files are created using the jmod tool included in the JDK:</p><pre>jmod create --class-path classes mymodule.jmod</pre><h4>Deployment:</h4><p>JMOD files are used within the context of the Java Module System and are typically managed by the JDK’s module loader. They are not intended for general application deployment like JAR, WAR, or EAR files, but rather for modularizing components within the JDK.</p><h3>Conclusion</h3><p>Choosing the right packaging format is crucial for the efficient distribution and deployment of your Java applications. Whether you’re building a simple library, a web application, a large enterprise system, or a modular application, Java’s packaging options (JAR, WAR, EAR, JMOD) provide the flexibility you need. By understanding the purpose, use case, structure, creation, and deployment processes for each format, you can ensure your applications are well-packaged and ready for deployment in their intended environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bccbb33d3673" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Roadmap: Your Complete DSA Preparation Guide]]></title>
            <link>https://medium.com/@samyakmoon855/leetcode-dsa-preperation-guide-eadc70123984?source=rss-dcfb410276f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/eadc70123984</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Samyak Moon]]></dc:creator>
            <pubDate>Tue, 14 May 2024 16:48:01 GMT</pubDate>
            <atom:updated>2024-05-15T02:54:06.829Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the LeetCode DSA Preparation Guide! This blog is a curated collection of valuable resources sourced from the LeetCode discussion forum, aimed at assisting individuals in their journey towards preparing Data Structures and Algorithms (DSA). Here, you’ll find a comprehensive compilation of links to articles covering various DSA topics, each handpicked to provide you with insights and strategies for effective preparation.</p><blockquote>A heartfelt thank you to all the dedicated authors who have contributed their time and expertise to create the invaluable content referenced in this guide. Your hard work and commitment have made these resources possible, and we are immensely grateful for your contributions to the learning community. Happy learning!</blockquote><h3>Important Patterns</h3><p>Here are some crucial patterns frequently asked in interviews and online assessments:</p><ul><li>Sliding Window: Fixed and variable-sized window problems on arrays and strings.</li><li>Island Problems: DFS/BFS or different traversals on grids.</li><li>Two Pointers: Including fast and slow pointer techniques.</li><li>Merge Intervals</li><li>Cyclic Sort: A vital sorting technique.</li><li>DFS and BFS</li><li>Two Heaps Problems: Such as finding the median in a stream.</li><li>Subset Problems</li><li>Subarray/Substring Problems: Utilizing hashing.</li><li>Binary Search</li><li>Bitwise XOR: Frequently asked in various online assessments.</li><li>Top k Elements</li><li>K-way Merge</li><li>Topological Sort</li><li>Bit Manipulation</li><li>Number Theory</li></ul><h3>Blogs for DSA Preparation</h3><p><strong>Note</strong>: There are multiple links available for each topic to aid in preparation. Feel free to choose the one that aligns best with your learning style and preparation journey, and practice it thoroughly.</p><h4><strong>1. Data Structure and Algorithm</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/2009997/How-to-get-started-with-DSA-and-practice-Leetcode-Efficiently">How to Prepare DSA</a></li><li><a href="https://leetcode.com/discuss/study-guide/494279/Comprehensive-Data-Structure-and-Algorithm-Study-Guide">Comprehensive Data Structure and Algorithm Study Guide</a></li><li><a href="https://leetcode.com/discuss/study-guide/1204393/Algo-List">List of Important Algos for last minute prep</a></li><li><a href="https://leetcode.com/discuss/study-guide/448285/List-of-questions-sorted-by-common-patterns.">Leetcode List of various Questions sorted by Common patterns</a></li><li><a href="https://leetcode.com/discuss/study-guide/1612475/All-leetcode-discuss-lists-and-my-lists-so-far-topic-wisedifficulty-wise">All Leetcode discuss list and my list so far topic wise difficulty wise(MUST WATCH)</a></li><li><a href="https://leetcode.com/discuss/study-guide/1864255/topic">Leetcode List Collections</a></li><li><a href="https://emre.me/categories/#page-title">Various Types of patterns that exist (MUST READ)</a></li><li><a href="https://ujjwal3009.medium.com/leetcode-question-solved-with-common-pattern-leetcode-hacks-77345e439f78">Leetcode Question solved with common pattern</a></li></ol><h4><strong>2. C++ Standard Template Library (STL)</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1327203/C%2B%2B-STL-Guide-or-STL-Operations-and-Time-Complexities">STL Guide of STL Operations and TC</a></li><li><a href="https://leetcode.com/discuss/study-guide/1154632/C%2B%2B-STL-powerful-guide-or-Compiled-list-of-popular-STL-operations">STL Powerful guide or Compiled list of popular STL operations</a></li><li><a href="https://leetcode.com/discuss/study-guide/1387739/C%2B%2B-STL-Guide-or-Online-Coding-Rounds-or-Placements-2021-22">STL Guide for online Coding rounds or Placements 2021–22</a></li><li><a href="https://leetcode.com/discuss/study-guide/1359115/All-C%2B%2B-STL-internal-implementation-oror-last_minute_notes-oror-2021">STL Internal implementations</a></li></ol><h4><strong>3. Binary Search</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1233854/A-NOOB&#39;S-GUIDE-TO-THE-BINARY-SEARCH-ALGORITHM!!!">A Noobs Guide to the Binary Search Algorithm</a></li><li><a href="https://leetcode.com/discuss/study-guide/691825/Binary-Search-for-Beginners-Problems-or-Patterns-or-Sample-solutions">Binary Search Problems Patterns and Sample Solution</a></li><li><a href="https://leetcode.com/tag/binary-search/discuss/313216/Binary-search-Interview-Questions">Binary Search Interview Questions</a></li><li><a href="https://leetcode.com/tag/binary-search/discuss/1322500/5-variations-of-Binary-search-(A-Self-Note)">5 Variations of Binary Search(A self Note)</a></li><li><a href="https://leetcode.com/discuss/study-guide/2023248/Master-In-Binary-Search-oror-For-beginners-to-become-a-pro-oror-with-youtube-videos">Master in Binary Searh for Begineering to become a pro</a></li><li><a href="https://leetcode.com/discuss/study-guide/2371234/An-opinionated-guide-to-binary-search-(comprehensive-resource-with-a-bulletproof-template)">An opinionated guide to Binary search (Recommended)</a></li><li><a href="https://leetcode.com/discuss/study-guide/3266833/OP-Binary-Search-Questions">OP Binary Search Questions</a></li><li><a href="https://leetcode.com/discuss/study-guide/3726061/binary-search-a-comprehensive-guide">Binary Search a comprehensive guide</a></li></ol><h4><strong>4. String</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1333049/collections-of-string-questions-pattern-for-upcoming-placement-2021">Collection of String questions pattern for upcoming placement 2021</a></li><li><a href="https://leetcode.com/tag/string/discuss/2001789/Collections-of-Important-String-questions-Pattern">Collection of Important string questions patternwise</a></li><li>Must Do Parenthesis Problems<br>a. <a href="http://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/">Minimum Number of Swaps to Make the String Balanced</a><br>b. <a href="http://leetcode.com/problems/remove-invalid-parentheses/">Remove Invalid Parentheses</a><br>c. <a href="http://leetcode.com/problems/minimum-add-to-make-parentheses-valid/">Minimum Add to Make Parentheses Valid</a><br>d. <a href="http://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/">Minimum Remove to Make Valid Parentheses</a><br>e. <a href="http://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/">Minimum Insertions to Balance a Parentheses String</a></li></ol><h4><strong>5. Tree</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1820334/Become-Master-in-Tree">Become a master in Tree</a></li><li><a href="https://leetcode.com/discuss/study-guide/1337373/tree-question-pattern-2021-placement">Tree Questions for placement</a></li><li><a href="https://leetcode.com/discuss/study-guide/1212004/Binary-Trees-study-guide">Binary tree Study Guide</a></li><li><a href="https://leetcode.com/discuss/study-guide/1394782/Links-to-selected-LeetCode-questions-on-Trees">Link to selected leetcode questions on Trees</a></li><li><a href="https://leetcode.com/tag/binary-tree/discuss/1094690/Views-and-Traversal-of-binary-tree-or-Important-topics-or-Must-Read-%3A-">Views and Traversal of Binary tree or important topics (must read)</a></li></ol><h4><strong>6. Graph</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1808711/Graph-for-Beginners-Problems">Graph for Begineers Problems</a></li><li><a href="https://leetcode.com/discuss/study-guide/1326900/Graph-algorithms-%2B-problems-to-practice">Graph algorithms problems to practice</a></li><li><a href="https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/686774/suggestion-for-beginners-bfs-dijkshtra-dp">Cheapest flights within K stops(Must do)</a></li><li><a href="https://leetcode.com/discuss/study-guide/1072548/A-Beginners-guid-to-BFS-and-DFS">A begineers guide to BFS and DFS</a></li><li><a href="https://leetcode.com/discuss/study-guide/655708/Graph-For-Beginners-Problems-or-Pattern-or-Sample-Solutions">Graph for Begineers Problems pattern or sample solutions</a></li><li><a href="https://leetcode.com/discuss/study-guide/937307/Iterative-or-Recursive-or-DFS-and-BFS-Tree-Traversal-or-In-Pre-Post-and-LevelOrder-or-Views">Iterative or Recursive or DFS ,BFS Tree traversal IN-PRE-POST and LEVEL ORDER or Views</a></li><li><a href="https://leetcode.com/discuss/study-guide/969327/Graph-Algorithms-One-Place-or-Dijkstra-or-Bellman-Ford-or-Floyd-Warshall-or-Prims-or-Kruskals-or-DSU">Graph Algorithms One place or Dijkstra, Bellman Ford or Floyd Warshall or Prims or Kruskals or DSU</a></li><li><a href="https://leetcode.com/discuss/study-guide/1059477/A-noob&#39;s-guide-to-Dijkstra&#39;s-Algorithm">A noob’s guide to Dijkstra’s Algorithm</a></li><li><a href="https://leetcode.com/discuss/general-discussion/655708/Graph-For-Beginners-Problems-or-Pattern-or-Sample-Solutions">Graph for Begineers Problems or pattern or Sample Solutions</a></li><li><a href="https://leetcode.com/discuss/general-discussion/1116359/intro-to-floyds-cycle-detection-algorithm">Intro to floyds cycle detection algorithm</a></li><li><a href="https://leetcode.com/discuss/general-discussion/1078072/introduction-to-topological-sort">Introduction to topological sort</a></li><li><a href="https://leetcode.com/discuss/interview-question/731911/please-share-dijkstras-algorithm-questions">Dijkstra Questions</a></li><li><a href="https://leetcode.com/problems/satisfiability-of-equality-equations/">Question on Union Find</a></li></ol><h4><strong>7. Hashmap</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1068545/HASH-TABLE-and-MAP-POWERFUL-GUIDE-!!!">Hash table and map powerful guide</a></li></ol><h4><strong>8. Trie</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/680706/Article-on-Trie.-General-Template-and-List-of-problems.">Article on Trie General template and list of problems</a></li><li><a href="https://leetcode.com/discuss/study-guide/931977/Beginner-friendly-guide-to-Trie-Tutorial-%2B-Practice-Problems">Begineer friendly guide to Trie</a></li><li><a href="https://leetcode.com/discuss/general-discussion/1066206/introduction-to-trie">Introduction to Trie</a></li><li><a href="https://www.hackerearth.com/practice/data-structures/advanced-data-structures/trie-keyword-tree/practice-problems/1/?sort_by=partially%20solved&amp;p_level=">Hackerrank Practice problems on TRIE data structure(Questions on XOR are very important as they are asked in various online assesment rounds and Coding competitions)</a></li></ol><h4><strong>9. Sorting Alogrithm</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1091763/Must-do-all-required-Sorting-Algorithms%3A-Complete-Guide">Must do all required sorting algorithms</a></li><li><a href="https://leetcode.com/discuss/general-discussion/1088565/top-k-problems-sort-heap-and-quickselect">Top K problems sort heap and quickselect</a></li><li><a href="https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/138154/The-C%2B%2B-merge-sort-template-for-pairs-&#39;i&#39;-&#39;j&#39;-problem">Merge sort template for pair i,j problems (Most important)</a></li><li><a href="https://leetcode.com/discuss/general-discussion/547798/Static-Comparator-function-for-sort-(Reasons-as-to-why)">Static comparator function for sort reason why we use it?</a></li></ol><h4><strong>10. Greedy</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/669996/Greedy-for-Beginners-Problems-or-Sample-solutions">Greedy for Begineers problems or sample solutions</a></li></ol><h4><strong>11. Dynamic Programming</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1296872/Think-DP-How-I-approach-DP-problems-(Guide-for-Beginners)">How to approach a DP Problem</a></li><li><a href="https://leetcode.com/discuss/study-guide/662866/DP-for-Beginners-Problems-or-Patterns-or-Sample-Solutions">DP questions Pattern wise</a></li><li><a href="https://leetcode.com/discuss/study-guide/1000929/Solved-all-dynamic-programming-(dp)-problems-in-7-months.">Solved all DP problems in 7 months</a></li><li><a href="https://leetcode.com/discuss/study-guide/1050391/Must-do-Dynamic-programming-Problems-Category-wise">Must Do DP problems Category wise</a></li><li><a href="https://leetcode.com/discuss/study-guide/458695/Dynamic-Programming-Patterns">DP Patterns</a></li><li><a href="https://leetcode.com/discuss/study-guide/475924/My-experience-and-notes-for-learning-DP">My experience and notes for DP</a></li><li><a href="https://leetcode.com/discuss/study-guide/491522/Dynamic-Programming-Questions-Thread">DP questions Thread</a></li><li><a href="https://leetcode.com/discuss/study-guide/651719/How-to-solve-DP-String-Template-and-4-Steps-to-be-followed.">DP strings template and how to solve them</a></li><li><a href="https://leetcode.com/discuss/study-guide/1437879/Dynamic-Programming-Patterns">DP patterns</a></li><li><a href="https://leetcode.com/problems/house-robber/discuss/156523/From-good-to-great.-How-to-approach-most-of-DP-problems.">How to approach most of DP problems</a></li><li><a href="https://leetcode.com/discuss/study-guide/1490172/Dynamic-programming-is-simple">DP is simple</a></li><li><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/900050/Fully-explained-all-buy-and-sell-problems-C%2B%2B-oror-Recursive-oror-Memoization-oror-Minor-difference">Best time to buy and sell stocks</a></li><li><a href="https://leetcode.com/discuss/study-guide/2705056/Starting-your-DP-journey-Do-this-!!">Linear DP Questions</a></li></ol><h4><strong>12. Randomized Problem</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1334408/play-with-randomized-problems-get-out-fear-2021">Guide for randomized problems</a></li></ol><h4><strong>13. Sliding Window</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/657507/Sliding-Window-for-Beginners-Problems-or-Template-or-Sample-Solutions">Sliding window for begineers problems,templates and sample solutions</a></li><li><a href="https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/92007/Sliding-Window-algorithm-template-to-solve-all-the-Leetcode-substring-search-problem.">Sliding window template to solve all the leetcode substring search problems</a></li><li><a href="https://leetcode.com/problems/minimum-window-substring/discuss/26808/Here-is-a-10-line-template-that-can-solve-most-&#39;substring&#39;-problems">10 line template that can solve most substring problems</a></li><li><a href="https://leetcode.com/tag/array/discuss/1122776/Summary-of-Sliding-Window-Patterns-for-Subarray-Substring">Summary of sliding window patterns for subarray and substring</a></li><li><a href="https://leetcode.com/discuss/study-guide/3722472/Sliding-Window-Technique%3A-A-Comprehensive-Guide">Sliding Window Techniques A Commprehensive Guide</a></li></ol><h4><strong>14. Bit Manipulation</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1150415/Start-Bit-Manipulation-Here">Start bit manipulation here</a></li><li><a href="https://leetcode.com/discuss/study-guide/1151183/TIPS-or-HACKS-WHICH-YOU-CAN&#39;T-IGNORE-AS-A-CODER">TIPS and hacks which you can’t ignore as a coder</a></li><li><a href="https://graphics.stanford.edu/~seander/bithacks.html#">Stanford Blog for Bit hacks</a></li><li><a href="https://leetcode.com/discuss/interview-question/3695233/all-types-of-patterns-for-bits-manipulations-and-how-to-use-it">All types of patterns for bits manipulation</a></li></ol><h4><strong>15. Interview</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/698684/Interview-Preparation-for-Beginners-DS-or-Algorithms-or-OS-or-System-Design">Interview Prep for Begineers DS, Algo, OS and SD</a></li><li><a href="https://leetcode.com/discuss/study-guide/1098600/topics-which-you-cant-skip-interview-preparation-study-plan-using-leetcode">Topics which you cant skip interview prep study plan using Leetcode</a></li><li><a href="https://leetcode.com/discuss/study-guide/1177039/%22Practice-More-Learn-More%22-greater-Study-Guide-and-Interview-Preparation-Using-LEETCODE">Study Guide and Interview prep using Leetcode</a></li><li><a href="https://leetcode.com/discuss/study-guide/1098600/TOPICS-WHICH-YOU-CAN&#39;T-SKIP-INTERVIEW-PREPARATION-or-STUDY-PLAN-USING-LEETCODE">Topics which you cant skip interview prep or study plan using Leetcode</a></li><li><a href="https://leetcode.com/discuss/study-guide/1372500/Do-this-during-your-FAANG-interview-to-ace-it!">Do this during your FAANG interview to ace it</a></li><li><a href="https://leetcode.com/discuss/study-guide/1596831/Cleared-Google-L5-India-at-age-of-39-~-40">Cleared Google L5 India at the age of 39</a></li><li><a href="https://leetcode.com/discuss/study-guide/1568859/One-Stop-CN-guide-or-Useful-and-Short-topics-for-interviews-or-Computer-Networks">One stop CN guide or Useful and short topics for interview or CNs</a></li><li><a href="https://leetcode.com/discuss/interview-question/1898569/MetaFB-K-Closest-Points-to-Origin%3A-an-O(N)-avg.-timeO(1)-space-solution">K Closest Points to Origin</a></li><li><a href="https://leetcode.com/discuss/study-guide/2004928/Amazon-LP-Questions">Amazon LP Questions</a></li><li><a href="https://leetcode.com/discuss/study-guide/2106285/Journey-to-Google">Journey to Google</a></li><li><a href="https://leetcode.com/discuss/study-guide/2272161/Most-Important-topics-for-Interviews-or-CS-Core-topics">Most Important topics for Interviews or CS Core topics</a></li><li><a href="https://hackernoon.com/14-patterns-to-ace-any-coding-interview-question-c5bb3357f6ed">Patterns to ace any coding interview question</a></li><li><a href="https://leetcode.com/discuss/interview-question/2069641/The-Only-Lists-You-Need-For-Your-Interview-Preparation">The Only Lists you need for your Interview Prep</a></li><li><a href="https://leetcode.com/discuss/study-guide/2537468/INTUIT-SDE-SHEET-or-2023">Intuit SDE Sheet or 2023</a></li></ol><h4><strong>16. Random Tips</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1159129/RESUME-BUILDING-or-Things-we-read-but-ignore.">Resume Building Tips</a></li><li><a href="https://leetcode.com/discuss/general-discussion/1049269/understanding-how-numbers-are-stored-in-the-computer-using-only-0-and-1">How numbers are stored in computer using only 0 and 1</a></li><li><a href="https://leetcode.com/discuss/general-discussion/665604/Important-and-Useful-links-from-all-over-the-LeetCode">Important and useful links from all over the LeetCode</a></li><li><a href="https://leetcode.com/problems/make-sum-divisible-by-p/discuss/854895/how-to-approach-this-kind-of-problem-mind-map">Make sum divisible by p — How to approach this kind of problem mindmap</a></li><li><a href="https://leetcode.com/discuss/career/229177/My-System-Design-Template">My System Design Template</a></li><li><a href="https://leetcode.com/discuss/study-guide/2007535/Some-famous-posts-with-templates-and-suggested-patterns.">Some famous posts with templates and suggested patterns</a></li><li><a href="https://leetcode.com/discuss/interview-question/operating-system/124638/what-happens-in-the-background-from-the-time-you-press-the-Power-button-until-the-Linux-login-prompt-appears">What happens in the background from the time you press the Power button untill the Linux login prompt appears</a></li><li><a href="https://leetcode.com/discuss/study-guide/2122306/Python-Cheat-Sheet-for-Leetcode">Python Cheatsheet for Leetcode</a></li></ol><h4><strong>17. Backtracking</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1405817/Backtracking-algorithm-%2B-problems-to-practice">Backtracking algorithm problems to Practice</a></li><li><a href="https://leetcode.com/problems/combination-sum-iv/discuss/85120/C%2B%2B-template-for-ALL-Combination-Problem-Set">Template fir all Combination Problem Set</a></li><li><a href="https://leetcode.com/discuss/study-guide/2244368/Backtracking-for-Beginners-Problems">Backtracking for Begineers Problems</a></li></ol><h4><strong>18. Two Pointer Technique</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1688903/Solved-all-two-pointers-problems-in-100-days.">Solved all two pointers problems in 100 days</a></li><li><a href="https://leetcode.com/problems/subarray-sum-equals-k/discuss/301242/General-summary-of-what-kind-of-problem-can-cannot-solved-by-Two-Pointers">General summary of what kind of problem can and cannot be solved by Two Pointers</a></li></ol><h4><strong>19. Stack and Queue</strong></h4><ol><li><a href="https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/204290/Monotonic-Queue-Summary">Shortest subarray with sum atleast k- Monotonic Queue</a></li><li><a href="https://leetcode.com/problems/sum-of-subarray-minimums/discuss/178876/stack-solution-with-very-detailed-explanation-step-by-step">Sum of subarray minimum stack solution</a></li><li><a href="https://leetcode.com/discuss/study-guide/2347639/A-comprehensive-guide-and-template-for-monotonic-stack-based-problems">A comprehensive guide and template for monotonic stack based problems</a></li></ol><h4><strong>20. Prefix Sum</strong></h4><ol><li><a href="https://leetcode.com/discuss/general-discussion/563022/prefix-sum-problems">Prefix sum problems</a></li></ol><h4><strong>21. Recursion</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1733447/Become-Master-In-Recursion">Become master in Recursion</a></li></ol><h4><strong>22. Interval Problems</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1371455/Can-you-solve-interval-problems-No-Let&#39;s-practice!">Guide for interval problems</a></li><li><a href="https://leetcode.com/problems/merge-intervals/discuss/1644409/C%2B%2BPython-Simple-Solutions-w-Explanation-or-Sort-Merge-O(NlogN)-%2B-Count-Sort-O(N-%2B-R)">Merge intervals</a></li></ol><h4><strong>23. Reservoir Sampling</strong></h4><ol><li><a href="https://leetcode.com/problems/linked-list-random-node/discuss/85659/Brief-explanation-for-Reservoir-Sampling">Breif explanation for Reservoir sampling</a></li></ol><h4><strong>24. OOPS</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1852219/Object-Oriented-Programming-Made-Easy">OOP made easy</a></li><li><a href="https://leetcode.com/discuss/study-guide/1389824/One-Stop-OOP-Guide-or-Useful-and-Short-topics-for-interviews-or-Object-Oriented-Programming-(C%2B%2B)">One Stop OOP guide or useful and short topics for interviews or OOP</a></li><li><a href="https://leetcode.com/discuss/study-guide/2400588/Object-Oriented-Programming-(Oops)-for-Beginners-oror-Detail-Explained">OOP for Begineers</a></li></ol><h4><strong>25. Linked List</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/1800120/Become-Master-In-Linked-List">Become a Master in Linked List</a></li><li><a href="https://leetcode.com/problems/add-two-numbers/discuss/1340/a-summary-about-how-to-solve-linked-list-problem-c">A summary about how to solve linked list problem c</a></li><li><a href="https://medium.com/@tahichy48/linked-list-series-1c045f50e20d">Medium article on LinkedList</a></li></ol><h4><strong>26. Last Minute Prep</strong></h4><ol><li><a href="https://leetcode.com/discuss/interview-question/460599/Blind-75-LeetCode-Questions">Blind 75 Leetcode Questions (Must do of Leetcode-Highly recommended)</a></li></ol><h4><strong>27. Square root Decomposition</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/2432715/Tutorial-or-Square-root-decomposition-or-Dynamic-Range-Query">Sqaure root Decomposition</a></li></ol><h4><strong>28. Important Cyclic Sort Questions:</strong></h4><p><a href="https://leetcode.com/discuss/study-guide/1902662/Cyclic-Sort-(very-important-and-less-known-pattern)">Cyclic Sort blog(Credits to the author)</a></p><ol><li><a href="https://leetcode.com/problems/missing-number/">Missing Number</a></li><li><a href="https://leetcode.com/problems/find-all-duplicates-in-an-array/">Find All Duplicates</a></li><li><a href="https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/">Find All number disappearing in an array</a></li><li><a href="https://leetcode.com/problems/first-missing-positive/">First Missing number</a></li><li><a href="https://leetcode.com/problems/set-mismatch/">Set mismatch</a></li><li><a href="https://leetcode.com/problems/couples-holding-hands/">Couple Holding hands</a></li><li><a href="https://leetcode.com/problems/random-pick-with-blacklist/">Random Pick with blacklist</a></li></ol><h4><strong>29. Palindrome Problems</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/2259436/palindromic-problems-list-with-hints">Palindromic Problems with Hints</a></li></ol><h4><strong>30. Python</strong></h4><ol><li><a href="https://leetcode.com/discuss/study-guide/2713266/Python-Data-Structure-Guide-(Side-by-Side-Comparison-with-C%2B%2B)">DS in Python</a></li></ol><p>If You Know any Cool Post like this Feel free to add in comments. Let’s help each other grow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eadc70123984" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Inversion Principle]]></title>
            <link>https://medium.com/@samyakmoon855/dependency-inversion-principle-333482d2eb2e?source=rss-dcfb410276f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/333482d2eb2e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[solid-principles-in-java]]></category>
            <category><![CDATA[design-principles]]></category>
            <category><![CDATA[dependency-inversion]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Samyak Moon]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 12:00:17 GMT</pubDate>
            <atom:updated>2024-04-22T12:02:57.130Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>In the world of software development, building robust and maintainable applications is paramount. One approach to achieving this goal is through the SOLID principles, a set of five design principles that help guide developers toward creating more scalable and maintainable code. In this blog post, we’ll look into one of these principles, the Dependency Inversion Principle (DIP).</p><h3>What is the Dependency Inversion Principle (DIP)?</h3><p>The Dependency Inversion Principle is one of the SOLID principles in object-oriented programming. At its core, DIP suggests that:</p><ol><li>High-level modules should not depend on low-level modules. Both should depend on abstractions.</li><li>Abstractions should not depend on details. Details should depend on abstractions.</li></ol><p>In simpler terms, this principle advocates for coding to abstractions rather than concrete implementations. By doing so, we can achieve code that is more flexible, maintainable, and testable.</p><h3>Why Do We Need the Dependency Inversion Principle?</h3><p>Before diving into the implementation details, it’s essential to understand why DIP is crucial:</p><ol><li><strong>Flexibility</strong>: By depending on abstractions, we can easily swap out different implementations without affecting higher-level modules. This enables us to adapt to changing requirements or replace components with more efficient alternatives.</li><li><strong>Testability</strong>: Abstractions make it easier to mock dependencies in unit tests, facilitating more isolated and effective testing.</li><li><strong>Reduced Coupling</strong>: Following DIP reduces coupling between different modules in the codebase, making it easier to understand, maintain, and extend the application over time.</li></ol><p>Now, let’s explore how we can apply DIP in the context of an e-commerce application using Java.</p><h3>Example of DIP</h3><p>Let’s say in an e-commerce application, we’ve two main functionalities: managing products and processing orders. We’ll follow these steps to implement DIP:</p><ol><li>Define Interfaces: Create interfaces for managing products and processing orders.</li><li>Implement Concrete Classes: Provide concrete implementations for these interfaces.</li><li>Implement Higher-Level Modules: Develop higher-level modules that depend on these interfaces.</li><li>Use Dependency Injection: Inject concrete implementations into higher-level modules.</li></ol><p>Let’s dive into the implementation details:</p><h4>Step 1: Define Interfaces</h4><pre>// ProductRepositoryInterface.java<br>public interface ProductRepositoryInterface {<br>    Product getProduct(int productId);<br>}<br><br>// OrderServiceInterface.java<br>public interface OrderServiceInterface {<br>    void placeOrder(Order order);<br>}</pre><h4>Step 2: Implement Concrete Classes</h4><pre>// ProductRepository.java<br>public class ProductRepository implements ProductRepositoryInterface {<br>    @Override<br>    public Product getProduct(int productId) {<br>        // Implementation to fetch product from database<br>        return null;<br>    }<br>}<br><br>//OrderService.java<br>public class OrderService implements OrderServiceInterface {<br>    @Override<br>    public void placeOrder(Order order) {<br>        // Implementation to place order<br>    }<br>}</pre><h4>Step 3: Implement Higher-Level Modules</h4><pre>// OrderController.java<br>public class OrderController {<br>    private OrderServiceInterface orderService;<br><br>    public OrderController(OrderServiceInterface orderService) {<br>        this.orderService = orderService;<br>    }<br><br>    public void placeOrder(Order order) {<br>        // Call methods on orderService<br>        orderService.placeOrder(order);<br>    }<br>}</pre><h4>Step 4: Dependency Injection</h4><pre>// Main.java<br>public class Main {<br>    public static void main(String[] args) {<br>        // Create instances of concrete implementations<br>        ProductRepositoryInterface productRepository = new ProductRepository();<br>        OrderServiceInterface orderService = new OrderService();<br>        // Inject dependencies into higher-level modules<br>        OrderController orderController = new OrderController(orderService);<br>    }<br>}</pre><h3>Conclusion</h3><p>By adhering to the Dependency Inversion Principle, we’ve developed an e-commerce application in Java that is flexible, maintainable, and testable. We’ve demonstrated how coding to abstractions rather than concrete implementations leads to decoupled and extensible code, making it easier to adapt to changing requirements and enhance the application’s functionality over time.</p><p>Incorporating DIP into your software development process can significantly improve the quality and longevity of your codebase, ensuring that your applications remain robust and scalable as they evolve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=333482d2eb2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interface Segregation Principle]]></title>
            <link>https://medium.com/@samyakmoon855/interface-segregation-principle-57b7dbb4535d?source=rss-dcfb410276f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/57b7dbb4535d</guid>
            <category><![CDATA[design-principles]]></category>
            <category><![CDATA[solid-principles-in-java]]></category>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[maintainability]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Samyak Moon]]></dc:creator>
            <pubDate>Sun, 14 Jan 2024 07:29:24 GMT</pubDate>
            <atom:updated>2024-01-14T07:29:24.590Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, we delve into the Interface Segregation Principle(ISP), a crucial aspect of the SOLID principles in software design. Prior to exploring ISP, we’ve already covered the <a href="https://medium.com/@samyakmoon855/single-responsibility-principle-in-java-ec3dc5d5537b">Single Responsibility Principle</a>, <a href="https://medium.com/@samyakmoon855/open-closed-principle-cbe3e0de5128">Open/Closed Principle</a> and <a href="https://medium.com/@samyakmoon855/liskovs-substitution-principle-b1d415a5d15f">Liskov’s Substitution Principle</a>. These principles collectively play a vital role in shaping the design and development process of software applications.</p><h3>Definition</h3><p>Robert C. Martin introduced the Interface Segregation Principle(ISP). He stated that</p><blockquote>Clients should not be forced to depend upon interfaces that they do not use</blockquote><p>It means, If you have an interface with a bunch of methods and a class needs only a few of those methods, it shouldn’t be forced to implement all of them.</p><h3>Example</h3><p>Let’s consider a practical scenario involving a clothing franchise with both an online store (website) and an offline store. The online store facilitates payments exclusively through online modes, while the offline store accommodates both online and offline payment methods.</p><h3>Without ISP</h3><h4><strong>PaymentMethod interface</strong></h4><pre>public interface PaymentMethod {<br>    public void paymentByCreditCard();<br><br>    public void paymentByDebitCard();<br><br>    public void paymentByCheque();<br><br>    public void paymentByCash();<br>}</pre><h4>OnlineStore class</h4><pre><br>public class OnlineStore implements PaymentMethod {<br><br>    @Override<br>    public void paymentByCreditCard() {<br>        System.out.println(&quot;Payment by Credit Card&quot;);<br>    }<br><br>    @Override<br>    public void paymentByDebitCard() {<br>        System.out.println(&quot;Payment by Debit Card&quot;);<br>    }<br><br>    @Override<br>    public void paymentByCheque() {<br>        System.out.println(&quot;Can&#39;t do Payment by Cheque&quot;);<br>    }<br><br>    @Override<br>    public void paymentByCash() {<br>        System.out.println(&quot;Can&#39;t do Payment by Cash&quot;);<br>    }<br><br>}</pre><h4>OfflineStore class</h4><pre><br>public class OfflineStore implements PaymentMethod {<br><br>    @Override<br>    public void paymentByCreditCard() {<br>        System.out.println(&quot;Payment by Credit Card&quot;);<br>    }<br><br>    @Override<br>    public void paymentByDebitCard() {<br>        System.out.println(&quot;Payment by Debit Card&quot;);<br>    }<br><br>    @Override<br>    public void paymentByCheque() {<br>        System.out.println(&quot;Payment by Cheque&quot;);<br>    }<br><br>    @Override<br>    public void paymentByCash() {<br>        System.out.println(&quot;Payment by Cash&quot;);<br>    }<br><br>}</pre><p>In the above code,both the OnlineStore and OfflineStore classes implement the PaymentMethod interface, which declares four payment methods. However, this approach forces both stores to implement methods like paymentByCheque() and paymentByCash, even though online stores cannot accept payments via cheque or cash. This violates the ISP by enforcing methods that are not universally applicable to all implementing classes.</p><h3>With ISP</h3><p>To align with the ISP, we can refactor the code by creating separate interfaces for online and offline payment methods. The OnlinePaymentMethod interface includes methods for credit card and debit card payments, while the OfflinePaymentMethod interface contains methods for cheque and cash payments. This way, each class implements only the interfaces relevant to its context.</p><h4>OnlinePaymentMethod Interface</h4><pre><br>public interface OnlinePaymentMethod {<br>    public void paymentByCreditCard();<br><br>    public void paymentByDebitCard();<br>}</pre><h4>OnlineStore class</h4><pre><br>public class OnlineStore implements OnlinePaymentMethod {<br><br>    @Override<br>    public void paymentByCreditCard() {<br>        System.out.println(&quot;Payment by Credit Card&quot;);<br>    }<br><br>    @Override<br>    public void paymentByDebitCard() {<br>        System.out.println(&quot;Payment by Debit Card&quot;);<br>    }<br>}</pre><h4>OfflinePaymentMethod interface</h4><pre><br>public interface OfflinePaymentMethod {<br><br>    public void paymentByCheque();<br><br>    public void paymentByCash();<br>}</pre><h4>OfflineStore class</h4><pre><br>public class OfflineStore implements OfflinePaymentMethod, OnlinePaymentMethod {<br><br>    @Override<br>    public void paymentByCreditCard() {<br>        System.out.println(&quot;Payment by Credit Card&quot;);<br>    }<br><br>    @Override<br>    public void paymentByDebitCard() {<br>        System.out.println(&quot;Payment by Debit Card&quot;);<br>    }<br><br>    @Override<br>    public void paymentByCheque() {<br>        System.out.println(&quot;Payment by Cheque&quot;);<br>    }<br><br>    @Override<br>    public void paymentByCash() {<br>        System.out.println(&quot;Payment by Cash&quot;);<br>    }<br><br>}</pre><p>The OnlineStore class implementing the OnlinePaymentMethod interface, containing methods suitable for online payments. Similarly, the OfflineStore class implements both the OnlinePaymentMethod and OfflinePaymentMethod interfaces, ensuring that each class adheres to the principles relevant to its payment processing capabilities.</p><h3>Conclusion</h3><p>Following the Interface Segregation Principle enhances the modularity and flexibility of software design. By creating interfaces tailored to specific contexts, classes are relieved of implementing unnecessary methods, resulting in a more maintainable and extensible codebase. The ISP, along with other SOLID principles, contributes to the creation of robuts and scalable software architectures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57b7dbb4535d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Liskov’s Substitution Principle]]></title>
            <link>https://medium.com/@samyakmoon855/liskovs-substitution-principle-b1d415a5d15f?source=rss-dcfb410276f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1d415a5d15f</guid>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[design-principles]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[liskov-substitution]]></category>
            <dc:creator><![CDATA[Samyak Moon]]></dc:creator>
            <pubDate>Fri, 12 Jan 2024 17:50:44 GMT</pubDate>
            <atom:updated>2024-01-12T17:50:44.619Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@samyakmoon855/open-closed-principle-cbe3e0de5128">previous blog</a> we learnt about Open/Closed Principle. In this story we will cover Liskov’s Substitution Principle(LSP) which is one of the five principles of Object-oriented programming known as SOLID.</p><p>Barbara Liskov gave the Liskov Substitution Principle which is as follows</p><blockquote>Subtypes must be substitutable for their base types without altering the correctness of the program.</blockquote><p>In simple way, This principle states that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program. This principle is an extension of the Open/Closed principle.</p><p>Let’s say, If you have a class A and another class B that extends(inherits from) A, you should be able to use an object of class B wherever you could use an object of class A, and the program should still work as expected.</p><p>This principle encourages the creation of class hierarchies where subclasses can be easily substituted for their parent classes without causing any issues. By doing this, this principle promotes flexibility and maintainability in the code.</p><p>Let’s say in an E-commerce application, you have different discount types for each Product.</p><h4><strong>Discount.java</strong></h4><p>Discount is an abstract class that serves as the base for various discount types. It declares an abstract method <em>apply(double)</em> that must be implemented by its subclasses.</p><pre>abstract public class Discount {<br>    abstract double apply(double originalPrice);<br>}</pre><h4>FixedAmountDiscount.java and PercentageDiscount.java</h4><p>Two concreate subclasses, FixedAmountDiscount and PercentageDiscount, extends the Discount class. Each provides a specific implementation for the apply method defining how the discount is applied to the original price.</p><p>Both subclasses honor the contract established by the base class ensuring that they can be substituted for instances of the base class (‘Discount’) without altering the behavior expected from the apply method.</p><pre>public class FixedAmountDiscount extends Discount{<br><br>    private double amount;<br><br>    public FixedAmountDiscount(double amount){<br>        this.amount =amount;<br>    }<br>    @Override<br>    double apply(double originalPrice) {<br>        return originalPrice-amount;<br>    }<br>}</pre><pre>public class PercentageDiscount extends Discount{<br><br>    private double percentage;<br>    public PercentageDiscount(double percentage){<br>        this.percentage = percentage;<br>    }<br>    @Override<br>    double apply(double originalPrice) {<br>        return originalPrice-(percentage/100)*originalPrice;<br>    }<br>}</pre><h4>Product.java</h4><p>This class represents a product in the e-commerce application. The applyDiscount method takes a Discount object as a parameter and applies the discount to the product’s price by invoking the apply method. This is a key aspect that follows to LSP — any subclass of Discount can be used interchangeably.</p><pre>public class Product {<br>    private String name;<br>    private double price;<br>    <br>    public Product(String name,double price){<br>        this.name =name;<br>        this.price = price;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public double getPrice() {<br>        return price;<br>    }<br>    <br>    public void applyDiscount(Discount discount){<br>        this.price = discount.apply(price);<br>    }<br>}</pre><h4>Main.java</h4><p>In the main class, The applyDiscount method of the Product class is called with instances of both discount types(PercentageDiscount and FixedAmountDiscount). This showcases that both PercentageDiscount and FixedAmountDiscount can be seamlessly substituted in place of the generic Discount class.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        Product laptop = new Product(&quot;Laptop&quot;,100.0);<br>        Discount percentageDiscount = new PercentageDiscount(10);<br>        laptop.applyDiscount(percentageDiscount);<br>        System.out.println(&quot;After 10% discount: Rs.&quot;+laptop.getPrice());<br><br>        Discount fixedAmountDiscount = new FixedAmountDiscount(50);<br>        laptop.applyDiscount(fixedAmountDiscount);<br>        System.out.println(&quot;After Rs.50 discount: Rs.&quot;+laptop.getPrice());<br>    }<br>}</pre><p>The code follows the Liskov Substitution Principle by establishing a common base class (Discount), which is then extended by concrete subclasses (FixedAmountDiscount and PercentageDiscount). Instances of these subclasses can be used interchangeably where a Discount is expected, without causing any issues or altering the expected behavior.</p><h4>Conclusion</h4><p>Liskov’s Substitution Principle plays a vital role in creating maintainable and flexible code structures, allowing for easy substitution of subclasses and enhancing the overall design and extensibility of object-oriented systems. By following LSP, developers can build robust and adaptable software solutions that stand the test of time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1d415a5d15f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Open Closed Principle]]></title>
            <link>https://medium.com/@samyakmoon855/open-closed-principle-cbe3e0de5128?source=rss-dcfb410276f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbe3e0de5128</guid>
            <category><![CDATA[open-closed-principle]]></category>
            <category><![CDATA[design-principles]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[inheritance]]></category>
            <dc:creator><![CDATA[Samyak Moon]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 16:52:59 GMT</pubDate>
            <atom:updated>2024-01-11T16:52:59.964Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@samyakmoon855/single-responsibility-principle-in-java-ec3dc5d5537b">last blog</a>, we saw what is Single Responsibility Design Principle and where to use it, In this blog we will discuss the next principle i.e. Open/Closed Principle.</p><h3><strong>Introduction</strong></h3><p>Open/Closed Principle(OCP) was term that was given by Bertrand Meyer. He stated that</p><blockquote>Software entities like Classes, Modules, Functions, etc should be open for extension but closed for modification.</blockquote><p>This principle encourages us to add new functionality to a system without changing the existing code.</p><p>Let’s say in an E-commerce application you have a class called “PaymentProcessor” which is responsible for handling payments during the Order Checkout process.</p><pre>public class PaymentProcessor{<br>  public void processCreditCardPayment(double amount){<br>      System.out.println(&quot;Processing credit card payment of amount Rs.&quot;+amount);  <br>  }<br>}</pre><p>You initially built it to supported only Credit card payments. But in future when your customer base grows you want to integrate more ways to do payment to the existing PaymentProcessor.</p><h3><strong>Without Open/Closed Principle</strong></h3><figure><img alt="PaymentProcessor class without OCP" src="https://cdn-images-1.medium.com/max/311/1*x27DkiXb3b8-zgcCTaVomA.jpeg" /><figcaption>Payment Processor class without OCP</figcaption></figure><pre>public class PaymentProcessor{<br>  public void processCreditCardPayment(double amount){<br>    System.out.println(&quot;Processing credit card payment of amount Rs.&quot;+amount);<br>  }<br><br>  public void processDebitCardPayment(double amount){<br>    System.out.println(&quot;Processing debit card payment of amount Rs.&quot;+amount);<br>  }<br>}</pre><p><strong>Drawbacks of this approach</strong></p><p>Modifying the existing class to accommodate new payment methods can lead to increased complexity, reduced maintainability and challenges in testing as more payment methods are added in future.</p><h3><strong>With Open/Closed Principle</strong></h3><p>To overcome these drawbacks, you can apply Open/Closed Principle that allows for extension without modifying the existing code.</p><figure><img alt="PaymentProcessor class with OCP" src="https://cdn-images-1.medium.com/max/571/1*vwInXVgQ6F7ZKNoTuPepKQ.jpeg" /><figcaption>PaymentProcessor Class with OCP</figcaption></figure><pre>public interface PaymentProcessor{<br>   void process(double amount);<br>}<br><br>public class CreditCardPayment implements PaymentProcessor{<br>  @Override<br>  public void process(double amount){<br>    System.out.println(&quot;Processing credit card payment for amount Rs. &quot;+amount);<br>  }<br>}<br><br>public class DebitCardPayment implements PaymentProcessor{<br>  @Override<br>  public void process(double amount){<br>    System.out.println(&quot;Processing debit card payment for amount Rs. &quot;+amount);<br>  }<br>}<br><br>public class Main{<br>  public static void main(String[] args){<br>    PaymentProcessor creditCard = new CreditCardPayment();<br>    PaymentProcessor debitCard = new DebitCardPayment();<br><br>    creditCard.processPayment(50.0);<br>    debitCard.processPayment(100.0);<br>  }<br>}</pre><p>Using Open/Closed Principle it becomes very convenient to add new payment processor without hampering the existing payment processors. This promotes a more maintainable and flexible design.</p><h3>Conclusion</h3><p>Open/Closed Principle promotes more maintainable and flexible design, addressing the challenges associated with modifying existing code as the system evolves. This principle encourages a mindset that fosters extensibility and adaptability in software design, contributing to the overall robustness of a system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbe3e0de5128" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Single Responsibility Principle]]></title>
            <link>https://medium.com/@samyakmoon855/single-responsibility-principle-in-java-ec3dc5d5537b?source=rss-dcfb410276f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec3dc5d5537b</guid>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[design-principles]]></category>
            <category><![CDATA[single-responsibility]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[maintainability]]></category>
            <dc:creator><![CDATA[Samyak Moon]]></dc:creator>
            <pubDate>Wed, 10 Jan 2024 16:57:47 GMT</pubDate>
            <atom:updated>2024-01-11T07:02:52.016Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction to Design Principles and Patterns</strong></h3><p>In this series of blogs, we’ll be learning various design principles and patterns. These are like the rules and blueprints that help us build better software. Understanding these principles is crucial because they help us in creating code that is easy to manage, scale and adapt.</p><p>In software world, design principles act as our guiding principles and patterns as our blueprints. They make sure our codebase is well structured, organized and ready for future changes and modifications.</p><p>In this blog, we will be learning about the first principle of SOLID design i.e. Single Responsibility principle.</p><h3><strong>Single Responsibility Principle (SRP)</strong></h3><p>It was said by Robert C. Martin that “A class must have only one reason to change”. To put it another way, each class should only have one task or responsibility.</p><p>Let’s consider an example of E-commerce application and how can be apply SRP in that. Let’s say we are building an e-commerce system, and we have a class namely ‘Order’.</p><p>The Order class is responsible for following functionalities</p><ol><li>Calculating total price.</li><li>Managing the items in the order.</li><li>Generating order confirmations and many more</li></ol><p>Now, let’s say we also want an email notifications to customers when their orders are placed. Instead of adding the email-sending functionality directly into the Order class, we create a separate class called NotificationSender which will be responsible for sending email notifications.</p><p>By keeping these responsibilities separate, each class has a clear and distinct purpose. If any of the class needs any updates in future, let’s say in NotificationSender class we want to send an notification via email as well as sms then this modification can be done easily without affecting the Order class code.</p><p>This separation of classes makes code more modular, maintainable and easier to understand.</p><p>Now let’s understand this with the help of code.</p><h3><strong>Without SRP</strong></h3><pre><br>import java.util.List;<br><br>class Item {<br>    private String name;<br>    private double price;<br><br>    public Item(String name, double price) {<br>        this.name = name;<br>        this.price = price;<br>    }<br>    // getters and setters<br>}<br><br>class Order {<br>    private List&lt;Item&gt; items;<br><br>    public Order(List&lt;Item&gt; items) {<br>        this.items = items;<br>    }<br><br>    public double calculateTotal() {<br>        double total = 0;<br>        for (Item item : items) {<br>            total += item.getPrice();<br>        }<br>        return total;<br>    }<br><br>    public void generateOrderConfirmation() {<br>        System.out.println(&quot;Order Confirmation: Order processed successfully!&quot;);<br>    }<br><br>    public void sendEmailNotification(String customerEmail) {<br>        System.out.println(&quot;Email sent to &quot; + customerEmail + &quot;: Your order has been processed.&quot;);<br>    }<br>}<br><br>public class ECommerceApp {<br>    public static void main(String[] args) {<br><br>        Item item1 = new Item(&quot;Laptop&quot;, 999.99);<br>        Item item2 = new Item(&quot;Mouse&quot;, 19.99);<br><br>        Order order = new Order(List.of(item1, item2));<br><br>        double total = order.calculateTotal();<br>        System.out.println(&quot;Total: Rs.&quot; + total);<br>        order.generateOrderConfirmation();<br><br>        order.sendEmailNotification(&quot;example.123@gmail.com&quot;);<br>    }<br>}</pre><p>In the above code we have put the notification method in Order class only. In future any change to the notification method or any addition related to notification will cause changes to Order class as well.</p><h3><strong>With SRP</strong></h3><pre>import java.util.List;<br><br>class Item {<br>    private String name;<br>    private double price;<br><br>    public Item(String name, double price) {<br>        this.name = name;<br>        this.price = price;<br>    }<br><br>    // Getters and setters<br>}<br><br>class Order {<br>    private List&lt;Item&gt; items;<br><br>    public Order(List&lt;Item&gt; items) {<br>        this.items = items;<br>    }<br><br>    public double calculateTotal() {<br>        double total = 0;<br>        for (Item item : items) {<br>            total += item.getPrice();<br>        }<br>        return total;<br>    }<br><br>    public void orderConfirmation() {<br>        System.out.println(&quot;Order Confirmation: Order processed successfully!&quot;);<br>    }<br>}<br><br>class NotificationSender {<br>    public void sendEmailNotification(String customerEmail) {<br>        System.out.println(&quot;Email sent to &quot; + customerEmail + &quot;: Your order has been processed.&quot;);<br>    }<br>}<br><br>public class ECommerceApp {<br>    public static void main(String[] args) {<br>        Item item1 = new Item(&quot;Laptop&quot;, 999.99);<br>        Item item2 = new Item(&quot;Mouse&quot;, 19.99);<br><br>        Order order = new Order(List.of(item1, item2));<br><br>        double total = order.calculateTotal();<br>        System.out.println(&quot;Total: $&quot; + total);<br>        order.orderConfirmation();<br><br>        NotificationSender notificationSender = new NotificationSender();<br>        notificationSender.sendEmailNotification(&quot;example.123@gmail.com&quot;);<br>    }<br>}</pre><p>In this code, we have a new class called NotificationSender specifically for sending email notifications. This way, each class does one thing well. If we need to change how notifications work later or add any new notification method(like for sms), it won&#39;t change the Order class.</p><h3><strong>Conclusion</strong></h3><p>So, the Single Responsibility Principle is all about giving each class a clear task. This makes our code easier to manage and ready for any tweaks we might need down the road. Keep it simple, make it clean — that’s the power of SRP in Java!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec3dc5d5537b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Send Email Notification using Springboot: Part 3 — Asynchronous approach using RabbitMQ]]></title>
            <link>https://medium.com/@samyakmoon855/send-email-notification-using-springboot-part-3-asynchronous-approach-using-rabbitmq-adebf0477a2a?source=rss-dcfb410276f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/adebf0477a2a</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jms]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[mail-sender]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Samyak Moon]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 17:51:55 GMT</pubDate>
            <atom:updated>2023-12-06T17:54:56.576Z</atom:updated>
            <content:encoded><![CDATA[<h3>Send Email Notification using Springboot: Part 3 — Asynchronous approach using RabbitMQ</h3><p>In <a href="https://medium.com/@samyakmoon855/send-email-notification-using-spring-boot-part-1-synchronous-approach-311d80620a8e">Part 1</a>, we explored sending emails synchronously, highlighting the significant delay it introduced, especially affecting the User registration API’s performance. <a href="https://medium.com/@samyakmoon855/send-email-notification-using-springboot-part-2-asynchronous-approach-using-async-annotation-05d10cad5ae5">Part 2</a> then optimized this API by making the sendEmail method asynchronous with the @Async annotation, resulting in a substantial reduction in delay. However, as we delved deeper, challenges arose when considering the scalability and management complexities of numerous threads in larger applications.</p><h3>Challenges with @Async in Large Applications</h3><ol><li><strong>Thread Management Complexity</strong>: In larger applications, the default creation of a new thread for each asynchronous method invocation by @Async introduces complexity and becomes resource-intensive.</li><li><strong>Limited Control over Concurrency</strong>: Spring’s default configuration for @Async lacks fine-grained control over thread pooling and concurrency limits, potentially leading to issues such as thread exhaustion.</li><li><strong>Lack of Message Queue</strong>: @Async lacks a built-in message queue system, making it less suitable for scenarios where tasks need queuing, prioritization, or handling by multiple instances.</li></ol><h3>Advantages of JMS(Java Messaging Service) for Asynchronous Processing</h3><ol><li><strong>Robust Message Queues</strong>: JMS provides a robust and scalable message queuing system, facilitating decoupling between components and enabling asynchronous communication.</li><li><strong>Guaranteed Message Delivery</strong>: JMS brokers like RabbitMQ ensure reliable message delivery, queuing messages when a consumer is temporarily unavailable and delivering them upon accessibility.</li><li><strong>Scalability</strong>: JMS supports distributed processing, scaling well across multiple instances of an application, making it suitable for large-scale applications with high concurrency requirements.</li><li><strong>Fault Tolerance</strong>: JMS brokers often feature clustering and replication, providing fault tolerance. In case of a broker failure, another node can seamlessly take over, ensuring continuous message processing.</li><li><strong>Transaction Management</strong>: JMS supports transactional message processing, crucial for maintaining data consistency in applications with complex business logic.</li></ol><p>While @Async suits simple asynchronous processing, its limitations become apparent in large-scale applications. For scenarios involving a significant number of asynchronous tasks, JMS, with its robust queuing mechanisms and scalability, emerges as a more suitable choice.</p><h3>Configuring RabbitMQ for Email Sending</h3><h4>Add dependency in pom.xml.</h4><pre>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-amqp&lt;/artifactId&gt;<br>  &lt;/dependency&gt;</pre><p>This dependency ensures that your Spring Boot application includes the necessary libraries for RabbitMQ integration.</p><h4>YAML Configuration</h4><pre>spring:<br>  rabbitmq:<br>    host: localhost<br>    port: 5672<br>    username: guest<br>    password: guest<br>rabbitmq:<br>  queue:<br>    email:<br>      name: email_queue<br>  exchange:<br>    email:<br>      name: email_exchange<br>  binding:<br>    email:<br>      name: email_routing_key</pre><p>This YAML configuration ensures the integration of RabbitMQ for asynchronous email sending. It specifies the RabbitMQ server details, queue, exchange, and binding configurations for handling email-related messages.</p><h4>Create a RabbitMQConfig class</h4><pre>@Configuration<br>public class RabbitMQConfig {<br>    @Value(&quot;${rabbitmq.queue.email.name}&quot;)<br>    private String emailQueue;<br><br>    @Value(&quot;${rabbitmq.exchange.email.name}&quot;)<br>    private String emailExchange;<br><br>    @Value(&quot;${rabbitmq.binding.email.name}&quot;)<br>    private String emailRoutingKey;<br><br>    @Bean<br>    public Queue emailQueue(){<br>        return new Queue(emailQueue);<br>    }<br><br><br>    @Bean<br>    public TopicExchange emailExchange(){<br>        return new TopicExchange(emailExchange);<br>    }<br><br><br>    @Bean<br>    public Binding emailBinding(){<br>        return BindingBuilder.bind(emailQueue())<br>                .to(emailExchange())<br>                .with(emailRoutingKey);<br>    }<br><br><br>    @Bean<br>    public AmqpTemplate amqpTemplate(ConnectionFactory connectionFactory){<br>        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);<br>        rabbitTemplate.setMessageConverter(converter());<br>        return rabbitTemplate;<br>    }<br><br>    @Bean<br>    MessageConverter converter() {<br>        return new Jackson2JsonMessageConverter();<br>    }<br>}</pre><p>In the RabbitMQConfig class, we use Spring&#39;s @Configuration annotation to define beans for configuring RabbitMQ elements. These include the email queue, exchange, and binding. Additionally, an AmqpTemplate bean is created for sending messages to the RabbitMQ queue, and a MessageConverter bean is configured to convert messages to JSON format.</p><h4>Implementing RabbitMQ in User Registration</h4><p>RabbitMQ Listener</p><pre>    @RabbitListener(queues = &quot;email_queue&quot;)<br>    public void sendEmail(EmailDetails emailDetails){<br>        try {<br>            SimpleMailMessage mailMessage = new SimpleMailMessage();<br>            mailMessage.setFrom(emailSender);<br>            mailMessage.setTo(emailDetails.getRecipient());<br>            mailMessage.setText(emailDetails.getMessageBody());<br>            mailMessage.setSubject(emailDetails.getSubject());<br>            javaMailSender.send(mailMessage);<br>            log.info(&quot;Mail sent successfully&quot;);<br>        }catch (MailException e){<br>            log.debug(&quot;Sending mail failed due to some error&quot;);<br>        }<br>    }</pre><p>The @RabbitListener annotation marks the sendEmail method as a listener for the specified email queue (email_queue). This method processes incoming messages from the RabbitMQ queue, sending emails asynchronously.</p><h4>User Registration with RabbitMQ</h4><pre>@Autowired<br>    private UserRepository userRepository;    <br>    <br>    @Autowired<br>    private RabbitTemplate rabbitTemplate;<br><br>    @Value(&quot;${rabbitmq.exchange.email.name}&quot;)<br>    private String emailExchange;<br><br>    @Value(&quot;${rabbitmq.binding.email.name}&quot;)<br>    private String emailRoutingKey;<br>    @Override<br>    public void registerUser(RequestDto requestDto) {<br>        if(userRepository.existsByEmail(requestDto.getEmail()))<br>            throw new UserAlreadyExistsException(UserConstants.USER_ALREADY_EXISTS);<br>        User user = UserMapper.mapToUser(new User(),requestDto);<br>        <br>        userRepository.save(user);<br>        rabbitTemplate.convertAndSend(emailExchange,<br>                emailRoutingKey,<br>                EmailDetails.builder()<br>                .messageBody(&quot;Registration Successful with mail id: &quot;+requestDto.getEmail())<br>                .recipient(requestDto.getEmail())<br>                .subject(&quot;REGISTRATION SUCCESS&quot;)<br>                .build());<br>    }</pre><p>In the registerUser method, after validating and saving the user, the RabbitMQ convertAndSend method is employed to enqueue the email details for processing. This ensures that the email is sent asynchronously via RabbitMQ.</p><h3>Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbmRJdAgUd442WiTC67e3w.png" /></figure><p>Upon running the application and triggering the registration process, the asynchronous email processing via RabbitMQ significantly reduces the time to 189ms, compared to the 3.78s observed with the synchronous approach. This enhancement demonstrates the power of JMS, specifically RabbitMQ, in optimizing asynchronous processing within Spring Boot applications.</p><h3>Conclusion</h3><p>This multipart series navigated through different strategies for sending emails in a Spring Boot application. <a href="https://medium.com/@samyakmoon855/send-email-notification-using-spring-boot-part-1-synchronous-approach-311d80620a8e">Part 1</a> uncovered the drawbacks of a synchronous email-sending approach, leading to a remedy in <a href="https://medium.com/@samyakmoon855/send-email-notification-using-springboot-part-2-asynchronous-approach-using-async-annotation-05d10cad5ae5">Part 2</a> by adopting an asynchronous approach using the @Async annotation. However, challenges emerged in larger applications. Part 3 leveraged the power of Java Message Service (JMS) with RabbitMQ, mitigating complexities introduced by managing numerous threads. This ensured improved scalability, fault tolerance, and transaction management, making it an ideal solution for large-scale applications.</p><p><a href="https://github.com/samyak2405/Send-email-using-Springboot-and-RabbitMQ/tree/main/EmailNotification3/EmailNotification">Send-email-using-Springboot-and-RabbitMQ/EmailNotification3/EmailNotification at main · samyak2405/Send-email-using-Springboot-and-RabbitMQ</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adebf0477a2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>