<?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[Blake's LeetCode Diary]]></title><description><![CDATA[Blake's LeetCode Diary]]></description><link>https://lc.sweezy.io</link><generator>RSS for Node</generator><lastBuildDate>Fri, 17 Apr 2026 11:12:04 GMT</lastBuildDate><atom:link href="https://lc.sweezy.io/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Weekly Contest 415]]></title><description><![CDATA[Q1: The Two Sneaky Numbers of Digitville
In the town of Digitville, there was a list of numbers called nums containing integers from 0 to n - 1. Each number was supposed to appear exactly once in the list, however, two mischievous numbers sneaked in ...]]></description><link>https://lc.sweezy.io/weekly-contest-415</link><guid isPermaLink="true">https://lc.sweezy.io/weekly-contest-415</guid><category><![CDATA[weekly contest]]></category><dc:creator><![CDATA[Blake Sweezy]]></dc:creator><pubDate>Sun, 15 Sep 2024 03:46:30 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-q1-the-two-sneaky-numbers-of-digitville">Q1: The Two Sneaky Numbers of Digitville</h2>
<p>In the town of Digitville, there was a list of numbers called <code>nums</code> containing integers from <code>0</code> to <code>n - 1</code>. Each number was supposed to appear <strong>exactly once</strong> in the list, however, <strong>two</strong> mischievous numbers sneaked in an <em>additional time</em>, making the list longer than usual.</p>
<p>As the town detective, your task is to find these two sneaky numbers. Return an array of size <strong>two</strong> containing the two numbers (in <em>any order</em>), so peace can return to Digitville.</p>
<h3 id="heading-thoughts">Thoughts</h3>
<ul>
<li>seems pretty simple, i think i’ll just use a hashset or something</li>
</ul>
<h3 id="heading-solution">Solution</h3>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span>[] getSneakyNumbers(<span class="hljs-keyword">int</span>[] nums) {
        HashSet&lt;Integer&gt; hs = <span class="hljs-keyword">new</span> HashSet();
        <span class="hljs-keyword">int</span>[] ans = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">2</span>];
        <span class="hljs-keyword">int</span> ansNum = <span class="hljs-number">0</span>;

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i : nums) {
            <span class="hljs-keyword">if</span> (!hs.add(i)) {
                ans[ansNum] = i;
                ansNum++;
                <span class="hljs-keyword">if</span> (ansNum == <span class="hljs-number">2</span>) <span class="hljs-keyword">return</span> ans;
            } 
        }
        <span class="hljs-keyword">return</span> ans;
    }
}
</code></pre>
<p><strong>Time Complexity:</strong> O(n)<br /><strong>Space Complexity:</strong> O(n)</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>ezpz hashset solution. I think there may be a better way though.</p>
<h2 id="heading-q2-maximum-multiplication-score">Q2: Maximum Multiplication Score</h2>
<p>You are given an integer array <code>a</code> of size 4 and another integer array <code>b</code> of size <strong>at least</strong> 4.</p>
<p>You need to choose 4 indices <code>i&lt;sub&gt;0&lt;/sub&gt;</code>, <code>i&lt;sub&gt;1&lt;/sub&gt;</code>, <code>i&lt;sub&gt;2&lt;/sub&gt;</code>, and <code>i&lt;sub&gt;3&lt;/sub&gt;</code> from the array <code>b</code> such that <code>i&lt;sub&gt;0&lt;/sub&gt; &lt; i&lt;sub&gt;1&lt;/sub&gt; &lt; i&lt;sub&gt;2&lt;/sub&gt; &lt; i&lt;sub&gt;3&lt;/sub&gt;</code>. Your score will be equal to the value <code>a[0] * b[i&lt;sub&gt;0&lt;/sub&gt;] + a[1] * b[i&lt;sub&gt;1&lt;/sub&gt;] + a[2] * b[i&lt;sub&gt;2&lt;/sub&gt;] + a[3] * b[i&lt;sub&gt;3&lt;/sub&gt;]</code>.</p>
<p>Return the <strong>maximum</strong> score you can achieve.</p>
<h3 id="heading-thoughts-1">Thoughts</h3>
<ul>
<li>best solution i could come up with was a brute force, I’m almost certain there is a way to do this with dynamic programming</li>
</ul>
<h3 id="heading-solution-1">Solution</h3>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">long</span> <span class="hljs-title">maxScore</span><span class="hljs-params">(<span class="hljs-keyword">int</span>[] a, <span class="hljs-keyword">int</span>[] b)</span> </span>{
        <span class="hljs-keyword">long</span> ans = Long.MIN_VALUE;
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; b.length - <span class="hljs-number">3</span>; i++) {
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = i + <span class="hljs-number">1</span>; j &lt; b.length - <span class="hljs-number">2</span>; j++) {
                <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> k = j + <span class="hljs-number">1</span>; k &lt; b.length - <span class="hljs-number">1</span>; k++) {
                    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> l = k + <span class="hljs-number">1</span>; l &lt; b.length; l++) {
                        <span class="hljs-keyword">long</span> temp = a[<span class="hljs-number">0</span>] * b[i] + a[<span class="hljs-number">1</span>] * b[j] + a[<span class="hljs-number">2</span>] * b[k] + a[<span class="hljs-number">3</span>] * b[l];
                        <span class="hljs-keyword">if</span> (Long.compare(temp,ans) &gt; <span class="hljs-number">0</span>) ans = temp;
                    }
                }
            }
        }

        <span class="hljs-keyword">return</span> ans;
    }
}
</code></pre>
<p><strong>Time Complexity:</strong> O(n^4)<br /><strong>Space Complexity:</strong> O(1)</p>
<h3 id="heading-conclusion-1">Conclusion</h3>
<p>Definitely should learn some more dynamic programming because this is (I think) a dynamic programming problem and my brute force solution is too slow to complete all of the test cases.</p>
<h1 id="heading-overall-conclusion">Overall Conclusion</h1>
<p>Yea I really need to work on my DP knowledge, otherwise I am going to keep hitting performance walls like this.</p>
]]></content:encoded></item><item><title><![CDATA[191. Number of 1 Bits]]></title><description><![CDATA[Write a function that takes the binary representation of a positive integer and returns the number of set bits it has (also known as the Hamming weight).
Thoughts

This one is basically identical to 2220 kekw

Solution
class Solution {
    public int...]]></description><link>https://lc.sweezy.io/191</link><guid isPermaLink="true">https://lc.sweezy.io/191</guid><category><![CDATA[bit-manipulation]]></category><dc:creator><![CDATA[Blake Sweezy]]></dc:creator><pubDate>Wed, 11 Sep 2024 03:41:03 GMT</pubDate><content:encoded><![CDATA[<p>Write a function that takes the binary representation of a positive integer and returns the number of set bits it has (also known as the <a target="_blank" href="http://en.wikipedia.org/wiki/Hamming_weight">Hamming weight</a>).</p>
<h3 id="heading-thoughts">Thoughts</h3>
<ul>
<li>This one is basically identical to <a target="_blank" href="https://lc.sweezy.io/2220">2220</a> kekw</li>
</ul>
<h3 id="heading-solution">Solution</h3>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">hammingWeight</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
        <span class="hljs-keyword">return</span> Integer.bitCount(n);
    }
}
</code></pre>
<p><strong>Time Complexity:</strong> O(1)<br /><strong>Space Complexity:</strong> O(1)</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>umm, these bit manipulation ones are pretty easy. I suppose I should find a way to calculate this myself and not use a built in function to do it. I can see providing this answer in an interview and being asked to provide a correct answer to it.</p>
]]></content:encoded></item><item><title><![CDATA[2220. Minimum Bit Flips to Convert Number]]></title><description><![CDATA[A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0.

For example, for x = 7, the binary representation is 111 and we may choose any bit (including any leading zeros not shown) and...]]></description><link>https://lc.sweezy.io/2220</link><guid isPermaLink="true">https://lc.sweezy.io/2220</guid><category><![CDATA[bit-manipulation]]></category><dc:creator><![CDATA[Blake Sweezy]]></dc:creator><pubDate>Wed, 11 Sep 2024 03:18:32 GMT</pubDate><content:encoded><![CDATA[<p>A <strong>bit flip</strong> of a number <code>x</code> is choosing a bit in the binary representation of <code>x</code> and <strong>flipping</strong> it from either <code>0</code> to <code>1</code> or <code>1</code> to <code>0</code>.</p>
<ul>
<li>For example, for <code>x = 7</code>, the binary representation is <code>111</code> and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get <code>110</code>, flip the second bit from the right to get <code>101</code>, flip the fifth bit from the right (a leading zero) to get <code>10111</code>, etc.</li>
</ul>
<p>Given two integers <code>start</code> and <code>goal</code>, return <em>the</em> <strong><em>minimum</em></strong> <em>number of</em> <strong><em>bit flips</em></strong> <em>to convert</em> <code>start</code> <em>to</em> <code>goal</code>.</p>
<h3 id="heading-thoughts">Thoughts</h3>
<ul>
<li>I accidentally solved this one before I even had a chance to write down my thoughts about it 💀</li>
</ul>
<h3 id="heading-solution">Solution</h3>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">minBitFlips</span><span class="hljs-params">(<span class="hljs-keyword">int</span> start, <span class="hljs-keyword">int</span> goal)</span> </span>{
        <span class="hljs-keyword">return</span> Integer.bitCount(start ^ goal);
    }
}
</code></pre>
<p><strong>Time Complexity:</strong> O(1)<br /><strong>Space Complexity:</strong> O(1)</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Idek what to say about this one it was so simple 💀</p>
]]></content:encoded></item><item><title><![CDATA[104. Maximum Depth of Binary Tree]]></title><description><![CDATA[Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Thoughts

As with a lot of tree algorithms I think the best solu...]]></description><link>https://lc.sweezy.io/104</link><guid isPermaLink="true">https://lc.sweezy.io/104</guid><category><![CDATA[Tree]]></category><category><![CDATA[Depth First Search]]></category><category><![CDATA[Breadth First Search]]></category><category><![CDATA[binary tree]]></category><dc:creator><![CDATA[Blake Sweezy]]></dc:creator><pubDate>Sat, 07 Sep 2024 20:50:14 GMT</pubDate><content:encoded><![CDATA[<p>Given the <code>root</code> of a binary tree, return <em>its maximum depth</em>.</p>
<p>A binary tree's <strong>maximum depth</strong> is the number of nodes along the longest path from the root node down to the farthest leaf node.</p>
<h3 id="heading-thoughts">Thoughts</h3>
<ul>
<li>As with a lot of tree algorithms I think the best solution here is to use a recursive algorithm to count while traversing down the tree</li>
</ul>
<h3 id="heading-solution">Solution</h3>
<pre><code class="lang-java"><span class="hljs-comment">/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">maxDepth</span><span class="hljs-params">(TreeNode root)</span> </span>{
        <span class="hljs-keyword">if</span> (root == <span class="hljs-keyword">null</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;

        <span class="hljs-keyword">return</span> Math.max(maxDepth(root.left) + <span class="hljs-number">1</span>, maxDepth(root.right) + <span class="hljs-number">1</span>);
    }
}
</code></pre>
<p><strong>Time Complexity:</strong> O(n)<br /><strong>Space Complexity:</strong> O(1)</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Wow. This was much easier than I was thinking it would be lmao. I forgot just how easy this was. Still good review and gets me in a tree-thinking mindset.</p>
]]></content:encoded></item><item><title><![CDATA[226. Invert Binary Tree]]></title><description><![CDATA[Given the root of a binary tree, invert the tree, and return its root.
Thoughts

Seems like a pretty simple problem, I would imagine that doing this recursively would be the easiest way to go about it

Simply swap the left and right nodes, then recur...]]></description><link>https://lc.sweezy.io/226</link><guid isPermaLink="true">https://lc.sweezy.io/226</guid><category><![CDATA[Tree]]></category><category><![CDATA[Depth First Search]]></category><category><![CDATA[Breadth First Search]]></category><category><![CDATA[binary tree]]></category><dc:creator><![CDATA[Blake Sweezy]]></dc:creator><pubDate>Sat, 07 Sep 2024 20:42:00 GMT</pubDate><content:encoded><![CDATA[<p>Given the <code>root</code> of a binary tree, invert the tree, and return <em>its root</em>.</p>
<h3 id="heading-thoughts">Thoughts</h3>
<ul>
<li><p>Seems like a pretty simple problem, I would imagine that doing this recursively would be the easiest way to go about it</p>
<ul>
<li>Simply swap the left and right nodes, then recursively swap the child node's left and right nodes</li>
</ul>
</li>
</ul>
<h3 id="heading-solution">Solution</h3>
<pre><code class="lang-java"><span class="hljs-comment">/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> TreeNode <span class="hljs-title">invertTree</span><span class="hljs-params">(TreeNode root)</span> </span>{
        <span class="hljs-comment">// Handle null case</span>
        <span class="hljs-keyword">if</span> (root == <span class="hljs-keyword">null</span>) <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;

        <span class="hljs-comment">// Recursively swap the left and right nodes</span>
        <span class="hljs-keyword">if</span> (root.left != <span class="hljs-keyword">null</span> &amp;&amp; root.right != <span class="hljs-keyword">null</span>) {
            TreeNode temp = root.right;
            root.right = root.left;
            root.left = temp;
            invertTree(root.left);
            invertTree(root.right);
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (root.left == <span class="hljs-keyword">null</span>) {
            root.left = root.right;
            root.right = <span class="hljs-keyword">null</span>;
            invertTree(root.left);
        } <span class="hljs-keyword">else</span> {
            root.right = root.left;
            root.left = <span class="hljs-keyword">null</span>;
            invertTree(root.right);
        }

        <span class="hljs-keyword">return</span> root;
    }
}
</code></pre>
<p><strong>Time Complexity:</strong> O(n)<br /><strong>Space Complexity:</strong> O(n)</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Pretty simple algorithm to implement and understand, good refresher on tree stuff. My space complexity is O(n) and I feel like there is a more space efficient algorithm to complete the task. I will revisit this problem in the future and try to devise a better algorithm.</p>
]]></content:encoded></item><item><title><![CDATA[206. Reverse Linked List]]></title><description><![CDATA[Given the head of a singly linked list, reverse the list, and return the reversed list.
Thoughts

Pretty easy, simple as iterating through the list and building the list in reverse order

Solution
/**
 * Definition for singly-linked list.
 * public c...]]></description><link>https://lc.sweezy.io/206</link><guid isPermaLink="true">https://lc.sweezy.io/206</guid><category><![CDATA[linked list]]></category><category><![CDATA[Recursion]]></category><dc:creator><![CDATA[Blake Sweezy]]></dc:creator><pubDate>Sat, 31 Aug 2024 16:38:06 GMT</pubDate><content:encoded><![CDATA[<p>Given the <code>head</code> of a singly linked list, reverse the list, and return <em>the reversed list</em>.</p>
<h3 id="heading-thoughts">Thoughts</h3>
<ul>
<li>Pretty easy, simple as iterating through the list and building the list in reverse order</li>
</ul>
<h3 id="heading-solution">Solution</h3>
<pre><code class="lang-java"><span class="hljs-comment">/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> ListNode <span class="hljs-title">reverseList</span><span class="hljs-params">(ListNode head)</span> </span>{
        ListNode cur = head;
        ListNode newList = <span class="hljs-keyword">null</span>;
        <span class="hljs-keyword">while</span> (cur != <span class="hljs-keyword">null</span>) {
            <span class="hljs-keyword">if</span> (newList == <span class="hljs-keyword">null</span>) {
                newList = <span class="hljs-keyword">new</span> ListNode(cur.val);
            } <span class="hljs-keyword">else</span> {
                ListNode newNode = <span class="hljs-keyword">new</span> ListNode(cur.val, newList);
                newList = newNode;
            }
            cur = cur.next;
        }
        <span class="hljs-keyword">return</span> newList;
    }
}
</code></pre>
<p><strong>Time Complexity:</strong> O(n)<br /><strong>Space Complexity:</strong> O(n)</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Pretty simple, but its good to brush up on concepts I haven't used in a while. I honestly can't remember the last time I had to manipulate a linked list so this was a nice refresher on that. Definitely need to work on some of the more complex linked list topics though.</p>
]]></content:encoded></item><item><title><![CDATA[74. Search a 2D Matrix]]></title><description><![CDATA[You are given an m x n integer matrix matrix with the following two properties:

Each row is sorted in non-decreasing order.

The first integer of each row is greater than the last integer of the previous row.


Given an integer target, return true i...]]></description><link>https://lc.sweezy.io/74</link><guid isPermaLink="true">https://lc.sweezy.io/74</guid><category><![CDATA[array]]></category><category><![CDATA[binary search]]></category><category><![CDATA[Matrix]]></category><dc:creator><![CDATA[Blake Sweezy]]></dc:creator><pubDate>Sat, 31 Aug 2024 06:21:45 GMT</pubDate><content:encoded><![CDATA[<p>You are given an <code>m x n</code> integer matrix <code>matrix</code> with the following two properties:</p>
<ul>
<li><p>Each row is sorted in non-decreasing order.</p>
</li>
<li><p>The first integer of each row is greater than the last integer of the previous row.</p>
</li>
</ul>
<p>Given an integer <code>target</code>, return <code>true</code> <em>if</em> <code>target</code> <em>is in</em> <code>matrix</code> <em>or</em> <code>false</code> <em>otherwise</em>.</p>
<p>You must write a solution in <code>O(log(m * n))</code> time complexity.</p>
<h3 id="heading-thoughts">Thoughts</h3>
<ul>
<li><p>I think this should be as simple as performing a binary search on the last index of each row, and then binary searching within the correct row from there</p>
<ul>
<li><p>This should cut down on the number of searches made and achieve O(log m*n)</p>
</li>
<li><p>yea just two consecutive while loops seems to be the play here</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-solution">Solution</h3>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">searchMatrix</span><span class="hljs-params">(<span class="hljs-keyword">int</span>[][] matrix, <span class="hljs-keyword">int</span> target)</span> </span>{
        <span class="hljs-keyword">int</span> rowLow = <span class="hljs-number">0</span>, rowHigh = matrix.length - <span class="hljs-number">1</span>;
        <span class="hljs-keyword">int</span> colLow = <span class="hljs-number">0</span>, colHigh = matrix[<span class="hljs-number">0</span>].length - <span class="hljs-number">1</span>;
        <span class="hljs-keyword">int</span> row = <span class="hljs-number">0</span>;

        <span class="hljs-comment">// Binary search by the last element of the rows to find which row the target would be in</span>
        <span class="hljs-keyword">while</span> (rowLow &lt;= rowHigh) {
            <span class="hljs-keyword">int</span> rowMid = ((rowHigh - rowLow) / <span class="hljs-number">2</span>) + rowLow;
            <span class="hljs-keyword">if</span> (matrix[rowMid][matrix[rowMid].length - <span class="hljs-number">1</span>] &gt;= target) {
                <span class="hljs-keyword">if</span> (matrix[rowMid][matrix[rowMid].length - <span class="hljs-number">1</span>] == target) {
                    <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
                }
                row = rowMid;
            }

            <span class="hljs-keyword">if</span> (matrix[rowMid][matrix[rowMid].length - <span class="hljs-number">1</span>] &gt; target) {
                rowHigh = rowMid - <span class="hljs-number">1</span>;
            } <span class="hljs-keyword">else</span> {
                rowLow = rowMid + <span class="hljs-number">1</span>;
            }
        }

        <span class="hljs-comment">// Binary search within the rows to find (or not find) the target</span>
        <span class="hljs-keyword">while</span> (colLow &lt;= colHigh) {
            <span class="hljs-keyword">int</span> colMid = ((colHigh - colLow) / <span class="hljs-number">2</span>) + colLow;
            <span class="hljs-keyword">if</span> (matrix[row][colMid] == target) {
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
            }

            <span class="hljs-keyword">if</span> (matrix[row][colMid] &gt; target) {
                colHigh = colMid - <span class="hljs-number">1</span>;
            } <span class="hljs-keyword">else</span> {
                colLow = colMid + <span class="hljs-number">1</span>;
            }
        } 

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
    }
}
</code></pre>
<p><strong>Time Complexity:</strong> O(log m * n)<br /><strong>Space Complexity:</strong> O(1)</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>This one was much easier since I had just reviewed my binary search knowledge by doing <a target="_blank" href="https://lc.sweezy.io/704">704. Binary Search</a>. This was much more fun and interesting than just a regular binary search problem. I felt like my brain was more stimulated by this than 704. Overall though, I definitely still need to brush up on my data structures and algorithms knowledge. I can feel some of my knowledge there slipping away and I really would like to prevent that from happening.</p>
]]></content:encoded></item><item><title><![CDATA[704. Binary Search]]></title><description><![CDATA[Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime com...]]></description><link>https://lc.sweezy.io/704</link><guid isPermaLink="true">https://lc.sweezy.io/704</guid><category><![CDATA[array]]></category><category><![CDATA[binary search]]></category><dc:creator><![CDATA[Blake Sweezy]]></dc:creator><pubDate>Sat, 31 Aug 2024 05:46:58 GMT</pubDate><content:encoded><![CDATA[<p>Given an array of integers <code>nums</code> which is sorted in ascending order, and an integer <code>target</code>, write a function to search <code>target</code> in <code>nums</code>. If <code>target</code> exists, then return its index. Otherwise, return <code>-1</code>.</p>
<p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p>
<h3 id="heading-thoughts">Thoughts</h3>
<ul>
<li>I mean, this is just a binary search....... idk that I have many other thoughts on this :sob:</li>
</ul>
<h3 id="heading-solution">Solution</h3>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">search</span><span class="hljs-params">(<span class="hljs-keyword">int</span>[] nums, <span class="hljs-keyword">int</span> target)</span> </span>{
        <span class="hljs-comment">// Declare variables</span>
        <span class="hljs-keyword">int</span> h = nums.length - <span class="hljs-number">1</span>, l = <span class="hljs-number">0</span>;

        <span class="hljs-keyword">while</span> (l &lt;= h) {
            <span class="hljs-comment">// Calculate the midpoint given the previous highs and lows</span>
            <span class="hljs-keyword">int</span> curIndex = ((h - l) / <span class="hljs-number">2</span>) + l;

            <span class="hljs-keyword">if</span> (nums[curIndex] == target) {
                <span class="hljs-keyword">return</span> curIndex;
            }

            <span class="hljs-comment">// Set the highs and lows, excludes half of the data at a time for each iteration</span>
            <span class="hljs-keyword">if</span> (nums[curIndex] &gt; target) {
                h = curIndex - <span class="hljs-number">1</span>;
            } <span class="hljs-keyword">else</span> {
                l = curIndex + <span class="hljs-number">1</span>;
            }
        }

        <span class="hljs-keyword">return</span> -<span class="hljs-number">1</span>;
    }
}
</code></pre>
<p><strong>Time Complexity:</strong> O(log n)<br /><strong>Space Complexity:</strong> O(1)</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>This one took me embarrassingly long to get. It has been a long time since I have had to use binary search, so it took me a while to remember how to do it. (Clearly I should've done more thinking about the question before I actually started!) Now that I have refreshed on it though, I feel way better about my understanding of it now, so perhaps this wasn't a complete wash.</p>
]]></content:encoded></item><item><title><![CDATA[20. Valid Parentheses]]></title><description><![CDATA[Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:

Open brackets must be closed by the same type of brackets.

Open brackets must be closed in the cor...]]></description><link>https://lc.sweezy.io/20</link><guid isPermaLink="true">https://lc.sweezy.io/20</guid><category><![CDATA[string]]></category><category><![CDATA[stack]]></category><dc:creator><![CDATA[Blake Sweezy]]></dc:creator><pubDate>Sun, 18 Aug 2024 20:37:53 GMT</pubDate><content:encoded><![CDATA[<p>Given a string <code>s</code> containing just the characters <code>'('</code>, <code>')'</code>, <code>'{'</code>, <code>'}'</code>, <code>'['</code> and <code>']'</code>, determine if the input string is valid.</p>
<p>An input string is valid if:</p>
<ol>
<li><p>Open brackets must be closed by the same type of brackets.</p>
</li>
<li><p>Open brackets must be closed in the correct order.</p>
</li>
<li><p>Every close bracket has a corresponding open bracket of the same type.</p>
</li>
</ol>
<h3 id="heading-thoughts">Thoughts</h3>
<ul>
<li><p>My immediate thought is that this problem is possible with some weird recursion-y thing</p>
<ul>
<li><p>Although I imagine that this isn't super efficient as you have to perform many substring operations</p>
</li>
<li><p>nvm recursion is dumb for this</p>
</li>
</ul>
</li>
<li><p>I think a stack works better here</p>
</li>
</ul>
<h3 id="heading-solution">Solution</h3>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">isValid</span><span class="hljs-params">(String s)</span> </span>{
        <span class="hljs-keyword">if</span> (s.length() &lt;= <span class="hljs-number">1</span>) <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
        Stack&lt;Character&gt; stack = <span class="hljs-keyword">new</span> Stack();

        <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">char</span> c = s.charAt(i);
            <span class="hljs-keyword">if</span> (c == <span class="hljs-string">'('</span> || c == <span class="hljs-string">'{'</span> || c == <span class="hljs-string">'['</span>) {
                stack.push(c);
            } <span class="hljs-keyword">else</span> {
                <span class="hljs-keyword">if</span> (stack.size() != <span class="hljs-number">0</span>) {
                    <span class="hljs-keyword">char</span> c2 = stack.peek();
                    <span class="hljs-keyword">if</span> (c == <span class="hljs-string">')'</span> &amp;&amp; c2 == <span class="hljs-string">'('</span>) stack.pop();
                    <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (c == <span class="hljs-string">'}'</span> &amp;&amp; c2 == <span class="hljs-string">'{'</span>) stack.pop();
                    <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (c == <span class="hljs-string">']'</span> &amp;&amp; c2 == <span class="hljs-string">'['</span>) stack.pop();
                    <span class="hljs-keyword">else</span> <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
                } <span class="hljs-keyword">else</span> <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;

            }
        }

        <span class="hljs-keyword">if</span> (stack.size() == <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
    }
}
</code></pre>
<p><strong>Time Complexity:</strong> O(n)<br /><strong>Space Complexity:</strong> O(n)</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>This took embarrassingly long for me to figure out for some reason. I definitely need to do more of these types of questions because the amount of time I just sank into this problem is simply ridiculous. Really the biggest part was actually accounting for the <em>invalid</em> cases, such as a string starting with a closing parenthesis or a string being only one parenthesis. Basically I need to work on better edge case detection when I am reading these questions and doing more thinking before I actually get started on writing my solutions.</p>
]]></content:encoded></item><item><title><![CDATA[885. Spiral Matrix III]]></title><description><![CDATA[You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.
You will walk in a clockwise spiral shape to visit eve...]]></description><link>https://lc.sweezy.io/885</link><guid isPermaLink="true">https://lc.sweezy.io/885</guid><category><![CDATA[array]]></category><category><![CDATA[Matrix]]></category><category><![CDATA[simulation]]></category><dc:creator><![CDATA[Blake Sweezy]]></dc:creator><pubDate>Thu, 08 Aug 2024 20:38:41 GMT</pubDate><content:encoded><![CDATA[<p>You start at the cell <code>(rStart, cStart)</code> of an <code>rows x cols</code> grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.</p>
<p>You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all <code>rows * cols</code> spaces of the grid.</p>
<p>Return <em>an array of coordinates representing the positions of the grid in the order you visited them</em>.</p>
<h3 id="heading-thoughts">Thoughts</h3>
<ul>
<li><p>Immediately I wanted to create a 2D array for some reason, but I don't think that is necessary to actually solve this problem</p>
</li>
<li><p>this seems relatively straight forward, just have to keep track of which cells are actually part of the grid</p>
</li>
<li><p>testing for completion is probably as simple as checking that you have visited <code>rows * cols</code> cells</p>
</li>
<li><p>i think using placeholder variables that keep track of the last horizontal and vertical distances traveled before turning would be the way to go, and then just checking along the way that the current indices are within the bounds of the rows and columns of the grid</p>
</li>
</ul>
<h3 id="heading-solution">Solution</h3>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span>[][] spiralMatrixIII(<span class="hljs-keyword">int</span> rows, <span class="hljs-keyword">int</span> cols, <span class="hljs-keyword">int</span> rStart, <span class="hljs-keyword">int</span> cStart) {
        <span class="hljs-keyword">int</span>[][] coords = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[rows * cols][<span class="hljs-number">2</span>];
        <span class="hljs-keyword">int</span> curRow = rStart;
        <span class="hljs-keyword">int</span> curCol = cStart;
        <span class="hljs-keyword">int</span> lastHorizontal = <span class="hljs-number">0</span>;
        <span class="hljs-keyword">int</span> lastVertical = <span class="hljs-number">0</span>;
        <span class="hljs-keyword">int</span> curCoord = <span class="hljs-number">0</span>;

        coords[curCoord] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[]{rStart, cStart};
        curCoord++;

        <span class="hljs-keyword">while</span> (curCoord &lt; rows * cols) {
            <span class="hljs-comment">// Right</span>
            lastHorizontal++;
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; lastHorizontal; i++) {
                curCol++;
                <span class="hljs-keyword">if</span> ((curRow &lt; rows &amp;&amp; curRow &gt;= <span class="hljs-number">0</span>) &amp;&amp; (curCol &lt; cols &amp;&amp; curCol &gt;= <span class="hljs-number">0</span>)) {
                    coords[curCoord] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[]{curRow, curCol};
                    curCoord++;
                }
            }

            <span class="hljs-comment">// Down</span>
            lastVertical++;
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; lastVertical; i++) {
                curRow++;
                <span class="hljs-keyword">if</span> ((curRow &lt; rows &amp;&amp; curRow &gt;= <span class="hljs-number">0</span>) &amp;&amp; (curCol &lt; cols &amp;&amp; curCol &gt;= <span class="hljs-number">0</span>)) {
                    coords[curCoord] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[]{curRow, curCol};
                    curCoord++;
                }
            }

            <span class="hljs-comment">// Left</span>
            lastHorizontal++;
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; lastHorizontal; i++) {
                curCol--;
                <span class="hljs-keyword">if</span> ((curRow &lt; rows &amp;&amp; curRow &gt;= <span class="hljs-number">0</span>) &amp;&amp; (curCol &lt; cols &amp;&amp; curCol &gt;= <span class="hljs-number">0</span>)) {
                    coords[curCoord] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[]{curRow, curCol};
                    curCoord++;
                }
            }

            <span class="hljs-comment">// Up</span>
            lastVertical++;
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; lastVertical; i++) {
                curRow--;
                <span class="hljs-keyword">if</span> ((curRow &lt; rows &amp;&amp; curRow &gt;= <span class="hljs-number">0</span>) &amp;&amp; (curCol &lt; cols &amp;&amp; curCol &gt;= <span class="hljs-number">0</span>)) {
                    coords[curCoord] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[]{curRow, curCol};
                    curCoord++;
                }
            }
        }

        <span class="hljs-keyword">return</span> coords;
    }
}
</code></pre>
<p><strong>Time Complexity:</strong> O(<code>rows * columns</code>) == O(n)<br /><strong>Space Complexity:</strong> O(<code>rows * columns</code>)</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>This was actually a really fun problem in my opinion. The solution was pretty straightforward and I was able to get it implemented fairly quickly, it just took some debugging because of some silly errors. Like for when I was traversing left/right I was actually moving up/down, and vice-versa, and it took a while for me to figure that out. Overall though this problem was actually really fun.</p>
]]></content:encoded></item><item><title><![CDATA[49. Group Anagrams]]></title><description><![CDATA[Given an array of strings strs, group the anagrams together. You can return the answer in any order.
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 once...]]></description><link>https://lc.sweezy.io/49</link><guid isPermaLink="true">https://lc.sweezy.io/49</guid><category><![CDATA[array]]></category><category><![CDATA[hash table]]></category><category><![CDATA[string]]></category><category><![CDATA[sorting]]></category><dc:creator><![CDATA[Blake Sweezy]]></dc:creator><pubDate>Thu, 08 Aug 2024 00:39:45 GMT</pubDate><content:encoded><![CDATA[<p>Given an array of strings <code>strs</code>, group <strong>the anagrams</strong> together. You can return the answer in <strong>any order</strong>.</p>
<p>An <strong>Anagram</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-thoughts">Thoughts</h3>
<ul>
<li><p>Probably can reuse at least part of my solution to 242: Valid Anagram</p>
<ul>
<li><p>I think there would be a way to use a HashMap as the key and a String list as the value</p>
</li>
<li><p>Use my solution for 242: Valid Anagram to gather keys on each word of the input, gradually adding them to the map, if the same character array exists, then add it to that list, otherwise its a new anagram</p>
<ul>
<li><p>SO turns out you can't use primitive arrays as keys because, since they are primitives, they don't refer to the same information if they were non-primitive. Primitive arrays with the same values are actually distinct memory from each other instead of how non-primitive objects function in that objects of the same type and value point to the same physical location in memory</p>
<ul>
<li>Because of this I had to figure out how to do some weird streaming stuff to convert the frequency array into a list</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="heading-solution">Solution</h3>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-keyword">public</span> List&lt;List&lt;String&gt;&gt; groupAnagrams(String[] strs) {
        Map&lt;List&lt;Integer&gt;, ArrayList&lt;String&gt;&gt; anas = <span class="hljs-keyword">new</span> HashMap&lt;List&lt;Integer&gt;, ArrayList&lt;String&gt;&gt;();

        <span class="hljs-keyword">for</span> (String s : strs) {
            <span class="hljs-comment">// Calculate letter frequency</span>
            <span class="hljs-keyword">int</span>[] freq = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">26</span>];
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">char</span> i : s.toCharArray()) {
                freq[i - <span class="hljs-number">97</span>]++;
            }
            <span class="hljs-comment">// Do some weird Stream stuff because int[]'s with the same values are not actually the same</span>
            List&lt;Integer&gt; t = IntStream.of(freq).boxed().collect(Collectors.toList());

            <span class="hljs-comment">// If the frequency table doesn't exist, create it, otherwise add to the existing table.</span>
            <span class="hljs-keyword">if</span> (!anas.containsKey(t)) {
                ArrayList&lt;String&gt; temp = <span class="hljs-keyword">new</span> ArrayList&lt;String&gt;();
                temp.add(s);
                anas.put(t, temp);
            } <span class="hljs-keyword">else</span> {
                ArrayList&lt;String&gt; temp = anas.get(t);
                temp.add(s);
                anas.put(t, temp);
            }
        }

        List&lt;List&lt;String&gt;&gt; ans = <span class="hljs-keyword">new</span> ArrayList&lt;List&lt;String&gt;&gt;();
        <span class="hljs-keyword">for</span> (ArrayList&lt;String&gt; a : anas.values()) {
            ans.add(a);
        }

        <span class="hljs-keyword">return</span> ans;
    }
}
</code></pre>
<p><strong>Time Complexity:</strong> O(n * <em>k</em>), where <em>k</em> is the average number of characters per string in the input<br /><strong>Space Complexity:</strong> O(n)</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>My solution was not fast, likely due in part to the weird streaming stuff I did to convert from an integer array to a List. I think there is definitely a better way to approach this problem considering that my solution is amount the slowest submissions. Overall not terrible for a problem though, it led to me reviewing some of the internal workings of Java as how it relates to arrays and primitives.</p>
]]></content:encoded></item><item><title><![CDATA[1. Two Sum]]></title><description><![CDATA[Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the a...]]></description><link>https://lc.sweezy.io/1</link><guid isPermaLink="true">https://lc.sweezy.io/1</guid><category><![CDATA[array]]></category><category><![CDATA[hash table]]></category><dc:creator><![CDATA[Blake Sweezy]]></dc:creator><pubDate>Wed, 07 Aug 2024 23:40:29 GMT</pubDate><content:encoded><![CDATA[<p>Given an array of integers <code>nums</code> and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to</em> <code>target</code>.</p>
<p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> element twice.</p>
<p>You can return the answer in any order.</p>
<h3 id="heading-thoughts">Thoughts</h3>
<ul>
<li><p>Immediately I know that this is possible using nested for-loops, but that isn't an efficient solution as it achieves an O(n²) runtime complexity</p>
<ul>
<li><p>I will implement it like this anyway before trying to optimize</p>
<ul>
<li><pre><code class="lang-java">  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
      <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span>[] twoSum(<span class="hljs-keyword">int</span>[] nums, <span class="hljs-keyword">int</span> target) {
          <span class="hljs-keyword">int</span>[] ans = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">2</span>];
          <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; nums.length; i++) {
              <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; nums.length; j++) {
                  <span class="hljs-keyword">if</span> (j == i) <span class="hljs-keyword">continue</span>;
                  <span class="hljs-keyword">if</span> (nums[i] + nums[j] == target) {
                      ans[<span class="hljs-number">0</span>] = i;
                      ans[<span class="hljs-number">1</span>] = j;
                  }
              }
          }
          <span class="hljs-keyword">return</span> ans;
      }
  }
</code></pre>
</li>
<li><p>Almost certain there is a faster way</p>
</li>
</ul>
</li>
</ul>
</li>
<li><p>I think using a Map would potentially be a good way to do this</p>
<ul>
<li>It would take O(n) to add all of the numbers to a Map, then another O(n) to find the correct other term, so overall O(n)</li>
</ul>
</li>
</ul>
<h3 id="heading-solution">Solution</h3>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span>[] twoSum(<span class="hljs-keyword">int</span>[] nums, <span class="hljs-keyword">int</span> target) {
        Map&lt;Integer, Integer&gt; newNums = <span class="hljs-keyword">new</span> HashMap&lt;Integer, Integer&gt;();
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; nums.length; i++) {
            newNums.put(nums[i], i);
        }

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; nums.length; i++) {
            <span class="hljs-keyword">if</span> (newNums.getOrDefault(target - nums[i], -<span class="hljs-number">1</span>) != -<span class="hljs-number">1</span>) {
                <span class="hljs-keyword">if</span> (i == newNums.get(target - nums[i])) <span class="hljs-keyword">continue</span>;
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[]{i, newNums.get(target - nums[i])};
            }
        }

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">2</span>];
    }
}
</code></pre>
<p><strong>Time Complexity:</strong> O(n)<br /><strong>Space Complexity:</strong> O(n)</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Finally completed the infamous Two Sum. These are the types of problems that I like, where there is a really simple solution that is immediately obvious, but there are more complex solutions that are much better in a variety of ways.</p>
]]></content:encoded></item><item><title><![CDATA[3016. Minimum Number of Pushes to Type Word II]]></title><description><![CDATA[You are given a string word containing lowercase English letters.
Telephone keypads have keys mapped with distinct collections of lowercase English letters, which can be used to form words by pushing them. For example, the key 2 is mapped with ["a","...]]></description><link>https://lc.sweezy.io/3016</link><guid isPermaLink="true">https://lc.sweezy.io/3016</guid><category><![CDATA[hash table]]></category><category><![CDATA[string]]></category><category><![CDATA[greedy]]></category><category><![CDATA[sorting]]></category><category><![CDATA[counting]]></category><dc:creator><![CDATA[Blake Sweezy]]></dc:creator><pubDate>Tue, 06 Aug 2024 19:48:59 GMT</pubDate><content:encoded><![CDATA[<p>You are given a string <code>word</code> containing lowercase English letters.</p>
<p>Telephone keypads have keys mapped with <strong>distinct</strong> collections of lowercase English letters, which can be used to form words by pushing them. For example, the key <code>2</code> is mapped with <code>["a","b","c"]</code>, we need to push the key one time to type <code>"a"</code>, two times to type <code>"b"</code>, and three times to type <code>"c"</code> .</p>
<p>It is allowed to remap the keys numbered <code>2</code> to <code>9</code> to <strong>distinct</strong> collections of letters. The keys can be remapped to <strong>any</strong> amount of letters, but each letter <strong>must</strong> be mapped to <strong>exactly</strong> one key. You need to find the <strong>minimum</strong> number of times the keys will be pushed to type the string <code>word</code>.</p>
<p>Return <em>the</em> <strong><em>minimum</em></strong> <em>number of pushes needed to type</em> ​<code>word</code> ​<em>after remapping the keys</em>.</p>
<h3 id="heading-thoughts">Thoughts</h3>
<ul>
<li><p>Immediately before I even finished reading I am thinking this may involve a greedy algorithm</p>
<ul>
<li>definitely a greedy problem</li>
</ul>
</li>
<li><p>need to represent the keypad, an array would work</p>
</li>
<li><p>if there are less than 8 unique letters in the word, the obvious solution is to just remap all of the keys to have one of the less than 8 letters</p>
<ul>
<li><p>the harder solution is when there is more than 8 characters that need to be mapped, in this case looking at the character frequency matters (I think) because you don't want to have to make multiple presses for a character you need a lot</p>
<ul>
<li>like in example 3: the word is <code>aabbccddeeffgghhiiiiii</code>, so obviously you want <code>i</code> to be the first letter on a key so that you don't have to double push to get to <code>i</code> every time</li>
</ul>
</li>
<li><p>I think that the best solution would be to sort the characters by their frequency within the word, and then just remap the keys with those characters in descending order</p>
</li>
</ul>
</li>
<li><p>was stumped for a while, but I think the solution is to disregard what the letters actually are after calculating the frequencies. I was getting too bogged down with trying to associate the specific letters with their specific frequencies, when really the specific letters don't matter, what matters is <em>a</em> letter has that frequency</p>
<ul>
<li>the solution now seems to be to calculate the frequencies using a map, and then sorting the values in a separate data structure, then iterating through them in descending order to remap the characters</li>
</ul>
</li>
</ul>
<h3 id="heading-solution">Solution</h3>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">minimumPushes</span><span class="hljs-params">(String word)</span> </span>{
        HashMap&lt;Character, Integer&gt; map = <span class="hljs-keyword">new</span> HashMap();
        <span class="hljs-keyword">int</span> pushes = <span class="hljs-number">0</span>;

        <span class="hljs-comment">// Add all characters to the map with their frequencies</span>
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">char</span> c : word.toCharArray()) {
            map.put(c, (map.containsKey(c) ? map.get(c) + <span class="hljs-number">1</span> : <span class="hljs-number">1</span>));
        }

        <span class="hljs-comment">// Sort the frequencies by descending order</span>
        ArrayList&lt;Integer&gt; arr = <span class="hljs-keyword">new</span> ArrayList(map.values());
        Collections.sort(arr, Collections.reverseOrder());

        <span class="hljs-comment">// Iterate through the frequencies, and sum the pushes</span>
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; arr.size(); i++) {
            <span class="hljs-keyword">int</span> key = (i / <span class="hljs-number">8</span>) + <span class="hljs-number">1</span>;
            pushes += key * arr.get(i);
        }

        <span class="hljs-keyword">return</span> pushes;
    }
}
</code></pre>
<p><strong>Time Complexity:</strong> O(n log n)<br /><strong>Space Complexity:</strong> O(n)</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>This one definitely took me a lot longer than it should have. I got too focused on the individual letters and their frequencies instead of just thinking about the frequencies as a whole. Because the specific frequency of <code>j</code> or <code>q</code> or <code>a</code> doesn't matter, what matters is the frequencies together since this problem is only asking about the <strong>number</strong> of pushes, not exactly how you would remap the keys. I should continue to work on similar problems to this so that I get more used to thinking in the correct way to see the answer.</p>
]]></content:encoded></item><item><title><![CDATA[2053. Kth Distinct String in an Array]]></title><description><![CDATA[A distinct string is a string that is present only once in an array.
Given an array of strings arr, and an integer k, return the kᵗʰ distinct string present in arr. If there are fewer than k distinct strings, return an empty string "".
Note that the ...]]></description><link>https://lc.sweezy.io/2053</link><guid isPermaLink="true">https://lc.sweezy.io/2053</guid><category><![CDATA[array]]></category><category><![CDATA[hash table]]></category><category><![CDATA[string]]></category><category><![CDATA[counting]]></category><dc:creator><![CDATA[Blake Sweezy]]></dc:creator><pubDate>Mon, 05 Aug 2024 20:17:46 GMT</pubDate><content:encoded><![CDATA[<p>A <strong>distinct string</strong> is a string that is present only <strong>once</strong> in an array.</p>
<p>Given an array of strings <code>arr</code>, and an integer <code>k</code>, return <em>the</em> <code>kᵗʰ</code> <strong><em>distinct string</em></strong> <em>present in</em> <code>arr</code>. If there are <strong>fewer</strong> than <code>k</code> distinct strings, return <em>an</em> <strong><em>empty string</em></strong> <code>""</code>.</p>
<p>Note that the strings are considered in the <strong>order in which they appear</strong> in the array.</p>
<h3 id="heading-thoughts">Thoughts</h3>
<ul>
<li><p>Definitely something with a hash table or map</p>
</li>
<li><p>ordering is important here to get the kth distinct</p>
</li>
<li><p>java's <code>LinkedHashMap</code> might be a good solution here as it is a hash map which allows for faster checking of duplicates via <code>contains()</code> while also maintaining the ordering of the elements</p>
<ul>
<li><p>googled and found that there is a <code>LinkedHashSet</code> as well, which is more applicable here since there is no need for storing any value</p>
</li>
<li><p>Problem with this solution is actually getting the kth entry, neither of these classes provide methods allowing for getting arbitrary indices</p>
<ul>
<li><p><code>LinkedHashSet</code> has <code>forEach()</code> which could be hacked together to get the correct entry I think</p>
<ul>
<li><p>can't break out of a lambda function, so <code>forEach()</code> might not be the solution here</p>
</li>
<li><p>can just set a temp variable equal to the correct index, the problem is that there is the problem of atomicity due to it being a lambda, although an <code>AtomicReference</code> would fix this</p>
</li>
<li><p>I make my life unnecessarily hard sometimes by doing things in silly ways</p>
<ul>
<li>(Also had to use <code>AtomicInteger</code> so that my temp variable worked)</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><p>First solution:</p>
<ul>
<li><pre><code class="lang-java">        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
            <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">kthDistinct</span><span class="hljs-params">(String[] arr, <span class="hljs-keyword">int</span> k)</span> </span>{
                LinkedHashSet&lt;String&gt; lhs = <span class="hljs-keyword">new</span> LinkedHashSet();
                <span class="hljs-keyword">for</span> (String s : arr) {
                    <span class="hljs-keyword">if</span> (!lhs.add(s)) {
                        lhs.remove(s);
                    }
                }

                AtomicInteger i = <span class="hljs-keyword">new</span> AtomicInteger(<span class="hljs-number">1</span>);
                AtomicReference&lt;String&gt; temp = <span class="hljs-keyword">new</span> AtomicReference(<span class="hljs-string">""</span>);
                lhs.forEach(s -&gt; {
                    System.out.println(s);
                    <span class="hljs-keyword">if</span> (i.intValue() == k) {
                        temp.set(s);
                    }
                    i.set(i.get() + <span class="hljs-number">1</span>);
                });

                <span class="hljs-keyword">return</span> temp.toString();
            }
        }
</code></pre>
</li>
<li><p>turns out this solution is flawed, as it allows for readding of duplicate entries back to the <code>LinkedHashSet</code> (ty ceru &lt;3)</p>
<ul>
<li>Ended up just adding another <code>LinkedHashSet</code> to it to contain duplicates, which I am pretty sure is not the optimal solution</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="heading-solution">Solution</h3>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">kthDistinct</span><span class="hljs-params">(String[] arr, <span class="hljs-keyword">int</span> k)</span> </span>{
        LinkedHashSet&lt;String&gt; lhs = <span class="hljs-keyword">new</span> LinkedHashSet();
        LinkedHashSet&lt;String&gt; olhs = <span class="hljs-keyword">new</span> LinkedHashSet();

        <span class="hljs-comment">// Iterate through arr, adding them to lhs if not a duplicate, olhs if they are        </span>
        <span class="hljs-keyword">for</span> (String s : arr) {
            <span class="hljs-keyword">if</span> (olhs.contains(s) || !lhs.add(s)) {
                lhs.remove(s);
                olhs.add(s);
            }
        }

        <span class="hljs-comment">// Using AtomicReferences here because of the lambda</span>
        AtomicInteger i = <span class="hljs-keyword">new</span> AtomicInteger(<span class="hljs-number">1</span>);
        AtomicReference&lt;String&gt; temp = <span class="hljs-keyword">new</span> AtomicReference(<span class="hljs-string">""</span>);
        lhs.forEach(s -&gt; {
            <span class="hljs-comment">// Iterate through all of the distinct values until finding the correct index</span>
            <span class="hljs-keyword">if</span> (i.intValue() == k) {
                temp.set(s);
            }
            i.set(i.get() + <span class="hljs-number">1</span>);
        });

        <span class="hljs-keyword">return</span> temp.toString();
    }
}
</code></pre>
<p><strong>Time Complexity:</strong> O(n)<br /><strong>Space Complexity:</strong> O(n)</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Overall this one was relatively easy once I determined how I wanted to go about it. I had to reference the Javadocs for both <code>LinkedHashSet</code> and <code>AtomicReference</code>/<code>AtomicInteger</code> as I had forgotten the specifics of how they worked. I am also pretty sure that there is a better solution than using two <code>LinkedHashSet</code>, perhaps using just a <code>LinkedHashMap</code> instead and using the values to keep track of duplicates. It also took me a while to figure out exactly how I wanted to go about this solving this problem, I think with more practice though, this should get better.</p>
]]></content:encoded></item></channel></rss>