<?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[LeetSolve - Master your coding skills by solving Leetcode challenges]]></title><description><![CDATA[LeetSolve shares how to solve Leetcode coding challenges in C++. Here you can learn essential algorithms, basic data structures, and elementary C++.]]></description><link>https://leetsolve.com</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1655412617829/G9c-8p161.png</url><title>LeetSolve - Master your coding skills by solving Leetcode challenges</title><link>https://leetsolve.com</link></image><generator>RSS for Node</generator><lastBuildDate>Fri, 16 Oct 2026 21:11:45 GMT</lastBuildDate><atom:link href="https://leetsolve.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Leetcode 59. How To Go Around A Square Matrix In Spiral Order]]></title><description><![CDATA[Problem statement
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n^2 in spiral order.
Example 1

Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]

Example 2
Input: n = 1
Output: [[1]]

Constraints

1 <= n <= 20.

So...]]></description><link>https://leetsolve.com/59-spiral-matrix-ii</link><guid isPermaLink="true">https://leetsolve.com/59-spiral-matrix-ii</guid><category><![CDATA[leetcode]]></category><category><![CDATA[C++]]></category><category><![CDATA[coding challenge]]></category><category><![CDATA[coding]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Wed, 31 Jan 2024 11:00:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1718828387276/a6ee677a-785b-4d04-af2f-860dc6eba1cd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-statementhttpsleetcodecomproblemsspiral-matrix-ii"><a target="_blank" href="https://leetcode.com/problems/spiral-matrix-ii/">Problem statement</a></h2>
<p>Given a positive integer <code>n</code>, generate an <code>n x n</code> matrix filled with elements from <code>1</code> to <code>n^2</code> in spiral order.</p>
<h3 id="heading-example-1">Example 1</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706699064517/6911fbf6-ff66-4320-9286-0ccfb91d742c.jpeg" alt class="image--center mx-auto" /></p>
<pre><code class="lang-plaintext">Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
</code></pre>
<h3 id="heading-example-2">Example 2</h3>
<pre><code class="lang-plaintext">Input: n = 1
Output: [[1]]
</code></pre>
<h3 id="heading-constraints">Constraints</h3>
<ul>
<li><code>1 &lt;= n &lt;= 20</code>.</li>
</ul>
<h2 id="heading-solution">Solution</h2>
<ol>
<li><p>Starting from the top left of the matrix.</p>
</li>
<li><p>Going along the spiral direction.</p>
</li>
<li><p>Put the value to the matrix, starting from <code>1</code>.</p>
</li>
</ol>
<h3 id="heading-code">Code</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-keyword">enum</span> Direction {RIGHT, DOWN, LEFT, UP};
<span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt; <span class="hljs-title">generateMatrix</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt; <span class="hljs-title">m</span><span class="hljs-params">(n, <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;(n))</span></span>;
    <span class="hljs-keyword">int</span> bottom = n - <span class="hljs-number">1</span>;
    <span class="hljs-keyword">int</span> right = n - <span class="hljs-number">1</span>;
    <span class="hljs-keyword">int</span> top = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">int</span> left = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">int</span> row = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">int</span> col = <span class="hljs-number">0</span>;
    Direction d = RIGHT;
    <span class="hljs-keyword">int</span> a = <span class="hljs-number">1</span>;
    <span class="hljs-keyword">while</span> (top &lt;= bottom &amp;&amp; left &lt;= right) {
        m[row][col] = a++;
        <span class="hljs-keyword">switch</span> (d) {
            <span class="hljs-keyword">case</span> RIGHT: <span class="hljs-keyword">if</span> (col == right) {
                            top++;
                            d = DOWN;
                            row++;
                        } <span class="hljs-keyword">else</span> {
                            col++;
                        }
                        <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> DOWN:  <span class="hljs-keyword">if</span> (row == bottom) {
                            right--;
                            d = LEFT;
                            col--;
                        } <span class="hljs-keyword">else</span> {
                            row++;
                        }
                        <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> LEFT:  <span class="hljs-keyword">if</span> (col == left) {
                            bottom--;
                            d = UP;
                            row--;
                        } <span class="hljs-keyword">else</span> {
                            col--;
                        }
                        <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> UP:    <span class="hljs-keyword">if</span> (row == top) {
                            left++;
                            d = RIGHT;
                            col++;
                        } <span class="hljs-keyword">else</span> {
                            row--;
                        }
                        <span class="hljs-keyword">break</span>;
        }
    }
    <span class="hljs-keyword">return</span> m;
}
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">printResult</span><span class="hljs-params">(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt;&amp; m)</span> </span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"["</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span>&amp; r : m) {
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"["</span>;
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> a : r) {
            <span class="hljs-built_in">cout</span> &lt;&lt; a &lt;&lt; <span class="hljs-string">","</span>;
        }
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"]"</span>;
    }
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"]\n"</span>;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">auto</span> m = generateMatrix(<span class="hljs-number">3</span>);
    printResult(m);
    m = generateMatrix(<span class="hljs-number">1</span>);
    printResult(m);
}
</code></pre>
<pre><code class="lang-plaintext">Output:
[[1,2,3,][8,9,4,][7,6,5,]]
[[1,]]
</code></pre>
<p>This solution uses a <code>Direction</code> <code>enum</code> and boundary variables to iteratively fill the matrix in a spiral pattern. Updating the direction of movement based on the current position and boundaries efficiently populates the matrix with sequential values, traversing in a clockwise direction from the outer layer to the inner layer.</p>
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li>Runtime: <code>O(n^2)</code>, where <code>n x n</code> is the size of the matrix.</li>
<li>Extra space: <code>O(1)</code>.</li>
</ul>
<h2 id="heading-key-takeaway">Key Takeaway</h2>
<p>Enumerating directions with an enum (like <code>Direction</code>) can enhance code readability and maintainability, especially in algorithms involving traversal or movement. It aids in clearly defining and referencing the possible directions within the problem domain.</p>
<h2 id="heading-exercise">Exercise</h2>
<ul>
<li><a target="_blank" href="https://leetcode.com/problems/spiral-matrix/">Spiral Matrix</a>.</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Leetcode 120. How To Find The Minimum Path From Top To Bottom Of A Triangle]]></title><description><![CDATA[Problem statement
You're provided with a triangle array. Your goal is to find the smallest possible sum of a path from the top of the triangle to the bottom.
You can move to an adjacent number in the row below at each step. Specifically, if you're at...]]></description><link>https://leetsolve.com/120-triangle</link><guid isPermaLink="true">https://leetsolve.com/120-triangle</guid><category><![CDATA[C++]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[Dynamic Programming]]></category><category><![CDATA[learn coding]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Tue, 23 Jan 2024 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1718830443293/d03d0842-eb51-413a-a0c2-af03324cd601.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-statementhttpsleetcodecomproblemstriangle"><a target="_blank" href="https://leetcode.com/problems/triangle/">Problem statement</a></h2>
<p>You're provided with a <code>triangle</code> array. Your goal is to find the smallest possible sum of a path from the top of the triangle to the bottom.</p>
<p>You can move to an adjacent number in the row below at each step. Specifically, if you're at index <code>i</code> in the current row, you can move to either index <code>i</code> or index <code>i + 1</code> in the next row. </p>
<h3 id="heading-example-1">Example 1</h3>
<pre><code class="lang-text">Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Explanation: The triangle looks like:
   2
  3 4
 6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
</code></pre>
<h3 id="heading-example-2">Example 2</h3>
<pre><code class="lang-text">Input: triangle = [[-10]]
Output: -10
</code></pre>
<h3 id="heading-constraints">Constraints</h3>
<ul>
<li><code>1 &lt;= triangle.length &lt;= 200</code>.</li>
<li><code>triangle[0].length == 1</code>.</li>
<li><code>triangle[i].length == triangle[i - 1].length + 1</code>.</li>
<li><code>-10^4 &lt;= triangle[i][j] &lt;= 10^4</code>.</li>
</ul>
<h3 id="heading-follow-up">Follow up</h3>
<ul>
<li>Could you use only <code>O(n)</code> extra space, where <code>n</code> is the total number of rows in the triangle?</li>
</ul>
<h2 id="heading-solution-1-store-all-minimum-paths">Solution 1: Store all minimum paths</h2>
<p>You can store all minimum paths at every positions <code>(i,j)</code> to compute the next ones with this relationship.</p>
<pre><code class="lang-text">minPath[i][j] = triangle[i][j] + min(minPath[i - 1][j - 1], minPath[i - 1][j]);
</code></pre>
<h3 id="heading-code">Code</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">minimumTotal</span><span class="hljs-params">(<span class="hljs-keyword">const</span> <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt;&amp; triangle)</span> </span>{
    <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> n = triangle.size(); <span class="hljs-comment">// triangle's height</span>
    <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt; <span class="hljs-title">minPath</span><span class="hljs-params">(n)</span></span>;
    minPath[<span class="hljs-number">0</span>] = triangle[<span class="hljs-number">0</span>];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; n; i++) {
        <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> N = triangle[i].size();
        minPath[i].resize(N);
        <span class="hljs-comment">// left most number</span>
        minPath[i][<span class="hljs-number">0</span>] = triangle[i][<span class="hljs-number">0</span>] + minPath[i<span class="hljs-number">-1</span>][<span class="hljs-number">0</span>];
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">1</span>; j &lt; N - <span class="hljs-number">1</span>; j++) {
            minPath[i][j] = triangle[i][j] + min(minPath[i<span class="hljs-number">-1</span>][j<span class="hljs-number">-1</span>], minPath[i<span class="hljs-number">-1</span>][j]);
        }
        <span class="hljs-comment">// right most number</span>
        minPath[i][N<span class="hljs-number">-1</span>] = triangle[i][N<span class="hljs-number">-1</span>] + minPath[i<span class="hljs-number">-1</span>][N<span class="hljs-number">-2</span>];

    }
    <span class="hljs-comment">// pick the min path among the ones (begin -&gt; end)</span>
    <span class="hljs-comment">// go to the bottom (n-1)</span>
    <span class="hljs-keyword">return</span> *min_element(minPath[n<span class="hljs-number">-1</span>].begin(), minPath[n<span class="hljs-number">-1</span>].end());
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt; triangle{{<span class="hljs-number">2</span>},{<span class="hljs-number">3</span>,<span class="hljs-number">4</span>},{<span class="hljs-number">6</span>,<span class="hljs-number">5</span>,<span class="hljs-number">7</span>},{<span class="hljs-number">4</span>,<span class="hljs-number">1</span>,<span class="hljs-number">8</span>,<span class="hljs-number">3</span>}};
    <span class="hljs-built_in">cout</span> &lt;&lt; minimumTotal(triangle) &lt;&lt; <span class="hljs-built_in">endl</span>;
    triangle = {{<span class="hljs-number">-10</span>}};
    <span class="hljs-built_in">cout</span> &lt;&lt; minimumTotal(triangle) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-text">Output:
11
-10
</code></pre>
<p>This solution finds the minimum path sum from the top to the bottom of a triangle, represented as a vector of vectors. It uses dynamic programming to calculate the minimum path sum.</p>
<p>The algorithm initializes a <code>minPath</code> vector of vectors to store the minimum path sum for each element in the <code>triangle</code>. It starts by setting the first row of <code>minPath</code> to be the same as the first row of the <code>triangle</code>.</p>
<p>Then, it iterates through the rows of the <code>triangle</code> starting from the second row. For each element in the current row, the minimum path sum is calculated by considering the two paths from the previous row leading to that element. It takes the minimum of the two paths and adds the current element's value. This way, it accumulates the minimum path sum efficiently.</p>
<p>The algorithm continues this process until it reaches the last row of the <code>triangle</code>. Finally, it returns the minimum element from the last row of <code>minPath</code>, representing the minimum path sum from top to bottom.</p>
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li>Runtime: <code>O(n^2)</code>, where <code>n</code> is the number of rows in the <code>triangle</code>.</li>
<li>Extra space: <code>O(n^2)</code>.</li>
</ul>
<h2 id="heading-solution-2-store-only-the-minimum-paths-of-each-row">Solution 2: Store only the minimum paths of each row</h2>
<p>You do not need to store all paths for all rows. The computation of the next row only depends on its previous one.</p>
<h3 id="heading-code-1">Code</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">minimumTotal</span><span class="hljs-params">(<span class="hljs-keyword">const</span> <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt;&amp; triangle)</span> </span>{
    <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> n = triangle.size();
    <span class="hljs-comment">// store only min path for each row</span>
    <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">minPath</span><span class="hljs-params">(n)</span></span>;
    minPath[<span class="hljs-number">0</span>] = triangle[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; n; i++) {
        <span class="hljs-comment">// right most number</span>
        minPath[i] = triangle[i][i] + minPath[i - <span class="hljs-number">1</span>];
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = i - <span class="hljs-number">1</span>; j &gt; <span class="hljs-number">0</span>; j--) {
            minPath[j] = triangle[i][j] + min(minPath[j - <span class="hljs-number">1</span>], minPath[j]);
        }
        <span class="hljs-comment">// left most number</span>
        minPath[<span class="hljs-number">0</span>] = triangle[i][<span class="hljs-number">0</span>] + minPath[<span class="hljs-number">0</span>];
    }
    <span class="hljs-keyword">return</span> *min_element(minPath.begin(), minPath.end());
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt; triangle{{<span class="hljs-number">2</span>},{<span class="hljs-number">3</span>,<span class="hljs-number">4</span>},{<span class="hljs-number">6</span>,<span class="hljs-number">5</span>,<span class="hljs-number">7</span>},{<span class="hljs-number">4</span>,<span class="hljs-number">1</span>,<span class="hljs-number">8</span>,<span class="hljs-number">3</span>}};
    <span class="hljs-built_in">cout</span> &lt;&lt; minimumTotal(triangle) &lt;&lt; <span class="hljs-built_in">endl</span>;
    triangle = {{<span class="hljs-number">-10</span>}};
    <span class="hljs-built_in">cout</span> &lt;&lt; minimumTotal(triangle) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-text">Output:
11
-10
</code></pre>
<h3 id="heading-complexity-1">Complexity</h3>
<ul>
<li>Runtime: <code>O(n^2)</code>, where <code>n</code> is the number of rows in the triangle.</li>
<li>Extra space: <code>O(n)</code>.</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[How To Find The Longest Substring Without Repeating Characters]]></title><description><![CDATA[Problem statement
Given a string s, find the length of the longest substring without repeating characters.
Example 1
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with a length of 3.

Example 2
Input: s = "bbbbb"
Output: 1
Explana...]]></description><link>https://leetsolve.com/3-longest-substring-without-repeating-characters</link><guid isPermaLink="true">https://leetsolve.com/3-longest-substring-without-repeating-characters</guid><category><![CDATA[C++]]></category><category><![CDATA[leetcode]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[coding]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Tue, 16 Jan 2024 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706382665547/a91fe9ba-2a42-4658-a856-ee6fa75b7d4e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-problem-statement">Problem statement</h3>
<p>Given a string <code>s</code>, find the length of the longest substring without repeating characters.</p>
<h3 id="heading-example-1">Example 1</h3>
<pre><code class="lang-plaintext">Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with a length of 3.
</code></pre>
<h3 id="heading-example-2">Example 2</h3>
<pre><code class="lang-plaintext">Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
</code></pre>
<h3 id="heading-example-3">Example 3</h3>
<pre><code class="lang-plaintext">Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with a length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
</code></pre>
<h3 id="heading-constraints">Constraints</h3>
<ul>
<li><p><code>0 &lt;= s.length &lt;= 5 * 10^4</code>.</p>
</li>
<li><p><code>s</code> consists of English letters, digits, symbols and spaces.</p>
</li>
</ul>
<h2 id="heading-solution-store-the-position-of-the-visited-characters">Solution: Store the position of the visited characters</h2>
<p>One way of checking the repetition of the characters is by using a map to store their indices. For example:</p>
<pre><code class="lang-plaintext">last_visit[s[i]] = i
</code></pre>
<p>You might want to find every substring of nonrepeating characters in the string <code>s</code>, then identify the longest one among them.</p>
<ol>
<li><p>The character you are checking its repetition and computing the length should be done within its substring;</p>
</li>
<li><p>The map should always update the latest visited index of a character; and</p>
</li>
<li><p>The starting index of a substring is also updated when repetition happens.</p>
</li>
</ol>
<h3 id="heading-example-1-1">Example 1</h3>
<p>For the string <code>s = "abcabcbb"</code>:</p>
<ul>
<li><p>When you visit the second letter <code>'a'</code>, the first substring is formed <code>"abc"</code>, the next substring starts from the second letter <code>'a'</code>: <code>start = 3</code> , <code>last_visit['a']</code> is updated to be <code>3</code>.</p>
</li>
<li><p>When you visit the second letter <code>'b'</code>, its <code>last_visit['b']</code> is updated to be <code>4</code>.</p>
</li>
<li><p>Repetition is found when you visit the third letter <code>'b'</code>, the second substring <code>"abc"</code> is formed. The next <code>start = 6</code>; <code>last_visit['b'] = 6</code>.</p>
</li>
<li><p>The fourth letter <code>'b'</code> causes a repetition and forms a one-letter substring <code>"b"</code>.</p>
</li>
<li><p>The string <code>s</code> ends and form another one-letter substring <code>"b"</code>.</p>
</li>
</ul>
<h3 id="heading-code">Code</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;unordered_map&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">lengthOfLongestSubstring</span><span class="hljs-params">(<span class="hljs-built_in">string</span> s)</span> </span>{
    <span class="hljs-built_in">unordered_map</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-keyword">int</span>&gt; last_visit;
    <span class="hljs-keyword">int</span> maxLen = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">int</span> start = <span class="hljs-number">-1</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; s.length(); i++) {
        <span class="hljs-keyword">auto</span> it = last_visit.find(s.at(i));
        <span class="hljs-keyword">if</span> (it != last_visit.end()) {
            start = max(start, it-&gt;second);
            it-&gt;second = i;
        } <span class="hljs-keyword">else</span> {
            last_visit.insert({s.at(i), i});
        }
        maxLen = max(maxLen, i - start);
    }
    <span class="hljs-keyword">return</span> maxLen;

}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; lengthOfLongestSubstring(<span class="hljs-string">"abcabcbb"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; lengthOfLongestSubstring(<span class="hljs-string">"bbbbb"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; lengthOfLongestSubstring(<span class="hljs-string">"pwwkew"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
3
1
3
</code></pre>
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p>Runtime: <code>O(N)</code>, where <code>N = s.length</code>.</p>
</li>
<li><p>Extra space: <code>O(N)</code>.</p>
</li>
</ul>
<h2 id="heading-implementation-notes">Implementation notes</h2>
<ul>
<li><p>You can initialize the <code>start</code> index of the substrings with <code>-1</code> to deal with the boundary cases.</p>
</li>
<li><p>As a best practice, when you check if a map contains a key and retrieve its value, use an iterator and <code>find()</code> like the above solution. DO NOT implement as follow</p>
</li>
</ul>
<pre><code class="lang-cpp"><span class="hljs-keyword">if</span> (last_visit.find(s.at(i)) != last_visit.end()) {
    start = max(start, last_visit[s.at(i)]);
}
</code></pre>
<p>Because the operator <code>[]</code> might perform an additional <code>find()</code>.</p>
<hr />
<p><em>Thanks for reading. Feel free to share your thought about my content and check out my book</em><a target="_blank" href="https://store.nhutnguyen.com/l/10_classic"><em>10 Classic Coding Challenges</em></a> <em>for FREE:</em></p>
]]></content:encoded></item><item><title><![CDATA[How To Find The Maximal Subarray Having Distinct Elements]]></title><description><![CDATA[Problem statement
You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.
Return the maximum score you can get by erasing...]]></description><link>https://leetsolve.com/1695-maximum-erasure-value</link><guid isPermaLink="true">https://leetsolve.com/1695-maximum-erasure-value</guid><category><![CDATA[C++]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[learn coding]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[Programming Tips]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Tue, 09 Jan 2024 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706389078279/17b7687d-3437-4df2-b8a2-a0b629b250be.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-problem-statement">Problem statement</h3>
<p>You are given an array of positive integers <code>nums</code> and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.</p>
<p>Return the maximum score you can get by erasing exactly one subarray.</p>
<p>An array <code>b</code> is called to be a subarray of <code>a</code> if it forms a contiguous subsequence of <code>a</code>, that is, if it is equal to <code>a[l],a[l+1],...,a[r]</code> for some <code>(l,r)</code>.</p>
<h4 id="heading-example-1">Example 1</h4>
<pre><code class="lang-plaintext">Input: nums = [4,2,4,5,6]
Output: 17
Explanation: The optimal subarray here is [2,4,5,6].
</code></pre>
<h4 id="heading-example-2">Example 2</h4>
<pre><code class="lang-plaintext">Input: nums = [5,2,1,2,5,2,1,2,5]
Output: 8
Explanation: The optimal subarray here is [5,2,1] or [1,2,5].
</code></pre>
<h4 id="heading-constraints">Constraints</h4>
<ul>
<li><p><code>1 &lt;= nums.length &lt;= 10^5</code>.</p>
</li>
<li><p><code>1 &lt;= nums[i] &lt;= 10^4</code>.</p>
</li>
</ul>
<h3 id="heading-solution-store-the-position-of-the-visited-elements">Solution: Store the position of the visited elements</h3>
<p>You can use a map to store the position of the elements of <code>nums</code>. Then when iterating <code>nums</code> you can identify if an element has been visited before. That helps you to decide if a subarray contains unique elements.</p>
<h4 id="heading-code">Code</h4>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;unordered_map&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">maximumUniqueSubarray</span><span class="hljs-params">(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&amp; nums)</span> </span>{
    <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">sum</span><span class="hljs-params">(nums.size(), <span class="hljs-number">0</span>)</span></span>;
    sum[<span class="hljs-number">0</span>] = nums[<span class="hljs-number">0</span>];    
    <span class="hljs-keyword">int</span> maxSum = sum[<span class="hljs-number">0</span>];
    <span class="hljs-built_in">unordered_map</span>&lt;<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>&gt; position;
    position[nums[<span class="hljs-number">0</span>]] = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">int</span> start = <span class="hljs-number">-1</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; nums.size(); i++) {
        sum[i] = sum[i - <span class="hljs-number">1</span>] + nums[i];
        <span class="hljs-keyword">if</span> (position.find(nums[i]) != position.end()) {
            start = max(start, position[nums[i]]);
        }
        position[nums[i]] = i;
        maxSum = (start == <span class="hljs-number">-1</span>) ? sum[i] : max(maxSum, sum[i] - sum[start]);
    }
    <span class="hljs-keyword">return</span> maxSum;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; nums{<span class="hljs-number">4</span>,<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>};
    <span class="hljs-built_in">cout</span> &lt;&lt; maximumUniqueSubarray(nums) &lt;&lt; <span class="hljs-built_in">endl</span>;
    nums = {<span class="hljs-number">5</span>,<span class="hljs-number">2</span>,<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">5</span>,<span class="hljs-number">2</span>,<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">5</span>};
    <span class="hljs-built_in">cout</span> &lt;&lt; maximumUniqueSubarray(nums) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
