<?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"><channel><title><![CDATA[LeetCode Shahwar]]></title><description><![CDATA[I write LeetCode Explanations here]]></description><link>https://is-power-of-two.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 17 Jun 2026 19:18:25 GMT</lastBuildDate><atom:link href="https://is-power-of-two.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[LeetCode: Contains Duplicate II]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/contains-duplicate-ii/
Code:
class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        # window = k
        seen_in_window = set()
        for i in range(len(nums)):
       ...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-contains-duplicate-ii</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-contains-duplicate-ii</guid><category><![CDATA[leetcode]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Fri, 09 Jan 2026 17:52:50 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/contains-duplicate-ii/">https://leetcode.com/problems/contains-duplicate-ii/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">containsNearbyDuplicate</span>(<span class="hljs-params">self, nums: List[int], k: int</span>) -&gt; bool:</span>
        <span class="hljs-comment"># window = k</span>
        seen_in_window = set()
        <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(nums)):
            <span class="hljs-keyword">if</span> i&gt;k:
                seen_in_window.discard(nums[i-k<span class="hljs-number">-1</span>])
            <span class="hljs-keyword">if</span> nums[i] <span class="hljs-keyword">in</span> seen_in_window:
                <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
            <span class="hljs-keyword">else</span>:
                seen_in_window.add(nums[i])
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>You are given an array of numbers and an integer <code>k</code>. You must check whether there are <strong>two equal numbers</strong> such that:</p>
<ul>
<li>Their indices differ by <strong>at most</strong> <code>k</code></li>
</ul>
<p>In short:</p>
<blockquote>
<p>Same value + close enough positions → return True</p>
</blockquote>
<p>Example:</p>
<ul>
<li><p>nums = [1,2,3,1], k = 3 → True</p>
</li>
<li><p>nums = [1,0,1,1], k = 1 → True</p>
</li>
<li><p>nums = [1,2,3,1,2,3], k = 2 → False</p>
</li>
</ul>
<hr />
<h3 id="heading-core-idea-sliding-window-set">Core Idea (Sliding Window + Set)</h3>
<p>We only care about duplicates <strong>within distance</strong> <code>k</code>. So we maintain a <strong>sliding window of size</strong> <code>k</code> using a set.</p>
<p>The set always stores:</p>
<ul>
<li>the last <code>k</code> elements we have seen</li>
</ul>
<hr />
<h3 id="heading-how-the-algorithm-works">How the Algorithm Works</h3>
<ul>
<li><p>Traverse the array from left to right</p>
</li>
<li><p>For each index <code>i</code>:</p>
<ol>
<li><p>If the window size exceeds <code>k</code>:</p>
<ul>
<li>Remove the element that just moved out of the window<br />  (<code>nums[i - k - 1]</code>)</li>
</ul>
</li>
<li><p>Check if the current number already exists in the window:</p>
<ul>
<li><p>If yes → duplicate within range → return True</p>
</li>
<li><p>If no → add it to the window</p>
</li>
</ul>
</li>
</ol>
</li>
</ul>
<p>If we finish the loop without finding duplicates → return False</p>
<hr />
<h3 id="heading-why-removing-numsi-k-1-is-important">Why Removing <code>nums[i - k - 1]</code> Is Important</h3>
<ul>
<li><p>It keeps the window size limited to <code>k</code></p>
</li>
<li><p>Ensures we only compare elements whose index difference ≤ <code>k</code></p>
</li>
<li><p>Prevents false positives from far-away duplicates</p>
</li>
</ul>
<hr />
<h3 id="heading-why-a-set-is-perfect-here">Why a Set Is Perfect Here</h3>
<ul>
<li><p>Fast lookup: O(1)</p>
</li>
<li><p>No duplicate storage</p>
</li>
<li><p>Automatically tracks what’s inside the current window</p>
</li>
</ul>
<hr />
<h3 id="heading-why-this-works">Why This Works</h3>
<p>At any index <code>i</code>, the set contains exactly the elements from: indices: [i - k, i - 1]</p>
<p>So if <code>nums[i]</code> is already in the set:</p>
<ul>
<li><p>There exists some <code>j</code> where:</p>
<ul>
<li><p>nums[i] == nums[j]</p>
</li>
<li><p>|i - j| ≤ k</p>
</li>
</ul>
</li>
</ul>
<p>Which is exactly the condition asked.</p>
<hr />
<h3 id="heading-edge-cases-covered">Edge Cases Covered</h3>
<ul>
<li><p>k = 0 → window always empty → always False</p>
</li>
<li><p>Array with no duplicates → False</p>
</li>
<li><p>Duplicate values but too far apart → correctly ignored</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p><strong>Time:</strong> O(n)</p>
</li>
<li><p><strong>Space:</strong> O(k)</p>
</li>
</ul>
<hr />
<h3 id="heading-key-insight-to-remember">Key Insight to Remember</h3>
<p>Whenever a problem says:</p>
<blockquote>
<p>“same value within a distance constraint”</p>
</blockquote>
<p>👉 Think <strong>sliding window + set</strong>, not brute force.</p>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Rearrange Array Elements by Sign]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/rearrange-array-elements-by-sign/
Code:
class Solution:
    def rearrangeArray(self, nums: List[int]) -> List[int]:
        non_neg_nums = []
        neg_nums = []
        result = []

        # Segregated non-n...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-rearrange-array-elements-by-sign</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-rearrange-array-elements-by-sign</guid><category><![CDATA[leetcode]]></category><category><![CDATA[array]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Fri, 26 Dec 2025 06:39:59 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/rearrange-array-elements-by-sign/">https://leetcode.com/problems/rearrange-array-elements-by-sign/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">rearrangeArray</span>(<span class="hljs-params">self, nums: List[int]</span>) -&gt; List[int]:</span>
        non_neg_nums = []
        neg_nums = []
        result = []

        <span class="hljs-comment"># Segregated non-negs and negs</span>
        <span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> nums:
            <span class="hljs-keyword">if</span> num&gt;=<span class="hljs-number">0</span>:
                non_neg_nums.append(num)
            <span class="hljs-keyword">else</span>:
                neg_nums.append(num)

        <span class="hljs-comment"># thinking to use zip for corresponding pairs</span>
        <span class="hljs-keyword">for</span> pos, neg <span class="hljs-keyword">in</span> zip(non_neg_nums, neg_nums):
            result.append(pos)
            result.append(neg)

        <span class="hljs-keyword">return</span> result
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>You are given an array with:</p>
<ul>
<li>equal number of <strong>positive (or zero)</strong> and <strong>negative</strong> numbers</li>
</ul>
<p>You must rearrange the array so that:</p>
<ul>
<li><p>elements <strong>alternate by sign</strong></p>
</li>
<li><p>a <strong>non-negative number comes first</strong></p>
</li>
<li><p>the relative order <strong>within positives and negatives is preserved</strong></p>
</li>
</ul>
<p>Example:</p>
<ul>
<li><code>[3,1,-2,-5,2,-4]</code> → <code>[3,-2,1,-5,2,-4]</code></li>
</ul>
<hr />
<h3 id="heading-core-idea-separate-then-interleave">Core Idea (Separate → Then Interleave)</h3>
<p>The idea is very simple and clean:</p>
<ol>
<li><p><strong>Separate</strong> the numbers by sign</p>
</li>
<li><p><strong>Interleave</strong> them one by one in the required order</p>
</li>
</ol>
<p>This avoids complex index juggling.</p>
<hr />
<h3 id="heading-how-the-solution-works">How the Solution Works</h3>
<ol>
<li><p>Traverse the array once:</p>
<ul>
<li><p>Store all non-negative numbers in <code>non_neg_nums</code></p>
</li>
<li><p>Store all negative numbers in <code>neg_nums</code></p>
</li>
</ul>
</li>
<li><p>Since the problem guarantees equal counts:</p>
<ul>
<li>Use <code>zip(non_neg_nums, neg_nums)</code></li>
</ul>
</li>
<li><p>For each <code>(pos, neg)</code> pair:</p>
<ul>
<li><p>Append <code>pos</code></p>
</li>
<li><p>Append <code>neg</code></p>
</li>
</ul>
</li>
<li><p>The resulting list automatically follows:</p>
<ul>
<li>non-negative, negative, non-negative, negative…</li>
</ul>
</li>
</ol>
<hr />
<h3 id="heading-why-zip-is-a-good-choice">Why <code>zip</code> Is a Good Choice</h3>
<ul>
<li><p>It pairs elements <strong>one-to-one</strong></p>
</li>
<li><p>Stops automatically at correct length</p>
</li>
<li><p>Makes the code concise and readable</p>
</li>
<li><p>Guarantees correct alternation</p>
</li>
</ul>
<hr />
<h3 id="heading-why-this-approach-is-correct">Why This Approach Is Correct</h3>
<ul>
<li><p>Order inside positives is preserved</p>
</li>
<li><p>Order inside negatives is preserved</p>
</li>
<li><p>Alternating pattern is guaranteed</p>
</li>
<li><p>Simple logic, no tricky pointer bugs</p>
</li>
</ul>
<hr />
<h3 id="heading-edge-cases-covered">Edge Cases Covered</h3>
<ul>
<li><p>All constraints guarantee valid input (equal positives &amp; negatives)</p>
</li>
<li><p>Zero is treated as non-negative (as required)</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p><strong>Time:</strong> O(n)</p>
</li>
<li><p><strong>Space:</strong> O(n) for temporary lists</p>
</li>
</ul>
<hr />
<h3 id="heading-key-insight-to-remember">Key Insight to Remember</h3>
<p>Whenever a problem asks for:</p>
<blockquote>
<p>“rearrange elements by categories but preserve order”</p>
</blockquote>
<p>👉 Think <strong>segregate first, then merge/interleave</strong>.</p>
]]></content:encoded></item><item><title><![CDATA[GeeksForGeeks: Array Leaders]]></title><description><![CDATA[Problem:
https://www.geeksforgeeks.org/problems/leaders-in-an-array-1587115620/1
Code:
class Solution:
    def leaders(self, arr):
        leads = []
        n = len(arr)
        maximum = arr[-1] # till will handle negatives

        # we will colle...]]></description><link>https://is-power-of-two.hashnode.dev/geeksforgeeks-array-leaders</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/geeksforgeeks-array-leaders</guid><category><![CDATA[leetcode]]></category><category><![CDATA[array]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Fri, 26 Dec 2025 05:24:24 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://www.geeksforgeeks.org/problems/leaders-in-an-array-1587115620/1">https://www.geeksforgeeks.org/problems/leaders-in-an-array-1587115620/1</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">leaders</span>(<span class="hljs-params">self, arr</span>):</span>
        leads = []
        n = len(arr)
        maximum = arr[<span class="hljs-number">-1</span>] <span class="hljs-comment"># till will handle negatives</span>

        <span class="hljs-comment"># we will collect the max seen so far from right</span>

        <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(n<span class="hljs-number">-1</span>, <span class="hljs-number">-1</span>, <span class="hljs-number">-1</span>):
            <span class="hljs-keyword">if</span> arr[i]&gt;=maximum:
                maximum=arr[i]
                leads.append(maximum)
        <span class="hljs-keyword">return</span> leads[::<span class="hljs-number">-1</span>]

<span class="hljs-comment"># Below Solution is correct/brute-force, does O(n^2), very witty but not optimised</span>
<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def leaders(self, arr):</span>
<span class="hljs-comment">#         leaders = []</span>

<span class="hljs-comment">#         n=len(arr)</span>

<span class="hljs-comment">#         if n&lt;2:</span>
<span class="hljs-comment">#             return arr</span>

<span class="hljs-comment">#         # Traverse trrough array</span>
<span class="hljs-comment">#         for traverser in range(n):</span>
<span class="hljs-comment">#             i=traverser+1 # i = next index</span>
<span class="hljs-comment">#             # check till right end, from present index</span>
<span class="hljs-comment">#             while i&lt;n:</span>
<span class="hljs-comment">#                 if arr[i] &gt; arr[traverser]:</span>
<span class="hljs-comment">#                     break</span>
<span class="hljs-comment">#                 i+=1</span>

<span class="hljs-comment">#             if i==n:</span>
<span class="hljs-comment">#                 leaders.append(arr[traverser])</span>

<span class="hljs-comment">#         return leaders</span>
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>An element in an array is called a <strong>leader</strong> if:</p>
<ul>
<li><p>It is <strong>greater than or equal to all elements to its right</strong></p>
</li>
<li><p>The <strong>rightmost element is always a leader</strong></p>
</li>
</ul>
<p>Example:</p>
<ul>
<li><code>[16, 17, 4, 3, 5, 2]</code> → leaders = <code>[17, 5, 2]</code></li>
</ul>
<hr />
<h3 id="heading-core-idea-scan-from-right-track-maximum">Core Idea (Scan from Right, Track Maximum)</h3>
<p>Instead of checking every element against all elements to its right, we scan the array <strong>from right to left</strong> and keep track of the <strong>maximum seen so far</strong>.</p>
<p>Why this works:</p>
<ul>
<li><p>When moving right → left, everything to the right is already known</p>
</li>
<li><p>If the current element is ≥ max_so_far, it must be a leader</p>
</li>
</ul>
<hr />
<h3 id="heading-how-the-optimized-solution-works">How the Optimized Solution Works</h3>
<ol>
<li><p>Start from the <strong>rightmost element</strong></p>
<ul>
<li><p>It is always a leader</p>
</li>
<li><p>Initialize <code>maximum = arr[-1]</code></p>
</li>
</ul>
</li>
<li><p>Move left one element at a time:</p>
<ul>
<li>If <code>arr[i] ≥ maximum</code>: → it is a leader → update <code>maximum</code> → add it to the leaders list</li>
</ul>
</li>
<li><p>Since leaders are collected from right to left:</p>
<ul>
<li>Reverse the list before returning</li>
</ul>
</li>
</ol>
<hr />
<h3 id="heading-why-initializing-maximum-arr-1-is-important">Why Initializing <code>maximum = arr[-1]</code> Is Important</h3>
<ul>
<li><p>Handles <strong>negative numbers</strong> correctly</p>
</li>
<li><p>Ensures first comparison is valid</p>
</li>
<li><p>Avoids incorrect assumptions like starting from 0</p>
</li>
</ul>
<hr />
<h3 id="heading-why-this-is-better-than-brute-force">Why This Is Better Than Brute Force</h3>
<p>Brute-force approach:</p>
<ul>
<li><p>For each element, scan all elements to its right</p>
</li>
<li><p>Time complexity: O(n²)</p>
</li>
</ul>
<p>Optimized approach:</p>
<ul>
<li><p>Single pass from right to left</p>
</li>
<li><p>Time complexity: O(n)</p>
</li>
</ul>
<hr />
<h3 id="heading-edge-cases-covered">Edge Cases Covered</h3>
<ul>
<li><p>Single element array → that element is the leader</p>
</li>
<li><p>All elements decreasing → all are leaders</p>
</li>
<li><p>Negative values → handled correctly</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p><strong>Time:</strong> O(n)</p>
</li>
<li><p><strong>Space:</strong> O(k) for leaders list</p>
</li>
</ul>
<hr />
<h3 id="heading-key-insight-to-remember">Key Insight to Remember</h3>
<p>Whenever a problem says:</p>
<blockquote>
<p>“compare each element with everything to its right”</p>
</blockquote>
<p>👉 Try <strong>reverse traversal + running maximum</strong> instead of nested loops.</p>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Intersection of Two Arrays]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/intersection-of-two-arrays/
Code:
class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        result = set()
        n2 = set(nums2)

        for num in nums1:
          ...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-intersection-of-two-arrays</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-intersection-of-two-arrays</guid><category><![CDATA[leetcode]]></category><category><![CDATA[array]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Wed, 24 Dec 2025 02:22:06 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/intersection-of-two-arrays/">https://leetcode.com/problems/intersection-of-two-arrays/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">intersection</span>(<span class="hljs-params">self, nums1: List[int], nums2: List[int]</span>) -&gt; List[int]:</span>
        result = set()
        n2 = set(nums2)

        <span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> nums1:
            <span class="hljs-keyword">if</span> num <span class="hljs-keyword">in</span> n2:
                result.add(num)

        <span class="hljs-keyword">return</span> list(result)

<span class="hljs-comment"># olution below is brute force, not optimised, sol above uses set effectively to make overall sol more optimized.</span>
<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def intersection(self, nums1: List[int], nums2: List[int]) -&gt; List[int]:</span>
<span class="hljs-comment">#         result = set()</span>
<span class="hljs-comment">#         for i in range(len(nums1)):</span>
<span class="hljs-comment">#             for j in range(len(nums2)):</span>
<span class="hljs-comment">#                 if nums1[i] ^ nums2[j] == 0:</span>
<span class="hljs-comment">#                     result.add(nums1[i])</span>
<span class="hljs-comment">#         return list(result)</span>
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>You are given two arrays. You need to return <strong>all numbers that appear in both arrays</strong>.</p>
<ul>
<li><p>Each number should appear <strong>only once</strong> in the result</p>
</li>
<li><p>Order does not matter</p>
</li>
</ul>
<p>Example:</p>
<ul>
<li><p>nums1 = [1,2,2,1], nums2 = [2,2] → [2]</p>
</li>
<li><p>nums1 = [4,9,5], nums2 = [9,4,9,8,4] → [4,9]</p>
</li>
</ul>
<hr />
<h3 id="heading-core-idea-use-sets-for-fast-lookup-uniqueness">Core Idea (Use Sets for Fast Lookup + Uniqueness)</h3>
<p>We use <strong>sets</strong> because they:</p>
<ul>
<li><p>Automatically remove duplicates</p>
</li>
<li><p>Allow very fast membership checking (O(1) average)</p>
</li>
</ul>
<hr />
<h3 id="heading-how-the-optimized-solution-works">How the Optimized Solution Works</h3>
<ol>
<li><p>Convert <code>nums2</code> into a set:</p>
<ul>
<li>This makes checking “is this number present?” very fast</li>
</ul>
</li>
<li><p>Loop through each number in <code>nums1</code>:</p>
<ul>
<li>If the number exists in the set made from <code>nums2</code>: → add it to the result set</li>
</ul>
</li>
<li><p>Convert the result set to a list and return it</p>
</li>
</ol>
<hr />
<h3 id="heading-why-we-use-a-set-for-nums2">Why We Use a Set for <code>nums2</code></h3>
<ul>
<li><p>Checking <code>num in nums2_list</code> would take O(n) time</p>
</li>
<li><p>Checking <code>num in nums2_set</code> takes O(1) time</p>
</li>
<li><p>This reduces overall time significantly</p>
</li>
</ul>
<hr />
<h3 id="heading-why-the-result-is-also-a-set">Why the Result Is Also a Set</h3>
<ul>
<li><p>The problem requires <strong>unique values only</strong></p>
</li>
<li><p>Set automatically ensures no duplicates in the result</p>
</li>
</ul>
<hr />
<h3 id="heading-why-this-is-better-than-brute-force">Why This Is Better Than Brute Force</h3>
<p>Brute force:</p>
<ul>
<li><p>Compare every element of nums1 with every element of nums2</p>
</li>
<li><p>Time complexity: O(n × m)</p>
</li>
</ul>
<p>Optimized approach:</p>
<ul>
<li><p>One pass with fast lookups</p>
</li>
<li><p>Much more efficient for large inputs</p>
</li>
</ul>
<hr />
<h3 id="heading-edge-cases-covered">Edge Cases Covered</h3>
<ul>
<li><p>No common elements → empty list returned</p>
</li>
<li><p>One or both arrays empty → empty list returned</p>
</li>
<li><p>Duplicate values in input → handled automatically</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p><strong>Time:</strong> O(n + m)</p>
</li>
<li><p><strong>Space:</strong> O(m + k)</p>
<ul>
<li><p>m = size of nums2 (set)</p>
</li>
<li><p>k = size of intersection set</p>
</li>
</ul>
</li>
</ul>
<hr />
<h3 id="heading-key-insight-to-remember">Key Insight to Remember</h3>
<p>Whenever a problem asks for:</p>
<blockquote>
<p>“common elements” + “unique values”</p>
</blockquote>
<p>👉 Think <strong>set + membership checking</strong>, not nested loops.</p>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Repeated Substring Pattern]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/repeated-substring-pattern/
Code:
class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        return s in (s + s)[1:-1]

        # Points to note:
        # - A repeated string will reappear ...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-repeated-substring-pattern</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-repeated-substring-pattern</guid><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Mon, 22 Dec 2025 06:04:13 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/repeated-substring-pattern/">https://leetcode.com/problems/repeated-substring-pattern/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">repeatedSubstringPattern</span>(<span class="hljs-params">self, s: str</span>) -&gt; bool:</span>
        <span class="hljs-keyword">return</span> s <span class="hljs-keyword">in</span> (s + s)[<span class="hljs-number">1</span>:<span class="hljs-number">-1</span>]

        <span class="hljs-comment"># Points to note:</span>
        <span class="hljs-comment"># - A repeated string will reappear inside its own doubled version (minus edges).</span>
        <span class="hljs-comment"># - If s is made by repeating a substring. Then s must appear inside (s + s) after removing first &amp; last chars</span>
        <span class="hljs-comment"># - First anf Last characters are removed. This removes the trivial full-string match.</span>

<span class="hljs-comment"># Below is a good solution but time comlexity for worst case is still O(n^2) due to new string formations everytime.</span>
<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def repeatedSubstringPattern(self, s: str) -&gt; bool:</span>
<span class="hljs-comment">#         n = len(s)</span>
<span class="hljs-comment">#         result=""</span>
<span class="hljs-comment">#         i=1</span>
<span class="hljs-comment">#         while i&lt;=n//2:</span>
<span class="hljs-comment">#             sub_str = s[:i]</span>
<span class="hljs-comment">#             factor = n//i</span>
<span class="hljs-comment">#             result = sub_str * factor</span>
<span class="hljs-comment">#             i+=1</span>
<span class="hljs-comment">#             if result == s:</span>
<span class="hljs-comment">#                 return True</span>
<span class="hljs-comment">#         return False</span>
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>You are given a string <code>s</code>. Check if it can be formed by <strong>repeating one of its substrings multiple times</strong>.</p>
<p>Example:</p>
<ul>
<li><p><code>"abab"</code> → <code>"ab"</code> repeated → True</p>
</li>
<li><p><code>"aba"</code> → cannot be repeated → False</p>
</li>
<li><p><code>"aaaa"</code> → <code>"a"</code> repeated → True</p>
</li>
</ul>
<hr />
<h3 id="heading-core-idea-smart-string-trick">Core Idea (Smart String Trick)</h3>
<p>If a string is made by repeating a smaller substring, then:</p>
<ul>
<li><p>It will appear <strong>inside its own doubled version</strong> (<code>s + s</code>)</p>
</li>
<li><p>But we must remove the <strong>first and last characters</strong> to avoid a trivial full match</p>
</li>
</ul>
<p>So:</p>
<ul>
<li>Check whether <code>s</code> exists inside <code>(s + s)[1:-1]</code></li>
</ul>
<p>If yes → string is built by repetition<br />If no → it is not</p>
<hr />
<h3 id="heading-why-removing-first-amp-last-characters-is-important">Why Removing First &amp; Last Characters Is Important</h3>
<ul>
<li><p><code>s + s</code> always contains <code>s</code> as a full match at the start and end</p>
</li>
<li><p>Removing the edges forces us to detect only <strong>true internal repetitions</strong></p>
</li>
<li><p>This eliminates false positives</p>
</li>
</ul>
<hr />
<h3 id="heading-why-this-works">Why This Works</h3>
<ul>
<li><p>Repeated patterns naturally shift and overlap in the doubled string</p>
</li>
<li><p>Non-repeated strings cannot fully reappear once edges are removed</p>
</li>
<li><p>This trick avoids checking every possible substring</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p><strong>Time:</strong> O(n)</p>
</li>
<li><p><strong>Space:</strong> O(n)</p>
</li>
</ul>
<hr />
<h2 id="heading-key-points-for-the-substring-construction-approach-commented-solution">Key Points for the <strong>Substring Construction Approach</strong> (Commented Solution)</h2>
<h3 id="heading-core-idea-try-all-possible-substrings">Core Idea (Try All Possible Substrings)</h3>
<p>If <code>s</code> is made by repeating a substring:</p>
<ul>
<li><p>That substring’s length must be a <strong>divisor</strong> of <code>len(s)</code></p>
</li>
<li><p>The substring must start from index <code>0</code></p>
</li>
<li><p>Repeating it enough times should recreate the full string</p>
</li>
</ul>
<p>So we:</p>
<ul>
<li><p>Try all possible substring lengths from <code>1</code> to <code>n // 2</code></p>
</li>
<li><p>Check if repeating that substring forms the original string</p>
</li>
</ul>
<hr />
<h3 id="heading-how-the-logic-works">How the Logic Works</h3>
<ol>
<li><p>Let <code>n = len(s)</code></p>
</li>
<li><p>For each possible substring length <code>i</code> (from <code>1</code> to <code>n//2</code>):</p>
<ul>
<li><p>Take <code>sub_str = s[:i]</code></p>
</li>
<li><p>Calculate how many times it must repeat:</p>
<ul>
<li><code>factor = n // i</code></li>
</ul>
</li>
<li><p>Build a new string by repeating:</p>
<ul>
<li><code>sub_str * factor</code></li>
</ul>
</li>
</ul>
</li>
<li><p>Compare this newly formed string with <code>s</code></p>
<ul>
<li>If equal → repeated pattern exists → return True</li>
</ul>
</li>
<li><p>If no substring works → return False</p>
</li>
</ol>
<hr />
<h3 id="heading-why-we-only-check-up-to-n2">Why We Only Check Up to <code>n//2</code></h3>
<ul>
<li><p>A repeating substring must be <strong>smaller than the full string</strong></p>
</li>
<li><p>Any substring longer than <code>n//2</code> can repeat at most once → not useful (in simple words, if length of a substring is more than half of the length of string, then it cannot even double itself, forget, it repeats multiple times in the string)</p>
</li>
</ul>
<hr />
<h3 id="heading-why-this-approach-is-correct">Why This Approach Is Correct</h3>
<ul>
<li><p>Every valid repeated pattern must start from index <code>0</code></p>
</li>
<li><p>Trying all possible substring lengths ensures we don’t miss any case</p>
</li>
<li><p>Direct comparison guarantees correctness</p>
</li>
</ul>
<hr />
<h3 id="heading-why-this-approach-is-slower">Why This Approach Is Slower</h3>
<ul>
<li><p>Each repetition creates a <strong>new string</strong></p>
</li>
<li><p>In worst case:</p>
<ul>
<li><p>We try O(n) substring lengths</p>
</li>
<li><p>Each string creation + comparison costs O(n)</p>
</li>
</ul>
</li>
<li><p>Overall worst-case time: <strong>O(n²)</strong></p>
</li>
</ul>
<hr />
<h3 id="heading-when-this-approach-is-still-useful">When This Approach Is Still Useful</h3>
<ul>
<li><p>Easy to understand</p>
</li>
<li><p>Good for learning / brute-force reasoning</p>
</li>
<li><p>Works fine for small strings</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity-1">Complexity</h3>
<ul>
<li><p><strong>Time:</strong> O(n²) in worst case</p>
</li>
<li><p><strong>Space:</strong> O(n) due to new string creation</p>
</li>
</ul>
<hr />
<h3 id="heading-key-insight-to-remember">Key Insight to Remember</h3>
<p>This method focuses on:</p>
<blockquote>
<p>“Try every possible repeating block and rebuild the string”</p>
</blockquote>
<p>It’s intuitive and correct — but <strong>not optimal</strong> compared to the<br /><code>(s + s)[1:-1]</code> trick, which achieves O(n) time.</p>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Missing Number]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/missing-number/
Code:
class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        n = len(nums)
        actual_sum = sum(nums)
        expected_sum = (n * (n + 1))//2 # including the missing num...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-missing-number</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-missing-number</guid><category><![CDATA[leetcode]]></category><category><![CDATA[array]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Sun, 21 Dec 2025 11:48:05 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/missing-number/">https://leetcode.com/problems/missing-number/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">missingNumber</span>(<span class="hljs-params">self, nums: List[int]</span>) -&gt; int:</span>
        n = len(nums)
        actual_sum = sum(nums)
        expected_sum = (n * (n + <span class="hljs-number">1</span>))//<span class="hljs-number">2</span> <span class="hljs-comment"># including the missing number</span>
        missing_number = expected_sum - actual_sum <span class="hljs-comment"># common sense, diff -&gt; missing number</span>
        <span class="hljs-keyword">return</span> missing_number

<span class="hljs-comment"># This one is the 2nd best solution, good but space can still be optimised and made from O(n) to O(1)</span>
<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def missingNumber(self, nums: List[int]) -&gt; int:</span>
<span class="hljs-comment">#         numbers = set(nums)</span>
<span class="hljs-comment">#         for i in range(0, len(nums)+1):</span>
<span class="hljs-comment">#             if i not in numbers:</span>
<span class="hljs-comment">#                 return i</span>

<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def missingNumber(self, nums: List[int]) -&gt; int:</span>
<span class="hljs-comment">#         for number in range(0, len(nums)+1):</span>
<span class="hljs-comment">#             if number not in set(nums):</span>
<span class="hljs-comment">#                 return number</span>

<span class="hljs-comment"># =============</span>

<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def missingNumber(self, nums: List[int]) -&gt; int:</span>
<span class="hljs-comment">#         numbers = set(range(len(nums)+1))</span>
<span class="hljs-comment">#         for n in numbers:</span>
<span class="hljs-comment">#             if n not in nums:</span>
<span class="hljs-comment">#                 return n</span>

<span class="hljs-comment"># ===========</span>

<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def missingNumber(self, nums: List[int]) -&gt; int:</span>
<span class="hljs-comment">#         n = len(nums)</span>
<span class="hljs-comment">#         for number in range(n+1):</span>
<span class="hljs-comment">#             if not number in nums:</span>
<span class="hljs-comment">#                 return number</span>
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>You are given an array containing <code>n</code> <strong>distinct numbers</strong>. The numbers are from the range <strong>0 to n</strong>, but <strong>one number is missing</strong>. You must find and return that missing number.</p>
<p>Example:</p>
<ul>
<li><p><code>[3,0,1]</code> → missing number = <code>2</code></p>
</li>
<li><p><code>[0,1]</code> → missing number = <code>2</code></p>
</li>
</ul>
<hr />
<h3 id="heading-core-idea-math-trick-expected-sum-vs-actual-sum">Core Idea (Math Trick: Expected Sum vs Actual Sum)</h3>
<p>If <strong>no number were missing</strong>, the sum of numbers from <code>0</code> to <code>n</code> would be:</p>
<p>0 + 1 + 2 + ... + n = n × (n + 1) / 2</p>
<p>So:</p>
<ul>
<li><p><strong>Expected sum</strong> = sum of all numbers from <code>0</code> to <code>n</code></p>
</li>
<li><p><strong>Actual sum</strong> = sum of numbers present in the array</p>
</li>
</ul>
<p>The <strong>difference</strong> between these two sums is exactly the missing number.</p>
<hr />
<h3 id="heading-how-the-solution-works">How the Solution Works</h3>
<ol>
<li><p>Let <code>n = len(nums)</code></p>
</li>
<li><p>Compute:</p>
<ul>
<li><code>expected_sum = n × (n + 1) // 2</code></li>
</ul>
</li>
<li><p>Compute:</p>
<ul>
<li><code>actual_sum = sum(nums)</code></li>
</ul>
</li>
<li><p>The missing number is:</p>
<ul>
<li><code>expected_sum - actual_sum</code></li>
</ul>
</li>
</ol>
<p>This works because:</p>
<ul>
<li><p>Every number except one appears exactly once</p>
</li>
<li><p>All other values cancel out in the subtraction</p>
</li>
</ul>
<hr />
<h3 id="heading-why-this-approach-is-optimal">Why This Approach Is Optimal</h3>
<ul>
<li><p>Only one pass over the array</p>
</li>
<li><p>No extra data structures</p>
</li>
<li><p>Clean mathematical reasoning</p>
</li>
</ul>
<hr />
<h3 id="heading-edge-cases-covered">Edge Cases Covered</h3>
<ul>
<li><p>Missing number is <code>0</code></p>
</li>
<li><p>Missing number is <code>n</code></p>
</li>
<li><p>Array in any order</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p><strong>Time:</strong> O(n)</p>
</li>
<li><p><strong>Space:</strong> O(1)</p>
</li>
</ul>
<hr />
<h3 id="heading-key-insight-to-remember">Key Insight to Remember</h3>
<p>Whenever you see:</p>
<blockquote>
<p>“numbers from 0 to n with exactly one missing”</p>
</blockquote>
<p>👉 Think <strong>sum formula or XOR trick</strong> instead of sets or loops.</p>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Second Largest Digit in a String]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/second-largest-digit-in-a-string/
Code:
class Solution:
    def secondHighest(self, s: str) -> int:
        dgts = set()
        for ch in s:
            if ch.isdigit():
                dgts.add(int(ch)) 
     ...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-second-largest-digit-in-a-string</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-second-largest-digit-in-a-string</guid><category><![CDATA[leetcode]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Sun, 21 Dec 2025 10:19:37 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/second-largest-digit-in-a-string/">https://leetcode.com/problems/second-largest-digit-in-a-string/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">secondHighest</span>(<span class="hljs-params">self, s: str</span>) -&gt; int:</span>
        dgts = set()
        <span class="hljs-keyword">for</span> ch <span class="hljs-keyword">in</span> s:
            <span class="hljs-keyword">if</span> ch.isdigit():
                dgts.add(int(ch)) 
        <span class="hljs-comment"># now we have all unique digits</span>

        <span class="hljs-comment"># if dgts has 1 or no value, there can be no 2nd largest</span>
        <span class="hljs-keyword">if</span> len(dgts)&lt;=<span class="hljs-number">1</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>

        <span class="hljs-comment"># if control come here, it has sufficient values</span>
        <span class="hljs-comment"># remove the max digit</span>
        dgts.remove(max(dgts))
        <span class="hljs-keyword">return</span> max(dgts)

<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def secondHighest(self, s: str) -&gt; int:</span>
<span class="hljs-comment">#         dgts = []</span>
<span class="hljs-comment">#         for ch in s:</span>
<span class="hljs-comment">#             if ch.isdigit():</span>
<span class="hljs-comment">#                 dgts.append(int(ch))</span>

<span class="hljs-comment">#         if not dgts:</span>
<span class="hljs-comment">#             return -1</span>

<span class="hljs-comment">#         dgts = set(dgts)</span>
<span class="hljs-comment">#         dgts.remove(max(dgts))</span>

<span class="hljs-comment">#         if len(dgts)&lt;1:</span>
<span class="hljs-comment">#             return -1</span>
<span class="hljs-comment">#         else:</span>
<span class="hljs-comment">#             return max(dgts)</span>
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>You are given a string that may contain letters and digits. You need to find the <strong>second largest digit</strong> that appears in the string.</p>
<ul>
<li><p>Digits are from 0 to 9</p>
</li>
<li><p>Digits must be <strong>distinct</strong></p>
</li>
<li><p>If there is no second largest digit → return <code>-1</code></p>
</li>
</ul>
<p>Example:</p>
<ul>
<li><p><code>"dfa12321afd"</code> → digits = {1,2,3} → second largest = 2</p>
</li>
<li><p><code>"abc111"</code> → only one digit → return -1</p>
</li>
</ul>
<hr />
<h3 id="heading-core-idea-use-a-set-for-unique-digits">Core Idea (Use a Set for Unique Digits)</h3>
<p>We only care about:</p>
<ul>
<li><p><strong>digits</strong>, not letters</p>
</li>
<li><p><strong>unique digits</strong>, not duplicates</p>
</li>
</ul>
<p>So the best structure is a <strong>set</strong>:</p>
<ul>
<li><p>Automatically removes duplicates</p>
</li>
<li><p>Makes it easy to find max values</p>
</li>
</ul>
<hr />
<h3 id="heading-how-the-solution-works">How the Solution Works</h3>
<ol>
<li><p>Traverse the string character by character</p>
</li>
<li><p>If the character is a digit:</p>
<ul>
<li><p>Convert it to int</p>
</li>
<li><p>Add it to a set</p>
</li>
</ul>
</li>
<li><p>After traversal:</p>
<ul>
<li>If the set has <strong>0 or 1 element</strong> → no second largest → return -1</li>
</ul>
</li>
<li><p>Otherwise:</p>
<ul>
<li><p>Remove the <strong>largest digit</strong></p>
</li>
<li><p>The new maximum is the <strong>second largest digit</strong></p>
</li>
<li><p>Return it</p>
</li>
</ul>
</li>
</ol>
<hr />
<h3 id="heading-why-removing-the-maximum-works">Why Removing the Maximum Works</h3>
<ul>
<li><p>After removing the largest digit,</p>
</li>
<li><p>the largest remaining digit is automatically the <strong>second largest overall</strong></p>
</li>
<li><p>No sorting is needed</p>
</li>
</ul>
<hr />
<h3 id="heading-why-this-approach-is-efficient">Why This Approach Is Efficient</h3>
<ul>
<li><p>Set ensures uniqueness without extra checks</p>
</li>
<li><p>We scan the string only once</p>
</li>
<li><p>Operations like <code>max()</code> on a small set (digits 0–9) are very fast</p>
</li>
</ul>
<hr />
<h3 id="heading-edge-cases-covered">Edge Cases Covered</h3>
<ul>
<li><p>No digits in string → return -1</p>
</li>
<li><p>Only one unique digit → return -1</p>
</li>
<li><p>Multiple same digits → handled by set</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p><strong>Time:</strong> O(n), where n = length of string</p>
</li>
<li><p><strong>Space:</strong> O(1), because at most 10 digits (0–9) can be stored</p>
</li>
</ul>
<hr />
<h3 id="heading-key-insight-to-remember">Key Insight to Remember</h3>
<p>Whenever a problem asks for:</p>
<blockquote>
<p>“largest / second largest unique value”</p>
</blockquote>
<p>👉 Think <strong>set + remove max</strong>, instead of sorting everything.</p>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Merge Sorted Array]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/merge-sorted-array/description/
Code:
class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
 ...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-merge-sorted-array</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-merge-sorted-array</guid><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Sun, 21 Dec 2025 04:04:26 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/merge-sorted-array/description/">https://leetcode.com/problems/merge-sorted-array/description/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">merge</span>(<span class="hljs-params">self, nums1: List[int], m: int, nums2: List[int], n: int</span>) -&gt; <span class="hljs-keyword">None</span>:</span>
        <span class="hljs-string">"""
        Do not return anything, modify nums1 in-place instead.
        """</span>
        i = m - <span class="hljs-number">1</span>
        j = n - <span class="hljs-number">1</span>
        write = m + n - <span class="hljs-number">1</span>

        <span class="hljs-keyword">while</span> j&gt;=<span class="hljs-number">0</span>: <span class="hljs-comment"># will loop till all nums2 numbers are placed</span>
            <span class="hljs-keyword">if</span> i&gt;=<span class="hljs-number">0</span> <span class="hljs-keyword">and</span> nums1[i]&gt;nums2[j]: <span class="hljs-comment"># i&gt;0, if imp as nums1 can finish before nums2</span>
                nums1[write]=nums1[i]
                i-=<span class="hljs-number">1</span>
            <span class="hljs-keyword">else</span>:
                nums1[write]=nums2[j] <span class="hljs-comment"># if nums2 is lenthier, then remaining can get copied here</span>
                j-=<span class="hljs-number">1</span>
            write-=<span class="hljs-number">1</span>

