<?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 Vino Babu Thomas on Medium]]></title>
        <description><![CDATA[Stories by Vino Babu Thomas on Medium]]></description>
        <link>https://medium.com/@vinobabu.t?source=rss-356d33dfc28a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y4Nqjf3mdQ3PTFRwvQYH4Q.jpeg</url>
            <title>Stories by Vino Babu Thomas on Medium</title>
            <link>https://medium.com/@vinobabu.t?source=rss-356d33dfc28a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:54:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vinobabu.t/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[Find the Pivot Integer — Easy Solution Using BinarySearch]]></title>
            <link>https://medium.com/@vinobabu.t/find-the-pivot-integer-easy-solution-using-binarysearch-cb5439dba059?source=rss-356d33dfc28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb5439dba059</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Vino Babu Thomas]]></dc:creator>
            <pubDate>Wed, 13 Mar 2024 12:43:40 GMT</pubDate>
            <atom:updated>2024-03-13T12:44:42.969Z</atom:updated>
            <content:encoded><![CDATA[<h3>Find the Pivot Integer — Easy Solution Using BinarySearch</h3><h3>Problem Description</h3><p>Given a positive integer n, find the <strong>pivot integer</strong> x such that:</p><ul><li>The sum of all elements between 1 and x inclusively equals the sum of all elements between x and n inclusively.</li></ul><p>Return <em>the pivot integer </em>x. If no such integer exists, return -1. It is guaranteed that there will be at most one pivot index for the given input.</p><p><strong>Example 1:</strong></p><pre>Input: n = 8<br>Output: 6<br>Explanation: 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21.</pre><p><strong>Example 2:</strong></p><pre>Input: n = 1<br>Output: 1<br>Explanation: 1 is the pivot integer since: 1 = 1.</pre><p><strong>Example 3:</strong></p><pre>Input: n = 4<br>Output: -1<br>Explanation: It can be proved that no such integer exist.</pre><h3>Approach</h3><p>This approach uses a binary search approach, starting from the middle of the array. In each iteration, it calculates the sum of numbers on both sides of the current midpoint and adjusts the search range based on the comparison of these sums. If it finds a midpoint where the sums are equal, it returns it as the pivot. If no such midpoint is found, it returns -1.</p><h3>Program</h3><pre>class Solution {<br>    public int pivotInteger(int n) {<br>        //pivot cannot be there anywhere before n/2<br>        int left = n / 2, right = n;<br>        //sum of real numbers<br>        int sum = n * (n + 1) / 2;<br>        while (left &lt;= right) {<br>            int mid = left + (right - left) / 2;<br>            int leftSum = mid * (mid + 1) / 2;<br>            //adding mid element as its inclusive in both left and right sums<br>            int rightSum = sum - leftSum + mid;<br>            if (leftSum == rightSum) {<br>                return mid;<br>            } else if (leftSum &gt; rightSum) {<br>                right = mid - 1;<br>            } else {<br>                left = mid + 1;<br>            }<br>        }<br>        return -1;<br>    }<br>}</pre><h3><strong>Explanation</strong></h3><p>The method uses a binary search approach to find the pivot. It starts by calculating the total sum of integers from 1 to n using the formula n*(n+1)/2. Then it initializes two pointers, left and right, to the middle and the end of the array, respectively.</p><p>In each iteration of the while loop, it calculates the sum of integers from 1 to mid (which is the middle point between left and right), and compares it with the sum of integers from mid to n. If the two sums are equal, it returns mid as the pivot. If the left sum is greater than the right sum, it moves the right pointer to mid - 1. If the left sum is less than the right sum, it moves the left pointer to mid + 1.</p><p>The method continues this process until it finds a pivot or until the left pointer is greater than the right pointer. If it doesn&#39;t find a pivot, it returns -1.</p><h3>Complexity Analysis</h3><ul><li>Time Complexity: The time complexity is O(log n) because the method uses a binary search approach, which cuts the search space in half in each iteration of the while loop.</li><li>Space Complexity: The space complexity is O(1) because the method uses a constant amount of space.</li></ul><p>Thanks for reading. Please consider upvoting. Happy coding!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb5439dba059" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intersection of Two Arrays — Two Different Java Solutions]]></title>
            <link>https://medium.com/@vinobabu.t/intersection-of-two-arrays-two-different-java-solutions-6b86ba3a46a1?source=rss-356d33dfc28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b86ba3a46a1</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Vino Babu Thomas]]></dc:creator>
            <pubDate>Sun, 10 Mar 2024 14:14:45 GMT</pubDate>
            <atom:updated>2024-03-10T14:14:45.068Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intersection of Two Arrays — Two Different Java Solutions</h3><h3><strong>Problem Statement</strong></h3><p>Given two integer arrays nums1 and nums2, return <em>an array of their intersection</em>. Each element in the result must be <strong>unique</strong> and you may return the result in <strong>any order</strong>.</p><p><strong>Example 1:</strong></p><pre>Input: nums1 = [1,2,2,1], nums2 = [2,2]<br>Output: [2]</pre><p><strong>Example 2:</strong></p><pre>Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]<br>Output: [9,4]<br>Explanation: [4,9] is also accepted.</pre><h3><strong>Approach using HashSet</strong></h3><p>This approach finds the intersection of two arrays by using two sets. It first adds all elements from the first array to a set, then iterates over the second array and adds any element that is also in the first set to a result set. Finally, it converts the result set to an array.</p><h3>Program</h3><pre>class Solution {<br>    public int[] intersection(int[] nums1, int[] nums2) {<br>        Set&lt;Integer&gt; res = new HashSet&lt;&gt;();<br>        Set&lt;Integer&gt; s = new HashSet&lt;&gt;();<br>        for (int n : nums1) {<br>            s.add(n);<br>        }<br>        for (int n : nums2) {<br>            if (s.contains(n)) {<br>                res.add(n);<br>            }<br>        }<br>        int[] resAry = new int[res.size()];<br>        int ctr = 0;<br>        for (Integer num : res) {<br>            resAry[ctr++] = num;<br>        }<br>        return resAry;<br>    }<br>}</pre><h3><strong>Explanation</strong></h3><ol><li><strong>Initialize Sets:</strong> The code first initializes two sets, s and res. s is used to store the elements of nums1, and res is used to store the intersection of nums1 and nums2.</li><li><strong>Add Elements to </strong><strong>s:</strong> The code then iterates over nums1 and adds each element to s.</li><li><strong>Find Intersection:</strong> The code iterates over nums2. For each element in nums2, if it is also in s, it adds it to res.</li><li><strong>Convert Set to Array:</strong> The code initializes an array resAry with the same size as res, then iterates over res and adds each element to resAry.</li></ol><h3><strong>Analysis</strong></h3><p><strong>Time Complexity:</strong> The time complexity of this approach is O(n + m), where n is the length of nums1 and m is the length of nums2.</p><p><strong>Space Complexity:</strong> The space complexity is O(n + m), where n is the length of nums1 and m is the length of nums2. This is because in the worst-case scenario, all elements in both arrays are distinct, so the sets s and res could potentially contain all elements from both arrays.</p><h3><strong>Approach using sorting, two pointers</strong></h3><p>This approach finds the intersection of two arrays by sorting both arrays first and then using two pointers to find common elements. It adds common elements to a set to ensure uniqueness, and finally converts the set to an array.</p><h3><strong>Program</strong></h3><pre>class Solution {<br>    public int[] intersection(int[] nums1, int[] nums2) {<br>        Set&lt;Integer&gt; s = new HashSet&lt;&gt;();<br>        Arrays.sort(nums1);<br>        Arrays.sort(nums2);<br>        int m = nums1.length;<br>        int n = nums2.length;<br>        int i = 0, j = 0;<br>        while (i &lt; m &amp;&amp; j &lt; n) {<br>            if (nums1[i] == nums2[j]) {<br>                s.add(nums1[i]);<br>                i++;<br>                j++;<br>            } else if (nums1[i] &gt; nums2[j]) {<br>                j++;<br>            } else {<br>                i++;<br>            }<br>        }<br>        int[] res = new int[s.size()];<br>        int ctr = 0;<br>        for (Integer num : s) {<br>            res[ctr++] = num;<br>        }<br>        return res;<br>    }<br>}</pre><h3><strong>Explanation</strong></h3><ol><li><strong>Initialize Set and Sort Arrays:</strong> The code first initializes a set s to store the intersection of nums1 and nums2. It then sorts both nums1 and nums2.</li><li><strong>Find Intersection:</strong> The code uses two pointers i and j to iterate over nums1 and nums2 respectively. If nums1[i] equals nums2[j], it adds nums1[i] to s and increments both i and j. If nums1[i] is greater than nums2[j], it increments j. If nums1[i] is less than nums2[j], it increments i. This process continues until either i or j reaches the end of its respective array.</li><li><strong>Convert Set to Array:</strong> The code initializes an array res with the same size as s, then iterates over s and adds each element to res.</li></ol><h3><strong>Analysis</strong></h3><p><strong>Time Complexity:</strong> The time complexity of this approach is <strong>O(n log n + m log m)</strong>, where n is the length of nums1 and m is the length of nums2. This is because the solution sorts both arrays first, which takes O(n log n) and O(m log m) time respectively. The subsequent while loop takes O(n + m) time, but this is dominated by the sorting operations.</p><p><strong>Space Complexity:</strong> The space complexity is <strong>O(n + m)</strong>, where n is the length of nums1 and m is the length of nums2. This is because in the worst-case scenario, all elements in both arrays are distinct, so the set s could potentially contain all elements from both arrays. The array res could contain all elements from s, so it also contributes to the space complexity.</p><p>Thanks for reading. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b86ba3a46a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minimum Common Value — Java solution]]></title>
            <link>https://medium.com/@vinobabu.t/minimum-common-value-java-solution-427f282925df?source=rss-356d33dfc28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/427f282925df</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Vino Babu Thomas]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 15:20:12 GMT</pubDate>
            <atom:updated>2024-03-09T15:20:12.501Z</atom:updated>
            <content:encoded><![CDATA[<h3>Minimum Common Value — Java solution</h3><h3><strong>Problem Statement</strong></h3><p>Given two integer arrays nums1 and nums2, sorted in non-decreasing order, return <em>the </em><strong><em>minimum integer common</em></strong><em> to both arrays</em>. If there is no common integer amongst nums1 and nums2, return -1.</p><p>Note that an integer is said to be <strong>common</strong> to nums1 and nums2 if both arrays have <strong>at least one</strong> occurrence of that integer.</p><p><strong>Example 1:</strong></p><pre>Input: nums1 = [1,2,3], nums2 = [2,4]<br>Output: 2<br>Explanation: The smallest element common to both arrays is 2, so we return 2.</pre><p><strong>Example 2:</strong></p><pre>Input: nums1 = [1,2,3,6], nums2 = [2,3,4,5]<br>Output: 2<br>Explanation: There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned.</pre><h3>Approach-1 — Binary Search</h3><p>This approach uses binary search to find a common element in two sorted arrays. It iterates over the first array and for each element, it performs a binary search in the second array. If it finds a match, it returns that element. If no common element is found after checking all elements in the first array, it returns -1.</p><h3><strong>Program</strong></h3><pre>class Solution {<br>    public int getCommon(int[] nums1, int[] nums2) {<br>        int m = nums1.length;<br>        int n = nums2.length;<br>        for (int i = 0; i &lt; m; i++) {<br>            int q = nums1[i];<br>            if (bs(nums2, q)) {<br>                return q;<br>            }<br>        }<br>        return -1;<br>    }<br><br>    private boolean bs(int[] ar, int q) {<br>        int l = 0, r = ar.length - 1;<br>        int mid = 0;<br>        ;<br>        while (l &lt;= r) {<br>            mid = l + (r - l) / 2;<br>            if (ar[mid] == q) {<br>                return true;<br>            } else if (ar[mid] &gt; q) {<br>                r = mid - 1;<br>            } else {<br>                l = mid + 1;<br>            }<br>        }<br>        return false;<br>    }<br>}</pre><p><strong>Explanation</strong></p><ol><li><strong>Iterate Over First Array:</strong> The code first iterates over the elements in the first array.</li><li><strong>Binary Search in Second Array:</strong> For each element in the first array, it performs a binary search in the second array. The binary search function bs takes an array and a query element as input, and returns true if the query element is found in the array, and false otherwise.</li></ol><p><strong>Analysis</strong></p><p><strong>Time Complexity:</strong> The time complexity of this approach is <strong>O(m log n)</strong>, where m is the number of elements in the first array and n is the number of elements in the second array. This is because we’re iterating over the first array once (O(m)) and for each element, we’re performing a binary search in the second array (O(log n)).</p><p><strong>Space Complexity:</strong> The space complexity of this approach is <strong>O(1)</strong>,<strong> </strong>which means the space required does not increase with the size of the input arrays.</p><h3><strong>Approach-2 — Two Pointers</strong></h3><p>This approach uses the two-pointer technique to find a common element in two sorted arrays. It maintains a pointer for each array and moves them intelligently to find a common element</p><p><strong>Program</strong></p><pre>class Solution {<br>    public int getCommon(int[] nums1, int[] nums2) {<br>        int m = nums1.length;<br>        int n = nums2.length;<br>        int i = 0, j = 0;<br>        while (i &lt; m &amp;&amp; j &lt; n) {<br>            if (nums1[i] == nums2[j]) {<br>                return nums1[i];<br>            } else if (nums1[i] &gt; nums2[j]) {<br>                j++;<br>            } else {<br>                i++;<br>            }<br>        }<br>        return -1;<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ol><li><strong>Initialize Pointers:</strong> The code first initializes two pointers, i and j, to the beginning of the first and second arrays respectively.</li><li><strong>Iterate Until a Common Element is Found:</strong> The code then enters a loop that continues until either pointer reaches the end of its respective array. In each iteration, it compares the elements pointed to by i and j. If they are equal, it returns that element.</li><li><strong>Move Pointers:</strong> If the elements are not equal, it moves the pointer that is pointing to the smaller element forward. This is because the arrays are sorted, so if nums1[i] is less than nums2[j], there&#39;s no point in comparing nums1[i] with the rest of nums2, and vice versa.</li></ol><p><strong>Analysis</strong></p><p><strong>Time Complexity:</strong> The time complexity of this approach is <strong>O(m + n)</strong>, where m is the number of elements in the first array and n is the number of elements in the second array. This is because in the worst case, we’re iterating over all elements in both arrays once.</p><p><strong>Space Complexity:</strong> The space complexity of this approach is <strong>O(1)</strong>, which means the space required does not increase with the size of the input arrays.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=427f282925df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Count Elements With Maximum Frequency — Leetcode Java Solution]]></title>
            <link>https://medium.com/@vinobabu.t/count-elements-with-maximum-frequency-leetcode-java-solution-a45297ac510a?source=rss-356d33dfc28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a45297ac510a</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Vino Babu Thomas]]></dc:creator>
            <pubDate>Fri, 08 Mar 2024 04:03:36 GMT</pubDate>
            <atom:updated>2024-03-08T04:03:36.507Z</atom:updated>
            <content:encoded><![CDATA[<h3>Count Elements With Maximum Frequency — Leetcode Java Solution</h3><h3>Problem Statement</h3><p>You are given an array nums consisting of <strong>positive</strong> integers.</p><p>Return <em>the </em><strong><em>total frequencies</em></strong><em> of elements in </em>nums <em>such that those elements all have the </em><strong><em>maximum</em></strong><em> frequency</em>.</p><p>The <strong>frequency</strong> of an element is the number of occurrences of that element in the array.</p><p><strong>Example 1:</strong></p><pre>Input: nums = [1,2,2,3,1,4]<br>Output: 4<br>Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.<br>So the number of elements in the array with maximum frequency is 4.</pre><p><strong>Example 2:</strong></p><pre>Input: nums = [1,2,3,4,5]<br>Output: 5<br>Explanation: All elements of the array have a frequency of 1 which is the maximum.<br>So the number of elements in the array with maximum frequency is 5.</pre><h3>Approach-1 using Priority Queue</h3><p>The approach first counts the frequency of each element in the array using a HashMap. Then, it adds all entries to a priority queue, which is sorted in descending order based on frequency. It then iterates through the queue, accumulating the frequencies of the elements until it encounters a frequency less than the maximum frequency found so far.</p><h3>Java Solution</h3><pre>class Solution {<br>    public int maxFrequencyElements(int[] nums) {<br>        Map&lt;Integer, Integer&gt; freq = new HashMap&lt;&gt;();<br>        for (int n : nums) {<br>            freq.put(n, freq.getOrDefault(n, 0) + 1);<br>        }<br>        Queue&lt;Map.Entry&lt;Integer, Integer&gt;&gt; pq =<br>                new PriorityQueue&lt;&gt;((a, b) -&gt; b.getValue() - a.getValue());<br>        pq.addAll(freq.entrySet());<br>        int maxFreq = 0;<br>        int res = 0;<br>        while (!pq.isEmpty()) {<br>            Map.Entry&lt;Integer, Integer&gt; entry = pq.poll();<br>            if (entry.getValue() &gt;= maxFreq) {<br>                res += entry.getValue();<br>                maxFreq = Math.max(maxFreq, entry.getValue());<br>            } else {<br>                break;<br>            }<br>        }<br>        return res;<br>    }<br>}</pre><p><strong>Explanation:</strong><br>The approach used in this code is to find the maximum frequency of elements in an array. Here’s a step-by-step explanation:</p><ol><li><strong>Count Frequencies</strong>: The code first iterates over the input array and counts the frequency of each number using a HashMap. The number is the key and the frequency is the value.</li><li><strong>Sort by Frequency</strong>: The code then adds all the entries from the HashMap to a priority queue. The priority queue is sorted in descending order based on the frequency of the numbers. This is achieved by providing a custom comparator to the priority queue that sorts the entries based on their values (i.e., the frequencies).</li><li><strong>Find Maximum Frequency</strong>: The code then starts a loop that continues until the priority queue is empty. In each iteration, it polls an entry from the priority queue (which will be the entry with the highest frequency due to the sorting order of the queue). It checks if the frequency of the current entry is greater than or equal to the maximum frequency found so far. If it is, it adds the frequency to a running total (res) and updates the maximum frequency. If the frequency of the current entry is less than the maximum frequency, it breaks the loop.</li></ol><p><strong>Analysis<br></strong>The time complexity of this approach is dominated by two parts:</p><ol><li>Building the frequency map: This operation takes O(n) time, where n is the number of elements in the input array.</li><li>Building and processing the priority queue: Adding all elements to the priority queue takes O(n log n) time, as each insertion operation in a priority queue takes O(log n) time and we’re doing this n times. The while loop also operates in O(n log n) time in the worst case, as each removal operation from a priority queue takes O(log n) time and we’re doing this n times in the worst case.</li></ol><p>Therefore, the overall time complexity of this approach is <strong>O(n log n).</strong></p><p><strong>Space Complexity:<br></strong>The space complexity of this approach is O(n), where n is the number of elements in the input array.</p><h3><strong>Approach-2 Optimized</strong></h3><p>This approach calculates the frequency of each element in the array using a HashMap. It then iterates over the HashMap entries to find the maximum frequency and sums up all frequencies that are equal to the maximum.</p><h3><strong>Java Solution</strong></h3><pre>class Solution {<br>    public int maxFrequencyElements(int[] nums) {<br>        Map&lt;Integer, Integer&gt; freq = new HashMap&lt;&gt;();<br>        for (int n : nums) {<br>            freq.put(n, freq.getOrDefault(n, 0) + 1);<br>        }<br>        int curMax = 0;<br>        int res = 0;<br>        for (Map.Entry&lt;Integer, Integer&gt; entry : freq.entrySet()) {<br>            if (entry.getValue() &gt; curMax) {<br>                curMax = entry.getValue();<br>                res = entry.getValue();<br>            } else if (entry.getValue() == curMax) {<br>                res += entry.getValue();<br>            }<br>        }<br>        return res;<br>    }<br>}</pre><h3><strong>Explanation</strong></h3><ol><li><strong>Count Frequencies:</strong> The code first iterates over the input array and counts the frequency of each number using a HashMap. The number is the key and the frequency is the value.</li><li><strong>Find Maximum Frequency and Sum:</strong> The code then iterates over the entries in the HashMap. For each entry, it checks if the frequency is greater than the current maximum frequency. If it is, it updates the maximum frequency and the result. If the frequency is equal to the current maximum frequency, it adds the frequency to the result.</li></ol><p><strong>Analysis<br>Time Complexity:</strong> The time complexity of this approach is O(n), where n is the number of elements in the input array. This is because we’re iterating over the array once to build the frequency map, and then iterating over the map entries once to find the maximum frequency and sum.</p><p><strong>Space Complexity:</strong> The space complexity of this approach is also O(n), where n is the number of elements in the input array</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a45297ac510a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Squares of a Sorted Array — Leetcode problem Java Solution]]></title>
            <link>https://medium.com/@vinobabu.t/squares-of-a-sorted-array-leetcode-problem-java-solution-5a8dbfe591d3?source=rss-356d33dfc28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a8dbfe591d3</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Vino Babu Thomas]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 15:22:00 GMT</pubDate>
            <atom:updated>2024-03-02T15:22:00.332Z</atom:updated>
            <content:encoded><![CDATA[<h3>Squares of a Sorted Array — Leetcode problem Java Solution</h3><h3><strong>Problem Statement</strong></h3><p>Given an integer array nums sorted in <strong>non-decreasing</strong> order, return <em>an array of </em><strong><em>the squares of each number</em></strong><em> sorted in non-decreasing order</em>.</p><p><strong>Example 1:</strong></p><pre>Input: nums = [-4,-1,0,3,10]<br>Output: [0,1,9,16,100]<br>Explanation: After squaring, the array becomes [16,1,0,9,100].<br>After sorting, it becomes [0,1,9,16,100].</pre><p><strong>Example 2:</strong></p><pre>Input: nums = [-7,-3,2,3,11]<br>Output: [4,9,9,49,121]</pre><h3><strong>Approach</strong></h3><p>To achieve a solution with a time complexity of O(n), we can use a two-pointer approach. Since the input array is sorted in non-decreasing order, the largest square of a number could be at the beginning or the end of the array.</p><h3><strong>Java Program</strong></h3><pre>class Solution {<br>    public int[] sortedSquares(int[] nums) {<br>        int l = 0;<br>        int r = nums.length - 1;<br>        int ptr = nums.length - 1;<br>        int[] res = new int[nums.length];<br>        while (l &lt;= r) {<br>            if (Math.abs(nums[l]) &gt; Math.abs(nums[r])) {<br>                res[ptr] = nums[l] * nums[l];<br>                l++;<br>            } else {<br>                res[ptr] = nums[r] * nums[r];<br>                r--;<br>            }<br>            ptr--;<br>        }<br>        return res;<br><br>    }<br>}</pre><h3><strong>Explanation</strong></h3><p>Here’s the step-by-step approach:</p><ol><li>Initialize two pointers, one at the start of the array and one at the end.</li><li>Compare the absolute values at the two pointers.</li><li>The larger absolute value will give the larger square. Add this square at the end of the result array.</li><li>Move the pointer inward from the larger absolute value.</li><li>Repeat steps 2–4 until the start and end pointers meet.</li></ol><h3>Analysis</h3><p><strong>Time Complexity:</strong><br>The time complexity of this algorithm is O(n), where n is the length of the input array.</p><p><strong>Space Complexity:</strong><br>The space complexity of this algorithm is also O(n), where n is the length of the input array. This is because you’re creating a new array result to store the squared and sorted numbers</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a8dbfe591d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Check if two binary trees are the same or not — Leetcode Java Solution using recursion]]></title>
            <link>https://towardsdev.com/check-if-two-binary-trees-are-the-same-or-not-leetcode-java-solution-using-recursion-2317beded802?source=rss-356d33dfc28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2317beded802</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[trees]]></category>
            <dc:creator><![CDATA[Vino Babu Thomas]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 14:46:04 GMT</pubDate>
            <atom:updated>2024-02-26T18:54:25.250Z</atom:updated>
            <content:encoded><![CDATA[<h3>Check if two binary trees are the same or not — Leetcode Java solution using recursion</h3><h3>Problem statement</h3><p>Given the roots of two binary trees p and q, write a function to check if they are the same or not.</p><p>Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.</p><p><strong>Example 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*fD_FsqV7YfbjJdsf.jpg" /></figure><pre>Input: p = [1,2,3], q = [1,2,3]<br>Output: true</pre><p><strong>Example 2:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/0*7SmYFBMpclRfeuUh.jpg" /></figure><pre>Input: p = [1,2], q = [1,null,2]<br>Output: false</pre><p><strong>Example 3:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*Bp6NwFRc3r0W8hiL.jpg" /></figure><pre>Input: p = [1,2,1], q = [1,1,2]<br>Output: false</pre><h3><strong>Approach</strong></h3><p>The approach employs a recursive strategy to ascertain if two binary trees are identical in structure and node values. It iterates through both trees simultaneously, comparing nodes at corresponding positions. If both nodes are null, it returns true; if only one is null, it returns false. Otherwise, it verifies if the values of the current nodes match and recursively evaluates their left and right subtrees. This recursive process ensures thorough comparison of all nodes, confirming whether the trees are identical or not.</p><h3>Java Solution using recursion</h3><pre>/**<br> * Definition for a binary tree node.<br> * public class TreeNode {<br> * int val;<br> * TreeNode left;<br> * TreeNode right;<br> * TreeNode() {}<br> * TreeNode(int val) { this.val = val; }<br> * TreeNode(int val, TreeNode left, TreeNode right) {<br> * this.val = val;<br> * this.left = left;<br> * this.right = right;<br> * }<br> * }<br> */<br>class Solution {<br>    public boolean isSameTree(TreeNode p, TreeNode q) {<br>        return isSame(p, q);<br>    }<br><br>    private boolean isSame(TreeNode p, TreeNode q) {<br>        if (p == null &amp;&amp; q == null) {<br>            return true;<br>        }<br>        if (p == null || q == null) {<br>            return false;<br>        }<br>        return p.val == q.val &amp;&amp; isSame(p.left, q.left) &amp;&amp; isSame(p.right, q.right);<br><br>    }<br>}</pre><h3><strong>Explanation</strong></h3><p>The provided code defines a method that checks if two binary trees, represented by their root nodes p and q, are identical in structure and node values.</p><ol><li>It starts by checking if both nodes are null. If they are, it returns true, indicating that the trees are identical (base case).</li><li>If only one of the nodes is null while the other is not, it returns false, indicating a mismatch in structure.</li><li>If neither node is null, it checks if their values are equal. If not, it returns false, indicating a difference in node values.</li><li>Finally, it recursively calls itself for the left and right subtrees of both nodes, comparing each corresponding pair of child nodes.</li></ol><p>This process continues recursively until all nodes have been compared, and the method returns true if and only if all corresponding nodes are identical in value and structure.</p><h3><strong>Analysis</strong></h3><p><strong>Time Complexity:</strong> <br>O(n) where n is the total number of nodes in the smaller of the two trees. This is because the function traverses each node in both trees exactly once in a depth-first manner, comparing their values.</p><p><strong>Space Complexity:<br></strong>The space complexity is also O(n) in the worst case. This is because the function uses recursion, and in the worst case scenario, the recursion stack can grow as deep as the height of the smaller tree.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2317beded802" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/check-if-two-binary-trees-are-the-same-or-not-leetcode-java-solution-using-recursion-2317beded802">Check if two binary trees are the same or not — Leetcode Java Solution using recursion</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Search a 2D Matrix II — Java Leetcode Solution]]></title>
            <link>https://medium.com/@vinobabu.t/search-a-2d-matrix-ii-java-leetcode-solution-e68d8dfe87ef?source=rss-356d33dfc28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e68d8dfe87ef</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Vino Babu Thomas]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 13:27:09 GMT</pubDate>
            <atom:updated>2024-02-23T13:27:09.238Z</atom:updated>
            <content:encoded><![CDATA[<h3>Search a 2D Matrix II — Java Leetcode Solution</h3><h3><strong>Problem Statement</strong></h3><p>Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:</p><ul><li>Integers in each row are sorted in ascending from left to right.</li><li>Integers in each column are sorted in ascending from top to bottom.</li></ul><p><strong>Example 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/0*KADZZuOEL2YibMem.jpg" /></figure><pre>Input: matrix = [[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]], target = 5<br>Output: true</pre><p><strong>Example 2:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/0*FgXtx2NWrM46-1mf.jpg" /></figure><pre>Input: matrix = [[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]], target = 20<br>Output: false</pre><h3><strong>Approach</strong></h3><p>The approach used in the searchMatrix method is known as the &quot;Search Space Reduction&quot; approach. This algorithm is designed to efficiently search for a target value in a sorted 2D matrix where:</p><ul><li>The rows are sorted in ascending order from left to right.</li><li>The columns are sorted in ascending order from top to bottom.</li></ul><p>This algorithm efficiently searches a sorted 2D matrix by starting from a corner and iteratively narrowing down the search space based on comparisons with the target value. If the current value is greater than the target, the column is decremented; if less, the row is incremented. Time complexity is O(m + n).</p><h3><strong>Java Program</strong></h3><pre>class Solution {<br>    public boolean searchMatrix(int[][] matrix, int target) {<br>        int rowLen = matrix.length;<br>        int colLen = matrix[0].length;<br>        int row = 0;<br>        int col = colLen - 1;<br><br>        while (row &lt; rowLen &amp;&amp; col &gt;= 0) {<br>            if (matrix[row][col] &gt; target) {<br>                col--;<br>            } else if (matrix[row][col] &lt; target) {<br>                row++;<br>            } else {<br>                return true;<br>            }<br>        }<br>        return false;<br>    }<br><br>}</pre><h3><strong>Explanation</strong></h3><p>Here’s how the algorithm works:</p><ol><li>Initialize Pointers: Start with a pointer at the top-right corner of the matrix (or bottom-left corner could also be chosen), which is typically chosen as it helps to either increase or decrease row or column indices to navigate through the matrix.</li><li>Search Loop: Use a loop (in this case, a while loop) to traverse through the matrix while the pointers remain within the bounds of the matrix.</li><li>Comparison: At each iteration of the loop, compare the value at the current position (matrix[row][col]) with the target value.</li></ol><ul><li>If the current value is greater than the target, it means the target value can’t exist in the entire column to the right of the current position (as the column is sorted in ascending order). So, move the column pointer (col) one step to the left.</li><li>If the current value is less than the target, it means the target value can’t exist in the entire row above the current position (as the row is sorted in ascending order). So, move the row pointer (row) one step down.</li><li>If the current value is equal to the target, return true, as the target is found.</li></ul><h3><strong>Analysis</strong></h3><p>Time Complexity: O(m + n) where ‘m’ is the number of rows and ’n’ is the number of columns in the matrix<br>Space Complexity: O(1)</p><p>Thanks for reading. Kindly upvote if you find my post is useful.</p><p>Happy Coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e68d8dfe87ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Power of Two — Leetcode Java Solution]]></title>
            <link>https://medium.com/@vinobabu.t/power-of-two-leetcode-java-solution-721ba53f2227?source=rss-356d33dfc28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/721ba53f2227</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Vino Babu Thomas]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 14:13:08 GMT</pubDate>
            <atom:updated>2024-02-20T14:13:08.902Z</atom:updated>
            <content:encoded><![CDATA[<h3>Power of Two — Leetcode Java Solution</h3><h3><strong>Problem Statement</strong></h3><p>Given an integer n, return <em>true if it is a power of two. Otherwise, return </em><em>false</em>.</p><p>An integer n is a power of two, if there exists an integer x such that n == 2x.</p><p><strong>Example 1:</strong></p><pre>Input: n = 1<br>Output: true<br>Explanation: 20 = 1</pre><p><strong>Example 2:</strong></p><pre>Input: n = 16<br>Output: true<br>Explanation: 24 = 16</pre><p><strong>Example 3:</strong></p><pre>Input: n = 3<br>Output: false</pre><h3><strong>Approach:</strong></h3><p>This method iteratively divides the input integer by 2 until reaching 1 or an odd number, checking if it’s a power of two. It returns true if the input is 1 or a power of 2, otherwise false.</p><h3><strong>Java Program</strong></h3><pre>class Solution {<br>    public boolean isPowerOfTwo(int n) {<br>        if (n &lt;= 1) {<br>            return n == 1;<br>        }<br>        while (n &gt; 1) {<br>            if (n % 2 == 1) {<br>                return false;<br>            }<br>            n = n / 2;<br>        }<br>        return true;<br>    }<br><br>}</pre><h3><strong>Explanation</strong></h3><p>The approach checks if an integer n is a power of two:</p><ol><li>It handles edge cases where n is less than or equal to 1. If n equals 1, the approach returns true; otherwise, it returns false for any other non-positive n.</li><li>For n greater than 1, the approach iteratively divides n by 2 until it becomes 1 or an odd number.</li><li>If n becomes 1 after division, it&#39;s a power of two, so the approach returns true.</li><li>If n becomes an odd number during the division, it&#39;s not a power of two, so the approach returns false.</li></ol><p><strong>Analysis</strong></p><p>Time Complexity: <strong>O(log n)</strong>, where n is the input integer. This is because the program iteratively divides the input integer by 2 until it reaches 1 or an odd number. The number of iterations required to reach 1 or an odd number is logarithmic in the value of n, hence the time complexity is O(log n).<br>Space Complexity: <strong>O(1)</strong>, which means it uses constant space.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=721ba53f2227" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Least Number of Unique Integers after K Removals — Leetcode Java Solution]]></title>
            <link>https://medium.com/@vinobabu.t/least-number-of-unique-integers-after-k-removals-leetcode-java-solution-8909c43197b0?source=rss-356d33dfc28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8909c43197b0</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Vino Babu Thomas]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 18:23:33 GMT</pubDate>
            <atom:updated>2024-02-16T18:23:33.260Z</atom:updated>
            <content:encoded><![CDATA[<h3>Least Number of Unique Integers after K Removals — Leetcode Java Solution</h3><h3><strong>Problem Statement</strong></h3><p>Given an array of integers arr and an integer k. Find the <em>least number of unique integers</em> after removing <strong>exactly</strong> k elements<strong>.</strong></p><p><strong>Example 1:</strong></p><pre>Input: arr = [5,5,4], k = 1<br>Output: 1<br>Explanation: Remove the single 4, only 5 is left.</pre><p><strong>Example 2:</strong></p><pre>Input: arr = [4,3,1,1,3,3,2], k = 3<br>Output: 2<br>Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.</pre><h3><strong>Approach</strong></h3><p>The idea is to remove numbers with the least frequency first and only distinct elements are to be considered in the result. More the frequency, less the count due to distinct constraint. The approach involves counting the frequency of each integer in the array and storing it in a data structure. Then, it utilizes a priority queue to keep track of the frequencies, allowing efficient removal of the least frequent elements. By iteratively removing elements based on a given limit, it determines the least number of unique integers remaining in the array. This method ensures that the removal process prioritizes the least frequent elements, ultimately achieving the desired result.</p><h3><strong>Java Program:</strong></h3><pre>class Solution {<br>    public int findLeastNumOfUniqueInts(int[] arr, int k) {<br>        Map&lt;Integer, Integer&gt; freq = new HashMap&lt;Integer, Integer&gt;();<br>        for (int n : arr) {<br>            freq.put(n, freq.getOrDefault(n, 0) + 1);<br>        }<br>        PriorityQueue&lt;Map.Entry&lt;Integer, Integer&gt;&gt; pq =<br>                new PriorityQueue&lt;&gt;((a, b) -&gt; a.getValue() - b.getValue());<br>        pq.addAll(freq.entrySet());<br>        while (k &gt; 0) {<br>            pq.poll();<br>            k--;<br>        }<br>        return pq.size();<br>    }<br>}</pre><h3>Explanation</h3><ol><li><strong>Frequency Counting</strong>: Initialize a HashMap named freq to count the frequency of each integer in the array. Iterate through the array, updating the count of each integer in the map.</li><li><strong>PriorityQueue</strong>: Create a PriorityQueue named pq to store the frequency map entries. Set up a custom comparator to prioritize entries based on their frequency.</li><li><strong>Removing Elements</strong>: Enter a while loop to remove k elements from the priority queue. This action effectively eliminates the k least frequent integers from the array.</li><li><strong>Returning Result:</strong> Return the size of the priority queue, representing the number of unique integers remaining after removing k elements.</li></ol><h3><strong>Analysis</strong></h3><p><strong>Time Complexity:</strong></p><ul><li>Frequency Counting: This step requires iterating through the entire array once, which takes O(n) time, where n is the number of elements in the array.</li><li>Creating PriorityQueue: Building the priority queue from the frequency map entries takes O(n log n) time, where n is the number of unique elements in the array.</li><li>Removing Elements: Removing k elements from the priority queue takes O(k log n) time. Overall, the time complexity is dominated by O(n log n) due to building the priority queue.</li></ul><p><strong>Space Complexity:</strong></p><ul><li>Frequency Counting: Requires O(n) space to store the frequency map.</li><li>PriorityQueue: Requires O(n) space to store the frequency map entries. Overall, the space complexity is O(n) due to storing the frequency map and priority queue.</li></ul><p>In summary:</p><ul><li>Time complexity: O(n log n)</li><li>Space complexity: O(n)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8909c43197b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Find Polygon With the Largest Perimeter — Java Leetcode Solution]]></title>
            <link>https://medium.com/@vinobabu.t/find-polygon-with-the-largest-perimeter-java-leetcode-solution-2c33e0a9d5c0?source=rss-356d33dfc28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c33e0a9d5c0</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Vino Babu Thomas]]></dc:creator>
            <pubDate>Thu, 15 Feb 2024 10:30:54 GMT</pubDate>
            <atom:updated>2024-02-15T10:50:23.829Z</atom:updated>
            <content:encoded><![CDATA[<h3>Find Polygon With the Largest Perimeter — Java Leetcode Solution</h3><h3>Problem Statement</h3><p>You are given an array of <strong>positive</strong> integers nums of length n.</p><p>A <strong>polygon</strong> is a closed plane figure that has at least 3 sides. The <strong>longest side</strong> of a polygon is <strong>smaller</strong> than the sum of its other sides.</p><p>Conversely, if you have k (k &gt;= 3) <strong>positive</strong> real numbers a1, a2, a3, ..., ak where a1 &lt;= a2 &lt;= a3 &lt;= ... &lt;= ak <strong>and</strong> a1 + a2 + a3 + ... + ak-1 &gt; ak, then there <strong>always</strong> exists a polygon with k sides whose lengths are a1, a2, a3, ..., ak.</p><p>The <strong>perimeter</strong> of a polygon is the sum of lengths of its sides.</p><p>Return <em>the </em><strong><em>largest</em></strong><em> possible </em><strong><em>perimeter</em></strong><em> of a </em><strong><em>polygon</em></strong><em> whose sides can be formed from</em> nums, <em>or</em> -1 <em>if it is not possible to create a polygon</em>.</p><p><strong>Example 1:</strong></p><pre>Input: nums = [5,5,5]<br>Output: 15<br>Explanation: The only possible polygon that can be made from nums has 3 sides: 5, 5, and 5. The perimeter is 5 + 5 + 5 = 15.</pre><p><strong>Example 2:</strong></p><pre>Input: nums = [1,12,1,2,5,50,3]<br>Output: 12<br>Explanation: The polygon with the largest perimeter which can be made from nums has 5 sides: 1, 1, 2, 3, and 5. The perimeter is 1 + 1 + 2 + 3 + 5 = 12.<br>We cannot have a polygon with either 12 or 50 as the longest side because it is not possible to include 2 or more smaller sides that have a greater sum than either of them.<br>It can be shown that the largest possible perimeter is 12.</pre><h3>Approach -1 || Using prefix sum:</h3><p>This approach utilizes prefix sums and array sorting. It checks if forming a polygon is feasible. It computes prefix sums for array elements and iterates to find the largest perimeter. The longest side is determined dynamically. The solution efficiently identifies valid polygon sides and calculates the maximum perimeter possible.</p><h3>JAVA PROGRAM</h3><pre>class Solution {<br>    public long largestPerimeter(int[] nums) {<br>        int n = nums.length;<br>        long[] prefSum = new long[n];<br>        if (n &lt; 3) {<br>            return -1;<br>        }<br>        Arrays.sort(nums);<br>        prefSum[0] = nums[0];<br>        for (int i = 1; i &lt; n; i++) {<br>            prefSum[i] = nums[i] + prefSum[i - 1];<br>        }<br>        long peri = -1;<br>        for (int i = 2; i &lt; n; i++) {<br>            if (nums[i] &lt; prefSum[i - 1]) {<br>                peri = Math.max(peri, prefSum[i - 1] + nums[i]);<br>            }<br>        }<br>        return peri;<br><br>    }<br>}</pre><h3>Explanation:</h3><ol><li>First, it checks if the length of the array nums is less than 3. If it is, then it&#39;s impossible to form a polygon, so it returns -1.</li><li>It sorts the array nums in non-decreasing order. This is crucial for the algorithm because it allows us to easily identify the longest side of the potential polygon.</li><li>It initializes a prefSum array to store the prefix sum of elements in nums. This array will help efficiently compute the sum of the sides of the polygon.</li><li>It computes the prefix sum by iterating over the sorted array nums and accumulating the sums.</li><li>Then, it iterates over the array nums starting from the third element (index 2). For each element, it checks if the current element is smaller than the sum of the elements before it (using prefSum[i-1]). If this condition holds, it updates the peri variable with the maximum of its current value and the sum of the side lengths at this point.</li><li>Finally, it returns the value of peri, which represents the largest possible perimeter of a polygon that can be formed from the array nums.</li></ol><p><strong>Analysis:<br></strong>Time Complexity: O(n log n) for sorting<br>Space Complexity: O(n) for prefix sum</p><p>We will avoid the extra space using the below approach.</p><h3><strong>Approach-2 || Avoiding Extra Space</strong></h3><p>The optimized approach calculates the sum of array elements upfront. It sorts the array to identify potential polygon sides efficiently. It iterates backward, checking if the sum of remaining elements exceeds the current element, ensuring polygon validity. This approach improves both time and space complexities, eliminating the need for a separate prefix sum array.</p><p><strong>JAVA PROGRAM</strong></p><pre>class Solution {<br>    public long largestPerimeter(int[] nums) {<br>        int n = nums.length;<br>        if (n &lt; 3) {<br>            return -1;<br>        }<br>        long sum = 0;<br>        for (int i = 0; i &lt; n; i++) {<br>            sum += nums[i];<br>        }<br>        Arrays.sort(nums);<br>        long peri = -1;<br><br>        for (int i = n - 1; i &gt;= 2; i--) {<br>            if (sum - nums[i] &gt; nums[i]) {<br>                peri = Math.max(peri, sum);<br>            }<br>            sum -= nums[i];<br>        }<br>        return peri;<br>    }<br>}</pre><h3>Explanation</h3><ol><li>It first checks if the length of the array nums is less than 3. If so, it returns -1 immediately as it&#39;s impossible to form a polygon with less than 3 sides.</li><li>It calculates the total sum of all elements in the array nums in a single pass. This reduces the need for prefix sum computation, saving both time and space.</li><li>It sorts the array nums in non-decreasing order, crucial for identifying the longest side of the potential polygon.</li><li>It iterates backward over the sorted array nums, starting from the end. For each element, it checks if the sum of all elements excluding the current one is greater than the current element itself, which ensures the validity of a potential polygon.</li><li>If a valid polygon side is found, it updates the peri variable with the maximum of its current value and the total sum of all elements.</li><li>Finally, it returns the value of peri, representing the largest possible perimeter of a polygon that can be formed from the array nums.</li></ol><p><strong>Analysis:<br></strong>Time Complexity: O(n log n) for sorting<br>Space Complexity: O(1) since no extra space is introduced</p><p>Hope this post is helpful. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c33e0a9d5c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>