17
8
</code></pre>
<p>This C++ code defines a function <code>maximumUniqueSubarray</code> that finds the maximum sum of a subarray in the given vector <code>nums</code> with the constraint that all elements must be unique. It uses two key techniques: prefix sums and a sliding window approach.</p>
<h4 id="heading-complexity">Complexity</h4>
<ul>
<li><p>Runtime: <code>O(N)</code>, where <code>N = nums.length</code>.</p>
</li>
<li><p>Extra space: <code>O(N)</code>.</p>
</li>
</ul>
<hr />
<p>Thanks for reading. <a target="_blank" href="https://nhutnguyen.gumroad.com/l/10_classic">Get my book "10 Classic Coding Challenges"</a> for FREE.</p>
]]></content:encoded></item><item><title><![CDATA[Common Mistakes in Coding Interviews and How to Avoid Them]]></title><description><![CDATA[Coding interviews are a pivotal part of the hiring process for software engineers and developers. These interviews assess your problem-solving skills, algorithmic thinking, and coding abilities under pressure.
While coding interviews can be challengi...]]></description><link>https://leetsolve.com/common-mistakes-in-coding-interviews-and-how-to-avoid-them</link><guid isPermaLink="true">https://leetsolve.com/common-mistakes-in-coding-interviews-and-how-to-avoid-them</guid><category><![CDATA[CodingInterview]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Tue, 02 Jan 2024 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Hcfwew744z4/upload/135a90982affcc5040edbdd1a13f5bad.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Coding interviews</strong> are a pivotal part of the hiring process for software engineers and developers. These interviews assess your <strong>problem-solving skills</strong>, <strong>algorithmic thinking</strong>, and <strong>coding abilities</strong> under pressure.</p>
<p>While coding interviews can be challenging, even for experienced candidates, avoiding common mistakes is crucial to success. This comprehensive guide will explore the <strong>most common mistakes</strong> in coding interviews and provide strategies to avoid them, helping you excel in your next technical interview.</p>
<h2 id="heading-why-coding-interviews-matter">Why Coding Interviews Matter</h2>
<p>Coding interviews assess candidates' <strong>technical skills</strong>, <strong>problem-solving ability</strong>, and <strong>coding proficiency</strong>. Companies use them to determine if a candidate can handle the job demands.</p>
<p>For the interviewee, performing well in these interviews is often a gateway to exciting job opportunities and career advancement. However, making mistakes during coding interviews can be a significant obstacle. Let's dive into some of the most common pitfalls and how to avoid them.</p>
<hr />
<h2 id="heading-common-mistakes-in-coding-interviews">Common Mistakes in Coding Interviews</h2>
<h3 id="heading-1-lack-of-preparation">1. Lack of Preparation</h3>
<p><strong>Mistake:</strong> A lack of preparation is one of the most common and detrimental mistakes. Some candidates underestimate the importance of thorough preparation, assuming their experience or knowledge is sufficient to carry them through the interview.</p>
<p><strong>Avoidance:</strong> To prepare effectively, review the fundamentals of <strong>data structures</strong>, <strong>algorithms</strong>, and <strong>problem-solving techniques</strong>. Invest time practicing coding challenges on platforms like LeetCode, HackerRank, or CodeSignal. Consider conducting <strong>mock interviews</strong> with peers or mentors to simulate the interview experience.</p>
<h3 id="heading-2-poor-time-management">2. Poor Time Management</h3>
<p><strong>Mistake:</strong> Time management can be a significant challenge in coding interviews. Candidates may spend <strong>too much time on a single problem</strong>, leaving insufficient time for other questions.</p>
<p><strong>Avoidance:</strong> Practice time management by setting time limits when solving practice problems. In real interviews, it's essential to maintain a steady pace. If you are stuck on a particular problem, consider moving on to other questions and returning to the challenging one later. <strong>Prioritize questions based on your strengths and tackle the low-hanging fruit first</strong>.</p>
<h3 id="heading-3-lack-of-communication">3. Lack of Communication</h3>
<p><strong>Mistake:</strong> Some candidates remain <strong>silent</strong> during interviews, failing to communicate their thoughts to the interviewer. This can lead to <strong>misunderstandings</strong> and missed opportunities to showcase their problem-solving skills.</p>
<p><strong>Avoidance:</strong> Communicate your thought process. Explain your approach before starting to code. Discuss your <strong>assumptions</strong> and <strong>strategies</strong> with the interviewer. Effective communication demonstrates your problem-solving abilities and allows you to receive valuable <strong>feedback</strong>. Please <strong>don't assume</strong> the interviewer can read your mind; they appreciate clear, structured communication.</p>
<h3 id="heading-4-ignoring-edge-cases">4. Ignoring Edge Cases</h3>
<p><strong>Mistake:</strong> Neglecting edge cases or failing to consider all possible scenarios can lead to <strong>incomplete</strong> or <strong>incorrect</strong> solutions.</p>
<p><strong>Avoidance:</strong> Always consider edge cases and test your code against them. Discuss <strong>potential edge cases</strong> with the interviewer to demonstrate your thorough problem-solving approach. Address <strong>boundary conditions</strong> and exceptional scenarios explicitly in your code.</p>
<h3 id="heading-5-over-complicated-solutions">5. Over-Complicated Solutions</h3>
<p><strong>Mistake:</strong> Some candidates tend to overcomplicate their solutions. This can lead to more <strong>complex</strong> and <strong>error-prone</strong> code, which is challenging for the interviewer to understand.</p>
<p><strong>Avoidance:</strong> Strive for <strong>simplicity</strong> in your solutions. Break the problem down into <strong>smaller</strong>, <strong>manageable</strong> steps. Write code that is <strong>clean</strong>, <strong>easy</strong> to understand, and <strong>efficient</strong>. Remember that the goal is to find a <strong>working</strong> solution, not necessarily the most elegant one. <strong>Prioritize clarity over complexity</strong>.</p>
<h3 id="heading-6-focusing-only-on-syntax">6. Focusing Only on Syntax</h3>
<p><strong>Mistake:</strong> Candidates may become overly concerned with <strong>perfect syntax</strong> during interviews, leading to slow progress and stress.</p>
<p><strong>Avoidance:</strong> While correct syntax is essential, prioritize problem-solving and algorithmic thinking. If you make a minor syntax error, the interviewer will often overlook it if your approach is sound. Concentrate on conveying your understanding of the problem and how you intend to solve it. Focus on your <strong>problem-solving</strong> abilities rather than syntax perfection.</p>
<h3 id="heading-7-giving-up-too-soon">7. Giving Up Too Soon</h3>
<p><strong>Mistake:</strong> Some candidates <strong>give up too quickly</strong> when encountering difficulties in a problem. This can prevent them from reaching a solution and showcasing their problem-solving skills.</p>
<p><strong>Avoidance:</strong> Persistence is key. <strong>Don't give up at the first sign of difficulty</strong>. Approach the problem methodically, break it into smaller subproblems, and tackle each. If you get stuck, <strong>communicate</strong> your thought process and discuss potential approaches with the interviewer. Interviewers often appreciate your determination and problem-solving resilience.</p>
<h3 id="heading-8-not-asking-clarifying-questions">8. Not Asking Clarifying Questions</h3>
<p><strong>Mistake:</strong> Candidates often <strong>make assumptions</strong> about the problem without seeking clarification from the interviewer. This can lead to misunderstandings and incorrect solutions.</p>
<p><strong>Avoidance:</strong> Ask questions to <strong>clarify</strong> any ambiguities or uncertainties in the problem statement. Don't hesitate to seek <strong>additional information</strong> or constraints to guide your solution. Interviewers appreciate candidates who ask thoughtful questions and validate their understanding of the problem.</p>
<h3 id="heading-9-lack-of-testing">9. Lack of Testing</h3>
<p><strong>Mistake:</strong> Failing to test your solution thoroughly can result in <strong>uncaught bugs</strong> or errors.</p>
<p><strong>Avoidance:</strong> After writing your code, <strong>test</strong> it with various inputs, including common and edge cases. Verify that your solution produces the expected output and handles all possible scenarios. Demonstrating the effectiveness of your code through testing can enhance your credibility and reassure the interviewer that your solution is robust.</p>
<h3 id="heading-10-not-learning-from-rejections">10. Not Learning from Rejections</h3>
<p><strong>Mistake:</strong> Rejections in coding interviews can be disheartening, but not learning from them can hinder your progress.</p>
<p><strong>Avoidance:</strong> Treat rejections as opportunities to <strong>learn</strong> and <strong>improve</strong>. <strong>Request feedback</strong> from interviewers or mentors to understand your weaknesses and areas for growth. Adjust your preparation based on the feedback received to increase your chances of success in future interviews. Continuous improvement is essential in the competitive field of software engineering.</p>
<h3 id="heading-11-not-seeking-help">11. Not Seeking Help</h3>
<p><strong>Mistake:</strong> Some candidates feel they must solve problems independently, leading to frustration and <strong>wasted time</strong>.</p>
<p><strong>Avoidance:</strong> Don't hesitate to seek help or hints from the interviewer if you're stuck. They may provide valuable guidance or nudges to help you find the correct solution. It's better to <strong>seek help</strong> than to remain stuck and fail to solve the problem. Interviewers are often interested in your problem-solving approach and how you adapt to new information.</p>
<h3 id="heading-12-not-tailoring-preparation">12. Not Tailoring Preparation</h3>
<p><strong>Mistake:</strong> Failing to tailor your interview preparation to the <strong>specific</strong> company or role can result in suboptimal performance.</p>
<p><strong>Avoidance:</strong> <strong>Research</strong> the company's interview process and expectations. <strong>Understand</strong> the technologies and languages they use. Tailor your preparation to <strong>align with</strong> the company's requirements and industry trends. If a company strongly focuses on a particular programming language, ensure your skills in that language are up to par.</p>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Mastering coding interviews is valuable for any aspiring software engineer or developer. Avoiding common mistakes and following best practices can significantly increase your chances of success. Remember to <strong>focus on problem-solving</strong>, <strong>communicate effectively</strong>, and <strong>continuously improve your skills</strong>. With dedication and a structured approach to interview preparation, you can excel in coding interviews and secure the job you desire.</p>
<p>Coding interviews are not just about technical knowledge; they also showcase your problem-solving, communication, and adaptability skills. You'll perform better in interviews and grow as a well-rounded software professional by learning from mistakes and consistently improving.</p>
]]></content:encoded></item><item><title><![CDATA[How to Check If a Number is a Power of Four]]></title><description><![CDATA[Problem statement
Given an integer n, return true if it is a power of four. Otherwise, return false.
An integer n is a power of four if there exists an integer x such that n == 4^x.
Example 1
Input: n = 16
Output: true

Example 2
Input: n = 5
Output:...]]></description><link>https://leetsolve.com/how-to-check-if-a-number-is-a-power-of-four</link><guid isPermaLink="true">https://leetsolve.com/how-to-check-if-a-number-is-a-power-of-four</guid><category><![CDATA[C++]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Programming Tips]]></category><category><![CDATA[leetcode]]></category><category><![CDATA[learn coding]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Tue, 26 Dec 2023 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706389315267/750cbcd6-0857-4fd0-877b-7d2300bff74a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-problem-statement">Problem statement</h3>
<p>Given an integer <code>n</code>, return <code>true</code> if it is a power of four. Otherwise, return <code>false</code>.</p>
<p>An integer <code>n</code> is a power of four if there exists an integer <code>x</code> such that <code>n == 4^x</code>.</p>
<h4 id="heading-example-1">Example 1</h4>
<pre><code class="lang-plaintext">Input: n = 16
Output: true
</code></pre>
<h4 id="heading-example-2">Example 2</h4>
<pre><code class="lang-plaintext">Input: n = 5
Output: false
</code></pre>
<h4 id="heading-example-3">Example 3</h4>
<pre><code class="lang-plaintext">Input: n = 1
Output: true
</code></pre>
<h4 id="heading-constraints">Constraints</h4>
<ul>
<li><code>-2^31 &lt;= n &lt;= 2^31 - 1</code>.</li>
</ul>
<p><strong>Follow up</strong>: Could you solve it without loops/recursion?</p>
<h3 id="heading-solution-1-division-by-four">Solution 1: Division by four</h3>
<h4 id="heading-code">Code</h4>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">isPowerOfFour</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    <span class="hljs-keyword">while</span> (n % <span class="hljs-number">4</span> == <span class="hljs-number">0</span> &amp;&amp; n &gt; <span class="hljs-number">0</span>) {
        n /= <span class="hljs-number">4</span>;
    }
    <span class="hljs-keyword">return</span> n == <span class="hljs-number">1</span>;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; isPowerOfFour(<span class="hljs-number">16</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; isPowerOfFour(<span class="hljs-number">5</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; isPowerOfFour(<span class="hljs-number">1</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
1
0
1
</code></pre>
<h4 id="heading-complexity">Complexity</h4>
<ul>
<li><p>Runtime: <code>O(logn)</code>.</p>
</li>
<li><p>Extra space: <code>O(1)</code>.</p>
</li>
</ul>
<h3 id="heading-solution-2-binary-representation">Solution 2: Binary representation</h3>
<p>You can write down the binary representation of the powers of four to find the pattern.</p>
<pre><code class="lang-plaintext">1   : 1
4   : 100
16  : 10000
64  : 1000000
256 : 100000000
...
</code></pre>
<p>You might notice the patterns are <strong>n is a positive integer having only one bit</strong><code>1</code> in its binary representation and it is located at the odd positions (starting from the right).</p>
<p>How can you formulate those conditions?</p>
<p>If <code>n</code> has only one bit <code>1</code> in its binary representation <code>10...0</code>, then <code>n - 1</code> has the complete opposite binary representation <code>01...1</code>.</p>
<p>You can use the bit operator AND to formulate this condition</p>
<pre><code class="lang-plaintext">n &amp; (n - 1) == 0
</code></pre>
<p>Let <code>A</code> be the number whose binary representation has only bits <code>1</code> at all odd positions, then <code>n &amp; A</code> is never <code>0</code>.</p>
<p>In this problem, <code>A &lt; 2^31</code>. You can choose<code>A = 0x55555555</code>, the hexadecimal of <code>0101 0101 0101 0101 0101 0101 0101 0101</code>.</p>
<h4 id="heading-code-1">Code</h4>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">isPowerOfFour</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    <span class="hljs-keyword">return</span> n &gt; <span class="hljs-number">0</span> &amp;&amp; (n &amp; (n - <span class="hljs-number">1</span>)) == <span class="hljs-number">0</span> &amp;&amp; (n &amp; <span class="hljs-number">0x55555555</span>) != <span class="hljs-number">0</span>;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; isPowerOfFour(<span class="hljs-number">16</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; isPowerOfFour(<span class="hljs-number">5</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; isPowerOfFour(<span class="hljs-number">1</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
1
0
1
</code></pre>
<h4 id="heading-complexity-1">Complexity</h4>
<ul>
<li><p>Runtime: <code>O(1)</code>.</p>
</li>
<li><p>Extra space: <code>O(1)</code>.</p>
</li>
</ul>
<hr />
<p>Thanks for reading. <a target="_blank" href="https://nhutnguyen.gumroad.com/l/10_classic">Get my book "10 Classic Coding Challenges"</a> for FREE:</p>
]]></content:encoded></item><item><title><![CDATA[How to Encode Morse Code]]></title><description><![CDATA[Problem statement
The problem involves the International Morse Code, which defines a standard way to encode letters with dots and dashes. Each English letter corresponds to a specific sequence in Morse Code, and a full table mapping each letter is pr...]]></description><link>https://leetsolve.com/804-unique-morse-code-words</link><guid isPermaLink="true">https://leetsolve.com/804-unique-morse-code-words</guid><category><![CDATA[leetcode]]></category><category><![CDATA[C++]]></category><category><![CDATA[coding]]></category><category><![CDATA[coding challenge]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Tue, 19 Dec 2023 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706389590651/44f277b5-e7fa-4cf1-92af-ab944dc09841.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-statementhttpsleetcodecomproblemsunique-morse-code-wordsrefleetsolvecom"><a target="_blank" href="https://leetcode.com/problems/unique-morse-code-words/?ref=leetsolve.com">Problem statement</a></h2>
<p>The problem involves the International Morse Code, which defines a standard way to encode letters with dots and dashes. Each English letter corresponds to a specific sequence in Morse Code, and a full table mapping each letter is provided.</p>
<p>For instance, <code>'a'</code> is encoded as <code>".-"</code>, <code>'b'</code> as <code>"-..."</code>, and so on.</p>
<p>The full table for the <code>26</code> letters of the English alphabet is given below:</p>
<pre><code class="lang-text">[".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--", "-.",
"---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-", ".--", "-..-", "-.--", "--.."]
</code></pre>
<p>You are given an array of strings named <code>words</code>, where each word can be represented as a concatenation of the Morse code for each of its letters. For example, the word <code>"cab"</code> can be represented as <code>"-.-..--..."</code>, which is the concatenation of <code>"-.-."</code>, <code>".-"</code>, and <code>"-..."</code>. This concatenated Morse code representation is referred to as the "transformation" of a word.</p>
<p>Your task is to count the number of different transformations that can be obtained from all the words in the given array.</p>
<h3 id="heading-example-1">Example 1</h3>
<pre><code class="lang-text">Input: words = ["gin","zen","gig","msg"]
Output: 2
Explanation: The transformation of each word is:
"gin" -&gt; "--...-."
"zen" -&gt; "--...-."
"gig" -&gt; "--...--."
"msg" -&gt; "--...--."
There are 2 different transformations: "--...-." and "--...--.".
</code></pre>
<h3 id="heading-example-2">Example 2</h3>
<pre><code class="lang-text">Input: words = ["a"]
Output: 1
</code></pre>
<h3 id="heading-constraints">Constraints</h3>
<ul>
<li><p><code>1 &lt;= words.length &lt;= 100</code>.</p>
</li>
<li><p><code>1 &lt;= words[i].length &lt;= 12</code>.</p>
</li>
<li><p><code>words[i]</code> consists of lowercase English letters.</p>
</li>
</ul>
<h2 id="heading-solution-store-the-transformations-in-a-set">Solution: Store the transformations in a set</h2>
<h3 id="heading-code">Code</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;unordered_set&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">uniqueMorseRepresentations</span><span class="hljs-params">(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">string</span>&gt;&amp; words)</span> 
</span>{
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">string</span>&gt; morse{
        <span class="hljs-string">".-"</span>, <span class="hljs-string">"-..."</span>, <span class="hljs-string">"-.-."</span>, <span class="hljs-string">"-.."</span>, <span class="hljs-string">"."</span>, <span class="hljs-string">"..-."</span>, <span class="hljs-string">"--."</span>,
        <span class="hljs-string">"...."</span>, <span class="hljs-string">".."</span>, <span class="hljs-string">".---"</span>, <span class="hljs-string">"-.-"</span>, <span class="hljs-string">".-.."</span>, <span class="hljs-string">"--"</span>, <span class="hljs-string">"-."</span>,
        <span class="hljs-string">"---"</span>, <span class="hljs-string">".--."</span>, <span class="hljs-string">"--.-"</span>, <span class="hljs-string">".-."</span>, <span class="hljs-string">"..."</span>, <span class="hljs-string">"-"</span>, <span class="hljs-string">"..-"</span>,
        <span class="hljs-string">"...-"</span>, <span class="hljs-string">".--"</span>, <span class="hljs-string">"-..-"</span>, <span class="hljs-string">"-.--"</span>, <span class="hljs-string">"--.."</span>
    };
    <span class="hljs-built_in">unordered_set</span>&lt;<span class="hljs-built_in">string</span>&gt; transformations;
    <span class="hljs-keyword">for</span> (<span class="hljs-built_in">string</span>&amp; w : words) 
    {
        <span class="hljs-built_in">string</span> s{<span class="hljs-string">""</span>};
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">char</span>&amp; c : w) 
        {
            s += morse[c - <span class="hljs-string">'a'</span>];
        }
        transformations.insert(s);
    }
    <span class="hljs-keyword">return</span> transformations.size();
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> 
</span>{
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">string</span>&gt; words{<span class="hljs-string">"gin"</span>,<span class="hljs-string">"zen"</span>,<span class="hljs-string">"gig"</span>,<span class="hljs-string">"msg"</span>};
    <span class="hljs-built_in">cout</span> &lt;&lt; uniqueMorseRepresentations(words) &lt;&lt; <span class="hljs-built_in">endl</span>;
    words = {<span class="hljs-string">"a"</span>};
    <span class="hljs-built_in">cout</span> &lt;&lt; uniqueMorseRepresentations(words) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-text">Output:
2
1
</code></pre>
<h3 id="heading-code-explanation">Code explanation</h3>
<ol>
<li><p>The solution begins with a predefined mapping of lowercase English letters to their corresponding Morse code representations. The Morse code representations are stored in a vector called <code>morse</code>.</p>
</li>
<li><p>An <code>unordered_set&lt;string&gt; transformations</code> is used to store the unique Morse code representations generated from the input words. This set will automatically ensure that only unique representations are stored.</p>
</li>
<li><p>The code iterates through each word in the <code>words</code> vector. For each word, it initializes an empty string <code>s</code> to store the Morse code representation of that word.</p>
</li>
<li><p>It then iterates through each character in the word. For each character <code>c</code> in the word, it appends the corresponding Morse code representation (retrieved from the <code>morse</code> vector) for that character to the <code>s</code> string. The mapping is accessed using <code>morse[c - 'a']</code>.</p>
</li>
<li><p>After constructing the Morse code representation for the current word, it inserts the <code>s</code> string into the <code>transformations</code> set. If <code>s</code> is already present in the set, it will not be added again since sets only allow unique elements.</p>
</li>
<li><p>After processing all the words, the size of the <code>transformations</code> set is returned as the result. The size of the set corresponds to the number of unique Morse code representations generated from the input words.</p>
</li>
</ol>
<h3 id="heading-complexity">Complexity</h3>
<p>This solution converts each word into Morse code based on a predefined mapping and uses an unordered set to keep track of unique representations. By inserting each representation into the set, it automatically filters out duplicates. The final result is the size of the set, which represents the number of unique Morse code representations among the input words.</p>
<ul>
<li><p>Runtime: <code>O(N*M)</code>, where <code>N = words.length</code> and <code>M = words[i].length</code>.</p>
</li>
<li><p>Extra space: <code>O(N)</code>.</p>
</li>
</ul>
<hr />
<p>Thanks for reading! <a target="_blank" href="https://nhutnguyen.gumroad.com/l/10_classic"><strong>Get my book "10 Classic Coding Challenges"</strong></a> for FREE.</p>
]]></content:encoded></item><item><title><![CDATA[How To Add Two Numbers Represented As Linked Lists]]></title><description><![CDATA[Problem statement
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You m...]]></description><link>https://leetsolve.com/add-two-numbers</link><guid isPermaLink="true">https://leetsolve.com/add-two-numbers</guid><category><![CDATA[C++]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[leetcode]]></category><category><![CDATA[learn coding]]></category><category><![CDATA[data structures]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Tue, 12 Dec 2023 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706389971581/4a8a4e73-53da-4daa-be18-28d9c20e7d31.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-problem-statement">Problem statement</h3>
<p>You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.</p>
<p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.</p>
<h4 id="heading-example-1">Example 1</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661031117701/RoNySPnon.jpg" alt="2_addtwonumber1.jpg" /></p>
<pre><code class="lang-plaintext">Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
</code></pre>
<h4 id="heading-example-2">Example 2</h4>
<pre><code class="lang-plaintext">Input: l1 = [0], l2 = [0]
Output: [0]
</code></pre>
<h4 id="heading-example-3">Example 3</h4>
<pre><code class="lang-plaintext">Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
</code></pre>
<h4 id="heading-constraints">Constraints</h4>
<ul>
<li><p>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</p>
</li>
<li><p><code>0 &lt;= Node.val &lt;= 9</code>.</p>
</li>
<li><p>It is guaranteed that the list represents a number that does not have leading zeros.</p>
</li>
</ul>
<h3 id="heading-solution-addition-with-remember">Solution: Addition With Remember</h3>
<p>Perform the school addition calculation and store the result in one of the lists.</p>
<p>Without loss of generality, let us store the result in <code>l1</code>. Then you might need to extend it when <code>l2</code> is longer than <code>l1</code> and when the result requires one additional node (Example 3).</p>
<h4 id="heading-code">Code</h4>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">ListNode</span> {</span>
    <span class="hljs-keyword">int</span> val;
    ListNode *next;
    ListNode() : val(<span class="hljs-number">0</span>), next(<span class="hljs-literal">nullptr</span>) {}
    ListNode(<span class="hljs-keyword">int</span> x) : val(x), next(<span class="hljs-literal">nullptr</span>) {}
    ListNode(<span class="hljs-keyword">int</span> x, ListNode *next) : val(x), next(next) {}
};