<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -&gt; None:</span>
<span class="hljs-comment">#         """</span>
<span class="hljs-comment">#         Do not return anything, modify nums1 in-place instead.</span>
<span class="hljs-comment">#         """</span>
<span class="hljs-comment">#         for i in range(n):</span>
<span class="hljs-comment">#             nums1[m+i]=nums2[i]</span>
<span class="hljs-comment">#         nums1.sort()</span>
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>You are given two <strong>sorted arrays</strong>:</p>
<ul>
<li><p><code>nums1</code> has size <code>m + n</code></p>
<ul>
<li><p>First <code>m</code> elements are valid numbers</p>
</li>
<li><p>Last <code>n</code> elements are empty (0s as placeholders)</p>
</li>
</ul>
</li>
<li><p><code>nums2</code> has <code>n</code> valid numbers</p>
</li>
</ul>
<p>You must merge <code>nums2</code> into <code>nums1</code> so that:</p>
<ul>
<li><p>The final <code>nums1</code> is <strong>sorted</strong></p>
</li>
<li><p>The merge is done <strong>in-place</strong></p>
</li>
<li><p>Nothing is returned</p>
</li>
</ul>
<hr />
<h3 id="heading-core-idea-fill-from-the-end">Core Idea (Fill from the End)</h3>
<p>Since both arrays are already sorted:</p>
<ul>
<li><p>The <strong>largest</strong> numbers are at the <strong>end</strong></p>
</li>
<li><p>And <code>nums1</code> already has empty space at the end</p>
</li>
</ul>
<p>So instead of merging from the front (which would overwrite values), we <strong>fill</strong> <code>nums1</code> from the back.</p>
<hr />
<h3 id="heading-how-the-pointers-work">How the Pointers Work</h3>
<p>We use three pointers:</p>
<ul>
<li><p><code>i</code> → last valid element in <code>nums1</code> (<code>m - 1</code>)</p>
</li>
<li><p><code>j</code> → last element in <code>nums2</code> (<code>n - 1</code>)</p>
</li>
<li><p><code>write</code> → last position in <code>nums1</code> (<code>m + n - 1</code>)</p>
</li>
</ul>
<p>At each step:</p>
<ul>
<li><p>Compare <code>nums1[i]</code> and <code>nums2[j]</code></p>
</li>
<li><p>Put the <strong>larger one</strong> at <code>nums1[write]</code></p>
</li>
<li><p>Move the corresponding pointer backward</p>
</li>
<li><p>Decrease <code>write</code></p>
</li>
</ul>
<p>👉 <strong>Key Insight</strong><br />At every step, <strong>either</strong> <code>i</code> or <code>j</code> moves — never both.<br />The pointer that does <strong>not</strong> provide the value stays where it is,<br />so its element can still be compared in the next step.</p>
<p>This guarantees:</p>
<ul>
<li><p>No element is skipped</p>
</li>
<li><p>Every element is placed exactly once</p>
</li>
</ul>
<hr />
<h3 id="heading-why-the-loop-runs-while-j-gt-0">Why the Loop Runs While <code>j &gt;= 0</code></h3>
<ul>
<li><p>All elements of <code>nums2</code> <strong>must be placed</strong></p>
</li>
<li><p>If <code>nums1</code> finishes early (<code>i &lt; 0</code>):</p>
<ul>
<li>Remaining elements of <code>nums2</code> are copied directly</li>
</ul>
</li>
<li><p>If <code>nums2</code> finishes first:</p>
<ul>
<li>Remaining <code>nums1</code> elements are already in correct place</li>
</ul>
</li>
</ul>
<hr />
<h3 id="heading-why-this-works">Why This Works</h3>
<ul>
<li><p>We never overwrite useful data in <code>nums1</code></p>
</li>
<li><p>We always place the correct largest value first</p>
</li>
<li><p>Sorting is preserved naturally</p>
</li>
</ul>
<hr />
<h3 id="heading-why-this-is-better-than-sorting-again">Why This Is Better Than Sorting Again</h3>
<p>Alternative approach:</p>
<ul>
<li><p>Copy nums2 into nums1</p>
</li>
<li><p>Sort nums1</p>
</li>
</ul>
<p>That works but:</p>
<ul>
<li><p>Slower (<code>O((m+n) log (m+n))</code>)</p>
</li>
<li><p>Ignores the fact that arrays are already sorted</p>
</li>
</ul>
<p>This approach:</p>
<ul>
<li><p>Uses the sorted property fully</p>
</li>
<li><p>Runs in linear time</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p><strong>Time:</strong> O(m + n)</p>
</li>
<li><p><strong>Space:</strong> O(1) (in-place)</p>
</li>
</ul>
<hr />
<h3 id="heading-key-insight-to-remember">Key Insight to Remember</h3>
<p>When merging into an array with <strong>extra space at the end</strong>: 👉 <strong>Always merge from the back</strong>, not from the front.</p>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Rotate Array by One]]></title><description><![CDATA[Problem:
https://www.geeksforgeeks.org/problems/cyclically-rotate-an-array-by-one2614/1
Code:
class Solution:
    def rotate(self, arr):
        arr.insert(0, arr[-1])
        del arr[-1]
        return arr

# Below solution creates a new list, calle...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-rotate-array-by-one</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-rotate-array-by-one</guid><category><![CDATA[array]]></category><category><![CDATA[leetcode]]></category><category><![CDATA[geeksforgeeks]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Wed, 17 Dec 2025 17:28:50 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://www.geeksforgeeks.org/problems/cyclically-rotate-an-array-by-one2614/1">https://www.geeksforgeeks.org/problems/cyclically-rotate-an-array-by-one2614/1</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">rotate</span>(<span class="hljs-params">self, arr</span>):</span>
        arr.insert(<span class="hljs-number">0</span>, arr[<span class="hljs-number">-1</span>])
        <span class="hljs-keyword">del</span> arr[<span class="hljs-number">-1</span>]
        <span class="hljs-keyword">return</span> arr

<span class="hljs-comment"># Below solution creates a new list, caller may not be clling new list but may be using original list.</span>
<span class="hljs-comment"># So it is important to change the list in place</span>
<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def rotate(self, arr):</span>
<span class="hljs-comment">#         rotated_arr = [arr.pop()]</span>
<span class="hljs-comment">#         rotated_arr.extend(arr)</span>
<span class="hljs-comment">#         print(rotated_arr)</span>
<span class="hljs-comment">#         return rotated_arr</span>
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>You are given an array. You need to <strong>rotate it to the right by one position</strong>, meaning:</p>
<ul>
<li><p>The <strong>last element moves to the front</strong></p>
</li>
<li><p>All other elements shift one position to the right</p>
</li>
<li><p>The rotation must be done <strong>in-place</strong></p>
</li>
</ul>
<p>Example:</p>
<ul>
<li><code>[1, 2, 3, 4, 5]</code> → <code>[5, 1, 2, 3, 4]</code></li>
</ul>
<hr />
<h3 id="heading-core-idea-in-place-rotation">Core Idea (In-Place Rotation)</h3>
<p>We only need two simple steps:</p>
<ol>
<li><p>Take the <strong>last element</strong></p>
</li>
<li><p>Put it at the <strong>front</strong> of the array</p>
</li>
</ol>
<p>This achieves the required cyclic rotation.</p>
<hr />
<h3 id="heading-how-the-solution-works">How the Solution Works</h3>
<ul>
<li><p><code>arr[-1]</code> gives the last element</p>
</li>
<li><p><code>arr.insert(0, arr[-1])</code> inserts it at index 0</p>
</li>
<li><p><code>del arr[-1]</code> removes the extra copy at the end</p>
</li>
</ul>
<p>After these steps:</p>
<ul>
<li><p>Array is rotated correctly</p>
</li>
<li><p>The original array is modified in-place</p>
</li>
</ul>
<hr />
<h3 id="heading-why-in-place-matters">Why In-Place Matters</h3>
<ul>
<li><p>Some callers expect the <strong>same array object</strong> to be updated</p>
</li>
<li><p>Creating a new list may break that expectation</p>
</li>
<li><p>This solution respects the problem requirement</p>
</li>
</ul>
<hr />
<h3 id="heading-why-this-works">Why This Works</h3>
<ul>
<li><p>Python lists support fast insert/delete by index</p>
</li>
<li><p>Logic directly matches the definition of cyclic rotation</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p><strong>Time:</strong> O(n)<br />  (inserting at the front shifts elements)</p>
</li>
<li><p><strong>Space:</strong> O(1)<br />  (no extra array created)</p>
</li>
</ul>
<hr />
<h3 id="heading-key-insight-to-remember">Key Insight to Remember</h3>
<p>When a problem explicitly says:</p>
<blockquote>
<p>“Rotate the array in-place”</p>
</blockquote>
<p>👉 Always modify the <strong>original list</strong>, not a new one.</p>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Check If String Is a Prefix of Array]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/check-if-string-is-a-prefix-of-array/description/
Code:
class Solution:
    def isPrefixString(self, s: str, words: List[str]) -> bool:
        index=0
        for word in words:
            if not s.startswith(...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-check-if-string-is-a-prefix-of-array</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-check-if-string-is-a-prefix-of-array</guid><category><![CDATA[leetcode]]></category><category><![CDATA[string]]></category><category><![CDATA[two pointers]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Tue, 16 Dec 2025 17:59:06 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/check-if-string-is-a-prefix-of-array/description/">https://leetcode.com/problems/check-if-string-is-a-prefix-of-array/description/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">isPrefixString</span>(<span class="hljs-params">self, s: str, words: List[str]</span>) -&gt; bool:</span>
        index=<span class="hljs-number">0</span>
        <span class="hljs-keyword">for</span> word <span class="hljs-keyword">in</span> words:
            <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> s.startswith(word, index):
                <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

            index+=len(word)

            <span class="hljs-keyword">if</span> len(s) == index:
                <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def isPrefixString(self, s: str, words: List[str]) -&gt; bool:</span>
<span class="hljs-comment">#         index=0</span>
<span class="hljs-comment">#         for word in words:</span>
<span class="hljs-comment">#             if not s.startswith(word, index):</span>
<span class="hljs-comment">#                 return False</span>

<span class="hljs-comment">#             index+=len(word)</span>

<span class="hljs-comment">#             if len(s) == index:</span>
<span class="hljs-comment">#                 break</span>
<span class="hljs-comment">#         return len(s) == index</span>

<span class="hljs-comment"># Below solution will take more space</span>
<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def isPrefixString(self, s: str, words: List[str]) -&gt; bool:</span>
<span class="hljs-comment">#         building_phrase=""</span>
<span class="hljs-comment">#         for word in words:</span>
<span class="hljs-comment">#             building_phrase+=word</span>
<span class="hljs-comment">#             if s == building_phrase:</span>
<span class="hljs-comment">#                 return True</span>
<span class="hljs-comment">#         return False</span>
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>You are given:</p>
<ul>
<li><p>a string <code>s</code></p>
</li>
<li><p>an array of strings <code>words</code></p>
</li>
</ul>
<p>You must check whether <code>s</code> can be formed by <strong>joining the first few words from the array in order</strong>. You cannot skip words or rearrange them.</p>
<p>Example:</p>
<ul>
<li><p>s = "leetcode", words = ["leet","code","hello"] → True</p>
</li>
<li><p>s = "applepie", words = ["apple","pear","pie"] → False</p>
</li>
</ul>
<hr />
<h3 id="heading-core-idea-match-step-by-step-using-an-index">Core Idea (Match Step-by-Step Using an Index)</h3>
<p>Instead of building a new string, we:</p>
<ul>
<li><p>Walk through <code>s</code> using an index</p>
</li>
<li><p>Match each word from <code>words</code> <strong>exactly at the current index</strong></p>
</li>
</ul>
<p>This avoids extra memory and keeps the logic clean.</p>
<hr />
<h3 id="heading-how-the-algorithm-works">How the Algorithm Works</h3>
<ul>
<li><p>Start with <code>index = 0</code> (beginning of string <code>s</code>)</p>
</li>
<li><p>For each <code>word</code> in <code>words</code>:</p>
<ul>
<li><p>Check if <code>s</code> starts with <code>word</code> <strong>at position</strong> <code>index</code></p>
</li>
<li><p>If not → mismatch → return False</p>
</li>
<li><p>If yes:</p>
<ul>
<li>Move <code>index</code> forward by <code>len(word)</code></li>
</ul>
</li>
<li><p>If <code>index == len(s)</code>:</p>
<ul>
<li>We matched all characters of <code>s</code> exactly → return True</li>
</ul>
</li>
</ul>
</li>
</ul>
<hr />
<h3 id="heading-why-startswithword-index-is-important">Why <code>startswith(word, index)</code> Is Important</h3>
<ul>
<li><p>It ensures the word matches <strong>exactly where we are currently pointing</strong></p>
</li>
<li><p>Prevents partial or misplaced matches</p>
</li>
<li><p>Guarantees correct order without concatenation</p>
</li>
</ul>
<hr />
<h3 id="heading-why-this-approach-is-better-than-building-a-string">Why This Approach Is Better Than Building a String</h3>
<ul>
<li><p>No extra string creation → memory efficient</p>
</li>
<li><p>Stops early as soon as a mismatch is found</p>
</li>
<li><p>Works directly on the original string</p>
</li>
</ul>
<hr />
<h3 id="heading-edge-cases-covered">Edge Cases Covered</h3>
<ul>
<li><p><code>s</code> is shorter than combined words → returns False</p>
</li>
<li><p>Exact match after a few words → returns True</p>
</li>
<li><p>Extra words after match → safely ignored</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p><strong>Time:</strong> O(n), where n = length of <code>s</code></p>
</li>
<li><p><strong>Space:</strong> O(1), no extra strings created</p>
</li>
</ul>
<hr />
<h3 id="heading-key-insight-to-remember">Key Insight to Remember</h3>
<p>Whenever a problem says:</p>
<blockquote>
<p>“Check if a string is built from prefixes in order”</p>
</blockquote>
<p>👉 Think <strong>pointer/index walking</strong>, not string building.</p>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Find Sqrt(x)]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/sqrtx/description/
Code:
class Solution:
    def mySqrt(self, x: int) -> int:
        if x <= 1:
            return x

        low, high = 1, x // 2
        while low <= high:
            mid = (low + high) // 2...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-find-sqrtx</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-find-sqrtx</guid><category><![CDATA[leetcode]]></category><category><![CDATA[Binary Search Algorithm]]></category><category><![CDATA[Square root]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Tue, 16 Dec 2025 05:29:48 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/sqrtx/description/">https://leetcode.com/problems/sqrtx/description/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">mySqrt</span>(<span class="hljs-params">self, x: int</span>) -&gt; int:</span>
        <span class="hljs-keyword">if</span> x &lt;= <span class="hljs-number">1</span>:
            <span class="hljs-keyword">return</span> x

        low, high = <span class="hljs-number">1</span>, x // <span class="hljs-number">2</span>
        <span class="hljs-keyword">while</span> low &lt;= high:
            mid = (low + high) // <span class="hljs-number">2</span>
            square = mid * mid

            <span class="hljs-keyword">if</span> square == x:
                <span class="hljs-keyword">return</span> mid
            <span class="hljs-keyword">elif</span> square &gt; x:
                high = mid - <span class="hljs-number">1</span>
            <span class="hljs-keyword">else</span>:
                low = mid + <span class="hljs-number">1</span>

        <span class="hljs-keyword">return</span> high
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>You are given a non-negative number <code>x</code>. You need to return the <strong>integer part of √x</strong> (square root), meaning:</p>
<ul>
<li><p>Return the <strong>largest integer</strong> whose square is <strong>≤ x</strong></p>
</li>
<li><p>Do NOT use built-in sqrt functions</p>
</li>
</ul>
<p>Example:</p>
<ul>
<li><p>x = 8 → √8 ≈ 2.8 → answer = 2</p>
</li>
<li><p>x = 16 → √16 = 4 → answer = 4</p>
</li>
</ul>
<hr />
<h3 id="heading-core-idea-binary-search-on-the-answer">Core Idea (Binary Search on the Answer)</h3>
<p>The square root of <code>x</code> lies somewhere between:</p>
<ul>
<li><strong>1</strong> and <strong>x/2</strong> (for x &gt; 1)</li>
</ul>
<p>We use <strong>binary search</strong> to efficiently find the correct integer.</p>
<p>Why binary search?</p>
<ul>
<li><p>The function <code>f(n) = n²</code> is <strong>monotonic</strong> (always increasing)</p>
</li>
<li><p>This makes it perfect for binary search</p>
</li>
</ul>
<hr />
<h3 id="heading-how-the-search-works">How the Search Works</h3>
<p>At each step:</p>
<ol>
<li><p>Pick a middle value <code>mid</code></p>
</li>
<li><p>Compute <code>mid²</code></p>
</li>
<li><p>Compare <code>mid²</code> with <code>x</code></p>
</li>
</ol>
<p>Cases:</p>
<ul>
<li><p>If <code>mid² == x</code> → exact square root found → return <code>mid</code></p>
</li>
<li><p>If <code>mid² &gt; x</code> → mid is too big → search left side</p>
</li>
<li><p>If <code>mid² &lt; x</code> → mid is too small → search right side</p>
</li>
</ul>
<hr />
<h3 id="heading-why-we-return-high-at-the-end">Why We Return <code>high</code> at the End</h3>
<p>When the loop ends:</p>
<ul>
<li><p><code>low</code> has crossed over <code>high</code></p>
</li>
<li><p><code>high</code> points to the <strong>largest number whose square is ≤ x</strong></p>
</li>
</ul>
<p>This exactly matches the problem requirement:</p>
<blockquote>
<p>“Return the integer square root (rounded down)”</p>
</blockquote>
<hr />
<h3 id="heading-edge-cases-handled">Edge Cases Handled</h3>
<ul>
<li><p>x = 0 → return 0</p>
</li>
<li><p>x = 1 → return 1</p>
</li>
<li><p>Large x → binary search avoids slow looping</p>
</li>
</ul>
<hr />
<h3 id="heading-why-this-approach-is-good">Why This Approach Is Good</h3>
<ul>
<li><p>Much faster than checking every number</p>
</li>
<li><p>Works for very large inputs</p>
</li>
<li><p>Clean and commonly expected in interviews</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p><strong>Time:</strong> O(log x)</p>
</li>
<li><p><strong>Space:</strong> O(1)</p>
</li>
</ul>
<hr />
<h3 id="heading-key-insight-to-remember">Key Insight to Remember</h3>
<p>Whenever you are asked:</p>
<ul>
<li><p>“find the largest value satisfying some condition”</p>
</li>
<li><p>and the condition is <strong>monotonic</strong></p>
</li>
</ul>
<p>👉 Think <strong>binary search on the answer</strong></p>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Contains Duplicates]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/contains-duplicate/description/
Code:
class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        return len(nums) != len(set(nums))

# class Solution:
#     def containsDuplicate(self, num...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-contains-duplicates</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-contains-duplicates</guid><category><![CDATA[leetcode]]></category><category><![CDATA[data types]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Mon, 15 Dec 2025 06:03:58 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/contains-duplicate/description/">https://leetcode.com/problems/contains-duplicate/description/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">containsDuplicate</span>(<span class="hljs-params">self, nums: List[int]</span>) -&gt; bool:</span>
        <span class="hljs-keyword">return</span> len(nums) != len(set(nums))

<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def containsDuplicate(self, nums: List[int]) -&gt; bool:</span>
<span class="hljs-comment">#         c = Counter(nums)</span>
<span class="hljs-comment">#         for k,v in c.items():</span>
<span class="hljs-comment">#             if v&gt;1:</span>
<span class="hljs-comment">#                 return True</span>
<span class="hljs-comment">#         return False</span>
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>You are given a list of numbers. Return <strong>True</strong> if <strong>any number appears more than once</strong>. Otherwise, return <strong>False</strong>.</p>
<hr />
<h3 id="heading-core-idea-use-a-set">Core Idea (Use a Set)</h3>
<p>A <strong>set</strong> stores only <strong>unique values</strong>. So:</p>
<ul>
<li><p>If the list has duplicates → set size becomes smaller</p>
</li>
<li><p>If all elements are unique → sizes stay the same</p>
</li>
</ul>
<hr />
<h3 id="heading-how-the-check-works">How the Check Works</h3>
<ul>
<li><p><code>len(nums)</code> → total number of elements</p>
</li>
<li><p><code>len(set(nums))</code> → number of unique elements</p>
</li>
</ul>
<p>If these two lengths are <strong>not equal</strong>: → at least one duplicate exists → return True</p>
<hr />
<h3 id="heading-why-this-works">Why This Works</h3>
<ul>
<li><p>Sets automatically remove duplicates</p>
</li>
<li><p>Length comparison is a quick and reliable way to detect repetition</p>
</li>
<li><p>No need to manually count frequencies</p>
</li>
</ul>
<hr />
<h3 id="heading-edge-cases-covered">Edge Cases Covered</h3>
<ul>
<li><p>Empty list → no duplicates → False</p>
</li>
<li><p>Single element → no duplicates → False</p>
</li>
<li><p>Multiple repeats → detected immediately</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p><strong>Time:</strong> O(n)</p>
</li>
<li><p><strong>Space:</strong> O(n) for the set</p>
</li>
</ul>
<hr />
<h3 id="heading-alternative-when-you-need-more-control">Alternative (When You Need More Control)</h3>
<p>Using a frequency map (<code>Counter</code>) is useful if:</p>
<ul>
<li><p>You need to know <strong>which</strong> number is duplicated</p>
</li>
<li><p>You need the <strong>count</strong> of duplicates</p>
</li>
</ul>
<p>But for just checking existence, the set method is the cleanest.</p>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Majority Element]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/majority-element/description/
Code:
# Original Solution
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        elem_map = {}
        n=len(nums)
        for number in nums:
            if...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-majority-element</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-majority-element</guid><category><![CDATA[leetcode]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Sun, 14 Dec 2025 16:14:18 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/majority-element/description/">https://leetcode.com/problems/majority-element/description/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-comment"># Original Solution</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">majorityElement</span>(<span class="hljs-params">self, nums: List[int]</span>) -&gt; int:</span>
        elem_map = {}
        n=len(nums)
        <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> nums:
            <span class="hljs-keyword">if</span> number <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> elem_map:
                elem_map[number] = <span class="hljs-number">1</span>
            <span class="hljs-keyword">else</span>:
                elem_map[number] = elem_map.get(number) + <span class="hljs-number">1</span>

        <span class="hljs-keyword">for</span> k,v <span class="hljs-keyword">in</span> elem_map.items():
            <span class="hljs-keyword">if</span> v&gt;n//<span class="hljs-number">2</span>:
                <span class="hljs-keyword">return</span> k

<span class="hljs-comment"># Boyer–Moore Voting Algorithm. , O(1) Space</span>
<span class="hljs-comment"># count = 0</span>
<span class="hljs-comment"># candidate = None</span>

<span class="hljs-comment"># for num in nums:</span>
<span class="hljs-comment">#     if count == 0:</span>
<span class="hljs-comment">#         candidate = num</span>
<span class="hljs-comment">#     count += 1 if num == candidate else -1</span>

<span class="hljs-comment"># return candidate</span>
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>You are given a list of numbers. One number appears <strong>more than half of the time</strong> (<code>&gt; n/2</code>). That number is called the <strong>majority element</strong>. You must return that number.</p>
<p>Example:</p>
<ul>
<li><p><code>[3,2,3]</code> → <code>3</code></p>
</li>
<li><p><code>[2,2,1,1,1,2,2]</code> → <code>2</code></p>
</li>
</ul>
<hr />
<h3 id="heading-core-idea-counting-frequencies">Core Idea (Counting Frequencies)</h3>
<p>If a number appears more than <code>n // 2</code> times,<br />we can simply <strong>count how many times each number appears</strong>.</p>
<p>Steps:</p>
<ol>
<li><p>Count frequency of every number.</p>
</li>
<li><p>Find the number whose count is greater than <code>n // 2</code>.</p>
</li>
</ol>
<hr />
<h3 id="heading-how-the-solution-works">How the Solution Works</h3>
<ul>
<li><p>Use a dictionary (<code>elem_map</code>) to store: number → how many times it appears</p>
</li>
<li><p>Loop through the array and update counts.</p>
</li>
<li><p>After counting:</p>
</li>
<li><p>Check each <code>(number, frequency)</code></p>
</li>
<li><p>If <code>frequency &gt; n // 2</code>, return that number.</p>
</li>
</ul>
<hr />
<h3 id="heading-why-this-works">Why This Works</h3>
<ul>
<li><p>The problem <strong>guarantees</strong> that a majority element exists.</p>
</li>
<li><p>So exactly <strong>one number</strong> will satisfy <code>count &gt; n // 2</code>.</p>
</li>
<li><p>Dictionary gives fast O(1) average-time updates and lookups.</p>
</li>
</ul>
<hr />
<h3 id="heading-edge-cases-covered">Edge Cases Covered</h3>
<ul>
<li><p>Single element array → that element is the majority.</p>
</li>
<li><p>All same elements → obvious majority.</p>
</li>
<li><p>Mixed values → counting handles it safely.</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p><strong>Time:</strong> O(n)</p>
</li>
<li><p>One pass to count</p>
</li>
<li><p>One pass to find majority</p>
</li>
<li><p><strong>Space:</strong> O(n)</p>
</li>
<li><p>Dictionary may store all unique numbers</p>
</li>
</ul>
<h2 id="heading-if-solved-with-boyermoore-voting-algorithm">If solved with <mark>Boyer–Moore Voting Algorithm.</mark></h2>
<pre><code class="lang-plaintext">
### Core Idea (Boyer–Moore Voting Algorithm)
Instead of counting frequencies, we use a **voting idea**.

Think of it like this:
- Same numbers **support each other**
- Different numbers **cancel each other out**
- Since the majority element appears more than all others combined,
  it can never be fully cancelled

---

### How the Algorithm Thinks (Intuition)
We keep:
- `candidate` → the current possible majority element
- `count` → how strong its support is

We scan the array once:
- If `count == 0`:
    → pick the current number as the new candidate
- If current number == candidate:
    → increase count (support)
- Else:
    → decrease count (cancel out)

---

### Why Cancellation Works (The “Magic”)
Every time we see:
- one majority element
- and one non-majority element

They **cancel each other**.

Because the majority element appears **more than n/2 times**:
- After all cancellations,
- the majority element is the **only one left standing** as the candidate

---
</code></pre>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Isomorphic Strings]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/isomorphic-strings/description/
Code:
class Solution:
    def map_check(self, txt1: str,txt2: str, char_map: dict)->bool:
        for i in range(len(txt1)):
            if txt1[i] not in char_map:
              ...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-isomorphic-strings</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-isomorphic-strings</guid><category><![CDATA[leetcode]]></category><category><![CDATA[Strings]]></category><category><![CDATA[DSA]]></category><category><![CDATA[coding]]></category><category><![CDATA[coding challenge]]></category><category><![CDATA[map]]></category><category><![CDATA[hashmap]]></category><category><![CDATA[dictionary]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Sun, 14 Dec 2025 12:11:06 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/isomorphic-strings/description/">https://leetcode.com/problems/isomorphic-strings/description/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">map_check</span>(<span class="hljs-params">self, txt1: str,txt2: str, char_map: dict</span>)-&gt;bool:</span>
        <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(txt1)):
            <span class="hljs-keyword">if</span> txt1[i] <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> char_map:
                char_map[txt1[i]]=txt2[i]
            <span class="hljs-keyword">else</span>:
                <span class="hljs-keyword">if</span> char_map.get(txt1[i]) != txt2[i]:
                    <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">isIsomorphic</span>(<span class="hljs-params">self, s: str, t: str</span>) -&gt; bool:</span>
        <span class="hljs-comment"># We need to check map in both directions.</span>
        char_map_s_to_t = {}
        char_map_t_to_s = {}

        <span class="hljs-keyword">return</span> (
            self.map_check(txt1=s, txt2=t, char_map=char_map_s_to_t) 
            <span class="hljs-keyword">and</span>
            self.map_check(txt1=t, txt2=s, char_map=char_map_t_to_s)
        )
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>Two strings <code>s</code> and <code>t</code> are <strong>isomorphic</strong> if:</p>
<ul>
<li><p>Each character in <code>s</code> can be replaced to get <code>t</code></p>
</li>
<li><p>The replacement must be <strong>consistent</strong></p>
</li>
<li><p>No two different characters can map to the same character</p>
</li>
</ul>
<p>Example:</p>
<ul>
<li><p><code>"egg"</code> → <code>"add"</code> ✅</p>
</li>
<li><p><code>"foo"</code> → <code>"bar"</code> ❌</p>
</li>
<li><p><code>"paper"</code> → <code>"title"</code> ✅</p>
</li>
</ul>
<hr />
<h3 id="heading-core-idea-character-mapping">Core Idea (Character Mapping)</h3>
<p>We check whether characters from one string can be mapped to the other <strong>one-to-one</strong>.</p>
<p>Important rule:</p>
<ul>
<li><p>One character → one fixed character</p>
</li>
<li><p>Mapping must be <strong>unique in both directions</strong></p>
</li>
</ul>
<p>That’s why we check mappings <strong>both ways</strong>.</p>
<hr />
<h3 id="heading-why-two-maps-are-needed">Why Two Maps Are Needed</h3>
<p>Only checking <code>s → t</code> is <strong>not enough</strong>.</p>
<p>Example:</p>
<ul>
<li><p><code>s = "ab"</code></p>
</li>
<li><p><code>t = "cc"</code></p>
</li>
</ul>
<p><code>s → t</code> mapping:</p>
<p>a → c</p>
<p>b → c</p>
<p>This looks valid in one direction, but it breaks the rule: two different characters map to the same character.</p>
<p>So we must also check:</p>
<ul>
<li><code>t → s</code></li>
</ul>
<hr />
<h3 id="heading-how-mapcheck-works">How <code>map_check</code> Works</h3>
<p>For each position <code>i</code>:</p>
<ul>
<li><p>If character from <code>txt1</code> is <strong>not yet mapped</strong>: → create mapping to corresponding character in <code>txt2</code></p>
</li>
<li><p>If it <strong>is already mapped</strong>: → ensure it maps to the <strong>same character as before</strong> → otherwise return False</p>
</li>
</ul>
<p>If the loop finishes → mapping is consistent.</p>
<hr />
<h3 id="heading-execution-flow">Execution Flow</h3>
<ol>
<li><p>Check mapping from <code>s → t</code></p>
</li>
<li><p>Check mapping from <code>t → s</code></p>
</li>
<li><p>Only if <strong>both pass</strong>, the strings are isomorphic</p>
</li>
</ol>
<hr />
<h3 id="heading-why-this-works">Why This Works</h3>
<ul>
<li><p>Ensures <strong>consistency</strong> (same char always maps the same way)</p>
</li>
<li><p>Ensures <strong>uniqueness</strong> (no two chars map to one char)</p>
</li>
<li><p>Covers all tricky cases cleanly</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p>Time: O(n)</p>
</li>
<li><p>Space: O(n) for the two maps</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Longest Common Prefix]]></title><description><![CDATA[Problem
https://leetcode.com/problems/longest-common-prefix/
Code:
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        current_prefix = strs[0]
        for word in strs:
            while not word.startswith(current_pre...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-longest-common-prefix</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-longest-common-prefix</guid><category><![CDATA[leetcode]]></category><category><![CDATA[string]]></category><category><![CDATA[Python]]></category><category><![CDATA[DSA]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Sun, 14 Dec 2025 04:24:11 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem</h2>
<p>https://leetcode.com/problems/longest-common-prefix/</p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">longestCommonPrefix</span>(<span class="hljs-params">self, strs: List[str]</span>) -&gt; str:</span>
        current_prefix = strs[<span class="hljs-number">0</span>]
        <span class="hljs-keyword">for</span> word <span class="hljs-keyword">in</span> strs:
            <span class="hljs-keyword">while</span> <span class="hljs-keyword">not</span> word.startswith(current_prefix):
                current_prefix = current_prefix[:<span class="hljs-number">-1</span>]
        <span class="hljs-keyword">return</span> current_prefix
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>You are given a list of strings. You need to find the <strong>longest prefix</strong> (starting part of the word) that is <strong>common to all strings</strong>. If there is no common prefix, return an empty string.</p>
<p>Example:</p>
<ul>
<li><p>["flower","flow","flight"] → "fl"</p>
</li>
<li><p>["dog","racecar","car"] → ""</p>
</li>
</ul>
<hr />
<h3 id="heading-core-idea-shrink-the-prefix">Core Idea (Shrink the Prefix)</h3>
<ul>
<li><p>Start by assuming the <strong>first word</strong> is the common prefix.</p>
</li>
<li><p>Compare this prefix with every other word.</p>
</li>
<li><p>If a word does <strong>not</strong> start with the current prefix: → shorten the prefix from the <strong>right</strong> → keep checking until it matches or becomes empty.</p>
</li>
</ul>
<hr />
<h3 id="heading-why-we-reduce-from-the-right">Why We Reduce From the Right</h3>
<p>A prefix must start at index 0. If it doesn’t match:</p>
<ul>
<li><p>The only way to fix it is to <strong>remove characters from the end</strong>.</p>
</li>
<li><p>Removing from the front would break the idea of a prefix.</p>
</li>
</ul>
<hr />
<h3 id="heading-how-the-process-flows">How the Process Flows</h3>
<ol>
<li><p>Take the first string as the initial prefix.</p>
</li>
<li><p>For each next string:</p>
<ul>
<li><p>While that string does NOT start with the prefix:</p>
<ul>
<li>Shorten the prefix by one character.</li>
</ul>
</li>
</ul>
</li>
<li><p>If the prefix becomes empty:</p>
<ul>
<li>No common prefix exists → return "".</li>
</ul>
</li>
<li><p>After checking all strings:</p>
<ul>
<li>The remaining prefix is the answer.</li>
</ul>
</li>
</ol>
<hr />
<h3 id="heading-why-this-works">Why This Works</h3>
<ul>
<li><p>Any common prefix must be a prefix of the <strong>first string</strong>.</p>
</li>
<li><p>We only shrink when needed, never expand.</p>
</li>
<li><p>Once a prefix works for all words, it’s guaranteed to be the longest possible.</p>
</li>
</ul>
<hr />
<h3 id="heading-edge-cases-covered">Edge Cases Covered</h3>
<ul>
<li><p>Only one string → that string itself is the prefix.</p>
</li>
<li><p>No common prefix → prefix reduces to empty string.</p>
</li>
<li><p>Strings of different lengths handled naturally.</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p>Time: O(n × m) where n = number of strings, m = length of the prefix (shrinking cost)</p>
</li>
<li><p>Space: O(1) only the prefix variable is used.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Valid Anagram]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/valid-anagram/description/
Code:
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return Counter(s) == Counter(t)

# class Solution:
#     def isAnagram(self, s: str, t: str) -> bool:
#  ...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-valid-anagram</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-valid-anagram</guid><category><![CDATA[leetcode]]></category><category><![CDATA[counter]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Fri, 12 Dec 2025 11:50:09 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/valid-anagram/description/">https://leetcode.com/problems/valid-anagram/description/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">isAnagram</span>(<span class="hljs-params">self, s: str, t: str</span>) -&gt; bool:</span>
        <span class="hljs-keyword">return</span> Counter(s) == Counter(t)

<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def isAnagram(self, s: str, t: str) -&gt; bool:</span>
<span class="hljs-comment">#         s_freq = Counter(s)</span>
<span class="hljs-comment">#         t_freq = Counter(t)</span>

<span class="hljs-comment">#         return s_freq == t_freq</span>
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>Two strings <code>s</code> and <code>t</code> are <strong>anagrams</strong> if:</p>
<ul>
<li><p>They contain <strong>exactly the same characters</strong></p>
</li>
<li><p>With <strong>exactly the same frequencies</strong></p>
</li>
<li><p>Order does NOT matter<br />  Example: <code>"listen"</code> and <code>"silent"</code></p>
</li>
</ul>
<hr />
<h3 id="heading-core-idea">Core Idea</h3>
<p>Use a <strong>frequency counter</strong> for both strings and compare them. If both counters match exactly, the strings are anagrams.</p>
<p><code>Counter(s)</code> → tells how many times each character appears in <code>s</code><br /><code>Counter(t)</code> → same for <code>t</code></p>
<p>If these two dictionaries are equal → same characters &amp; same counts → anagram.</p>
<hr />
<h3 id="heading-why-this-works">Why This Works</h3>
<ul>
<li><p>An anagram must reuse letters <strong>perfectly</strong></p>
</li>
<li><p>Direct comparison of frequency maps guarantees:</p>
<ul>
<li><p>No extra characters</p>
</li>
<li><p>No missing characters</p>
</li>
<li><p>No mismatched counts</p>
</li>
</ul>
</li>
<li><p>Order of characters is fully ignored (as desired)</p>
</li>
</ul>
<hr />
<h3 id="heading-edge-cases-covered">Edge Cases Covered</h3>
<ul>
<li><p>Different lengths → counters won't match → returns False</p>
</li>
<li><p>Empty strings → both counters empty → returns True</p>
</li>
<li><p>Mixed characters (letters, digits, symbols) → Counter handles all</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p>Counting both strings: O(n + m)</p>
</li>
<li><p>Comparing dictionaries: O(k), where k is number of unique characters</p>
</li>
</ul>
<p>Overall: <strong>O(n)</strong> time, <strong>O(1)</strong> space for fixed character set (like ASCII)</p>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Sort Characters By Frequency]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/sort-characters-by-frequency/description/
Code:
class Solution:
    def frequencySort(self, s: str) -> str:
        c = Counter(s)
        sorted_c = sorted(c.items(), key=lambda x : (-x[1], x[0])) #1st sort by ...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-sort-characters-by-frequency</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-sort-characters-by-frequency</guid><category><![CDATA[leetcode]]></category><category><![CDATA[sorting]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Fri, 12 Dec 2025 11:31:26 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/sort-characters-by-frequency/description/">https://leetcode.com/problems/sort-characters-by-frequency/description/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">frequencySort</span>(<span class="hljs-params">self, s: str</span>) -&gt; str:</span>
        c = Counter(s)
        sorted_c = sorted(c.items(), key=<span class="hljs-keyword">lambda</span> x : (-x[<span class="hljs-number">1</span>], x[<span class="hljs-number">0</span>])) <span class="hljs-comment">#1st sort by descending, then sort by ascending # sort by char not req though # sorted func always retuns a list</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">''</span>.join(k*v <span class="hljs-keyword">for</span> k,v <span class="hljs-keyword">in</span> sorted_c) <span class="hljs-comment"># here intuitively people put list comprehension [...] but directly generator can be give (on the fly)</span>
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>We must reorder a string so that:</p>
<ul>
<li><p>Characters with <strong>higher frequency</strong> come first</p>
</li>
<li><p>Characters with <strong>lower frequency</strong> come later<br />  If two characters have the same frequency, their order doesn't matter for LeetCode.</p>
</li>
</ul>
<p>Example:<br /><code>s = "tree"</code> → <code>eetr</code> or <code>eert</code></p>
<hr />
<h3 id="heading-core-idea">Core Idea</h3>
<ol>
<li><p>Count how many times each character appears</p>
</li>
<li><p>Sort characters based on <strong>frequency (descending)</strong></p>
</li>
<li><p>Rebuild the string by repeating each character according to its count</p>
</li>
</ol>
<p>This is a straightforward <strong>frequency + sorting</strong> pattern.</p>
<hr />
<h3 id="heading-why-we-use-counter">Why We Use <code>Counter</code></h3>
<ul>
<li><p><code>Counter(s)</code> quickly gives us a dictionary: <code>{char: frequency}</code></p>
</li>
<li><p>Counting manually is slower and more error-prone.</p>
</li>
</ul>
<hr />
<h3 id="heading-why-the-sorting-key-is-x1-x0">Why the Sorting Key is <code>(-x[1], x[0])</code></h3>
<ul>
<li><p><code>x[1]</code> = frequency<br />  We use <code>-x[1]</code> to sort <strong>highest frequency first ( <mark>-</mark> denotes descending order)</strong></p>
</li>
<li><p><code>x[0]</code> = character<br />  Used only as a tie-breaker (not required for LeetCode correctness)</p>
</li>
</ul>
<p>Sorting produces something like: <code>[('e', 2), ('t', 1), ('r', 1)]</code></p>
<hr />
<h3 id="heading-why-joink-v-for-k-v-in-sortedc-works">Why <code>''.join(k * v for k, v in sorted_c)</code> Works</h3>
<ul>
<li><p>For each <code>(character, frequency)</code> pair:</p>
<ul>
<li><code>k * v</code> repeats the character v times<br />  e.g., <code>'e' * 2 = 'ee'</code></li>
</ul>
</li>
<li><p>Joining them together creates the final string in sorted order.</p>
</li>
</ul>
<p>Using a <strong>generator expression</strong> (not a list) is memory-efficient and clean.</p>
<hr />
<h3 id="heading-why-this-approach-is-correct">Why This Approach Is Correct</h3>
<ul>
<li><p>Sorting by frequency ensures the most common characters come first</p>
</li>
<li><p>Repeating characters according to their count preserves correct quantities</p>
</li>
<li><p>Exact ordering for ties is irrelevant to the output validity</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p>Counting: O(n)</p>
</li>
<li><p>Sorting: O(k log k), where k = number of unique characters (≤ 62 typically)</p>
</li>
<li><p>Building output: O(n)</p>
</li>
</ul>
<p>Total: <strong>O(n log k)</strong> (fast in practice)</p>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Rotate String]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/rotate-string/description/
Code:
# OPTIMISED
class Solution:
    def rotateString(self, s: str, goal: str) -> bool:
        return len(s)==len(goal) and goal in (s+s)

# BELOW TWO SOLUTIONS NOT (O(N^2))
# class ...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-rotate-string</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-rotate-string</guid><category><![CDATA[leetcode]]></category><category><![CDATA[Strings]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Wed, 10 Dec 2025 17:36:31 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/rotate-string/description/">https://leetcode.com/problems/rotate-string/description/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-comment"># OPTIMISED</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">rotateString</span>(<span class="hljs-params">self, s: str, goal: str</span>) -&gt; bool:</span>
        <span class="hljs-keyword">return</span> len(s)==len(goal) <span class="hljs-keyword">and</span> goal <span class="hljs-keyword">in</span> (s+s)

<span class="hljs-comment"># BELOW TWO SOLUTIONS NOT (O(N^2))</span>
<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def rotateString(self, s: str, goal: str) -&gt; bool:</span>
<span class="hljs-comment">#         sq=deque(s)</span>
<span class="hljs-comment">#         goal_q=deque(goal)</span>
<span class="hljs-comment">#         i=0</span>
<span class="hljs-comment">#         while i&lt;len(sq):</span>
<span class="hljs-comment">#             i+=1</span>
<span class="hljs-comment">#             sq.append(sq.popleft())</span>
<span class="hljs-comment">#             if sq==goal_q:</span>
<span class="hljs-comment">#                 return True</span>
<span class="hljs-comment">#         return False</span>

<span class="hljs-comment"># ======= These both are n^2 =========</span>

<span class="hljs-comment"># class Solution:</span>
<span class="hljs-comment">#     def rotateString(self, s: str, goal: str) -&gt; bool:</span>
<span class="hljs-comment">#         sq=deque(s)</span>
<span class="hljs-comment">#         i=0</span>
<span class="hljs-comment">#         while i&lt;len(sq):</span>
<span class="hljs-comment">#             i+=1</span>
<span class="hljs-comment">#             sq.append(sq.popleft())</span>
<span class="hljs-comment">#             if ''.join(sq) == goal:</span>
<span class="hljs-comment">#                 return True</span>
<span class="hljs-comment">#         return False</span>
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>You have two strings: <code>s</code> and <code>goal</code>.</p>
<p>You can <strong>rotate</strong> <code>s</code> by moving the first character to the end any number of times.<br />You must check: <strong>Can we turn</strong> <code>s</code> into <code>goal</code> using such rotations?</p>
<p>Example:</p>
<ul>
<li><p><code>s = "abcde"</code> → rotations: <code>"abcde"</code>, <code>"bcdea"</code>, <code>"cdeab"</code>, <code>"deabc"</code>, <code>"eabcd"</code></p>
</li>
<li><p>If <code>goal</code> is one of these, answer is <code>True</code>.</p>
</li>
</ul>
<hr />
<h3 id="heading-core-idea-smart-trick-with-s-s">Core Idea (Smart Trick with s + s)</h3>
<p>Key observation:</p>
<blockquote>
<p>If <code>goal</code> is a rotation of <code>s</code>, then <code>goal</code> will always appear as a <strong>substring</strong> of <code>s + s</code>.</p>
</blockquote>
<p>Example:</p>
<ul>
<li><p><code>s = "abcde"</code></p>
</li>
<li><p><code>s + s = "abcdeabcde"</code></p>
</li>
<li><p>All rotations of <code>"abcde"</code> are inside this:<br />  <code>"abcde"</code>, <code>"bcdea"</code>, <code>"cdeab"</code>, <code>"deabc"</code>, <code>"eabcd"</code></p>
</li>
</ul>
<p>So we just need to:</p>
<ol>
<li><p>Check that <code>s</code> and <code>goal</code> have the <strong>same length</strong><br /> (rotating doesn’t change length)</p>
</li>
<li><p>Check if <code>goal</code> is a <strong>substring</strong> of <code>s + s</code></p>
</li>
</ol>
<p>If both are true → <code>goal</code> is a rotation of <code>s</code>.</p>
<hr />
<h3 id="heading-why-length-check-is-important">Why Length Check Is Important</h3>
<ul>
<li>If lengths differ, rotation is <strong>impossible</strong>.<br />  No need to do the substring check at all.</li>
</ul>
<hr />
<h3 id="heading-why-this-is-better-than-simulating-rotations">Why This Is Better Than Simulating Rotations</h3>
<p>A slower way is:</p>
<ul>
<li><p>Actually rotate <code>s</code> one step at a time</p>
</li>
<li><p>Compare with <code>goal</code> after each rotation</p>
</li>
</ul>
<p>That takes:</p>
<ul>
<li><p>Up to <code>n</code> rotations</p>
</li>
<li><p>Each rotation + comparison can cost <code>O(n)</code></p>
</li>
<li><p>Total ≈ <code>O(n²)</code></p>
</li>
</ul>
<p>The <code>s + s</code> trick:</p>
<ul>
<li><p>Builds <code>s + s</code> once</p>
</li>
<li><p>Uses substring search which is <code>O(n)</code> (optimized internally)</p>
</li>
<li><p>Total ≈ <code>O(n)</code></p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p>Time: <code>O(n)</code></p>
</li>
<li><p>Space: <code>O(n)</code> for <code>s + s</code></p>
</li>
</ul>
<p>Simple, clean, and very efficient.</p>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Largest Odd Number in String]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/largest-odd-number-in-string/description/
Code:
class Solution:
    def largestOddNumber(self, num: str) -> str:
        for i in range(len(num)-1,-1, -1):
            if int(num[i])%2!=0:
                return...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-largest-odd-number-in-string</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-largest-odd-number-in-string</guid><category><![CDATA[leetcode]]></category><category><![CDATA[leetcode-solution]]></category><category><![CDATA[Strings]]></category><category><![CDATA[string]]></category><category><![CDATA[Python]]></category><category><![CDATA[Python 3]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Tue, 09 Dec 2025 14:16:33 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/largest-odd-number-in-string/description/">https://leetcode.com/problems/largest-odd-number-in-string/description/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">largestOddNumber</span>(<span class="hljs-params">self, num: str</span>) -&gt; str:</span>
        <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(num)<span class="hljs-number">-1</span>,<span class="hljs-number">-1</span>, <span class="hljs-number">-1</span>):
            <span class="hljs-keyword">if</span> int(num[i])%<span class="hljs-number">2</span>!=<span class="hljs-number">0</span>:
                <span class="hljs-keyword">return</span> num[:i+<span class="hljs-number">1</span>]
        <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>We are given a string of digits.<br />We must return the <strong>largest possible odd number</strong> that can be formed by cutting it from the <strong>left side only</strong>.</p>