<span class="hljs-function">ListNode* <span class="hljs-title">addTwoNumbers</span><span class="hljs-params">(ListNode* l1, ListNode* l2)</span> </span>{
    ListNode prehead;               <span class="hljs-comment">// dummy node to hook the head of the list</span>
    ListNode* node = l1;            <span class="hljs-comment">// store result on l1</span>
    prehead.next = node;
    <span class="hljs-keyword">int</span> sum = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">while</span> (node) {
        <span class="hljs-keyword">if</span> (l1) {
            sum += l1-&gt;val;
            l1 = l1-&gt;next;
        }
        <span class="hljs-keyword">if</span> (l2) {
            sum += l2-&gt;val;
            l2 = l2-&gt;next;
        }
        node-&gt;val = sum % <span class="hljs-number">10</span>;
        sum /= <span class="hljs-number">10</span>;
        <span class="hljs-keyword">if</span> (!l1) {        <span class="hljs-comment">// l1 ends</span>
            <span class="hljs-keyword">if</span> (l2) {               <span class="hljs-comment">// l1 is shorter than l2</span>
                node-&gt;next = l2;
            } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (sum == <span class="hljs-number">1</span>) {  <span class="hljs-comment">// both l1 and l2 end but the remember is not zero </span>
                ListNode* newNode = <span class="hljs-keyword">new</span> ListNode(sum);
                node-&gt;next = newNode;
            }
        }
        node = node-&gt;next;
    }
    <span class="hljs-keyword">return</span> prehead.next;
}
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">printResult</span><span class="hljs-params">(ListNode* l)</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"["</span>;
    <span class="hljs-keyword">while</span> (l) {
        <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; l-&gt;val &lt;&lt; <span class="hljs-string">","</span>;
        l = l-&gt;next;
    }
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"]\n"</span>;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    {
        <span class="hljs-function">ListNode <span class="hljs-title">three</span><span class="hljs-params">(<span class="hljs-number">3</span>)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">four1</span><span class="hljs-params">(<span class="hljs-number">4</span>, &amp;three)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">two</span><span class="hljs-params">(<span class="hljs-number">2</span>, &amp;four1)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">four2</span><span class="hljs-params">(<span class="hljs-number">4</span>)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">six</span><span class="hljs-params">(<span class="hljs-number">6</span>, &amp;four2)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">five</span><span class="hljs-params">(<span class="hljs-number">5</span>, &amp;six)</span></span>;
        printResult(addTwoNumbers(&amp;two, &amp;five));
    }
    {
        <span class="hljs-function">ListNode <span class="hljs-title">zero1</span><span class="hljs-params">(<span class="hljs-number">0</span>)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">zero2</span><span class="hljs-params">(<span class="hljs-number">0</span>)</span></span>;
        printResult(addTwoNumbers(&amp;zero1, &amp;zero2));
    }
    {
        <span class="hljs-function">ListNode <span class="hljs-title">nine0</span><span class="hljs-params">(<span class="hljs-number">9</span>)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">nine1</span><span class="hljs-params">(<span class="hljs-number">9</span>, &amp;nine0)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">nine2</span><span class="hljs-params">(<span class="hljs-number">9</span>, &amp;nine1)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">nine3</span><span class="hljs-params">(<span class="hljs-number">9</span>, &amp;nine2)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">nine4</span><span class="hljs-params">(<span class="hljs-number">9</span>, &amp;nine3)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">nine5</span><span class="hljs-params">(<span class="hljs-number">9</span>, &amp;nine4)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">nine6</span><span class="hljs-params">(<span class="hljs-number">9</span>, &amp;nine5)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">nine7</span><span class="hljs-params">(<span class="hljs-number">9</span>)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">nine8</span><span class="hljs-params">(<span class="hljs-number">9</span>, &amp;nine7)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">nine9</span><span class="hljs-params">(<span class="hljs-number">9</span>, &amp;nine8)</span></span>;
        <span class="hljs-function">ListNode <span class="hljs-title">nine10</span><span class="hljs-params">(<span class="hljs-number">9</span>, &amp;nine9)</span></span>;
        printResult(addTwoNumbers(&amp;nine6, &amp;nine10));
    }
}
</code></pre>
<pre><code class="lang-plaintext">Output:
[7,0,8,]
[0,]
[8,9,9,9,0,0,0,1,]
</code></pre>
<p>This solution efficiently adds two numbers represented as linked lists by iterating through both linked lists, digit by digit, and calculating the sum and carry. It also handles different scenarios for the lengths of the input lists and any remaining carry values.</p>
<h4 id="heading-complexity">Complexity</h4>
<ul>
<li><p>Runtime: <code>O(N)</code>, where <code>N = max(l1.length, l2.length)</code>.</p>
</li>
<li><p>Extra space: <code>O(1)</code>.</p>
</li>
</ul>
<hr />
<p>Thanks for reading! <a target="_blank" href="https://nhutnguyen.gumroad.com/l/10_classic"><strong>Get my book "10 Classic Coding Challenges"</strong></a> for FREE.</p>
]]></content:encoded></item><item><title><![CDATA[How to Solve Coding Challenges: A Comprehensive Guide]]></title><description><![CDATA[In the programming world, coding challenges are a common way to evaluate a programmer's problem-solving abilities and coding skills. Whether you're preparing for a technical interview, honing your coding skills, or participating in programming compet...]]></description><link>https://leetsolve.com/mastering-coding-challenges-a-comprehensive-guide</link><guid isPermaLink="true">https://leetsolve.com/mastering-coding-challenges-a-comprehensive-guide</guid><category><![CDATA[C++]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[leetcode]]></category><category><![CDATA[coding]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Tue, 05 Dec 2023 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/f77Bh3inUpE/upload/15705305ec36e70e67faecd70357164f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the programming world, coding challenges are a common way to evaluate a programmer's problem-solving abilities and coding skills. Whether you're preparing for a technical interview, honing your coding skills, or participating in programming competitions, the ability to tackle coding challenges is a valuable asset.</p>
<p>This comprehensive guide will walk you through a step-by-step approach to solving coding challenges. It helped me prepare for the coding interviews and land several jobs in my dev career.</p>
<hr />
<h2 id="heading-1-understand-the-problem">1. Understand the Problem</h2>
<p>The first and most crucial step in solving any coding challenge is thoroughly understanding the problem statement. To do this:</p>
<ul>
<li><p><strong>Read Carefully</strong>: Begin by reading the problem statement carefully. Pay attention to all the details, requirements, and constraints.</p>
</li>
<li><p><strong>Sample Inputs and Outputs</strong>: Review the sample inputs and outputs provided in the problem statement. This will help you understand the expected behavior of your solution.</p>
</li>
<li><p><strong>Clarify Ambiguities</strong>: If you encounter any ambiguities or uncertainties in the problem statement, don't hesitate to seek clarification. Contact the challenge provider or your instructor to ensure you clearly understand the problem.</p>
</li>
</ul>
<h2 id="heading-2-plan-your-approach">2. Plan Your Approach</h2>
<p>Before you start writing code, it's essential to plan your approach. Consider the following strategies:</p>
<ul>
<li><p><strong>Break It Down</strong>: If the problem seems complex, break it down into smaller, more manageable subproblems. Solving each subproblem individually can make the overall task more achievable.</p>
</li>
<li><p><strong>Data Structures and Algorithms</strong>: Think about the data structures and algorithms you might use. Choose the most suitable ones based on the problem's requirements. This step is crucial for optimizing your solution.</p>
</li>
<li><p><strong>Edge Cases</strong>: Identify potential edge cases and corner cases for the problem. Consider how your code should handle these situations. It's often a good idea to address these cases later in your solution.</p>
</li>
</ul>
<h2 id="heading-3-pseudocode">3. Pseudocode</h2>
<blockquote>
<p>I always write down my ideas before typing code.</p>
</blockquote>
<p>Before diving into coding, creating a pseudocode or an outline of the steps you plan to take is helpful. Pseudocode helps you structure your thoughts and provides a roadmap for your coding journey. While writing pseudocode:</p>
<ul>
<li><p>Use plain language to describe the steps concisely.</p>
</li>
<li><p>Avoid detailed syntax; focus on the algorithm's logic.</p>
</li>
<li><p>Make sure your pseudocode captures the essential elements of your solution.</p>
</li>
</ul>
<h2 id="heading-4-write-code">4. Write Code</h2>
<p>With a clear plan and pseudocode, it's time to start writing the actual code. Follow these guidelines:</p>
<ul>
<li><p><strong>Use a Familiar Language</strong>: Stick to a programming language you're comfortable with. You'll be more efficient and effective when working with a language you know well.</p>
</li>
<li><p><strong>Follow Your Plan</strong>: Translate your pseudocode or plan into actual code. Try to maintain a one-to-one correspondence between your plan and your code. This can help you stay organized and reduce the chances of making mistakes.</p>
</li>
<li><p><strong>Clean Code</strong>: Write clean and well-organized code. Use meaningful variable names and include comments to explain your code's purpose and any complex logic.</p>
</li>
</ul>
<h2 id="heading-5-test-your-code">5. Test Your Code</h2>
<p>Testing is a critical part of the coding challenge process. Thoroughly test your code to ensure it behaves correctly under various conditions. Here's how to approach testing:</p>
<ul>
<li><p><strong>Test with Sample Inputs</strong>: Test your code with the sample inputs and outputs in the problem statement. This helps you verify that your code meets the basic requirements.</p>
</li>
<li><p><strong>Edge Cases</strong>: Test your code with edge cases, such as empty inputs, minimum and maximum possible values, or any other unusual situations. This ensures your code handles exceptional scenarios gracefully.</p>
</li>
<li><p><strong>Debugging</strong>: If you encounter errors or unexpected behavior during testing, use tools and techniques to identify and resolve issues. Pay attention to error messages and use print statements or debugging tools to trace the code's execution.</p>
</li>
</ul>
<h2 id="heading-6-optimize-and-refactor">6. Optimize and Refactor</h2>
<p>Once your code passes the initial tests, consider optimizing it for efficiency. Optimization involves improving the code's runtime performance and memory usage. Here are some optimization techniques:</p>
<ul>
<li><p><strong>Algorithmic Optimization</strong>: Revisit the algorithms and data structures you chose. Can more efficient alternatives achieve the same results with fewer resources?</p>
</li>
<li><p><strong>Time and Space Complexity</strong>: Analyze your code's time and space complexity. Aim to reduce these complexities by optimizing loops, reducing redundant computations, and minimizing memory usage.</p>
</li>
<li><p><strong>Benchmarking</strong>: Compare the performance of your code with various inputs. Benchmarking can help you identify bottlenecks and areas for improvement.</p>
</li>
</ul>
<p>Remember that optimization should come after your code is correct. Don't sacrifice correctness for premature optimization.</p>
<h2 id="heading-7-documentation">7. Documentation</h2>
<p>Documentation is often overlooked but plays a crucial role in code quality and readability. When documenting your code:</p>
<ul>
<li><p>Add comments to explain the purpose of functions, classes, and complex code segments.</p>
</li>
<li><p>Include comments for any non-trivial logic or algorithmic steps.</p>
</li>
<li><p>Write clear and concise docstrings for functions, describing their inputs, outputs, and usage.</p>
</li>
</ul>
<p>Adequate documentation makes it easier for others to understand and maintain your code. It's also helpful for future reference when you revisit your code.</p>
<h2 id="heading-8-review-and-proofread">8. Review and Proofread</h2>
<p>Before your coding challenge is complete, take some time to review and proofread your code. Here's what to look for:</p>
<ul>
<li><p><strong>Errors and Bugs</strong>: Carefully review your code for syntax errors, logical issues, or runtime exceptions.</p>
</li>
<li><p><strong>Compliance with Requirements</strong>: Double-check that your solution meets all the requirements in the problem description.</p>
</li>
<li><p><strong>Code Style</strong>: Ensure your code adheres to a consistent code style, such as using proper indentation, following naming conventions and using consistent formatting.</p>
</li>
</ul>
<h2 id="heading-9-submit-or-share">9. Submit or Share</h2>
<p>The final step in solving a coding challenge depends on the context:</p>
<ul>
<li><p><strong>Technical Interviews</strong>: If you're solving a coding challenge as part of a technical interview, be prepared to discuss your code and approach with the interviewer. Provide clear explanations of your thought process.</p>
</li>
<li><p><strong>Programming Competitions</strong>: You should submit your code as instructed in competitive programming or coding competitions. Make sure to follow the submission guidelines carefully.</p>
</li>
<li><p><strong>Personal Projects or Learning</strong>: If you're solving coding challenges for personal development or learning, consider sharing your solution with others through coding platforms or personal portfolios. Share instructions on how to run and test your code.</p>
</li>
</ul>
<h2 id="heading-10-reflect-and-learn">10. Reflect and Learn</h2>
<p>After completing a coding challenge, take some time to reflect on your solution:</p>
<ul>
<li><p>Consider how you approached the problem. Were there any aha moments or insights during the process?</p>
</li>
<li><p>Think about how you could have solved the problem differently or more efficiently.</p>
</li>
<li><p>Identify areas where you encountered challenges or your knowledge is lacking, and use this as an opportunity to learn and grow.</p>
</li>
</ul>
<h2 id="heading-11-practice-regularly">11. Practice Regularly</h2>
<p>The more you practice solving coding challenges, the more proficient you become. Regular practice is essential for honing your problem-solving skills and coding abilities. Consider these tips for effective practice:</p>
<ul>
<li><p><strong>Variety of Challenges</strong>: Work on various coding challenges, including those related to data structures, algorithms, and specific domains (e.g., dynamic programming, graph theory, string manipulation).</p>
</li>
<li><p><strong>Online Platforms</strong>: Participate in online coding platforms like <a target="_blank" href="https://leetcode.com/?ref=leetsolve.ghost.io">LeetCode</a>, <a target="_blank" href="https://www.hackerrank.com/?ref=leetsolve.ghost.io">HackerRank</a>, <a target="_blank" href="https://codesignal.com/?ref=leetsolve.ghost.io">CodeSignal</a>, or <a target="_blank" href="https://projecteuler.net/?ref=leetsolve.ghost.io">Project Euler</a>. These platforms offer a wide range of challenges and a supportive community.</p>
</li>
<li><p><strong>Keep a Portfolio</strong>: To showcase your solutions and progress, consider maintaining a coding challenge portfolio. This can be beneficial for job applications and personal development.</p>
</li>
<li><p><strong>Competitions</strong>: If you're interested in competitive programming, participate in coding competitions like <a target="_blank" href="https://icpc.global/?ref=leetsolve.ghost.io">ACM ICPC</a> or <a target="_blank" href="https://www.topcoder.com/talent/single-round-matches/?ref=leetsolve.ghost.io">TopCoder's Single Round Matches</a>.</p>
</li>
</ul>
<blockquote>
<p>I chose Leetcode for its extensive collection of diverse and well-crafted problems.</p>
</blockquote>
<p>Remember that solving coding challenges is a skill that improves with practice. Don't be discouraged by complex challenges; each is an opportunity to learn and grow.</p>
<hr />
<h1 id="heading-conclusion">Conclusion</h1>
<p>Solving coding challenges is an essential skill for programmers, whether you're preparing for a technical interview, honing your coding abilities, or participating in programming competitions. Following a structured approach, understanding the problem, planning your solution, writing clean code, testing rigorously, optimizing when necessary, and practicing regularly can enhance your problem-solving skills and help you become a more proficient coder.</p>
<p>Coding challenges provide a platform for continuous learning and self-improvement. Through regular practice and thoughtful reflection on your solutions, you can tackle increasingly complex challenges and gain confidence in your coding abilities.</p>
<blockquote>
<p>So, embrace coding challenges as a valuable opportunity to learn, grow, and demonstrate your programming skills. Happy coding!</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[How To Count Unique Paths In A Grid With Obstacles]]></title><description><![CDATA[Problem statement
You're given an m x n grid represented as an integer array called grid. In this grid, there is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot's goal is to move to the bottom-right corner (i.e., grid[m...]]></description><link>https://leetsolve.com/how-to-count-unique-paths-in-a-grid-with-obstacles</link><guid isPermaLink="true">https://leetsolve.com/how-to-count-unique-paths-in-a-grid-with-obstacles</guid><category><![CDATA[Dynamic Programming]]></category><category><![CDATA[leetcode]]></category><category><![CDATA[coding]]></category><category><![CDATA[C++]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Thu, 30 Nov 2023 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706469520672/55a748ba-bd22-4620-8752-79041b15f6d2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-statementhttpsleetcodecomproblemsunique-paths-iirefleetsolveghostio"><a target="_blank" href="https://leetcode.com/problems/unique-paths-ii/?ref=leetsolve.ghost.io">Problem statement</a></h2>
<p>You're given an <code>m x n</code> grid represented as an integer array called <code>grid</code>. In this grid, there is a robot initially located at the top-left corner (i.e., <code>grid[0][0]</code>). The robot's goal is to move to the bottom-right corner (i.e., <code>grid[m-1][n-1]</code>). The robot can only move downwards or to the right at any given point.</p>
<p>The grid contains obstacles and empty spaces, which are marked as <code>1</code> or <code>0</code> respectively. The robot cannot pass through squares marked as obstacles.</p>
<p>Your task is determining the number of unique paths the robot can take to reach the bottom-right corner while avoiding obstacles.</p>
<p>It's important to note that the test cases are designed in such a way that the answer will always be less than or equal to <code>2 * 10^9</code>.</p>
<h3 id="heading-example-1">Example 1</h3>
<p><img src="https://leetsolve.ghost.io/content/images/2023/11/63_robot1.jpg" alt="The obstacle grid of Example 1" /></p>
<pre><code class="lang-text">Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 2
Explanation: There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -&gt; Right -&gt; Down -&gt; Down
2. Down -&gt; Down -&gt; Right -&gt; Right
</code></pre>
<h3 id="heading-example-2">Example 2</h3>
<p><img src="https://leetsolve.ghost.io/content/images/2023/11/63_robot2.jpg" alt="The obstacle grid of Example 2" /></p>
<pre><code class="lang-text">Input: obstacleGrid = [[0,1],[0,0]]
Output: 1
</code></pre>
<h3 id="heading-constraints">Constraints</h3>
<ul>
<li><p><code>m == obstacleGrid.length</code>.</p>
</li>
<li><p><code>n == obstacleGrid[i].length</code>.</p>
</li>
<li><p><code>1 &lt;= m, n &lt;= 100</code>.</p>
</li>
<li><p><code>obstacleGrid[i][j]</code> is <code>0</code> or <code>1</code>.</p>
</li>
</ul>
<h2 id="heading-solution-dynamic-programming-in-place">Solution: Dynamic programming in place</h2>
<p>Let us find the relationship between the positions.</p>
<p>If there is no obstacle at the position <code>(row = i, col = j)</code>, the number of paths <code>np[i][j]</code> that the robot can take to reach this position is:</p>
<pre><code class="lang-text">np[i][j] = np[i - 1][j] + np[i][j - 1]
</code></pre>
<ul>
<li><p>As long as there is no obstacle in the first row, <code>np[0][j] = 1</code>. Otherwise, <code>np[0][k] = 0</code> for all <code>k &gt;= j0</code>, where <code>(0, j0)</code> is the position of the first obstacle in the first row.</p>
</li>
<li><p>Similarly, as long as there is no obstacle in the first column, <code>np[i][0] = 1</code>. Otherwise, <code>np[k][0] = 0</code> for all <code>k &gt;= i0</code>, where <code>(i0, 0)</code> is the position of the first obstacle in the first column.</p>
</li>
</ul>
<h3 id="heading-code">Code</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">uniquePathsWithObstacles</span><span class="hljs-params">(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt;&amp; obstacleGrid)</span> 
</span>{
    <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> row = obstacleGrid.size();
    <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> col = obstacleGrid[<span class="hljs-number">0</span>].size();
    <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt; <span class="hljs-title">np</span><span class="hljs-params">(row, <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;(col, <span class="hljs-number">0</span>))</span></span>;    
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; row &amp;&amp; obstacleGrid[i][<span class="hljs-number">0</span>] == <span class="hljs-number">0</span>; i++) 
    {
        np[i][<span class="hljs-number">0</span>] = <span class="hljs-number">1</span>;
    }    
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; col &amp;&amp; obstacleGrid[<span class="hljs-number">0</span>][j] == <span class="hljs-number">0</span>; j++) 
    {
        np[<span class="hljs-number">0</span>][j] = <span class="hljs-number">1</span>;
    }
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; row; i++) 
    {
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">1</span>; j &lt; col; j++) 
        {
            <span class="hljs-keyword">if</span> (obstacleGrid[i][j] == <span class="hljs-number">0</span>) 
            {
                np[i][j] = np[i - <span class="hljs-number">1</span>][j] + np[i][j - <span class="hljs-number">1</span>];
            }
        }
    }
    <span class="hljs-keyword">return</span> np[row - <span class="hljs-number">1</span>][col - <span class="hljs-number">1</span>]; 
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> 
</span>{
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt; obstacleGrid = {{<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">0</span>},{<span class="hljs-number">0</span>,<span class="hljs-number">1</span>,<span class="hljs-number">0</span>},{<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">0</span>}};
    <span class="hljs-built_in">cout</span> &lt;&lt; uniquePathsWithObstacles(obstacleGrid) &lt;&lt; <span class="hljs-built_in">endl</span>;
    obstacleGrid = {{<span class="hljs-number">0</span>,<span class="hljs-number">1</span>},{<span class="hljs-number">0</span>,<span class="hljs-number">0</span>}};
    <span class="hljs-built_in">cout</span> &lt;&lt; uniquePathsWithObstacles(obstacleGrid) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-text">Output:
2
1
</code></pre>
<h3 id="heading-code-explanation">Code explanation</h3>
<p>This solution computes the number of unique paths in an <code>m x n</code> grid with obstacles using dynamic programming. It initializes a 2D vector <code>np</code> of the same size as <code>obstacleGrid</code> to store the number of unique paths for each cell.</p>
<p>First, it initializes the top row and left column of <code>np</code>. If there are no obstacles in the top row or left column of <code>obstacleGrid</code>, it sets the corresponding cells in <code>np</code> to 1 because there's only one way to reach any cell in the top row or left column.</p>
<p>Then, it iterates through the grid starting from the second row and second column (i.e., indices (1, 1)). For each cell, if there's no obstacle (<code>obstacleGrid[i][j] == 0</code>), it updates the value in <code>np</code> by summing up the values from the cell directly above it and the cell to the left of it. This step efficiently accumulates the number of unique paths while avoiding obstacles.</p>
<p>Finally, the value at <code>np[row-1][col-1]</code> contains the total number of unique paths to reach the bottom-right corner of the grid, which is returned as the result.</p>
<h3 id="heading-complexity">Complexity</h3>
<p>The time complexity of this solution is <code>O(m*n)</code>, where <code>m</code> and <code>n</code> are the grid dimensions, as it iterates through all grid cells once to compute the unique paths efficiently. Dynamic programming avoids redundant calculations and makes this solution efficient even for large grids.</p>
<ul>
<li><p>Runtime: <code>O(m*n)</code>.</p>
</li>
<li><p>Extra space: <code>O(m*n)</code>.</p>
</li>
</ul>
<hr />
<p>Thanks for reading! <a target="_blank" href="https://nhutnguyen.gumroad.com/l/10_classic"><strong>Get my book "10 Classic Coding Challenges"</strong></a> for FREE.</p>
]]></content:encoded></item><item><title><![CDATA[How to Perform a Counting Using Array and Hash Table]]></title><description><![CDATA[Problem statement
You have a string called s. Your objective is to locate the index of the first character in the string that does not repeat anywhere else in the string. If such a character doesn't exist, return -1.
Example 1
Input: s = "leetcode"
O...]]></description><link>https://leetsolve.com/387-first-unique-character-in-a-string</link><guid isPermaLink="true">https://leetsolve.com/387-first-unique-character-in-a-string</guid><category><![CDATA[C++]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Programming Tips]]></category><category><![CDATA[learn coding]]></category><category><![CDATA[leetcode]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Tue, 28 Nov 2023 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706469770624/b77a6e8d-b3cc-45b3-af14-c57551258c75.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-statementhttpsleetcodecomproblemsfirst-unique-character-in-a-stringrefleetsolveghostio"><a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">Problem statement</a></h2>
<p><a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">You have a strin</a>g <a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">called <code>s</code>. Your ob</a>jective is to locate the index of the first character in the string that does not repeat anywhere else in the string. If such a character doesn't exist, return <code>-1</code>.</p>
<h3 id="heading-example-1">Example 1</h3>
<pre><code class="lang-plaintext">Input: s = "leetcode"
Output: 0
</code></pre>
<h3 id="heading-example-2">Example 2</h3>
<pre><code class="lang-text">Input: s = "loveleetcode"
Output: 2
</code></pre>
<h3 id="heading-example-3">Example 3</h3>
<pre><code class="lang-text">Input: s = "aabb"
Output: -1
</code></pre>
<h3 id="heading-constraints">Constraints</h3>
<ul>
<li><p><code>1 &lt;</code><a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io"><code>= s.length &lt;= 10^5</code>.</a></p>
</li>
<li><p><a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io"><code>s</code> consist</a>s of only <a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">lowercase Englis</a>h letters.</p>
</li>
</ul>
<h2 id="heading-solution-1-using-a-map-to-store-thhttpsleetcodecomproblemsfirst-unique-character-in-a-stringrefleetsolveghostioe-appearances">Solution 1: Using <a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">a map to store th</a>e appearances</h2>
<h3 id="heading-code">Code</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;unordered_map&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">firstUniqChar</span><span class="hljs-params">(<span class="hljs-built_in">string</span> s)</span> 
</span>{
    <span class="hljs-built_in">unordered_map</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-keyword">int</span>&gt; count;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">char</span>&amp; c : s) 
    {
        count[c]++;
    }
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; s.length(); i++) 
    {
        <span class="hljs-keyword">if</span> (count[s[i]] == <span class="hljs-number">1</span>) 
        {
            <span class="hljs-keyword">return</span> i;
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> 
</span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; firstUniqChar(<span class="hljs-string">"leetcode"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; firstUniqChar(<span class="hljs-string">"loveleetcode"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; firstUniqChar(<span class="hljs-string">"aabb"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-text">Output:
0
2
-1
</code></pre>
<h3 id="heading-code-explanation">Code explanation</h3>
<ol>
<li><p><a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">The code initia</a>liz<a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">es an unordered m</a>ap <code>count</code> where characters from the string are keys, and their corresponding counts (how many times they appear in the string) are values.</p>
</li>
<li><p>The loop then iter<a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">ates through the</a> characters of the string <code>s</code>. For each character <code>c</code> encountered, it increments its count in the <code>count</code> map.</p>
</li>
<li><p>After counting all <a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">the characters i</a>n the string, it performs a second loop, this time using an index variable <code>i</code> that starts from 0 and goes up to the length of the string <code>s</code>.</p>
</li>
<li><p>In this loop, it c<a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">hecks whether the</a> count of the character at the current index <code>i</code> is equal to 1. If it is, this means that the character is unique in the string, and the function returns <code>i</code>, which is the index of the first occurrence of that unique character.</p>
</li>
<li><p>If no unique chara<a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">cter is found dur</a>ing the loop, the function returns -1 to indicate that there are no unique characters in the string.</p>
</li>
</ol>
<h3 id="heading-complexity">Complexity</h3>
<p>This s<a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">olution has a time complexity</a> of <code>O(n)</code>, where <code>n</code> is the length of the string <code>s</code>, because it iterates through the string twice: once to count the characters and once to find the first unique character.</p>
<p>It also has a spac<a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">e complexity of <code>O</code></a><code>(k)</code>, where <code>k</code> is the number of distinct characters in the string, as it stores character counts in the <code>count</code> unordered map. As the problem considers only lowercase English letters, <code>k = 26</code>, you can give it <code>O(1)</code> complexity.</p>
<ul>
<li><p>Runtime: <code>O(n)</code>, whe<a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">re <code>n = s.length</code>.</a></p>
</li>
<li><p>Extra space: <code>O(k)</code>, <a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">where <code>k</code> is the n</a>umber of distinct characters in the string. If <code>k=26</code>, it is <code>O(1)</code>.</p>
</li>
</ul>
<h2 id="heading-solution-2-using-an-array-to-storehttpsleetcodecomproblemsfirst-unique-character-in-a-stringrefleetsolveghostio-the-appearances">Solution 2: Using <a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">an array to store</a> the appearances</h2>
<p>From the constrain<a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">ts "<code>s</code> consists of</a> only lowercase English letters", you can use an array of 26 elements to store the counts.</p>
<h3 id="heading-code-1">Code</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">firstUniqChar</span><span class="hljs-params">(<span class="hljs-built_in">string</span> s)</span> 
</span>{
    <span class="hljs-comment">// initializes an array of 26 elements, all set to zero</span>
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">array</span>&lt;<span class="hljs-keyword">int</span>, 26&gt; count{};
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">char</span>&amp; c : s) 
    {
        count[c - <span class="hljs-string">'a'</span>]++;
    }
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; s.length(); i++) 
    {
        <span class="hljs-keyword">if</span> (count[s[i] - <span class="hljs-string">'a'</span>] == <span class="hljs-number">1</span>) 
        {
            <span class="hljs-keyword">return</span> i;
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> 
</span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; firstUniqChar(<span class="hljs-string">"leetcode"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; firstUniqChar(<span class="hljs-string">"loveleetcode"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; firstUniqChar(<span class="hljs-string">"aabb"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
0
2
-1
</code></pre>
<h3 id="heading-complexity-1">Complexity</h3>
<ul>
<li><p>Runt<a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">ime: <code>O(n)</code>, where <code>n = s.length</code>.</a></p>
</li>
<li><p>Extra space: <code>O(1)</code> <a target="_blank" href="https://leetcode.com/problems/first-unique-character-in-a-string/?ref=leetsolve.ghost.io">as the array's le</a>ngth is fixed 26.</p>
</li>
</ul>
<hr />
<p>Thanks for reading! <a target="_blank" href="https://nhutnguyen.gumroad.com/l/10_classic"><strong>Get my book "10 Classic Coding Challenges"</strong></a> for FREE.</p>
]]></content:encoded></item><item><title><![CDATA[How to Convert a Given Roman Numeral to its Equivalent Integer Value]]></title><description><![CDATA[Problem statement
Roman numerals are represented by seven symbols: I, V, X, L, C, D, and M.
Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, 2 is...]]></description><link>https://leetsolve.com/13-roman-to-integer</link><guid isPermaLink="true">https://leetsolve.com/13-roman-to-integer</guid><category><![CDATA[C++]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[leetcode]]></category><category><![CDATA[Mathematics]]></category><category><![CDATA[learn coding]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Sun, 26 Nov 2023 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706470225740/42f11ac6-4f1d-4805-85a7-27f39c49c2f7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-problem-statement"><strong>Problem statement</strong></h3>
<p>Roman numerals are represented by seven symbols: <code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code>, and <code>M</code>.</p>
<pre><code class="lang-plaintext">Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000
</code></pre>
<p>For example, <code>2</code> is written as <code>II</code> in Roman numeral, just two ones added together. <code>12</code> is written as <code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p>
<p>Roman numerals are usually written from largest to smallest and from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p>
<ul>
<li><p><code>I</code> can be placed before <code>V</code> (<code>5</code>) and <code>X</code> (<code>10</code>) to make <code>4</code> and <code>9</code>.</p>
</li>
<li><p><code>X</code> can be placed before <code>L</code> (<code>50</code>) and <code>C</code> (<code>100</code>) to make <code>40</code> and <code>90</code>.</p>
</li>
<li><p><code>C</code> can be placed before <code>D</code> (<code>500</code>) and <code>M</code> (<code>1000</code>) to make <code>400</code> and <code>900</code>.</p>
</li>
</ul>
<p>Given a Roman numeral, convert it to an integer.</p>
<h4 id="heading-example-1">Example 1</h4>
<pre><code class="lang-plaintext">Input: s = "III"
Output: 3
Explanation: III = 3.
</code></pre>
<h4 id="heading-example-2">Example 2</h4>
<pre><code class="lang-plaintext">Input: s = "LVIII"
Output: 58
Explanation: L = 50, V = 5, III = 3.
</code></pre>
<h4 id="heading-example-3">Example 3</h4>
<pre><code class="lang-plaintext">Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
</code></pre>
<h4 id="heading-constraints">Constraints</h4>
<ul>
<li><p><code>1 &lt;= s.length &lt;= 15</code>.</p>
</li>
<li><p><code>s</code> contains only the characters <code>'I'</code>, <code>'V'</code>, <code>'X'</code>, <code>'L'</code>, <code>'C'</code>, <code>'D'</code>, <code>'M'</code>.</p>
</li>
<li><p>It is guaranteed that <code>s</code> is a valid Roman numeral in the range <code>[1, 3999]</code>.</p>
</li>
</ul>
<h3 id="heading-solution-mapping-and-summing-the-values">Solution: Mapping and summing the values</h3>
<p>And to treat the subtraction cases easier, you can iterate the string <code>s</code> backward.</p>
<h4 id="heading-code">Code</h4>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;unordered_map&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">romanToInt</span><span class="hljs-params">(<span class="hljs-built_in">string</span> s)</span> </span>{
    <span class="hljs-built_in">unordered_map</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-keyword">int</span>&gt; value = {
        {<span class="hljs-string">'I'</span>, <span class="hljs-number">1</span>},
        {<span class="hljs-string">'V'</span>, <span class="hljs-number">5</span>},
        {<span class="hljs-string">'X'</span>, <span class="hljs-number">10</span>},
        {<span class="hljs-string">'L'</span>, <span class="hljs-number">50</span>},
        {<span class="hljs-string">'C'</span>, <span class="hljs-number">100</span>},
        {<span class="hljs-string">'D'</span>, <span class="hljs-number">500</span>},
        {<span class="hljs-string">'M'</span>, <span class="hljs-number">1000</span>}
    };
    <span class="hljs-keyword">int</span> i = s.length() - <span class="hljs-number">1</span>;
    <span class="hljs-keyword">int</span> result = value[s[i--]];
    <span class="hljs-keyword">while</span> (i &gt;= <span class="hljs-number">0</span>) {
        <span class="hljs-keyword">if</span> (value[s[i]] &lt; value[s[i+<span class="hljs-number">1</span>]]) {
            result -= value[s[i--]]; 
        } <span class="hljs-keyword">else</span> {
            result += value[s[i--]];
        }
    }
    <span class="hljs-keyword">return</span> result;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; romanToInt(<span class="hljs-string">"III"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; romanToInt(<span class="hljs-string">"LVIII"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; romanToInt(<span class="hljs-string">"MCMXCIV"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
3
58
1994
</code></pre>
<p>This solution efficiently converts a Roman numeral string into an integer by iterating through the string from right to left and applying the rules of Roman numerals, where subtractive combinations are subtracted and additive combinations are added to calculate the total value. The unordered map is used to look up the values of Roman numerals.</p>
<h4 id="heading-complexity">Complexity</h4>
<ul>
<li><p>Runtime: <code>O(N)</code> where <code>N = s.length</code>.</p>
</li>
<li><p>Extra space: <code>O(1)</code> (the map <code>value</code> is very small).</p>
</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>The problem is about encoding/decoding between a string and an integer, you could use an <a target="_blank" href="https://en.cppreference.com/w/cpp/container/unordered_map">unordered_map</a> here.</p>
<p>This is a very interesting problem since it is about history and mathematics. You can read more about it on <a target="_blank" href="https://en.wikipedia.org/wiki/Roman_numerals">Wikipedia</a>.</p>
<hr />
<p><em>Thanks for reading. Check out my</em> <a target="_blank" href="https://store.nhutnguyen.com/l/10_classic"><strong><em>book “10 Classic Coding Challenges”</em></strong></a> <strong><em>for FREE*</em></strong>.*</p>
]]></content:encoded></item><item><title><![CDATA[How To Check If a String Is a Valid Anagram]]></title><description><![CDATA[Problem statement
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly on...]]></description><link>https://leetsolve.com/242-valid-anagram</link><guid isPermaLink="true">https://leetsolve.com/242-valid-anagram</guid><category><![CDATA[C++]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[leetcode]]></category><category><![CDATA[learn coding]]></category><category><![CDATA[coding challenge]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Sun, 29 Oct 2023 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706384757196/dfb5764f-1f1c-478a-a554-fbcf527b8652.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-statement">Problem statement</h2>
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if <code>t</code> is an anagram of <code>s</code>, and <code>false</code> otherwise.</p>
<p>An <strong><em>Anagram</em></strong> is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.</p>
<h3 id="heading-example-1">Example 1</h3>
<pre><code class="lang-plaintext">Input: s = "anagram", t = "nagaram"
Output: true
</code></pre>
<h3 id="heading-example-2">Example 2</h3>
<pre><code class="lang-plaintext">Input: s = "rat", t = "car"
Output: false
</code></pre>
<h3 id="heading-constraints">Constraints</h3>
<ul>
<li><p><code>1 &lt;= s.length, t.length &lt;= 5 * 10^4</code>.</p>
</li>
<li><p><code>s</code> and <code>t</code> consist of lowercase English letters.</p>
</li>
</ul>
<p><strong>Follow up</strong>: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?</p>
<h2 id="heading-solution-1-rearrange-both-s-and-t-into-a-sorted-string">Solution 1: Rearrange both <code>s</code> and <code>t</code> into a sorted string</h2>
<h3 id="heading-code">Code</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">isAnagram</span><span class="hljs-params">(<span class="hljs-built_in">string</span> s, <span class="hljs-built_in">string</span> t)</span> </span>{
    <span class="hljs-keyword">if</span> (s.length() != t.length()) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
    sort(s.begin(), s.end());
    sort(t.begin(), t.end());
    <span class="hljs-keyword">return</span> s == t;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; isAnagram(<span class="hljs-string">"anagram"</span>, <span class="hljs-string">"nagaram"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; isAnagram(<span class="hljs-string">"rat"</span>, <span class="hljs-string">"car"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
1
0
</code></pre>
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p>Runtime: <code>O(NlogN)</code>, where <code>N = s.length</code>.</p>
</li>
<li><p>Extra space: <code>O(1)</code>.</p>
</li>
</ul>
<h2 id="heading-solution-2-count-the-appearances-of-each-letter">Solution 2: Count the appearances of each letter</h2>
<h3 id="heading-code-1">Code</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">isAnagram</span><span class="hljs-params">(<span class="hljs-built_in">string</span> s, <span class="hljs-built_in">string</span> t)</span> </span>{
    <span class="hljs-keyword">if</span> (s.length() != t.length()) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
    <span class="hljs-keyword">int</span> alphabet[<span class="hljs-number">26</span>];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">26</span>; i++) {
        alphabet[i] = <span class="hljs-number">0</span>;
    }
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">char</span>&amp; c : s) {
        alphabet[c - <span class="hljs-string">'a'</span>]++;
    }
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">char</span>&amp; c : t) {
        alphabet[c - <span class="hljs-string">'a'</span>]--;
        <span class="hljs-keyword">if</span> (alphabet[c - <span class="hljs-string">'a'</span>] &lt; <span class="hljs-number">0</span>) {
            <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">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; isAnagram(<span class="hljs-string">"anagram"</span>, <span class="hljs-string">"nagaram"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; isAnagram(<span class="hljs-string">"rat"</span>, <span class="hljs-string">"car"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
1
0
</code></pre>
<h3 id="heading-complexity-1">Complexity</h3>
<ul>
<li><p>Runtime: <code>O(N)</code>, where <code>N = s.length</code>.</p>
</li>
<li><p>Extra space: <code>O(1)</code>.</p>
</li>
</ul>
<h2 id="heading-solution-3-if-the-inputs-contain-unicode-characters">Solution 3: If the inputs contain Unicode characters</h2>
<p>In the solutions above, the array <code>alphabet</code> represents 26 letters <code>'a'</code> to <code>'z'</code>. You can generalize to allow it contains any character by using a map.</p>
<h3 id="heading-code-2">Code</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;unordered_map&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">isAnagram</span><span class="hljs-params">(<span class="hljs-built_in">string</span> s, <span class="hljs-built_in">string</span> t)</span> </span>{
    <span class="hljs-keyword">if</span> (s.length() != t.length()) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
    <span class="hljs-built_in">unordered_map</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-keyword">int</span>&gt; alphabet;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">char</span>&amp; c : s) {
        alphabet[c]++;
    }
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">char</span>&amp; c : t) {
        alphabet[c]--;
        <span class="hljs-keyword">if</span> (alphabet[c] &lt; <span class="hljs-number">0</span>) {
            <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">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; isAnagram(<span class="hljs-string">"anagæam"</span>, <span class="hljs-string">"nagaæam"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; isAnagram(<span class="hljs-string">"rat"</span>, <span class="hljs-string">"car"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
1
0
</code></pre>
<h3 id="heading-complexity-2">Complexity</h3>
<ul>
<li><p>Runtime: <code>O(N)</code>, where <code>N = s.length</code>.</p>
</li>
<li><p>Extra space: <code>O(1)</code>.</p>
</li>
</ul>
<hr />
<h2 id="heading-key-takeaway">Key takeaway</h2>
<ul>
<li><p>An array of 26 integers can represent the English alphabet.</p>
</li>
<li><p>Counting the appearances can help identify if a word is a permutation of another.</p>
</li>
<li><p>You can use a map to count the appearances of the letters of a word.</p>
</li>
</ul>
<hr />
<p>Thanks for reading! <a target="_blank" href="https://nhutnguyen.gumroad.com/l/10_classic"><strong>Get my book "10 Classic Coding Challenges"</strong></a> for FREE.</p>
]]></content:encoded></item><item><title><![CDATA[78. Subsets]]></title><description><![CDATA[Problem Statement
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1
Input: nums = [1,2,3]
Output: [[],[1],[2],...]]></description><link>https://leetsolve.com/78-subsets</link><guid isPermaLink="true">https://leetsolve.com/78-subsets</guid><category><![CDATA[C++]]></category><category><![CDATA[coding challenge]]></category><category><![CDATA[problem solving skills]]></category><category><![CDATA[Recursion]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Wed, 18 Oct 2023 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1697645930622/e9ed6f17-a2c6-4d13-ba4d-6fe665f10b42.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-statementhttpsleetcodecomproblemssubsets"><a target="_blank" href="https://leetcode.com/problems/subsets/">Problem Statement</a></h2>
<p>Given an integer array <code>nums</code> of unique elements, return all possible subsets (the power set).</p>
<p>The solution set must not contain duplicate subsets. Return the solution in any order.</p>
<h3 id="heading-example-1">Example 1</h3>
<pre><code class="lang-text">Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
</code></pre>
<h3 id="heading-example-2">Example 2</h3>
<pre><code class="lang-text">Input: nums = [1]
Output: [[],[1]]
</code></pre>
<h3 id="heading-constraints">Constraints</h3>
<ul>
<li><p><code>1 &lt;= nums.length &lt;= 10</code>.</p>
</li>
<li><p><code>-10 &lt;= nums[i] &lt;= 10</code>.</p>
</li>
<li><p>All the numbers of <code>nums</code> are unique..</p>
</li>
</ul>
<h2 id="heading-solution">Solution</h2>
<p>You might need to find the relationship between the result of the array <code>nums</code> with the result of itself without the last element.</p>
<h3 id="heading-example-3">Example 3</h3>
<pre><code class="lang-text">Input: nums = [1,2]
Output: [[],[1],[2],[1,2]]
</code></pre>
<p>You can see the powerset of Example 3 was obtained from the one in Example 2 with additional subsets <code>[2]</code>, <code>[1,2]</code>. These new subsets were constructed from subsets <code>[]</code>, <code>[1]</code> of Example 2 appended with the new element <code>2</code>.</p>
<p>Similarly, the powerset of Example 1 was obtained from the one in Example 3 with the additional subsets <code>[3]</code>, <code>[1,3]</code>, <code>[2,3]</code>, <code>[1,2,3]</code>. These new subsets were constructed from the ones of Example 3 appended with the new element <code>3</code>.</p>
<h3 id="heading-code">Code</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt; <span class="hljs-title">subsets</span><span class="hljs-params">(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&amp; nums)</span> </span>{
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt; powerset = {{}};
    <span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">while</span> (i &lt; nums.size()) {
        <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt; newSubsets;
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span> subset : powerset) {
            subset.push_back(nums[i]);  
            newSubsets.push_back(subset);
        }
        powerset.insert(powerset.end(), newSubsets.begin(), newSubsets.end());
        i++;
    }
    <span class="hljs-keyword">return</span> powerset;
}
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt;&amp; powerset)</span> </span>{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span>&amp; <span class="hljs-built_in">set</span> : powerset ) {
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"["</span>;
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span>&amp; element : <span class="hljs-built_in">set</span>) {
            <span class="hljs-built_in">cout</span> &lt;&lt; element &lt;&lt; <span class="hljs-string">","</span>;
        }
        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"]"</span>;
    }
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-built_in">endl</span>;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; nums{<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>};
    <span class="hljs-keyword">auto</span> powerset = subsets(nums);
    print(powerset);
    nums = {<span class="hljs-number">1</span>};
    powerset = subsets(nums);
    print(powerset);
}
</code></pre>
<pre><code class="lang-text">Output:
[][1,][2,][1,2,][3,][1,3,][2,3,][1,2,3,]
[][1,]
</code></pre>
<h3 id="heading-code-explanation">Code explanation</h3>
<ol>
<li><p>The code initializes an empty vector of vectors called <code>powerset</code> to store the subsets. It starts with an initial subset containing an empty vector, representing the empty set: <code>{{}}</code>.</p>
</li>
<li><p>Within the loop, it creates a new vector of vectors called <code>newSubsets</code> to store subsets that include the <code>i</code>-th element of <code>nums</code>.</p>
</li>
<li><p>It iterates through the existing subsets in <code>powerset</code>. For each subset, it creates a copy of it (represented by the <code>subset</code> variable), adds the <code>i</code>-th element from <code>nums</code> to the copied subset, and pushes the modified subset into the <code>newSubsets</code> vector.</p>
</li>
<li><p>After processing all existing subsets, the code adds the contents of <code>newSubsets</code> to the <code>powerset</code> vector. This effectively combines the current subsets with subsets that include the <code>i</code>-th element of <code>nums</code>.</p>
</li>
<li><p>It repeats steps 2-4 until all elements in <code>nums</code> have been considered.</p>
</li>
<li><p>Finally, the code returns the <code>powerset</code>, which now contains all possible subsets of <code>nums</code>.</p>
</li>
</ol>
<h3 id="heading-complexity">Complexity</h3>
<p>This code essentially generates subsets by iteratively adding each element of <code>nums</code> to the existing subsets and accumulating the results. The time complexity of this code is <code>O(2^N)</code>, where <code>N</code> is the number of elements in <code>nums</code>, as it generates all possible subsets. The space complexity is also <code>O(2^N)</code> due to the space required to store the subsets.</p>
<ul>
<li><p>Runtime: <code>O(2^N)</code>.</p>
</li>
<li><p>Extra space: <code>O(2^N)</code>.</p>
</li>
</ul>
<hr />
<p><em>Thanks for reading. Feel free to share your thought about my content and check out my FREE book</em> <a target="_blank" href="https://store.nhutnguyen.com/l/10_classic"><strong><em>10 Classic Coding Challenges</em></strong></a><em>.</em></p>
]]></content:encoded></item><item><title><![CDATA[80. Remove Duplicates from Sorted Array II]]></title><description><![CDATA[Problem statement
Given an integer array nums already sorted in non-decreasing order, you must remove duplicates so that each unique element appears at most twice. The relative order of the elements should remain unchanged.
Since changing the array's...]]></description><link>https://leetsolve.com/80-remove-duplicates-from-sorted-array-ii</link><guid isPermaLink="true">https://leetsolve.com/80-remove-duplicates-from-sorted-array-ii</guid><category><![CDATA[C++]]></category><category><![CDATA[coding challenge]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[problem solving skills]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Mon, 16 Oct 2023 22:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1647130808651/dah2CJ_8Y.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-statementhttpsleetcodecomproblemsremove-duplicates-from-sorted-array-ii"><a target="_blank" href="https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/">Problem statement</a></h2>
<p>Given an integer array <code>nums</code> already sorted in non-decreasing order, you must remove duplicates so that each unique element appears at most twice. The relative order of the elements should remain unchanged.</p>
<p>Since changing the array's length in some programming languages is impossible, you must place the result in the first part of the <code>nums</code> array. In other words, if there are <code>k</code> elements after removing the duplicates, the first <code>k</code> elements of <code>nums</code> should contain the final result. Anything beyond the first <code>k</code> elements is not important.</p>
<p>You should return the value of <code>k</code> after placing the final result in the first <code>k</code> slots of the <code>nums</code> array.</p>
<p>The key requirement is to accomplish this task without using extra space for another array. It must be done by modifying the input array <code>nums</code> in-place, using only <code>O(1)</code> extra memory.</p>
<h3 id="heading-example-1">Example 1</h3>
<pre><code class="lang-text">Input: nums = [1,1,1,2,2,3]
Output: 5, nums = [1,1,2,2,3,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2, and 3, respectively.
What you leave does not matter beyond the returned k (hence, they are underscores).
</code></pre>
<h3 id="heading-example-2">Example 2</h3>
<pre><code class="lang-text">Input: nums = [0,0,1,1,1,1,2,3,3]
Output: 7, nums = [0,0,1,1,2,3,3,_,_]
Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3, and 3, respectively.
What you leave does not matter beyond the returned k (hence, they are underscores).
</code></pre>
<h3 id="heading-constraints">Constraints</h3>
<ul>
<li><p><code>1 &lt;= nums.length &lt;= 3 * 10^4</code>.</p>
</li>
<li><p><code>-10^4 &lt;= nums[i] &lt;= 10^4</code>.</p>
</li>
<li><p><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</p>
</li>
</ul>
<h2 id="heading-solution-1-erasing-the-duplicates">Solution 1: Erasing the duplicates</h2>
<p>In order for each unique element to appear <strong>at most twice</strong>, you have to erase the further appearances if they exist.</p>
<p>Since the array <code>nums</code> is sorted, you can determine that existence by checking if <code>nums[i] == nums[i-2]</code> for <code>2 &lt;= i &lt; nums.length</code>.</p>
<h3 id="heading-code">Code</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">removeDuplicates</span><span class="hljs-params">(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&amp; nums)</span> 
</span>{
    <span class="hljs-keyword">int</span> i = <span class="hljs-number">2</span>;
    <span class="hljs-keyword">while</span> (i &lt; nums.size()) 
    {
        <span class="hljs-keyword">if</span> (nums[i] == nums[i<span class="hljs-number">-2</span>]) 
        {
            <span class="hljs-keyword">int</span> j = i;
            <span class="hljs-keyword">while</span> (j &lt; nums.size() &amp;&amp; nums[j] == nums[i]) 
            {
                j++;
            }
            nums.erase(nums.begin() + i, nums.begin() + j);
        } 
        <span class="hljs-keyword">else</span> 
        {
            i++;
        }
    }
    <span class="hljs-keyword">return</span> nums.size();
}
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">printResult</span><span class="hljs-params">(<span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> k, <span class="hljs-keyword">const</span> <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&amp; nums)</span> 
</span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; k &lt;&lt; <span class="hljs-string">", ["</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; k ; i++) 
    {
        <span class="hljs-built_in">cout</span> &lt;&lt; nums[i] &lt;&lt; <span class="hljs-string">","</span>;
    }
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"]\n"</span>;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> 
</span>{
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; nums{<span class="hljs-number">1</span>,<span class="hljs-number">1</span>,<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>};
    printResult(removeDuplicates(nums), nums);
    nums = {<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">1</span>,<span class="hljs-number">1</span>,<span class="hljs-number">1</span>,<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">3</span>};
    printResult(removeDuplicates(nums), nums);
}
</code></pre>
<pre><code class="lang-text">Output:
5, [1,1,2,2,3,]
7, [0,0,1,1,2,3,3,]
</code></pre>
<h3 id="heading-code-explanation">Code explanation</h3>
<ol>
<li><p>Inside the loop, it checks if the element at index <code>i</code> is equal to the element two positions before it.</p>
</li>
<li><p>If the condition is met, there are more than two occurrences of the current element. We need to remove the excess duplicates while preserving two instances. To do this, a second while loop is used until the duplicate elements are no longer found. At this point, <code>j</code> will be the index of the first element that differs from the current element.</p>
</li>
<li><p>After finding the range of duplicate elements to remove (from index <code>i</code> to <code>j-1</code>, inclusive), it uses the <code>vector</code>'s <code>erase</code> function to remove these elements from the <code>nums</code> array. This effectively keeps only two instances of the current element.</p>
</li>
<li><p>If the condition in step 2 is not met (i.e., there are at most two occurrences of the current element), it moves the index <code>i</code> to the next unique element in the array.</p>
</li>
<li><p>Repeat steps 2 to 4 until <code>i</code> has traversed the entire array. The while loop removes all duplicate elements beyond two occurrences while maintaining the order of unique elements.</p>
</li>
<li><p>Once the loop finishes, the <code>nums</code> array contains unique elements with at most two occurrences of each. Return the size of the modified array using <code>nums.size()</code>.</p>
</li>
</ol>
<p>This solution efficiently removes duplicates from the sorted array by checking for duplicates and erasing the excess occurrences while preserving two instances of each unique element. It then returns the length of the modified array.</p>
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p>Runtime:</p>
<ul>
<li>Worst case: <code>O(N^2/3)</code>, where <code>N = nums.size()</code>. The complexity of the <a target="_blank" href="https://en.cppreference.com/w/cpp/container/vector/erase"><code>erase()</code></a> method is linear in <code>N</code>. The worst case is when <code>erase()</code> is called maximum <code>N/3</code> times.</li>
</ul>
</li>
</ul>
<pre><code class="lang-text">    Example of the worst case:
    nums = [1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6].
</code></pre>
<ul>
<li>On average: <code>O(N)</code> since the number of <code>erase()</code> calls is <code>O(1)</code>.</li>
</ul>
<ul>
<li>Extra space: <code>O(1)</code>.</li>
</ul>
<h2 id="heading-solution-2-reassigning-the-satisfying-elements">Solution 2: Reassigning the satisfying elements</h2>
<p>You might need to avoid the <code>erase()</code> method in the solution above to reduce the complexity. Moreover, after removing the duplicates, the problem only cares about the first <code>k</code> elements of the array <code>nums</code>.</p>
<p>If you look at the final result after removing duplication, the <strong>expected</strong> <code>nums</code> satisfies</p>
<pre><code class="lang-text">nums[i] &gt; nums[i-2] for 2 &lt;= i &lt; nums.length.
</code></pre>
<p>You can use this invariant to <strong>reassign</strong> the array <code>nums</code> only the satisfied elements.</p>
<h3 id="heading-code-1">Code</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">removeDuplicates</span><span class="hljs-params">(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&amp; nums)</span> 
</span>{
    <span class="hljs-keyword">if</span> (nums.size() &lt;= <span class="hljs-number">2</span>) 
    {
        <span class="hljs-keyword">return</span> nums.size(); 
    } 
    <span class="hljs-keyword">int</span> k = <span class="hljs-number">2</span>; 
    <span class="hljs-keyword">int</span> i = <span class="hljs-number">2</span>;
    <span class="hljs-keyword">while</span> (i &lt; nums.size()) 
    {
        <span class="hljs-keyword">if</span> (nums[i] &gt; nums[k - <span class="hljs-number">2</span>]) 
        {
            nums[k++] = nums[i];
        }
        i++;
    }
    <span class="hljs-keyword">return</span> k;
}
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">printResult</span><span class="hljs-params">(<span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> k, <span class="hljs-keyword">const</span> <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&amp; nums)</span> 
</span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; k &lt;&lt; <span class="hljs-string">", ["</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; k ; i++) 
    {
        <span class="hljs-built_in">cout</span> &lt;&lt; nums[i] &lt;&lt; <span class="hljs-string">","</span>;
    }
    <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"]\n"</span>;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> 
</span>{
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; nums{<span class="hljs-number">1</span>,<span class="hljs-number">1</span>,<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>};
    printResult(removeDuplicates(nums), nums);
    nums = {<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">1</span>,<span class="hljs-number">1</span>,<span class="hljs-number">1</span>,<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">3</span>};
    printResult(removeDuplicates(nums), nums);
}
</code></pre>
<pre><code class="lang-text">Output:
Output:
5, [1,1,2,2,3,]
7, [0,0,1,1,2,3,3,]
</code></pre>
<h3 id="heading-code-explanation-1">Code explanation</h3>
<ol>
<li><p>The code checks the size of the input array <code>nums</code>. If it has 2 or fewer elements, there's no need to perform any removals, so the function simply returns the size of the original array.</p>
</li>
<li><p>It initializes two variables:</p>
<ul>
<li><p><code>k</code>: This will represent the length of the resulting array after removing duplicates (initially set to 2 since we allow up to two occurrences of each element).</p>
</li>
<li><p><code>i</code>: This is an iterator that starts from the array's third element (index 2) and is used to traverse the array.</p>
</li>
</ul>
</li>
<li><p>It starts a loop that iterates from the third element (<code>i = 2</code>) to the end of the array.</p>
</li>
<li><p>Inside the loop, it compares the current element at index <code>i</code> with the element at <code>k - 2</code>. This comparison checks if the current element exceeds the previous two positions. If it is, this means it's a new element. Otherwise, it is a third occurrence of the same element, which we want to skip.</p>
</li>
<li><p>If the current element is greater than the element at index <code>k - 2</code>, it updates the element at index <code>k</code> with the current element. Then, it increments <code>k</code> to indicate that a new unique element has been found.</p>
</li>
<li><p>Continue iterating through the array by incrementing <code>i</code>.</p>
</li>
<li><p>Once the loop finishes, the array up to index <code>k - 1</code> contains the unique elements with at most two occurrences each, and the rest of the array can be ignored.</p>
</li>
<li><p>Finally, return the value of <code>k</code>, which represents the length of the resulting array.</p>
</li>
</ol>
<h3 id="heading-complexity-1">Complexity</h3>
<p>This solution effectively modifies the input array in-place, removing duplicates that occur more than twice while maintaining the desired order of unique elements. It does so in a single pass through the array, resulting in a time complexity of <code>O(N)</code>, where <code>N</code> is the number of elements in the array.</p>
<ul>
<li><p>Runtime: <code>O(N)</code>, where <code>N = nums.size()</code>.</p>
</li>
<li><p>Extra space: <code>O(1)</code>.</p>
</li>
</ul>
<hr />
<p><em>Thanks for reading. Check out my book</em> <strong><em>10 Classic Coding Challenges</em></strong> <em>for free</em> <a target="_blank" href="https://store.nhutnguyen.com/l/10_classic"><strong><em>here</em></strong></a><em>.</em></p>
]]></content:encoded></item><item><title><![CDATA[21. Merge Two Sorted Lists]]></title><description><![CDATA[Problem statement
Given the starting nodes of two sorted linked lists, list1 and list2, your task is to combine these lists into a single sorted linked list.
This merged list should be created by connecting the nodes from both list1 and list2. Finall...]]></description><link>https://leetsolve.com/21-merge-two-sorted-lists</link><guid isPermaLink="true">https://leetsolve.com/21-merge-two-sorted-lists</guid><category><![CDATA[C++]]></category><category><![CDATA[coding challenge]]></category><category><![CDATA[problem solving skills]]></category><category><![CDATA[data structures]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Mon, 16 Oct 2023 16:32:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1697642015546/5394854d-edd4-464e-8580-2e61063023b4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-statementhttpsleetcodecomproblemsmerge-two-sorted-lists"><a target="_blank" href="https://leetcode.com/problems/merge-two-sorted-lists/">Problem statement</a></h2>
<p>Given the starting nodes of two sorted linked lists, <code>list1</code> and <code>list2</code>, your task is to combine these lists into a single sorted linked list.</p>
<p>This merged list should be created by connecting the nodes from both <code>list1</code> and <code>list2</code>. Finally, you should return the starting node of the resulting merged linked list.</p>
<h3 id="heading-example-1">Example 1</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654975656428/7TTEcTvQU.jpg" alt="The linked lists of Example 1 and their merging" /></p>
<pre><code class="lang-text">Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
</code></pre>
<h3 id="heading-example-2">Example 2</h3>
<pre><code class="lang-text">Input: list1 = [], list2 = []
Output: []
</code></pre>
<h3 id="heading-example-3">Example 3</h3>
<pre><code class="lang-text">Input: list1 = [], list2 = [0]
Output: [0]
</code></pre>
<h3 id="heading-constraints">Constraints</h3>
<ul>
<li><p>The number of nodes in both lists is in the range <code>[0, 50]</code>.</p>
</li>
<li><p><code>-100 &lt;= Node.val &lt;= 100</code>.</p>
</li>
<li><p>Both <code>list1</code> and <code>list2</code> are sorted in non-decreasing order.</p>
</li>
</ul>
<h2 id="heading-solution-constructing-a-new-list">Solution: Constructing a new list</h2>
<p>For each pair of nodes between the two lists, pick the node having a smaller value to append to the new list.</p>
<h3 id="heading-code">Code</h3>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">ListNode</span> {</span>
    <span class="hljs-keyword">int</span> val;
    ListNode *next;
    ListNode() : val(<span class="hljs-number">0</span>), next(<span class="hljs-literal">nullptr</span>) {}
    ListNode(<span class="hljs-keyword">int</span> x) : val(x), next(<span class="hljs-literal">nullptr</span>) {}
    ListNode(<span class="hljs-keyword">int</span> x, ListNode *next) : val(x), next(next) {}
};

<span class="hljs-function">ListNode* <span class="hljs-title">mergeTwoLists</span><span class="hljs-params">(ListNode* list1, ListNode* list2)</span> </span>{
    <span class="hljs-keyword">if</span> (list1 == <span class="hljs-literal">nullptr</span>) {
        <span class="hljs-keyword">return</span> list2;
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (list2 == <span class="hljs-literal">nullptr</span>) {
        <span class="hljs-keyword">return</span> list1;
    }
    <span class="hljs-comment">// identify which list is head</span>
    ListNode* head = list1;
    <span class="hljs-keyword">if</span> (list2-&gt;val &lt; head-&gt;val) {
        head = list2;
        list2 = list2-&gt;next;
    } <span class="hljs-keyword">else</span> {
        list1 = list1-&gt;next;
    }
    ListNode* node = head;
    <span class="hljs-keyword">while</span> (list1 &amp;&amp; list2) {
        <span class="hljs-keyword">if</span> (list1-&gt;val &lt; list2-&gt;val) {
            node-&gt;next = list1;
            list1 = list1-&gt;next;
        } <span class="hljs-keyword">else</span> {
            node-&gt;next = list2;
            list2 = list2-&gt;next;
        }
        node = node-&gt;next;
    }
    <span class="hljs-keyword">if</span> (list1 == <span class="hljs-literal">nullptr</span>) {
        node-&gt;next = list2;
    } <span class="hljs-keyword">else</span> {
        node-&gt;next = list1;
    }
    <span class="hljs-keyword">return</span> head;
}
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">printResult</span><span class="hljs-params">(ListNode* head)</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"["</span>;
    <span class="hljs-keyword">while</span> (head) {
        <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; head-&gt;val &lt;&lt; <span class="hljs-string">","</span>;
        head = head-&gt;next;
    }
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"]\n"</span>;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{   
    <span class="hljs-function">ListNode <span class="hljs-title">four1</span><span class="hljs-params">(<span class="hljs-number">4</span>)</span></span>;
    <span class="hljs-function">ListNode <span class="hljs-title">two1</span><span class="hljs-params">(<span class="hljs-number">2</span>, &amp;four1)</span></span>;
    <span class="hljs-function">ListNode <span class="hljs-title">one1</span><span class="hljs-params">(<span class="hljs-number">1</span>, &amp;two1)</span></span>;
    <span class="hljs-function">ListNode <span class="hljs-title">four2</span><span class="hljs-params">(<span class="hljs-number">4</span>)</span></span>;
    <span class="hljs-function">ListNode <span class="hljs-title">three2</span><span class="hljs-params">(<span class="hljs-number">3</span>, &amp;four2)</span></span>;
    <span class="hljs-function">ListNode <span class="hljs-title">one2</span><span class="hljs-params">(<span class="hljs-number">1</span>, &amp;three2)</span></span>;
    <span class="hljs-keyword">auto</span> newOne = mergeTwoLists(&amp;one1, &amp;one2);
    printResult(newOne);

    <span class="hljs-keyword">auto</span> empty = mergeTwoLists(<span class="hljs-literal">nullptr</span>, <span class="hljs-literal">nullptr</span>);
    printResult(empty);

    <span class="hljs-function">ListNode <span class="hljs-title">zero</span><span class="hljs-params">(<span class="hljs-number">0</span>)</span></span>;
    <span class="hljs-keyword">auto</span> z = mergeTwoLists(<span class="hljs-literal">nullptr</span>, &amp;zero);
    printResult(z);
}
</code></pre>
<pre><code class="lang-text">Output:
[1,1,2,3,4,4,]
[]
[0,]
</code></pre>
<h3 id="heading-code-explanation">Code explanation</h3>
<ol>
<li><p>The function begins with two base cases to handle situations where one of the input lists is empty:</p>
<ul>
<li><p>If <code>list1</code> is empty (i.e., <code>list1</code> is <code>nullptr</code>), the function simply returns <code>list2</code>. There is no need to merge anything because <code>list1</code> is empty.</p>
</li>
<li><p>Similarly, if <code>list2</code> is empty (i.e., <code>list2</code> is <code>nullptr</code>), the function returns <code>list1</code>.</p>
</li>
</ul>
</li>
<li><p>A <code>head</code> pointer will be used to keep track of the merged list. The code determines which of <code>list1</code> and <code>list2</code> should be the head of the merged list. It does this by comparing the values of the first nodes in <code>list1</code> and <code>list2</code>:</p>
<ul>
<li><p>If the value of the first node in <code>list2</code> is less than the value of the first node in <code>list1</code>, it means that <code>list2</code> should be the new head of the merged list. The code updates the <code>head</code> pointer to point to <code>list2</code>, and it advances the <code>list2</code> pointer to the next node.</p>
</li>
<li><p>If the value of the first node in <code>list1</code> is less than or equal to the value in <code>list2</code>, <code>list1</code> should be the new head. The code advances the <code>list1</code> pointer to the next node.</p>
</li>
</ul>
</li>
<li><p>The main merging process is performed using a <code>while</code> loop that continues as long as both <code>list1</code> and <code>list2</code> are not empty:</p>
<ul>
<li><p>Inside the loop, the code compares the values of the first nodes in <code>list1</code> and <code>list2</code>:</p>
<ul>
<li><p>If the value in <code>list1</code> is smaller, the code connects the current node pointed to by <code>node</code> to the node in <code>list1</code>, and advances <code>list1</code> to its next node.</p>
</li>
<li><p>If the value in <code>list2</code> is smaller or equal, the code connects the current node pointed to by <code>node</code> to the node in <code>list2</code>, and advances <code>list2</code> to its next node.</p>
</li>
</ul>
</li>
<li><p>After connecting a node, the <code>node</code> pointer is moved to the newly connected node.</p>
</li>
</ul>
</li>
<li><p>After the <code>while</code> loop completes, one of the input lists may still have remaining elements. To ensure that all elements are included in the merged list, the code appends the remaining nodes from either <code>list1</code> or <code>list2</code> (whichever is not empty) to the end of the merged list.</p>
</li>
<li><p>Finally, the function returns <code>head</code>, which points to the head of the merged sorted linked list.</p>
</li>
</ol>
<h3 id="heading-complexity">Complexity</h3>
<ul>
<li><p>Runtime: <code>O(N)</code>, where <code>N = list1.length + list2.length</code>.</p>
</li>
<li><p>Extra space: <code>O(1)</code>.</p>
</li>
</ul>
<hr />
<p><em>Thanks for reading. Feel free to share your thought about my content and check out my FREE book</em> <a target="_blank" href="https://store.nhutnguyen.com/l/10_classic"><strong><em>10 Classic Coding Challenges</em></strong></a><em>.</em></p>
]]></content:encoded></item><item><title><![CDATA[462. Minimum Moves to Equal Array Elements II]]></title><description><![CDATA[Problem statement
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.
In one move, you can increment or decrement an element of the array by 1.
Example 1
Input: nums = [1,2,3]
Output: 2...]]></description><link>https://leetsolve.com/462-minimum-moves-to-equal-array-elements-ii</link><guid isPermaLink="true">https://leetsolve.com/462-minimum-moves-to-equal-array-elements-ii</guid><category><![CDATA[C++]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Programming Tips]]></category><category><![CDATA[leetcode]]></category><category><![CDATA[coding challenge]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Mon, 10 Jul 2023 10:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1688761503587/13befc7d-ded3-4c76-a0fd-e3fca2ea198d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-problem-statement">Problem statement</h3>
<p>Given an integer array <code>nums</code> of size <code>n</code>, return the minimum number of moves required to make all array elements equal.</p>
<p>In one move, you can increment or decrement an element of the array by <code>1</code>.</p>
<h4 id="heading-example-1">Example 1</h4>
<pre><code class="lang-plaintext">Input: nums = [1,2,3]
Output: 2
Explanation:
Only two moves are needed (remember each move increments or decrements one element):
[1,2,3]  =&gt;  [2,2,3]  =&gt;  [2,2,2]
</code></pre>
<h4 id="heading-example-2">Example 2</h4>
<pre><code class="lang-plaintext">Input: nums = [1,10,2,9]
Output: 16
</code></pre>
<h4 id="heading-constraints">Constraints</h4>
<ul>
<li><p><code>n == nums.length</code>.</p>
</li>
<li><p><code>1 &lt;= nums.length &lt;= 10^5</code>.</p>
</li>
<li><p><code>-10^9 &lt;= nums[i] &lt;= 10^9</code>.</p>
</li>
</ul>
<h3 id="heading-solution-1-median-the-math-behind-the-problem">Solution 1: Median - The math behind the problem</h3>
<p>You are asked to move all elements of an array to the same value <code>M</code>. The problem can be reduced to identifying what <code>M</code> is.</p>
<p>First, moving elements of an unsorted array and moving a sorted one are the same. So you can assume <code>nums</code> is sorted in some order. Let us say it is sorted in ascending order.</p>
<p>Second, <code>M</code> must be in between the minimum element and the maximum one. Apparently!</p>
<p>We will prove that <code>M</code> will be the <a target="_blank" href="https://en.wikipedia.org/wiki/Median">median</a> of <code>nums</code>, which is <code>nums[n/2]</code> of the sorted <code>nums</code>.</p>
<p>In other words, we will prove that if you choose <code>M</code> a value different from <code>nums[n/2]</code>, then the number of moves will be increased.</p>
<p>In fact, if you choose <code>M = nums[n/2] + x</code>, where <code>x &gt; 0</code>, then:</p>
<ul>
<li><p>Each element <code>nums[i]</code> that is less than <code>M</code> needs more <code>x</code> moves, while each <code>nums[j]</code> that is greater than <code>M</code> can reduce <code>x</code> moves.</p>
</li>
<li><p>But the number of <code>nums[i]</code> is bigger than the number of <code>nums[j]</code>.</p>
</li>
<li><p>So the total number of moves is bigger.</p>
</li>
</ul>
<p>The same arguments apply for <code>x &lt; 0</code>.</p>
<h4 id="heading-example-3">Example 3</h4>
<p>For <code>nums = [0,1,2,2,10]</code>. Its median is <code>2</code>. The minimum number of moves is <code>2 + 1 + 0 + 0 + 8 = 11</code>.</p>
<p>If you choose <code>M = 3</code> (the average value, the mean), the total number of moves is <code>3 + 2 + 1 + 1 + 7 = 14</code>.</p>
<h4 id="heading-code">Code</h4>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">minMoves2</span><span class="hljs-params">(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&amp; nums)</span> </span>{
    sort(nums.begin(), nums.end());
    <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> median = nums[nums.size() / <span class="hljs-number">2</span>];
    <span class="hljs-keyword">int</span> moves = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span>&amp; a: nums) {
        moves += <span class="hljs-built_in">abs</span>(a - median);
    }
    <span class="hljs-keyword">return</span> moves;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; nums{<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>};
    <span class="hljs-built_in">cout</span> &lt;&lt; minMoves2(nums) &lt;&lt; <span class="hljs-built_in">endl</span>;
    nums = {<span class="hljs-number">1</span>,<span class="hljs-number">10</span>,<span class="hljs-number">2</span>,<span class="hljs-number">9</span>};
    <span class="hljs-built_in">cout</span> &lt;&lt; minMoves2(nums) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