<p>Meaning:</p>
<ul>
<li><p>We can only trim digits <strong>from the right end</strong></p>
</li>
<li><p>The final digit must be <strong>odd</strong></p>
</li>
<li><p>If no odd digit exists → return empty string</p>
</li>
</ul>
<hr />
<h3 id="heading-core-idea-scan-from-right">Core Idea (Scan from Right)</h3>
<p>The <strong>last digit</strong> of a number decides if it's odd or even. So, to get the <strong>largest odd number</strong>, we: 1️⃣ Start checking digits from the <strong>rightmost end</strong><br />2️⃣ Find the first digit that is <strong>odd</strong><br />3️⃣ Return the substring <strong>from start up to that digit</strong></p>
<p>This ensures:</p>
<ul>
<li><p>We keep as many digits as possible on the left (making the number largest)</p>
</li>
<li><p>We guarantee the final digit is odd</p>
</li>
</ul>
<hr />
<h3 id="heading-why-we-iterate-backwards">Why We Iterate Backwards</h3>
<p>If we started from the left:</p>
<ul>
<li><p>We might choose an odd digit too early and lose bigger digits behind it</p>
</li>
<li><p>Going from the right guarantees the <strong>longest valid prefix</strong></p>
</li>
</ul>
<hr />
<h3 id="heading-what-if-no-odd-digit-exists">What If No Odd Digit Exists?</h3>
<ul>
<li><p>Then it's impossible to form any odd number</p>
</li>
<li><p>Return <code>""</code></p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p><strong>Time:</strong> O(n) → one backward scan</p>
</li>
<li><p><strong>Space:</strong> O(1) → no extra data structures used</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[LeetCode: Number of Recent Calls]]></title><description><![CDATA[Problem:
https://leetcode.com/problems/number-of-recent-calls/
Code:
class RecentCounter:

    def __init__(self):
        self.timestamps = deque()

    def ping(self, t: int) -> int:
        self.timestamps.append(t)

        while self.timestamps[...]]></description><link>https://is-power-of-two.hashnode.dev/leetcode-number-of-recent-calls</link><guid isPermaLink="true">https://is-power-of-two.hashnode.dev/leetcode-number-of-recent-calls</guid><category><![CDATA[leetcode]]></category><category><![CDATA[leetcode-solution]]></category><category><![CDATA[DSA]]></category><category><![CDATA[Queues]]></category><dc:creator><![CDATA[Shahwar Alam Naqvi]]></dc:creator><pubDate>Tue, 09 Dec 2025 12:31:59 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-problem">Problem:</h2>
<p><a target="_blank" href="https://leetcode.com/problems/number-of-recent-calls/">https://leetcode.com/problems/number-of-recent-calls/</a></p>
<h2 id="heading-code">Code:</h2>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RecentCounter</span>:</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        self.timestamps = deque()

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">ping</span>(<span class="hljs-params">self, t: int</span>) -&gt; int:</span>
        self.timestamps.append(t)

        <span class="hljs-keyword">while</span> self.timestamps[<span class="hljs-number">0</span>]&lt;t<span class="hljs-number">-3000</span>: <span class="hljs-comment"># we directly remove te timestamps that won't fall in the new range, older ones, we pop them out.</span>
            self.timestamps.popleft()

        <span class="hljs-keyword">return</span> len(self.timestamps)
</code></pre>
<h2 id="heading-key-points">Key Points:</h2>
<h3 id="heading-problem-in-simple-words">Problem in Simple Words</h3>
<p>You keep calling <code>.ping(t)</code> with increasing timestamps <code>t</code>. You must return <strong>how many calls happened in the last 3000 ms</strong>: that means in the range: [t - 3000, t]</p>
<p>Any older calls are no longer counted.</p>
<hr />
<h3 id="heading-core-idea-sliding-window-using-queue">Core Idea (Sliding Window Using Queue)</h3>
<p>Use a <strong>queue (deque)</strong> to store timestamps of recent calls. Since <code>t</code> is always increasing:</p>
<ul>
<li><p>Newest calls go to the <strong>right</strong></p>
</li>
<li><p>Remove old timestamps from the <strong>left</strong></p>
</li>
</ul>
<p>This automatically keeps only the timestamps that are still valid.</p>
<hr />
<h3 id="heading-why-removing-from-the-left-works">Why Removing from the Left Works</h3>
<p><code>deque</code> pops from the left efficiently → O(1) And since timestamps are <strong>sorted by arrival</strong>:</p>
<ul>
<li><p>The oldest timestamps are always in front</p>
</li>
<li><p>Just remove them while they fall outside the valid range: any <code>timestamp &lt; t - 3000</code> must be discarded</p>
</li>
</ul>
<p>After cleanup, the queue size = number of valid recent calls</p>
<hr />
<h3 id="heading-execution-flow-of-pingt">Execution Flow of <code>ping(t)</code></h3>
<p>1️⃣ Append the new timestamp<br />2️⃣ Remove timestamps <strong>older than 3000 ms</strong><br />3️⃣ Return how many timestamps remain inside the window</p>
<hr />
<h3 id="heading-why-this-approach-is-good">Why This Approach Is Good</h3>
<ul>
<li><p>Every timestamp enters and leaves once → <strong>efficient</strong></p>
</li>
<li><p>No need to re-check entire history</p>
</li>
<li><p>Maintains a clean sliding window of recent calls</p>
</li>
</ul>
<hr />
<h3 id="heading-complexity">Complexity</h3>
<p>Time: O(1) amortized per ping<br />Space: O(n) → number of timestamps in the last 3000 ms</p>
]]></content:encoded></item></channel></rss>