2
16
</code></pre>
<h4 id="heading-complexity">Complexity</h4>
<ul>
<li><p>Runtime: <code>O(nlogn)</code>, where <code>n = nums.length</code>.</p>
</li>
<li><p>Extra space: <code>O(1)</code>.</p>
</li>
</ul>
<h3 id="heading-solution-2-using-stdnthelement-to-compute-the-median">Solution 2: Using <code>std::nth_element</code> to compute the median</h3>
<p>What you only need in Solution 1 is the median value. Computing the total number of moves in the <code>for</code> loop does not require the array <code>nums</code> to be fully sorted.</p>
<p>In this case, you can use <a target="_blank" href="https://en.cppreference.com/w/cpp/algorithm/nth_element"><code>std::nth_element</code></a> to reduce the runtime complexity.</p>
<h4 id="heading-code-1">Code</h4>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">minMoves2</span><span class="hljs-params">(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&amp; nums)</span> </span>{
    <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> mid = nums.size() / <span class="hljs-number">2</span>;    
    <span class="hljs-built_in">std</span>::nth_element(nums.begin(), nums.begin() + mid, nums.end());
    <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> median = nums[mid];
    <span class="hljs-keyword">int</span> moves = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span>&amp; a: nums) {
        moves += <span class="hljs-built_in">abs</span>(a - median);
    }
    <span class="hljs-keyword">return</span> moves;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; nums{<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>};
    <span class="hljs-built_in">cout</span> &lt;&lt; minMoves2(nums) &lt;&lt; <span class="hljs-built_in">endl</span>;
    nums = {<span class="hljs-number">1</span>,<span class="hljs-number">10</span>,<span class="hljs-number">2</span>,<span class="hljs-number">9</span>};
    <span class="hljs-built_in">cout</span> &lt;&lt; minMoves2(nums) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
2
16
</code></pre>
<h4 id="heading-complexity-1">Complexity</h4>
<ul>
<li><p>Runtime: <code>O(n)</code>, where <code>n = nums.length</code>.</p>
</li>
<li><p>Extra space: <code>O(1)</code>.</p>
</li>
</ul>
<h3 id="heading-modern-c-notes">Modern C++ notes</h3>
<p>In the code of Solution 2, the partial sorting algorithm <code>std::nth_element</code> will make sure for all indices <code>i</code> and <code>j</code> that satisfy <code>0 &lt;= i &lt;= mid &lt;= j &lt; nums.length</code>,</p>
<pre><code class="lang-plaintext">nums[i] &lt;= nums[mid] &lt;= nums[j].
</code></pre>
<p>With this property, if <code>mid = nums.length / 2</code>, then the value of <code>nums[mid]</code> is unchanged no matter how <code>nums</code> is sorted or not.</p>
<hr />
<p><em>What is your approach? The problem was picked from</em> <a target="_blank" href="https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/"><em>leetcode.com</em></a><em>. You can submit your solution in any programming language and check the performance.</em></p>
<p><em>Thanks for reading. Feel free to share your thought about my content and check out my FREE book</em> <a target="_blank" href="https://store.nhutnguyen.com/l/10_classic"><em>10 Classic Coding Challenges</em></a><em>.</em></p>
]]></content:encoded></item><item><title><![CDATA[1647. Minimum Deletions to Make Character Frequencies Unique]]></title><description><![CDATA[Problem statement
A string s is called good if there are no two different characters in s that have the same frequency.
Given a string s, return the minimum number of characters you need to delete to make s good.
The frequency of a character in a str...]]></description><link>https://leetsolve.com/1647-minimum-deletions-to-make-character-frequencies-unique</link><guid isPermaLink="true">https://leetsolve.com/1647-minimum-deletions-to-make-character-frequencies-unique</guid><category><![CDATA[C++]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Programming Tips]]></category><category><![CDATA[leetcode]]></category><category><![CDATA[coding]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Mon, 03 Jul 2023 10:01:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1688325162632/a1a6c86a-6447-4a0a-9ed4-352c971e3993.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-problem-statement">Problem statement</h3>
<p>A string <code>s</code> is called good if there are no two different characters in <code>s</code> that have the same frequency.</p>
<p>Given a string <code>s</code>, return the minimum number of characters you need to delete to make <code>s</code> good.</p>
<p>The frequency of a character in a string is the number of times it appears in the string. For example, in the string <code>"aab"</code>, the frequency of <code>'a'</code> is <code>2</code>, while the frequency of <code>'b'</code> is <code>1</code>.</p>
<h4 id="heading-example-1">Example 1</h4>
<pre><code class="lang-plaintext">Input: s = "aab"
Output: 0
Explanation: s is already good.
</code></pre>
<h4 id="heading-example-2">Example 2</h4>
<pre><code class="lang-plaintext">Input: s = "aaabbbcc"
Output: 2
Explanation: You can delete two 'b's resulting in the good string "aaabcc".
Another way is to delete one 'b' and one 'c' resulting in the good string "aaabbc".
</code></pre>
<h4 id="heading-example-3">Example 3</h4>
<pre><code class="lang-plaintext">Input: s = "ceabaacb"
Output: 2
Explanation: You can delete both 'c's resulting in the good string "eabaab".
Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).
</code></pre>
<h4 id="heading-constraints">Constraints</h4>
<ul>
<li><p><code>1 &lt;= s.length &lt;= 10^5</code>.</p>
</li>
<li><p><code>s</code> contains only lowercase English letters.</p>
</li>
</ul>
<h3 id="heading-solution-delete-the-frequencies-in-sorted-order">Solution: Delete the frequencies in sorted order</h3>
<p>Your goal is to make all the frequencies different.</p>
<p>One way of doing that is by sorting the frequencies and performing the deletion.</p>
<h4 id="heading-example-4">Example 4</h4>
<p>For <code>s = "ceaacbb"</code>, the frequencies of the characters are: <code>freq['a'] = 2, freq['b'] = 2, freq['c'] = 2</code> and <code>freq['e'] = 1</code>. They are already in sorted order.</p>
<ul>
<li><p>Let the current frequency be the first frequency <code>freq['a'] = 2</code>.</p>
</li>
<li><p>The next frequency is <code>freq['b'] = 2</code>, equal to the current frequency. Delete one appearance to make the current frequency be <code>1</code>.</p>
</li>
<li><p>The next frequency is <code>freq['c'] = 2</code>, bigger than the current frequency. Delete two appearances to make the current frequency be <code>0</code>.</p>
</li>
<li><p>Because the current frequency is <code>0</code>, delete all appearances of the remaining frequencies, which is <code>freq['e'] = 1</code>.</p>
</li>
<li><p>In total, there are <code>4</code> deletions.</p>
</li>
</ul>
<h4 id="heading-code">Code</h4>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">minDeletions</span><span class="hljs-params">(<span class="hljs-built_in">string</span> s)</span> </span>{
    <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">freq</span><span class="hljs-params">(<span class="hljs-number">26</span>, <span class="hljs-number">0</span>)</span></span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">char</span>&amp; c: s) {
        freq[c - <span class="hljs-string">'a'</span>]++;
    }
    sort(freq.begin(), freq.end(), greater&lt;<span class="hljs-keyword">int</span>&gt;());
    <span class="hljs-keyword">int</span> deletion = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">int</span> currentFreq = freq[<span class="hljs-number">0</span>];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; freq.size() &amp;&amp; freq[i] &gt; <span class="hljs-number">0</span>; i++) {
        <span class="hljs-keyword">if</span> (currentFreq == <span class="hljs-number">0</span>) {
            deletion += freq[i];
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (freq[i] &gt;= currentFreq) {
            deletion += freq[i] - currentFreq + <span class="hljs-number">1</span>;
            currentFreq--;
        } <span class="hljs-keyword">else</span> {
            currentFreq = freq[i];
        }
    }
    <span class="hljs-keyword">return</span> deletion;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; minDeletions(<span class="hljs-string">"aab"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; minDeletions(<span class="hljs-string">"aaabbbcc"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; minDeletions(<span class="hljs-string">"ceabaacb"</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
0
2
2
</code></pre>
<h4 id="heading-complexity">Complexity</h4>
<ul>
<li><p>Runtime: <code>O(N)</code>, where <code>N = s.length</code>;</p>
</li>
<li><p>Extra space: <code>O(1)</code> since <code>26</code> is not a big number.</p>
</li>
</ul>
<hr />
<p><em>What is your approach? The problem was picked from</em> <a target="_blank" href="https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/"><em>leetcode.com</em></a><em>. You can submit your solution in any programming language and check the performance.</em></p>
<p><em>Thanks for reading. Feel free to share your thought about my content and check out my FREE book</em> <a target="_blank" href="https://store.nhutnguyen.com/l/10_classic">10 Classic Coding Challenges</a>.*</p>
]]></content:encoded></item><item><title><![CDATA[1710. Maximum Units on a Truck]]></title><description><![CDATA[Problem statement
You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxes_i, numberOfUnitsPerBox_i]:

numberOfBoxes_i is the number of boxes of type i.

numberOfUnitsPerBox_i ...]]></description><link>https://leetsolve.com/1710-maximum-units-on-a-truck</link><guid isPermaLink="true">https://leetsolve.com/1710-maximum-units-on-a-truck</guid><category><![CDATA[leetcode]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Programming Tips]]></category><category><![CDATA[C++]]></category><category><![CDATA[coding]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Mon, 26 Jun 2023 10:01:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1687638643879/8e1cfcbc-2dd4-4191-b6aa-3f818a7e46db.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-problem-statement">Problem statement</h3>
<p>You are assigned to put some amount of boxes onto one truck. You are given a 2D array <code>boxTypes</code>, where <code>boxTypes[i] = [numberOfBoxes_i, numberOfUnitsPerBox_i]</code>:</p>
<ul>
<li><p><code>numberOfBoxes_i</code> is the number of boxes of type <code>i</code>.</p>
</li>
<li><p><code>numberOfUnitsPerBox_i</code> is the number of units in each box of the type <code>i</code>.</p>
</li>
</ul>
<p>You are also given an integer <code>truckSize</code>, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed <code>truckSize</code>.</p>
<p>Return the maximum total number of units that can be put on the truck.</p>
<h4 id="heading-example-1">Example 1</h4>
<pre><code class="lang-plaintext">Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
Output: 8
Explanation: There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.
</code></pre>
<h4 id="heading-example-2">Example 2</h4>
<pre><code class="lang-plaintext">Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
Output: 91
Explanation: (5 * 10) + (3 * 9) + (2 * 7) = 91.
</code></pre>
<h4 id="heading-constraints">Constraints</h4>
<ul>
<li><p><code>1 &lt;= boxTypes.length &lt;= 1000</code>.</p>
</li>
<li><p><code>1 &lt;= numberOfBoxes_i, numberOfUnitsPerBox_i &lt;= 1000</code>.</p>
</li>
<li><p><code>1 &lt;= truckSize &lt;= 10^6</code>.</p>
</li>
</ul>
<h3 id="heading-solution-greedy-algorithm">Solution: Greedy algorithm</h3>
<p>Put the boxes having more units first.</p>
<h4 id="heading-code">Code</h4>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;algorithm&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">maximumUnits</span><span class="hljs-params">(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt;&amp; boxTypes, <span class="hljs-keyword">int</span> truckSize)</span> </span>{
    <span class="hljs-comment">// sort for the boxes based on their number of units</span>
    sort(boxTypes.begin(), boxTypes.end(), [](<span class="hljs-keyword">const</span> <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&amp; a, <span class="hljs-keyword">const</span> <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&amp; b) {
        <span class="hljs-keyword">return</span> a[<span class="hljs-number">1</span>] &gt; b[<span class="hljs-number">1</span>];
    });
    <span class="hljs-keyword">int</span> maxUnits = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">while</span> (truckSize &gt; <span class="hljs-number">0</span> &amp;&amp; i &lt; boxTypes.size()) {
        <span class="hljs-keyword">if</span> (boxTypes[i][<span class="hljs-number">0</span>] &lt;= truckSize) {
            maxUnits += boxTypes[i][<span class="hljs-number">0</span>] * boxTypes[i][<span class="hljs-number">1</span>];
            truckSize -= boxTypes[i][<span class="hljs-number">0</span>];
        } <span class="hljs-keyword">else</span> {
            maxUnits += truckSize * boxTypes[i][<span class="hljs-number">1</span>];
            <span class="hljs-keyword">break</span>;
        }
        i++;
    }
    <span class="hljs-keyword">return</span> maxUnits;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt; boxTypes{{<span class="hljs-number">1</span>,<span class="hljs-number">3</span>},{<span class="hljs-number">2</span>,<span class="hljs-number">2</span>},{<span class="hljs-number">3</span>,<span class="hljs-number">1</span>}};
    <span class="hljs-built_in">cout</span> &lt;&lt; maximumUnits(boxTypes, <span class="hljs-number">4</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    boxTypes = {{<span class="hljs-number">5</span>,<span class="hljs-number">10</span>},{<span class="hljs-number">2</span>,<span class="hljs-number">5</span>},{<span class="hljs-number">4</span>,<span class="hljs-number">7</span>},{<span class="hljs-number">3</span>,<span class="hljs-number">9</span>}};
    <span class="hljs-built_in">cout</span> &lt;&lt; maximumUnits(boxTypes, <span class="hljs-number">10</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
8
91
</code></pre>
<h4 id="heading-complexity">Complexity</h4>
<ul>
<li><p>Runtime: <code>O(NlogN)</code>, where <code>N = boxTypes.length</code>.</p>
</li>
<li><p>Extra space: <code>O(1)</code>.</p>
</li>
</ul>
<h3 id="heading-modern-c-stl-notes">Modern C++ STL notes</h3>
<p>Note that two <a target="_blank" href="https://en.cppreference.com/w/cpp/container/vector"><code>vector</code>s</a> can be compared. That is why you can sort them.</p>
<p>But in this case you want to sort them based on the number of units. That is why you need to define the comparison function like the code above. Otherwise, the <a target="_blank" href="https://en.cppreference.com/w/cpp/algorithm/sort"><code>sort</code></a> algorithm will use the dictionary order to sort them by default.</p>
<hr />
<p><em>What is your approach? The problem was picked from</em> <a target="_blank" href="https://leetcode.com/problems/maximum-units-on-a-truck/"><em>leetcode.com</em></a><em>. You can submit your solution in any programming language and check the performance.</em></p>
<p><em>Thanks for reading. Feel free to share your thought about my content and check out my FREE book</em> <a target="_blank" href="https://store.nhutnguyen.com/l/10_classic"><em>10 Classic Coding Challenges</em></a><em>.</em></p>
]]></content:encoded></item><item><title><![CDATA[279. Perfect Squares]]></title><description><![CDATA[Problem statement
Given an integer n, return the least number of perfect square numbers that sum to n.
A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, ...]]></description><link>https://leetsolve.com/279-perfect-squares</link><guid isPermaLink="true">https://leetsolve.com/279-perfect-squares</guid><category><![CDATA[C++]]></category><category><![CDATA[leetcode]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[coding challenge]]></category><category><![CDATA[Mathematics]]></category><dc:creator><![CDATA[Nhut Nguyen]]></dc:creator><pubDate>Mon, 12 Jun 2023 08:00:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1685630957160/21a0df78-4e85-4c15-acac-a5d6786e404d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-problem-statement">Problem statement</h3>
<p>Given an integer <code>n</code>, return the least number of perfect square numbers that sum to <code>n</code>.</p>
<p>A <strong>perfect square</strong> is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, <code>1</code>, <code>4</code>, <code>9</code>, and <code>16</code> are perfect squares while <code>3</code> and <code>11</code> are not.</p>
<h4 id="heading-example-1">Example 1</h4>
<pre><code class="lang-plaintext">Input: n = 9
Output: 1
Explanation: 9 is already a perfect square.
</code></pre>
<h4 id="heading-example-2">Example 2</h4>
<pre><code class="lang-plaintext">Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
</code></pre>
<h4 id="heading-example-3">Example 3</h4>
<pre><code class="lang-plaintext">Input: n = 7
Output: 4
Explanation: 7 = 4 + 1 + 1 + 1.
</code></pre>
<h4 id="heading-example-4">Example 4</h4>
<pre><code class="lang-plaintext">Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
</code></pre>
<h4 id="heading-constraints">Constraints</h4>
<ul>
<li><code>1 &lt;= n &lt;= 10^4</code>.</li>
</ul>
<h3 id="heading-solution-1-dynamic-programming">Solution 1: Dynamic Programming</h3>
<p>Let us call the function to be computed <code>numSquares(n)</code>, which calculates the least number of perfect squares that sum to <code>n</code>.</p>
<p>Here are the findings.</p>
<ol>
<li><p>If <code>n</code> is already a perfect square then <code>numSquares(n) = 1</code>.</p>
</li>
<li><p>Otherwise, it could be written as <code>n = 1 + (n-1)</code>, or <code>n = 4 + (n-4)</code>, or <code>n = 9 + (n-9)</code>, etc. which means <code>n</code> is a sum of a perfect square (<code>1, 4</code> or <code>9</code>, etc.) and another number <code>m &lt; n</code>. That leads to the problems <code>numSquares(m)</code> of smaller values <code>m</code>.</p>
</li>
<li><p>If you have gotten the results of the smaller problems <code>numSquares(n-1)</code>, <code>numSquares(n-4)</code>, <code>numSquares(n-9)</code>, etc. then <code>numSquares(n) = 1 + the minimum of those results</code>.</p>
</li>
</ol>
<h4 id="heading-example-4-1">Example 4</h4>
<p><code>n = 12</code> is not a perfect square. It can be written as <code>n = 1 + 11 = 4 + 8 = 9 + 3</code>.</p>
<ul>
<li><p>For <code>m = 11</code>, it is not a perfect square and can be written as <code>m = 1 + 10 = 4 + 7 = 9 + 2</code>.</p>
</li>
<li><p>For <code>m = 8</code>, it is not a perfect square and can be written as <code>m = 1 + 7 = 4 + 4</code> (matched). You get <code>numSquares(8) = 2</code>.</p>
</li>
<li><p>For <code>m = 3</code>, it is not a perfect square and can be written as <code>m = 1 + 2</code>.</p>
</li>
</ul>
<p>You can continue to compute <code>numSquares(m)</code> for other values <code>m</code> in this recursive process. But you can see the case of <code>m = 8</code> was already the best solution. And <code>numSquares(12) = 1 + numSquares(8) = 1 + 2 = 3</code>, which is the case of <code>n = 12 = 4 + 4 + 4</code>.</p>
<p>To improve runtime, you can apply <em>dynamic programming</em> to cache the <code>numSquares(n)</code> that you have computed.</p>
<h4 id="heading-code">Code</h4>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cmath&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;unordered_map&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">nsq</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n, <span class="hljs-built_in">unordered_map</span>&lt;<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>&gt;&amp; ns)</span> </span>{
    <span class="hljs-keyword">auto</span> it = ns.find(n);
    <span class="hljs-keyword">if</span> (it != ns.end()) {
        <span class="hljs-keyword">return</span> it-&gt;second;
    }
    <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> sq = <span class="hljs-built_in">sqrt</span>(n);
    <span class="hljs-keyword">if</span> (sq * sq == n) {
        ns[n] = <span class="hljs-number">1</span>;
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    }
    <span class="hljs-keyword">int</span> result = n;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= sq; i++) {
        result = min(result, nsq(n - i*i, ns));
    }
    ns[n] = result + <span class="hljs-number">1</span>;
    <span class="hljs-keyword">return</span> ns[n];
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">numSquares</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    <span class="hljs-built_in">unordered_map</span>&lt;<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>&gt; ns;
    <span class="hljs-keyword">return</span> nsq(n, ns);
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; numSquares(<span class="hljs-number">12</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; numSquares(<span class="hljs-number">13</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
3
2
</code></pre>
<h4 id="heading-complexity">Complexity</h4>
<ul>
<li><p>Runtime: <code>O(n^2)</code>.</p>
</li>
<li><p>Extra space: <code>O(n)</code></p>
</li>
</ul>
<h3 id="heading-solution-2-number-theory">Solution 2: Number Theory</h3>
<p>The dynamic programming solution above is good enough. But for those who are interested in Algorithmic Number Theory, there is a very interesting theorem that can solve the problem directly without recursion.</p>
<p>It is called <a target="_blank" href="https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem">Lagrange's Four-Square Theorem</a>, which states</p>
<blockquote>
<p><em>every natural number can be represented as the sum of four integer squares.</em></p>
</blockquote>
<p>It was proven by Lagrange in 1770.</p>
<h4 id="heading-example-4-2">Example 4</h4>
<p><code>n = 12 = 4 + 4 + 4 + 0</code> or <code>12 = 1 + 1 + 1 + 9</code>.</p>
<p>Applying to our problem, <code>numSquares(n)</code> can only be 1, 2, 3, or 4. Not more.</p>
<p>It turns into the problem of</p>
<blockquote>
<p><em>identifying when</em> <code>numSquares(n)</code> returns 1, 2, 3, or 4.</p>
</blockquote>
<p>Here are the cases.</p>
<ol>
<li><p>If <code>n</code> is a perfect square, <code>numSquares(n) = 1</code>.</p>
</li>
<li><p>There is another theorem, <a target="_blank" href="https://en.wikipedia.org/wiki/Legendre%27s_three-square_theorem">Legendre's Three-Square Theorem</a>, which states that <code>numSquares(n)</code> cannot be 1, 2, or 3 if <code>n</code> can be expressed as</p>
<pre><code class="lang-plaintext"> n = 4^a(8*b + 7),
</code></pre>
<p> where <code>a, b</code> are nonnegative integers. In other words, <code>numSquares(n) = 4</code> if <code>n</code> is of this form.</p>
</li>
</ol>
<h4 id="heading-example-3-1">Example 3</h4>
<p><code>n = 7 = 4^0(8*0 + 7)</code>. It can only be written as <code>7 = 4 + 1 + 1 + 1</code>.</p>
<h4 id="heading-code-1">Code</h4>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cmath&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">isSquare</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    <span class="hljs-keyword">int</span> sq = <span class="hljs-built_in">sqrt</span>(n);
    <span class="hljs-keyword">return</span> sq * sq == n;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">numSquares</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    <span class="hljs-keyword">if</span> (isSquare(n)) {
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    }
    <span class="hljs-comment">// Legendre's three-square theorem</span>
    <span class="hljs-keyword">int</span> m = n;
    <span class="hljs-keyword">while</span> (m % <span class="hljs-number">4</span> == <span class="hljs-number">0</span>) {
        m /= <span class="hljs-number">4</span>;
    }
    <span class="hljs-keyword">if</span> (m % <span class="hljs-number">8</span> == <span class="hljs-number">7</span>) {
        <span class="hljs-keyword">return</span> <span class="hljs-number">4</span>;
    }
    <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> sq = <span class="hljs-built_in">sqrt</span>(n);
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= sq; i++) {
        <span class="hljs-keyword">if</span> (isSquare(n - i*i)) {
            <span class="hljs-keyword">return</span> <span class="hljs-number">2</span>;
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">3</span>;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; numSquares(<span class="hljs-number">12</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; numSquares(<span class="hljs-number">13</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
3
2
</code></pre>
<h4 id="heading-complexity-1">Complexity</h4>
<ul>
<li><p>Runtime: <code>O(logn)</code>.</p>
</li>
<li><p>Extra space: <code>O(1)</code>.</p>
</li>
</ul>
<h3 id="heading-solution-3-further-performance-improvement">Solution 3: Further performance improvement</h3>
<p>Lagrange's Four-Square Theorem and Legendre's Three-Square Theorem are so powerful to solve this problem. But you can still do a little more algebra to improve further the runtime of the implementation above.</p>
<p>Instead of looping over <code>sqrt(n)</code> in the final <code>for</code> loop, we will prove that this loop over <code>sqrt(m)</code> is enough. That will improve runtime a lot since <code>m</code> is much less than <code>n</code>.</p>
<p>Let <code>m</code> be the reduced value of <code>n</code> after the Legendre's <code>while</code> loop. It satisfies</p>
<pre><code class="lang-plaintext">n = 4^a * m.
</code></pre>
<p>We will prove that <code>numSquares(n) = numSquares(m)</code>.</p>
<p>In fact, if <code>m</code> is written as <code>m = x^2 + y^2 + z^2</code>, where <code>x, y, z</code> are nonnegative integers. Then</p>
<pre><code class="lang-plaintext">n = 4^a * m = (2^a)^2 * m = (2^a * x)^2 + (2^a * y)^2 + (2^a * z)^2.
</code></pre>
<p>In other words, <code>numSquares(n) = numSquares(m)</code>.</p>
<p>Now you can change directly the value <code>n</code> during the Legendre's <code>while</code> loop without affecting the final result.</p>
<h4 id="heading-code-2">Code</h4>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cmath&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;
<span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">isSquare</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    <span class="hljs-keyword">int</span> sq = <span class="hljs-built_in">sqrt</span>(n);
    <span class="hljs-keyword">return</span> sq * sq == n;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">numSquares</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    <span class="hljs-keyword">if</span> (isSquare(n)) {
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    }
    <span class="hljs-comment">// Legendre's three-square theorem</span>
    <span class="hljs-keyword">while</span> (n % <span class="hljs-number">4</span> == <span class="hljs-number">0</span>) {
        n /= <span class="hljs-number">4</span>;
    }
    <span class="hljs-keyword">if</span> (n % <span class="hljs-number">8</span> == <span class="hljs-number">7</span>) {
        <span class="hljs-keyword">return</span> <span class="hljs-number">4</span>;
    }
    <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> sq = <span class="hljs-built_in">sqrt</span>(n);
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= sq; i++) {
        <span class="hljs-keyword">if</span> (isSquare(n - i*i)) {
            <span class="hljs-keyword">return</span> <span class="hljs-number">2</span>;
        }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-number">3</span>;
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">cout</span> &lt;&lt; numSquares(<span class="hljs-number">12</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">cout</span> &lt;&lt; numSquares(<span class="hljs-number">13</span>) &lt;&lt; <span class="hljs-built_in">endl</span>;
}
</code></pre>
<pre><code class="lang-plaintext">Output:
3
2
</code></pre>
<h4 id="heading-complexity-2">Complexity</h4>
<ul>
<li><p>Runtime: <code>O(logn)</code>.</p>
</li>
<li><p>Extra space: <code>O(1)</code>.</p>
</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<ul>
<li><p>The title of this coding challenge (<em>Perfect squares</em>) gives you a hint it is more about mathematics than coding technique.</p>
</li>
<li><p>It is amazing from Lagrange's Four-Square Theorem there are only four possibilities for the answer to the problem. Not many people knowing it.</p>
</li>
<li><p>You can get an optimal solution to a coding problem when you know something about the mathematics behind it.</p>
</li>
</ul>
<p>Hope you learn something from this code challenge.</p>
<p><em>Have fun with coding and mathematics!</em></p>
<hr />
<p><em>Thanks for reading. Feel free to share your thought about my content and check out my FREE book</em> <a target="_blank" href="https://store.nhutnguyen.com/l/10_classic"><em>10 Classic Coding Challenges</em></a><em>.</em></p>
<p><em>What is your approach? The problem was picked from</em> <a target="_blank" href="https://leetcode.com/problems/perfect-squares/"><em>leetcode.com</em></a><em>. You can submit your solution in any programming language and check the performance.</em></p>
]]></content:encoded></item></channel></rss>