<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sandy Yang on Medium]]></title>
        <description><![CDATA[Stories by Sandy Yang on Medium]]></description>
        <link>https://medium.com/@sandy.yang992?source=rss-8a2d734dd544------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*psFgbaX1MLeqsfVr</url>
            <title>Stories by Sandy Yang on Medium</title>
            <link>https://medium.com/@sandy.yang992?source=rss-8a2d734dd544------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:27:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sandy.yang992/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Thought on Data Privacy in AI]]></title>
            <link>https://medium.com/@sandy.yang992/thought-on-data-privacy-in-ai-cf10de944509?source=rss-8a2d734dd544------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf10de944509</guid>
            <category><![CDATA[ethical-ai]]></category>
            <category><![CDATA[localai]]></category>
            <category><![CDATA[data-privacy]]></category>
            <dc:creator><![CDATA[Sandy Yang]]></dc:creator>
            <pubDate>Tue, 22 Jul 2025 16:22:39 GMT</pubDate>
            <atom:updated>2025-07-22T16:22:39.376Z</atom:updated>
            <content:encoded><![CDATA[<p>Lately, I’ve noticed growing concern around data privacy in AI — and with good reason.</p><p>A recent report by MIT Technology Review revealed that personally identifiable information (PII) was found in DataComp CommonPool, a major AI training dataset used for image generation. The dataset was scraped from publicly available web data.</p><p>As a data analyst, I believe AI ethics is an increasingly critical issue — especially given the current uncertainty around regulation, with the U.S. recently pausing its efforts to legislate AI governance.</p><p>In response, I’ve been exploring local large language models (LLMs) that can run directly on a laptop. This approach provides greater control, improved privacy, and increased transparency. I highly recommend <a href="https://simonwillison.net/">Simon Willison’s blog</a> for insights on the topic. I’m also experimenting with <a href="https://ollama.com/">Ollama</a>, a promising tool that enables running LLMs locally and privately.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf10de944509" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Review & Explanation: 141. Linked List Cycle]]></title>
            <link>https://medium.com/@sandy.yang992/leetcode-review-explanation-141-linked-list-cycle-4d294b418b7f?source=rss-8a2d734dd544------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d294b418b7f</guid>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[two-pointers]]></category>
            <category><![CDATA[fast-and-slow-pointer]]></category>
            <dc:creator><![CDATA[Sandy Yang]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 15:28:52 GMT</pubDate>
            <atom:updated>2025-07-06T15:28:52.164Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’m going to break down a basic but foundational Linked List question on LeetCode. We’ll begin with a straightforward (but less efficient) approach, and later introduce a much faster and space-optimized solution.</p><h3>Problem Description</h3><p>Given a ListNode head, the head of a singly linked list, determine if the linked list contains a <strong>cycle</strong>.</p><blockquote><em>A cycle occurs if a node can be reached again by continuously following the </em><em>next pointer.<br> Internally, </em><em>pos is used to denote the index of the node that the tail connects to. However, </em><em>pos is not passed as a parameter in the function.</em></blockquote><p>Our task:</p><ul><li>Return true if there is a cycle in the linked list.</li><li>Return false otherwise.</li></ul><h3>Intuition</h3><p>The intuition is simple:</p><ul><li>Traverse the linked list node by node.</li><li>If encounter a visited node → return true.</li><li>If reach the end (null) → return false.</li></ul><p>In this approach, we use a HashSet to keep track of all nodes we’ve visited. Since nodes in Java are objects, we can store the reference of each node, and check whether we&#39;ve seen it before.</p><pre>public class Solution {<br>    public boolean hasCycle(ListNode head) {<br>        <br>        Set&lt;ListNode&gt; numSet = new HashSet&lt;&gt;();<br>        ListNode curr = head;<br>        <br>        while(curr!=null) {    <br><br>            if(numSet.contains(curr)){<br>                return true; // cycle detected<br>            } <br>            numSet.add(curr);<br>            curr = curr.next;<br>        }       <br>        return false; // no cycle<br>    }<br>}</pre><h3>Time &amp; Space Complexity</h3><ul><li><strong>Time Complexity:</strong> O(n)<br> In the worst case, We may have to visit all nodes once.</li><li><strong>Space Complexity:</strong> O(n)<br> We store up to n node references in the set.</li></ul><h3>Second Approach — Using 2 Pointer Method (Fast-Slow pointer)</h3><p>A faster approach will not require the extra space to save the information — which is, no need to create a visited. Instead, we will use<strong> fast and slow pointer (aka </strong>Floyd’s Cycle Detection Algorithm<strong>)</strong>, which contains O(1) space.</p><ul><li>A <strong>slow pointer</strong> (slow), which moves one step at a time.</li><li>A <strong>fast pointer</strong> (fast), which moves two steps at a time.</li></ul><h3>💡 Key Idea:</h3><ul><li>If there’s <strong>no cycle</strong>, fast will eventually reach the end (null).</li><li>If there <strong>is a cycle</strong>, fast and slow will eventually <strong>meet</strong> inside the cycle.</li></ul><pre>A → B → C → D → E → F<br>             ↑     ↓<br>             H ← G<br><br># Node F links back to node D, creating a cycle: D → E → F → G → H → D...</pre><p>If you want a better visual representation, I recommend watch <a href="https://www.youtube.com/watch?v=b139yf7Ik-E&amp;ab_channel=AlgoMasterIO">this video</a>. The channel also cover many basic DSA algorithms with clear visual set up!</p><h3>Code Below:</h3><pre>public class Solution {<br>    public boolean hasCycle(ListNode head) {<br>        ListNode slow = head;<br>        ListNode fast = head;<br><br>        while (fast != null &amp;&amp; fast.next != null) {<br>            slow = slow.next;           // 1 step<br>            fast = fast.next.next;      // 2 steps<br><br>            if (slow == fast) {<br>                return true; // cycle detected<br>            }<br>        }<br><br>        return false; // no cycle<br>    }<br>}</pre><p>In this case, the Time Complexity will be O(n) and Space Complexity will be O(1) — We didn’t use any extra element to get the job done! Yay!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d294b418b7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Review and Explanation: 3160. Find the Number of Distinct Colors Among the Balls]]></title>
            <link>https://medium.com/@sandy.yang992/leetcode-review-and-explanation-3160-find-the-number-of-distinct-colors-among-the-balls-4b8e3453ff59?source=rss-8a2d734dd544------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b8e3453ff59</guid>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[code-review]]></category>
            <dc:creator><![CDATA[Sandy Yang]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 09:10:15 GMT</pubDate>
            <atom:updated>2025-07-06T09:10:15.281Z</atom:updated>
            <content:encoded><![CDATA[<p>You are given an integer limit and a 2D array queries of size n x 2.</p><p>There are limit + 1 balls with <strong>distinct</strong> labels in the range [0, limit]. Initially, all balls are uncolored. For every query in queries that is of the form [x, y], you mark ball x with the color y. After each query, you need to find the number of colors among the balls.</p><p>Return an array result of length n, where result[i] denotes the number of colors <em>after</em> i query.</p><h3>Intuition</h3><ol><li>Use HashMap to record the current status of ball-color.</li><li>Count the unique color in the current Set.</li><li>Record the set.size() into output array.</li></ol><pre>public int[] queryResults(int limit, int[][] queries) {<br>        // ball num: color<br>        Map&lt;Integer, Integer&gt; map = new HashMap&lt;&gt;();<br>        int[] arr = new int[queries.length];<br><br>        for(int i=0; i&lt;queries.length; i++){<br>            int ball_num = queries[i][0];<br>            int color = queries[i][1];<br><br>            map.put(ball_num, color);<br>            Set&lt;Integer&gt; unique_color_set = new HashSet&lt;&gt;(map.values());<br>            arr[i] = unique_color_set.size();<br>        }<br>    <br>        return arr;<br>}</pre><p>The method work in the test case, yet, does not pass the Time Limit when entries getting large.</p><h3>Issue</h3><p>The issue with this solution is that we are <strong>recalculates the entire unique color set from scratch</strong> every time. Once the size of queries increase, the times for the computation will growth in <em>O(mXn)</em>, whereas m is the size of the set.</p><h3>Improvement</h3><p>The code above can be improved to O(m) . Instead of building a new set of count each time, we can <strong>keeps track of that count as we go</strong>, using two maps:</p><ul><li>One to remember each ball’s color</li><li>One to track how many balls are using each color</li></ul><pre>   public int[] queryResults(int limit, int[][] queries) {<br>        // ball num: color<br>        Map&lt;Integer, Integer&gt; ball_color = new HashMap&lt;&gt;();<br>        <br>        // color: counts of ball with this color<br>        Map&lt;Integer, Integer&gt; colorFreq = new HashMap&lt;&gt;();<br><br>        int[] arr = new int[queries.length];<br><br>        for(int i=0; i&lt;queries.length; i++){<br>            int ball_num = queries[i][0];<br>            int color = queries[i][1];<br>            <br>            if(ball_color.containsKey(ball_num)){<br>              int prev_color = ball_color.get(ball_num);<br>              colorFreq.put(prev_color,colorFreq.get(prev_color)-1);<br>              <br>               if(colorFreq.get(prev_color) == 0){<br>                  colorFreq.remove(prev_color);<br>               }<br>                  <br>            }<br>            colorFreq.put(color,  colorFreq.getOrDefault(color,0)+1);<br>            ball_color.put(ball_num, color);<br>            arr[i] = colorFreq.size();<br>        }<br>        return arr;<br>    }</pre><h3>Comparison</h3><p>Let’s compare our first and second solution. Honestly, the only difference is what inside the loop, where we replace:</p><pre>Set&lt;Integer&gt; unique_color_set = new HashSet&lt;&gt;(map.values());</pre><ul><li>map.values() → O(n) (n = number of balls painted so far)</li><li>new HashSet&lt;&gt;(...) → O(n), because it iterates through all values to remove duplicates</li></ul><p>with:</p><pre><br>if(ball_color.containsKey(ball_num)){<br>    int prev_color = ball_color.get(ball_num);<br>    colorFreq.put(prev_color,colorFreq.get(prev_color)-1);<br>                <br>    if(colorFreq.get(prev_color) == 0){<br>        colorFreq.remove(prev_color);<br>    }                  <br>}<br>colorFreq.put(color,  colorFreq.getOrDefault(color,0)+1);</pre><ul><li>put, get, and remove on HashMap → O(1)</li><li>colorFreq.size() → O(1)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b8e3453ff59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with Linked List]]></title>
            <link>https://medium.com/@sandy.yang992/dealing-with-linked-list-d242cd0bea98?source=rss-8a2d734dd544------2</link>
            <guid isPermaLink="false">https://medium.com/p/d242cd0bea98</guid>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[best-code-learning]]></category>
            <dc:creator><![CDATA[Sandy Yang]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 07:30:41 GMT</pubDate>
            <atom:updated>2025-07-06T07:30:41.470Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>This article is for beginners just starting to learn the basics of Data Structures and Algorithms (DSA).</strong></p><p>If you’re an intermediate-level coder looking for more advanced solutions on LeetCode, feel free to check out <a href="https://medium.com/@sandy.yang992/leetcode-review-explanation-80-remove-duplicates-from-sorted-array-ii-3ad6a40322c2">this article</a>, or explore other posts in my <strong>LeetCode Review</strong> series, where I dive deep into algorithms and their reasoning.</p><h3>Facing My Fear: Linked Lists</h3><p>I’ve always been afraid of linked lists.</p><p>For such a “basic” data structure, they’ve given me disproportionate anxiety — to the point that I lost sleep during college nights. The panic of constantly losing track of node references inside a while loop made me feel not just frustrated, but hopeless — like no company would ever want to hire someone who couldn&#39;t get this right.</p><p>Am I better now? Not really. I’m still terrified — like a rooster in a cab.</p><p>But fear doesn’t go away by running. Facing it is better than avoiding it. So here I am, finally dealing with the mess.</p><h3><strong>Basic</strong></h3><p>A linked list is a data structure made up of a sequence of nodes, where each node contains a value and a reference to the next node.</p><p>In Java, a linked list can be implemented using a Node class, where val represents the value stored in the node, and next is a reference to the next node in the list.</p><pre>public class Node {<br>    int val;         // data stored in the node<br>    Node next;       // reference to the next node<br><br>    // Constructor<br>    public Node(int val) {<br>        this.val = val;<br>        this.next = null;<br>    }<br>}</pre><h3>Basic Operation</h3><h4>Looping through Linked List</h4><p>When traversing a linked list, we typically use a pointer like curr to represent the node we’re currently at. As long as curr is not null, we move forward by updating curr to curr.next.</p><pre>curr = node1;   // node1 is usually given, representing the head node<br>length = 0;     // assume we want to count the length of linked list<br><br>while (curr != null) {<br>    curr = curr.next;<br>    length++;<br>}</pre><p>⚠️ A common mistake I made early on was writing while (curr.next != null) instead of while (curr != null).<br> That would miss the last node and throw off the logic. I was always tracking the <strong>next</strong> thing, instead of focusing on the <strong>current</strong> one.</p><h3>Deleting a Node by Position (From the End)</h3><p>Now we’re dealing with one of my personal nightmares (yes, this early on).<br> When deleting a node with a given target, you only need to know two things:</p><ol><li>the current node</li><li>the next node.</li></ol><h3>🧠 Understanding the Problem</h3><p>Let’s break it down:</p><ul><li>Suppose your list is: 1 → 2 → 3 → 4 → 5</li><li>If n = 2, you’re supposed to remove the <strong>2nd node from the end</strong>, which is 4.</li><li>After removal, the list should become: 1 → 2 → 3 → 5</li></ul><p>But here’s the catch:</p><blockquote>Because you <strong>can’t go backward</strong>, you don’t know how many nodes are ahead unless you first walk through the entire list.</blockquote><p>So how do we handle this?</p><h3>Two-Pass Strategy</h3><p>This is the simplest and most beginner-friendly way to approach it:</p><h4>🔹 First pass:</h4><p>Walk through the list to <strong>count how many nodes</strong> there are. This gives you the total length.</p><h4>🔹 Second pass:</h4><p>Figure out which node is just <strong>before</strong> the one you need to remove (at position length - n) and adjust its next pointer to <strong>skip</strong> the target node.</p><p>This is why understanding the concept of “current node” and “next node” is so important in linked lists — especially when deleting.</p><h4>Sample Code: Remove the N-th Node from the End (Two-Pass Approach)</h4><pre>public static ListNode removeNthLastNode(ListNode head, int n) {<br>    int length = 0;<br>    ListNode curr = head;<br>// First pass: count length<br>    while (curr != null) {<br>        length++;<br>        curr = curr.next;<br>    }<br>    // If we&#39;re removing the head<br>    if (n == length) {<br>        return head.next;<br>    }<br>    // Second pass: find (length - n)-th node<br>    int target = length - n;<br>    curr = head;<br>    for (int i = 1; i &lt; target; i++) {<br>        curr = curr.next;<br>    }<br>    // Remove the n-th node from end<br>    curr.next = curr.next.next;<br>    return head;<br>}</pre><h3>⚠️ A Common Pitfall</h3><p>When I first tried to solve this problem, I got overwhelmed trying to juggle indexes and pointer positions. I kept trying to be “clever” with math, writing things like n - i in my loop condition, instead of just clearly naming the variable like targetIndex.</p><p>This didn’t help me write better code — it just made everything harder to follow.</p><p>One of the most important lessons I’ve learned is:</p><blockquote><em>✏️ </em><strong><em>Always write down what you&#39;re trying to do.</em></strong></blockquote><p>A lot of people — myself included — understand the logic behind a linked list problem, but end up writing overly complicated code. The loops, indexes, and pointer juggling mess with our heads.</p><p>For me, I also used to worry about “looking professional.” I’d use the most conventional variable names, or try to minimize memory usage by cramming logic into fewer variables. For example, instead of just declaring something like targetIndex, I’d write n - i directly — even if it made the code harder to read.</p><blockquote><strong>Clarity matters more than cleverness — especially with linked lists. The fewer things you force your brain to track, the better your code becomes.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d242cd0bea98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistic Review: Combination and Permutation]]></title>
            <link>https://medium.com/@sandy.yang992/statistic-review-combination-and-permutation-5c90d587bac6?source=rss-8a2d734dd544------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c90d587bac6</guid>
            <category><![CDATA[permutations]]></category>
            <category><![CDATA[combination]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Sandy Yang]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 02:01:12 GMT</pubDate>
            <atom:updated>2025-07-01T02:01:12.356Z</atom:updated>
            <content:encoded><![CDATA[<p>When I graduate from university, I thought I would never face a challenge that required me to count all possible combinations within a given set of constrains ever again. But, life comes full circle and here I am — opening my notebook from 3 years ago to solve <a href="https://medium.com/p/c5adf8066858/">a similar problem</a> on LeetCode.</p><p>It seems I just can’t escape from these problem, can I? So, I’ve decided to throughly review this topic before starting my master’s program. It’s not like I won’t encounter this on the future interview anyway.</p><p>I always find myself confused between “permutation” and “combination” — which one’s which?</p><p>Well, here’s how I keep them straight: <strong>Permutation — </strong>with the prefix ‘per’ — is all about order. When we talk about permutation, we are looking for arranging where sequence matter. For example, the arrangement ABC is different from BAC.</p><p>On the other side, <strong>Combination</strong> does not care about order at all. It’s all about selecting groups where arrangement doesn’t matter — ABC, BAC, and CAB are considered the same.</p><h3>Permutation</h3><p>You know what’s a fancy way to say “find all possible arrangements” of something? <strong>Permutation</strong>.</p><p>Tell your hackers try permutating your password and see if they pass their college statistic.</p><p>Joking aside. That’s look at some example:</p><p><strong><em>You have 8 students (A-H) and 3 groups (Gold, Silver, Bronze). How many possible ways to assign each students in to these group?</em></strong></p><p>We’re going to use permutations since the order of your group matters. Here’s how it breaks down:</p><blockquote><strong><em>Gold</em></strong> : We got 8 choices (A, B, C, D, E, F, G, H). We pick student A.</blockquote><blockquote><strong><em>Silver</em></strong> : We got 7 choices left (B, C, D, E, F, G, H). We pick student B.</blockquote><blockquote><strong><em>Bronze</em></strong> : We got 6 choices left (C, D, E, F, G, H). We pick student C.</blockquote><p>As our choice goes from 8, then 7, and to 6, the total number of options was 8*7*6 = 336.</p><p>We know the factorial is:</p><p><strong><em>8! = 8 ∗ 7 ∗ 6 ∗ 5 ∗ 4 ∗ 3 ∗ 2 ∗ 1</em></strong></p><p>We already know that all possible arrangements is 8*7*6, so how can we make 8*7*6*5*4*3*2*1into<strong><em> </em></strong>8*7*6 ?</p><p>Let’s right, we divided it by5*4*3*2*1 !</p><p>So we got:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*SRtIw60mnulfxWha.png" /></figure><p>You might wonder why is the factorial of number 5? Let’s is because we got 3 groups to pick to assign! Thus, we can make the equation into:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/0*x_FTBb8UFZN6ACeW.png" /></figure><p>To make it more general, we then derive: If we have <strong>n</strong> items total and want to pick <strong>k</strong> in a certain order, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/0*ZWP-6kyH8EJ8jGqF.png" /></figure><p>And this is the fancy permutation formula: You have <strong>n</strong> items and want to find the number of ways <strong>k</strong> items can be ordered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/0*NOQRdh7y7ChPvTTn.png" /></figure><h3>Permutation with Repetition</h3><p>You may notice that in the example above, the <strong>repetition is not the case. </strong>When student A is assigned to group Gold, they can not be assigned to Group Silver nor Bronze.</p><p>So, what if repetition is okay? For example, picking the password for a number lock? Let’s see the other example:</p><p><strong><em>You have a 10-digit (0–9) lock with 4 number input. How many password can you possibly make?</em></strong></p><p>Let’s break it down with the same technique:</p><blockquote><strong>First</strong> number: 10 choices, 0–9. Pick 1.</blockquote><blockquote><strong>Second</strong> number: 10 choices, 0–9. Pick 2.</blockquote><blockquote><strong>Third</strong> number: 10 choices, 0–9. Pick 3.</blockquote><blockquote><strong>Fourth</strong> number: 10 choices, 0–9. Pick 4.</blockquote><p>Thus, the total number of passwords will be 10*10*10*10 = 10⁴.</p><p>We can derive that if the repetition is allowed, we will get: <strong>n^k</strong>.</p><h3>Combination</h3><p>Be happy, folks, cause for <strong>Combinations</strong>,<strong> order doesn’t matter</strong>. Mixing up elements doesn’t create a new outcome — it’s the same group!</p><p>Lets’ say we are assigning 3 students (A, B, C) into 3 groups. But this time, we don’t classify groups in to gold, silver and bronze. Every group is the same.</p><ul><li>Let’s starting with Permutation, where selecting (A, B, C) is different from (C, A, B).</li><li>Total arrangements: P(3,3) = 3!/(3–3)! = 3!/1 =6.</li><li>However, since for combination, order doesn’t matter, all arrangement for ABC will be the same.</li><li>Thus C(3,3) = 1 = P(3,3)/3!</li></ul><h4>Why Divide by k! ?</h4><ol><li>We started with permutations <em>P</em>(<em>n</em>,<em>k</em>), where order matters.</li><li>Each unique group of k students appears in k! permutations (one per ordering).</li><li>To count unique groups (ignoring order), we divide by k!</li></ol><p>So the general formulas will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/0*4Xb_pxdTCSq0XLrK.png" /></figure><p>which means “Find all the ways to pick k people from n, and divide by the k! variants”. Writing this out, we get our <strong>combination formula</strong>, or the number of ways to combine k items from a set of n:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/0*dtVvAAUVfzn5a6j4.png" /></figure><p>Combinations C(n, k)are often written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/1*Ur_M5Lbs54OUVKbzE_XVog.png" /></figure><p>which is the the <a href="https://en.wikipedia.org/wiki/Binomial_coefficient">binomial coefficient</a>. See example below:</p><h3>Stars and Bars<strong>: </strong>A Visual Combinatorial Technique</h3><p>See the live example on LeetCode <a href="https://medium.com/@sandy.yang992/leetcode-review-review-explanation-80-2929-distribute-candies-among-children-ii-c5adf8066858"><em>here</em></a>!</p><p>For a alternative application problem, let’s define our Problem Statement:</p><p><strong>Find the number of non-negative integer solutions so that</strong></p><pre>x_1 + x_2 + x_3 … x_k = n</pre><p>You might think this question does not looks like <strong>Combination</strong> nor <strong>Permutation</strong> at all. Let me break it down for you:</p><ul><li>Let’s represent each unit of n as a star: *</li><li>Use (k-1) bars | to divide stars into k groups (one per variable).</li><li><strong><em>Example</em></strong>: For n=5 and k=3, the solution (2, 1, 2) becomes ** | * | **.</li></ul><p><strong>Combinatorial Translation:</strong></p><ul><li>We have n stars and k-1 bars.</li><li>Total items to arrange: n + (k-1).</li><li>The problem reduces to: <em>“</em><strong><em>How many ways can we arrange these </em></strong><strong><em>k-1 bars into </em></strong><strong><em>n stars?</em></strong><em>”</em></li></ul><h3>Why This is a Combination Problem</h3><ul><li>Arrangements are uniquely determined by positions of the bars (or stars).</li><li>Since bars are identical and stars are identical,<strong> order doesn’t matter</strong>.</li><li>Thus, we use <strong>combinations</strong>, not permutations, and we got a equations:</li><li>C(n+k-1, k-1) = (n+k-1)!/((k-1)!*(n+k-1-(k-1))!) = (n+k-1)!/((k-1)!*n!)</li></ul><p>This is the most</p><p>Don’t memorize the formulas, understand why they work. <strong>Combinations sound simpler than permutations, and they are. You have fewer combinations than permutations.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c90d587bac6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Review & Explanation: 2929. Distribute Candies Among Children II]]></title>
            <link>https://medium.com/@sandy.yang992/leetcode-review-review-explanation-80-2929-distribute-candies-among-children-ii-c5adf8066858?source=rss-8a2d734dd544------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5adf8066858</guid>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[code-newbie]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[stackoverflow]]></category>
            <dc:creator><![CDATA[Sandy Yang]]></dc:creator>
            <pubDate>Sun, 29 Jun 2025 06:51:05 GMT</pubDate>
            <atom:updated>2025-06-29T06:52:21.894Z</atom:updated>
            <content:encoded><![CDATA[<p>**This is a mind journal on how I solve this question. Also my writing practice as well.</p><p>In the coding interview questions or any college computer science courses, you are likely to encounter a type of problems referred as “<a href="https://leetcode.com/tag/enumeration/">Enumeration</a>” problems. It usually ask you to <strong>list or count all the possible combination/solution that meet the required condition</strong>.</p><h3><strong>Common Enumeration Questions</strong></h3><ul><li><strong>Output all valid path/permutation/subset</strong></li><li><strong>Count all valid solutions</strong></li><li><strong>May have certain constrains</strong></li></ul><p>While most of my code work when I try to solve these bad boys, it fails the efficient test and after long struggle, in these journel, I want to keeps this journal so I can record some of my pattern and bad habbit.</p><p>I will start with my takes on how to approach Enumeration problem based on the required output:</p><ul><li>Permutation — Backtracking</li><li>Subsets — Backtracking</li><li>Total Number of Combination — Backtracking + Pruning</li></ul><p>Leetcode <a href="https://leetcode.com/problems/distribute-candies-among-children-ii/">2929. Distribute Candies Among Children II</a> require us to return the <strong>total number</strong> of ways to distribute n candies among 3 children such that no child gets more than limit candies.</p><p>So that:</p><pre>x + y + z = n<br>where 0 ≤ x, y, z ≤ limit</pre><p>We need to navigate through all the possible ways to distribute candies such that no child gets more than limit of candies. So, if n-5and limit=2, we will have 3 combination: (1, 2, 2), (2, 1, 2) and (2, 2, 1).</p><p>Keep in mind that (1, 2, 2) and (2, 2, 1) are basically the same, thus, the order matters. We need to keep track of the permutation in this case.</p><p>Ok. So we know that oders matters. That’s think about what we want to start as the starting case:</p><p>We can start with the initial state:</p><p>(0, 0, 0) → Sum is not 5</p><p>(1, 0, 0)→ Sum is not 5</p><p>(2, 0, 0)→ Sum is not 5, and hit limit 2</p><p>(0, 1, 0)→ Sum is not 5</p><p>(1, 1, 0)→ Sum is 5, but break</p><p>… And following check repeat.</p><p>So here’s the first idea:</p><p>We can backtrack all the possibilities by starting with (0,0,0) and increment each indexes one by one. If any index breaks the limit or the sum is greater than n, we prune the choice. Otherwise, we record the configurations and continue.</p><pre>class Solution {<br>    <br>    public long distributeCandies(int n, int limit) {<br>        long count = 0;<br>        return  backtrack( 0,0,0 ,count, n, limit);<br>    } <br><br>    public long backtrack( int x, int y, int z ,long count, int n, int limit){<br>        if ( x+y+z &gt; n || x &gt; limit || y &gt; limit || z &gt; limit) {<br>            return 0; //prune<br>        }<br>        if (x+y+z==n) {<br>            System.out.println(x + &quot;,&quot; + y + &quot;,&quot; + z); //for debugging<br>            return 1; <br>        }<br>        return  backtrack(x+1, y, z, count, n, limit) + <br>                backtrack(x, y+1, z, count, n, limit)+ <br>                backtrack(x, y, z+1, count, n, limit); <br>    }<br>}</pre><p>Let’s give it a shot and run the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clRzmK0wkmulzr66FaS9cQ.png" /></figure><p>Well, the code works (first try ;) ). Yet, it counts way more combinations than what we expected. Why does this happen? If you print out the counted combination, you might see something like this:</p><p>(1,2,2)</p><p>(2,1,2)</p><p>(1,2,2)</p><p>…</p><p>Turns out that the <strong>same combinations</strong> can be counted multiple times, even though we only want to keep track of unique different combination! Thus, let’s <strong><em>record the combination</em></strong> that have already appeared. For efficient tracking, <strong>HashSet</strong> is a good data structure to use.</p><p>Here’s is the updated code.</p><pre>class Solution {<br>    public long distributeCandies(int n, int limit) {<br>        long count = 0;<br>        Set&lt;String&gt; seen = new HashSet&lt;&gt;(); <br>        return  backtrack( 0,0,0, seen, count, n, limit);<br>    } <br><br>    public long backtrack(int x, int y, int z, Set&lt;String&gt; seen,long count, int n, int limit){<br>        <br>        if ( x+y+z &gt; n || x &gt; limit || y &gt; limit || z &gt; limit){<br>            return 0; //prune<br>        }<br><br>        if (x+y+z == n){<br>            String arr = x + &quot;,&quot; + y + &quot;,&quot; + z ;<br>            if (!seen.contains(arr)) {<br>                seen.add(arr);<br>                return 1;<br>            }<br>            return 0;<br>        }<br>        <br>        return  backtrack(x+1, y, z, seen, count, n, limit) +<br>                backtrack(x, y+1, z, seen, count, n, limit) + <br>                backtrack(x, y, z+1, seen, count, n, limit); <br>    }<br>}</pre><p>You may notice that I am using Set&lt;String&gt; instead of Set&lt;int[]&gt;. This is because Set&lt;int[]&gt; only tracks object references, not the actual content of the integer arrays. As a result, using Set&lt;int[]&gt; will end up with the same 90+ answer as before, since the set would not recognize two different arrays with the same values as duplicates.</p><p>Let’s try submit the answer again…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*Nlp-O7ZCxdqjb6sc3SjV4Q.png" /><figcaption>Haha kill me</figcaption></figure><p>Well, here we are again — another classic <strong><em>Time Limit Exceeded</em></strong> error. As someone who writes code with mostly focus on data, I have to admit that this is one of the most frustrating parts of practicing on LeetCode. It’s especially annoying because we know our solution works, but it just isn’t efficient enough to pass within the time constraints. Ugh!</p><p>Let’s look at what is a possible reason that makes our code slow:</p><ol><li>I am exploring <strong>all the possible combinations</strong>, as some are clearly unnecessary, e.g (0,0,0).</li><li>I keep checking if set is in HashSet, which cost memories.</li></ol><p>** Okay, so thinking of a different approach can be extremely challenging, especially for beginners. If you’re in a similar situation, I’d recommend seeking help from AI assistance. However, please <strong>don’t just copy and paste the code or question into the prompt</strong> — doing so won’t help you learn effectively (even worse, <a href="https://medium.com/@sandy.yang992/quick-thought-on-ai-tool-to-creative-creation-2385445da25c">makes your brain perform worse</a>?). Instead, what I found helpful was to ask the AI for suggestions on more efficient methods or alternative ways to approach the problem.</p><p>So, instead of generating all possible combinations, how about directly counting valid candidate using known parameters? We are given total numbers of candy n and the distribution size of 3 children (x , y , and z ). Thus, the number z will be n-x-y .</p><pre>class Solution {<br>    public long distributeCandies(int n, int limit) {<br>        long count = 0;<br>        <br>        for(int x = 0; x &lt;= limit; x++) {<br>            for(int y=0; y &lt;= limit; y++){<br>                int z = n-x-y;<br>                if (z&gt;=0 &amp;&amp; z&lt;=limit){<br>                    count++;<br>                }<br>            }<br>        }<br>        return count;<br>    } <br>}</pre><p>Now, the code looks simple and more efficient! Let’s try submitting again!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*0Ypnh2R1zlvE2Uxs6rwhuA.png" /><figcaption>I hate my life sometimes.</figcaption></figure><p>Okay. We began with inefficient backtracking, then we move to a double for-loop, reducing the time complexity to O(limit²), which is a big improvement. But LeetCode is a tough place for beginners (this is only a medium level problem by the way.) But we are making progress. So don’t worry. Let’s keep revise this piece of code.</p><p>Currently, we have tried to brute force the combination, which means we are still checking all the possible combinations each by each. While for-loops is better than backtracking, we are still checking the unnecessary combination (like when z&lt;0 in our second version). So, how can we make the process even more efficient?</p><h3>Inclusion-Exclusion + Modular Combinatorics</h3><p>I hate this, but, we are going to return to Statistic.</p><h4>Step 1: Calculate all solutions without limits (just x + y + z = n)</h4><p>If we first ignore the limit, this will be the classic <strong>Stars and Bars question</strong>. Let’s start with a small example, saying we want to assign 5 candies to 3 children:</p><pre>x + y + z = 5<br>where 0 ≤ x, y, z  //(Let&#39;s ignore the limit for now) </pre><p>We’ll represent the <strong>5 candies as stars</strong> (* * * * *), and we want to divide them into 3 parts — for 3 kids — so we need <strong>2 bars</strong> (|) to separate the 3 groups:</p><pre>#An example of a distribution<br><br>* * | * * | *   #x = 2, y = 2, z = 1</pre><h3>Key idea:</h3><ul><li>We have n stars (candies).</li><li>We have k-1 bars (to divided the candies to k kids).</li><li><strong>Total items to arrange</strong>: n+k-1 items.</li></ul><p>So, for selection principle, <strong>we are choosing positions for the </strong><strong>k-1 bars (or equivalently, for the </strong><strong>n stars) from these </strong><strong>n + k - 1 positions</strong>.</p><ul><li>Since the order of selecting bar positions doesn’t matter, we use <strong>combinations</strong>, not permutations.</li><li>And since the number of k is fixed (3 children), we can write our equation in:</li></ul><pre>(n+k-1)!/(k-1)!(n+k-1-(k-1))!<br>= (n+2)!/(2!*n!)</pre><p>So, in our example, there are (5+2)!/(2!5!) = 21 ways to distribute 5 candies to 3 children. It’s time for us to add the limit back!</p><h4>Step 2: Subtract <strong>bad cases</strong> (where a variable &gt; limit)</h4><p>We know that in total of 21 combinations, we will have some arrangements that are exceeding the limit (let’s set limit=2). So, how can we get rid of these bad cases? We will use <a href="https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle"><strong>inclusion-exclusion</strong></a>.</p><p><strong><em>n (A ∪ B ∪ C) = n(A)+ n(B) + n(C) − n(A ∩ B) − n(B ∩ C) − n(A ∩ C) + n(A ∩ B ∩ C)</em></strong></p><p>We have 3 cases.</p><blockquote><strong>A</strong>: cases where x &gt; 2</blockquote><blockquote><strong>B</strong>: cases where y &gt; 2</blockquote><blockquote><strong>C</strong>: cases where z &gt; 2</blockquote><p><strong>2.1. First, let’s look at Case A.</strong></p><ul><li>We need to count arrangements wheres x&gt;2 — in other word, <strong>x≥3</strong>.</li><li>Since x≥3, let’s assume x’ = x-3 (so that x’≥0), and substitute it into x+y+z = 5 .</li><li>we got (x-3)+y+z = 5 — 3 =&gt; x&#39;+y+z = 2 .</li></ul><p><strong>2.2. Applying stars and bars:</strong></p><ul><li>We now have 2 stars (candies) and 2 bars (dividers for 3 children).</li><li>Total positions to arrange: 2+3-1 = 4 .</li><li>And, we got4!/(2!*2!) = 6 arrangements</li></ul><p><strong>2.3. Cases B and C:</strong></p><ul><li>For y&gt;2: Similarly, set y’ = y-3, leading to x+y’+z = 2. Again, 6 arrangements.</li><li>for z&gt;2: Set z&#39;=z-3 , giving x+y+z&#39;=2 . Getting 6 arrangement as well.</li></ul><p><strong>2.4. Concurrent Cases: When Both </strong><strong>x≥3and </strong><strong>y&gt;=3</strong></p><ul><li>Now, how about cases where two conditions overlap?</li><li>let’s assume x&#39;=x-3 and y&#39;=y-3 and substitute into x+y+z=5 again.</li><li>We got (x-3)+(y-3)+x = 5-3-3 = -1 . Since the output = -1, this can’t be happen. Thus, this will be 0 cases.</li></ul><p><strong>2.5 Generalize our formulas</strong></p><ul><li>For each cases, we assume the new variable where each variable is larger or equal to the limit +1, where x’ = x- (limit+1) , (x-(limit+1)) + y + z = x’ + y + z = n-(limit+1)</li><li>Using <em>Star and Bars</em>, we then calculate the number of arrangements: Combination(n-(limit+1)+(k-1), (k-1)) = (n-(limit+1)+(k-1))!/ (k-1)!*(n-(limit+1)+(k-1)-(k-1))! = (n-limit+k-2)!/((k-1)! * (n-limit-1)!)</li><li><strong>Individual cases</strong>: Since k=3, we have (n-limit+1)!/(2!*(n-limit-1)!)</li><li>For each cases where 2 conditions overlap, we have to pick (x-(limit+1)) + (y-(limit+1))+ z = x’ + y + z = n-(2*limit + 2)</li><li>Using <em>Star and Bars</em>, we then calculate the number of arrangements:Combination(n-(2*limit + 2)+(k-1), (k-1)) = (n-(2*limit + 2)+(k-1))!/ ((k-1)! * (n-(2*limit + 2)+(k-1)-(k-1))!) , so we get (n-2*limit +k -3)! /((k-1)! * (n-2*limit-2)!)</li><li><strong>Double cases</strong>: Substituting k=3 , (n-2*limit)! /(2! * (n-2*limit-2)!)</li><li>For each cases where 3 condition overlap, we now have (x-(limit+1)) + (y-(limit+1))+ (z-(limit+1))= x’ + y + z = n-(3*limit + 3)</li><li>Using <em>Star and Bars</em>, we then calculate the number of arrangements:Combination(n-(3*limit + 3)+(k-1), (k-1)) = (n- 3*limit -3+k-1)!/ ((k-1)! * (n-3*limit-3+(k-1)-(k-1))!) = (n- 3*limit + k- 4)!/ ((k-1)! * (n-3*limit-3)!)</li><li>Substituting k=3 ,(n- 3*limit — 1)!/ (2! * (n-3*limit-3)!)</li></ul><p>So, after calculating each cases, we will have</p><p><strong><em>All arrangements-n (A ∪ B ∪ C) = (n+2)!/(2!*n!)- 3* (n-limit+1)!/(2!*(n-limit-1)!) + 3*(n-2*limit)! /(2! * (n-2*limit-2)!) — (n- 3*limit — 1)!/ (2! * (n-3*limit-3)!)</em></strong></p><p>I know it looks overcomplicated on plain text, but it’s not too bad when we put them into code!</p><pre>class Solution {<br>    public long distributeCandies(int n, int limit) {<br><br>        // Convert to long to prevent overflow in intermediate calculations<br>        long N = n;<br>        long L = limit;<br>        long count = 0;<br>        <br>        //Step1: get all arrangements<br>        long total = C2(N+2);<br><br>        //Step2: exclude bad case<br>        //2.1 calculate single cases<br>        long single_case = C2(N-(L+1)+2);<br><br>        //2.2 calculate overlap cases (2 cases overlap)<br>        long double_case = C2(N-2*(L+1)+2);<br><br>        //2.2 calculate overlap cases (3 cases overlap)<br>        long triple_case =  C2(N-3*(L+1)+2);<br><br>        return total - 3*single_case + 3*double_case - triple_case;<br>    } <br><br>    public static long C2(long n) {<br>        // We can do factorial for small n<br>        // However, when n is around 20, we will <br>        // encounter stack overflow, so we simplified the function to C2<br><br>        // C(n,2) = n!/(2!(n-2)!) = n*(n-1)/2<br>        return (n &lt; 0 || 2 &gt; n) ? 0: (n*(n-1))/2;<br>    }<br>}</pre><p>Note that we have done several things that’s might seen unnecessary. These are to prevent stack over flow in our calculation.</p><h4>Long Arithmetic for Intermediate Values:</h4><ol><li>Convert n and limit to long (N and L) to prevent overflow in expressions like N - 3*(L+1) + 2</li><li>Using C2 function instead of making binom or factorial as a helper function. Calculating factorial can be computationally large and cause the false value if the n is big.</li></ol><p>Finally, let’s submit the answer again…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*gAnUR2J8qCHfQHnTmMuRYg.png" /></figure><p>Hooray! We solved the question — and did so really efficiently!</p><p>This challenge took me nearly a day to crack. Starting with a brute force approach and eventually progressing to a statistical equation, I gained valuable insight into the problem-solving process. I can clearly see how coding demands both experience and practice. I’m glad I started this journey, and I’m determined to keep going!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5adf8066858" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Thought on AI Tool to Creative Creation]]></title>
            <link>https://medium.com/@sandy.yang992/quick-thought-on-ai-tool-to-creative-creation-2385445da25c?source=rss-8a2d734dd544------2</link>
            <guid isPermaLink="false">https://medium.com/p/2385445da25c</guid>
            <category><![CDATA[creative-writing]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[mit-technology-review]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Sandy Yang]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 08:00:24 GMT</pubDate>
            <atom:updated>2025-06-26T08:00:24.473Z</atom:updated>
            <content:encoded><![CDATA[<p>“The devil is in the details” is one of my favorite quotes to bring up when discussing creative creation with my friends. As an amateur artist, the discords around artificial intelligence and IP law haven’t really affected my passion for drawing since I don’t financially depend on creating content nor I gain lots of attention on artist platform. I still don’t use any AI assistances on any of my comics — neither for illustration nor writing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0y08zl4n6Da5q2bH5sLPSQ.png" /><figcaption>Personal drawing for fun, yay</figcaption></figure><p>However, I am still a heavy AI user. I turn to AI when I need to know the process for applying F-1 visa, when I can’t find bugs in my code, or when I want to polish my writing. For instance, when I write my LeetCode review articles, I have a rough draft — maybe with some bullet points — turn into ChatGPT and it outputs a well-crafted article for me.</p><p>Yet, I always have a feeling of hollowness. Like something is missing. This feeling has bother me for a while until last week, I read a <a href="https://arxiv.org/abs/2506.08872">paper</a> studying the affect of ChatGPT of human brain. And, to be honest, the result had let me revaluate how I use AI tools and how should I approach them in the future.</p><p>The study explore the cognitive impact of LLM assistance on groups of writers. Participants were asked to complete a writing assignment and were assigned to one of three groups: LLM, Search Engine, and No-Tools.</p><p>The result indicated that LLM users experienced a significant reduction in brain connectivity, whereas writers with no tool displayed the strongest. LLM users even had difficulty quoting their own work. According to the study, this decline in cognitive activities associated with external tools use is referred to as “cognitive debt”. Although LLM tools are convenient, relying on them may decrease your abilities to connect ideas and recall concepts.</p><p>After finishing this article, I am sweating. Writing has never been my strong suit. I get nervous, lazy, and, most of all, insecure whenever I need to write a long article. When AI first appeared, I felt relief — as so much of the writing work could be done for me. Yet, that hollowness, that feeling of “that’s not me,” always bother me.</p><p>Now, I start wonder why, even though I use AI for work, I never use it for my personal interest — drawing.</p><blockquote><em>“The devil is in the details”</em></blockquote><p>Why don’t I want to use AI in my comic creation? Thinking of the dialogue, designing the panels, drawing, adding texture and shadow — creating comic is time consuming and require lots of thoughts. Yet, that’s what makes it fun. I like to add details in dialogue and scenes, not to communicate anything specific but simply to amuse myself.</p><p>The dopamine rush comes when I connect my pop-up ideas together, and that is one of the most wonderful experiences anyone could enjoy. I have come to realize that this is what we might lose if we keep accumulating “cognitive debt” — the ability to weave together different personal experience, ideas, and, thought into a cohesive thought.</p><p>I recently read an <a href="https://www.technologyreview.com/2025/04/22/1114874/generative-ai-south-korea-webcomics/">article</a> about legendary Korea cartoonist <a href="https://koreajoongangdaily.joins.com/2013/04/01/artsDesign/Lee-Hyunse-is-newly-subdued-in-life-work/2969448.html">Lee Hyun-se</a>, who stated that AI can help immortalize his characters. At first, I was surprised in his reaction, since most professional artists I know are strongly oppose to feeding their own works into generative AI. However, when I saw how Lee seen AI as a tools to preserve his worldview and legacy — even after his death, I started to understand the different between blindly using the AI to generate content and using AI as a tools to help achieving one own goals. As Lee state it:</p><blockquote><strong>“My mind is still sharp and my hand work just fine, so I have no interest in getting help from AI to draw or write stories,”</strong></blockquote><p>I believe that the most important part is that we must not give up on thinking. By this, I am don’t mean merely thinking of prompt to input into an AI model. I mean real thinking: linking ideas with your own experience, reflecting on your own way of expression, and finding the right word or analogy to describe your feeling. After all, isn’t the purpose of using AI to help us get more time to work with our own thought?</p><p>Now I realize I need to change my approach to using AI in writing. I’ll still use it to check my word choice and grammar. However, I should also bring more of personal experience, recent reading, and even conversations with friends into my writing — like how I did in my drawing.</p><p>And I’m sure these writings will be more childish, amateur, and random. But I guess that’s just who I am.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2385445da25c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Review and Explanation: 2140. Solving Questions With Brainpower]]></title>
            <link>https://medium.com/@sandy.yang992/leetcode-review-and-explanation-2140-solving-questions-with-brainpower-5228231c0f29?source=rss-8a2d734dd544------2</link>
            <guid isPermaLink="false">https://medium.com/p/5228231c0f29</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <dc:creator><![CDATA[Sandy Yang]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 10:54:22 GMT</pubDate>
            <atom:updated>2025-04-04T10:54:22.419Z</atom:updated>
            <content:encoded><![CDATA[<p>Back in college, anything related to TreeNode and recursive algorithms almost made me want to drop out. I really struggled with those classes — my grades looked awful. Thankfully, I did well in other courses, so my overall GPA stayed afloat.</p><p>Years later, after working for a while, I decided to face this tremendous fear again — and surprisingly, I kind of enjoy it now.</p><p>Today, I’m tackling <a href="https://leetcode.com/problems/solving-questions-with-brainpower/?envType=daily-question&amp;envId=2025-04-04"><strong>Leetcode 2140: Solving Questions With Brainpower</strong>.</a> In this problem, you’re given an array of questions, and for each question i:</p><ul><li>If you choose to solve it, you earn points[i], but you must then skip the next brainpower[i] questions.</li><li>If you skip the question, you move directly to question i + 1.</li></ul><p>This is what I’d call a <strong>combination-style recursive problem</strong>. It reminds me a lot of the classic TreeNode problems — we go deeper into the index tree and return something like a sum, max, or depth.</p><h3>🌱 Step 1: Recursive Template (No Optimization Yet)</h3><p>We can first write a recursive function that explores both options: solving the current question or skipping it.</p><pre>class Solution {<br>   <br>   // the returen type should be what we are looking for<br>   // @int i : tracking depth<br>   // @int[][]: origina input (can be int[][], TreeNode)<br>   public long recursiveMethod(int i, int[][] q){<br>        <br>        // Base case: when index is out of bounds<br>        if(stop_condition) return 0; // or null, or other depending on type<br>        <br>        // Option 1: take the question<br>        long take = value_at_this_level + recursiveMethod(next_index_if_taken, q);<br>        <br>        // Option 2: skip the question<br>        long skip = recursiveMethod(next_index_if_skipped, q);<br>        <br>       // Choose the option that gives the maximum points<br>        return Math.max(take, skip);<br>   }<br>    <br>    public long solutionFunction(int[][] original_input) {<br>    <br>        return recursiveMethod(0, original_input);<br>    }<br>}</pre><h3>🌱 Step 1: Understanding the Recursive Flow</h3><p>Imagine you’re standing at <strong>question index </strong><strong>i</strong>. At this moment, you have <strong>two choices</strong>:</p><h3>Choice 1: Take the question</h3><ul><li>You earn points[i]</li><li>But you must <strong>skip the next </strong><strong>brainpower[i] questions</strong></li><li>So you jump to i + brainpower[i] + 1</li></ul><h3>Choice 2: Skip the question</h3><ul><li>You earn <strong>nothing</strong> from this question</li><li>You move directly to the next question i + 1</li></ul><h3>Recursive Logic Flow</h3><p>Here’s how you can visualize the decision-making process in your recursiveMethod():</p><pre>recursiveMethod(i)<br>├── take: points[i] + recursiveMethod(i + brainpower[i] + 1)<br>└── skip: recursiveMethod(i + 1)<br>→ return max(take, skip)</pre><p>You repeat this decision for each question until you reach the end of the array. Here’s the visual diagram example:</p><pre>questions = {<br>    {3, 2},  // Question 0: 3 points, skip 2<br>    {2, 1},  // Question 1: 2 points, skip 1<br>    {4, 0},  // Question 2: 4 points, skip 0<br>    {3, 1},  // Question 3: 3 points, skip 1<br>    {1, 0}   // Question 4: 1 point, skip 0<br>};</pre><p>Let’s visualize what happens when we start from i = 0:</p><pre>                              recursive(0)<br>                             /            \<br>                       take(0)           skip(0)<br>                       | (3 + recursive(3))     |<br>                    recursive(3)         recursive(1)<br>                       /    \               /      \<br>                    take(3) skip(3)   take(1)   skip(1)</pre><p>It keeps expanding like a <strong>binary decision tree</strong>, where each node represents the current decision:</p><ul><li>Left branch = “take”</li><li>Right branch = “skip”</li></ul><p>Thus, our solution will look like:</p><pre>class Solution {<br><br>    // i: the current question index<br>    // q: the 2D array of questions<br>    public long recursiveMethod(int i, int[][] q){<br>        // 1. 🛑 Base case: no more questions left<br>        if (i &gt;= q.length) return 0;<br><br>        // 2. Take the current question<br>        int points = q[i][0];<br>        int brainpower = q[i][1];<br>        long take = points + recursiveMethod(i + brainpower + 1, q);<br><br>        // 3. Skip the current question<br>        long skip = recursiveMethod(i + 1, q);<br><br>        // 4. Choose the better option<br>        return Math.max(take, skip);<br>    }<br><br>    public long solutionFunction(int[][] questions) {<br>        return recursiveMethod(0, questions);<br>    }</pre><p>But there’s a catch…</p><h3>🐌 The Problem with Pure Recursion</h3><p>Let’s visualize the recursive call tree for recursiveMethod(0):</p><pre>               cal(0)<br>              /      \<br>        cal(2)        cal(1)<br>       /    \        /     \<br>   cal(5)  cal(3) cal(4)  cal(2)</pre><p>See how cal(2) appears multiple times?</p><p>That means we’re <strong>recalculating the same subproblems again and again</strong>, which leads to <strong>exponential time complexity</strong>. For large inputs, this will time out (TLE) on Leetcode.</p><h3>⚡ Step 2: Optimize with Memoization (aka Caching)</h3><p>To fix this, we use <strong>memoization</strong> — we store already computed results in an array so we don’t compute them again.</p><pre>class Solution {<br><br>    public long recursiveMethod(int i, int[][] q, long[] memo) {<br>        if (i &gt;= q.length) return 0;<br><br>        if (memo[i] != -1) return memo[i];  // check cache<br><br>        long take = q[i][0] + recursiveMethod(i + q[i][1] + 1, q, memo);<br>        long skip = recursiveMethod(i + 1, q, memo);<br><br>        return memo[i] = Math.max(take, skip);<br>    }<br><br>    public long solutionFunction(int[][] questions) {<br>        long[] memo = new long[questions.length];<br>        Arrays.fill(memo, -1);<br>        return recursiveMethod(0, questions, memo);<br>    }<br>}</pre><p>The array memo caches the maximum points you can earn starting from each index. Once we compute a result, we store it. Next time we hit the same index, we just return the cached result.</p><p>✅ Final Version</p><pre>class Solution {<br><br>    public long calTotal(int i, int[][] q, long[] dp){<br>        if (i &gt;= q.length) return 0;<br>        if (dp[i] != -1) return dp[i];<br><br>        long pt = q[i][0];<br>        int bp = q[i][1];<br><br>        long take = pt + calTotal(i + bp + 1, q, dp);<br>        long skip = calTotal(i + 1, q, dp);<br><br>        return dp[i] = Math.max(take, skip);<br>    }<br><br>    public long mostPoints(int[][] questions) {<br>        long[] dp = new long[questions.length];<br>        Arrays.fill(dp, -1);<br>        return calTotal(0, questions, dp);<br>    }<br>}</pre><h3>💡 Key Takeaways</h3><ul><li>Don’t be afraid of recursive problems. Once you understand the <strong>choices at each step</strong>, it’s just about building and pruning the decision tree.</li><li>Don’t be ashamed for using template! You will memorize this after several practice!</li><li>Use <strong>memoization</strong> to avoid redundant computations.</li><li>You can apply this recursive + caching structure to a wide range of problems — especially those that involve <strong>sequential decision-making</strong> like DP on arrays, tree traversals, or game theory.</li></ul><p>Thanks for reading! If you’re also working through these algorithmic fears, know that you’re not alone — and it does get easier with practice 💪</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5228231c0f29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Review and Explanation: 2874. Maximum Value of an Ordered Triplet II]]></title>
            <link>https://medium.com/@sandy.yang992/leetcode-review-and-explanation-2874-maximum-value-of-an-ordered-triplet-ii-6e122b27bc9f?source=rss-8a2d734dd544------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e122b27bc9f</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[leedcode]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[code-interview]]></category>
            <dc:creator><![CDATA[Sandy Yang]]></dc:creator>
            <pubDate>Thu, 03 Apr 2025 09:41:40 GMT</pubDate>
            <atom:updated>2025-04-03T10:00:13.073Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Hello World!</strong><br> It’s me again — a non-technical student who’s been diving into the world of code, all on my own. Today, I ran into a familiar yet frustrating challenge: the <strong>Time Limit Exceeded</strong> error. 😅</p><p>If you’ve used LeetCode before, you probably know this feeling: your code works, it gives the right answer, but it’s just <em>too slow</em>. That’s exactly what happened to me today when I tackled <strong>Leetcode 2874: Maximum Value of an Ordered Triplet II</strong>.</p><h3>💡 The Problem</h3><p>You’re given an array nums, and you need to find the <strong>maximum value</strong> of (nums[i] - nums[j]) * nums[k] where i &lt; j &lt; k. If all possible values are negative, return 0.</p><h3>🐢 My First Attempt: Brute Force (O(n³))</h3><p>Here’s my original code:</p><pre>class Solution {<br>    public long maximumTripletValue(int[] nums) {       <br>        if (nums.length &lt; 3) return 0;<br><br>        long max = (long)(nums[0] - nums[1]) * nums[2];<br><br>        for (int k = 2; k &lt; nums.length; k++) {<br>            for (int j = 1; j &lt; k; j++) {<br>                for (int i = 0; i &lt; j; i++) {<br>                    long num = (long)(nums[i] - nums[j]) * nums[k];<br>                    max = Math.max(max, num);<br>                }<br>            }<br>        }<br><br>        return Math.max(max, 0);<br>    }<br>}</pre><p><strong>What happened?</strong><br> Well, it worked for small inputs. But once n got big (like 1000), my solution blew up. The time complexity here is <strong>O(n³)</strong> — that&#39;s a <em>billion</em> operations in the worst case! Leetcode wasn&#39;t having it. 😭</p><h3>⏱ My Second Try: Smarter Brute Force (O(n²))</h3><p>So I thought — can I optimize just a bit? Instead of recalculating (nums[i] - nums[j]) for every triplet, maybe I can just find the <strong>maximum difference</strong> so far for each k.</p><pre>class Solution {<br>    public long maximumTripletValue(int[] nums) {       <br>        if (nums.length &lt; 3) return 0;<br><br>        long result = 0;<br>        for (int k = 2; k &lt; nums.length; k++) {<br>            long maxDiff = 0;<br>            for (int j = 1; j &lt; k; j++) {<br>                for (int i = 0; i &lt; j; i++) {<br>                    maxDiff = Math.max(maxDiff, nums[i] - nums[j]);<br>                }<br>            }<br>            result = Math.max(result, maxDiff * nums[k]);<br>        }<br>        return result;<br>    }<br>}</pre><p>This brought me down to <strong>O(n²)</strong> — a huge improvement! But for large inputs, it was <em>still</em> too slow. I was getting closer, but not quite there yet.</p><h3>⚡ Final Try: Optimized to O(n)</h3><p>Now it was time to think differently. I took a closer look at the equation:</p><pre>(nums[i] - nums[j]) * nums[k]</pre><p>I realized:</p><ul><li>I can <strong>keep track of the best nums[i]</strong> before each j</li><li>I can <strong>precompute the best nums[k]</strong> after each j</li></ul><p>This means for every j, I can efficiently compute:</p><pre>(max_i_so_far - nums[j]) * max_k_after</pre><p>Here’s the optimized solution:</p><pre>class Solution {<br>    public long maximumTripletValue(int[] nums) {<br>        int n = nums.length;<br>        int[] max_k = new int[n];<br>        max_k[n - 1] = 0;<br><br>        // Step 1: Build max_k[] from right to left<br>        for (int i = n - 2; i &gt;= 0; i--) {<br>            max_k[i] = Math.max(max_k[i + 1], nums[i + 1]);<br>        }<br><br>        int max_i = nums[0];<br>        long result = 0;<br><br>        // Step 2: Iterate through j, using max_i and max_k[j]<br>        for (int j = 1; j &lt; n - 1; j++) {<br>            long value = (long)(max_i - nums[j]) * max_k[j];<br>            result = Math.max(result, value);<br>            max_i = Math.max(max_i, nums[j]);<br>        }<br><br>        return result;<br>    }<br>}</pre><p>Now the time complexity is <strong>O(n)</strong> and it passes all test cases with flying colors.🎉</p><h3>🚧 Challenge</h3><p>One of the biggest challenges I face when trying to optimize a solution is figuring out <strong>what exactly I need to keep track of</strong>.<br> Should I store the <strong>index</strong>? Or the <strong>value</strong>? Should I just <strong>create a list</strong> to record things?</p><p>If you’ve ever felt the same way when solving “<strong>find the best combination</strong>” or “<strong>maximize/minimize something under conditions</strong>” kind of problems — here’s a <strong>5-step thinking process</strong> that really helps:</p><h3>🪜 Step 1: Observe the Equation</h3><p>In this problem, we’re working with:</p><pre>(nums[i] - nums[j]) * nums[k]</pre><p>with the condition:<br> i &lt; j &lt; k</p><p>Just by looking at the formula, we already know this is about picking <strong>three values in order</strong>, and we want the combination that gives the <strong>maximum result</strong>.</p><h3>🪜 Step 2: Break the Formula Into Parts</h3><p>Let’s divide it like this:</p><ul><li>(nums[i] - nums[j]) ← the <strong>first part</strong></li><li>* nums[k] ← the <strong>second part</strong></li></ul><p>This helps us understand how the value is built. Instead of thinking about all (i, j, k) triplets at once, we can break it down:<br> ➡️ Find the best (i, j) pair first, then combine with a suitable k.</p><h3>🪜 Step 3: Decide Who to Track</h3><p>Here’s where it gets real!</p><p>Ask yourself:</p><ul><li>Is the number <strong>before</strong> the current index? → Use a running <strong>max/min</strong> (prefix)</li><li>Is the number <strong>after</strong> the current index? → Use <strong>preprocessing</strong> like building a suffix array</li></ul><p>In this case:</p><ul><li>We track the <strong>maximum </strong><strong>nums[i]</strong> on the left of j</li><li>We track the <strong>maximum </strong><strong>nums[k]</strong> on the right of j</li></ul><p>Now we’re reducing the triple loop into a <strong>single pass</strong>, where we only need to check valid j, and grab the best i and k for it.</p><h3>🪜 Step 4: Think in Terms of Position</h3><p>Don’t just think of “values,” think of where they are:</p><ul><li>At each index j, you want:</li><li>the best value <strong>before</strong> it → max_i</li><li>the best value <strong>after</strong> it → max_k</li></ul><p>This mindset helps you decide:</p><ul><li>When do you need a list (e.g., suffix max list)?</li><li>When can a single variable do the job (e.g., running max)?</li></ul><h3>🪜 Step 5: Use a Small Example to Test</h3><p>Before writing code, pick a tiny input like [3, 1, 5, 2], and manually step through:</p><ul><li>What values do I have at each position?</li><li>Can I figure out the best i &lt; j and j &lt; k for each j?</li><li>Is my tracking method working?</li></ul><p>If it works on paper, it probably works in code. If not, it shows what you’re missing.</p><h3>🔚 Final Thoughts</h3><p>If you’re learning like me, it’s okay to start with the brute force approach. What matters is that you <em>keep thinking</em>, keep testing, and keep optimizing. Each version taught me something new — and now I know how to turn a TLE into a lightning-fast solution!</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e122b27bc9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Review & Explanation: 80. Remove Duplicates from Sorted Array II]]></title>
            <link>https://medium.com/@sandy.yang992/leetcode-review-explanation-80-remove-duplicates-from-sorted-array-ii-3ad6a40322c2?source=rss-8a2d734dd544------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ad6a40322c2</guid>
            <category><![CDATA[code-interview]]></category>
            <category><![CDATA[sorted-array]]></category>
            <category><![CDATA[two-pointer-technique]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <dc:creator><![CDATA[Sandy Yang]]></dc:creator>
            <pubDate>Thu, 03 Apr 2025 05:20:20 GMT</pubDate>
            <atom:updated>2025-04-03T05:20:20.517Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s a normal day practicing LeetCode for job interviews.</p><p>As a student without a computer science background, I know firsthand how array questions can feel <strong>intimidating</strong> at first. But just like standardized test questions, most coding problems can be <strong>broken down into patterns</strong> — and once you learn the patterns, they’re way easier to tackle.</p><p>One of the most important array patterns to know is the <strong>Two Pointers</strong> technique. And <a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/?envType=study-plan-v2&amp;envId=top-interview-150"><strong>LeetCode 80: Remove Duplicates from Sorted Array II</strong></a> — is a textbook example of it.</p><h3>💡 Two Pointers Pattern</h3><p>In Two Pointers problems, we use:</p><ul><li>one pointer (i) to <strong>scan</strong> through the array, and</li><li>another pointer (k) to <strong>build</strong> the result.</li></ul><p>Here’s a common template:</p><pre>int k = initial_index;<br><br>for (int i = initial_index; i &lt; nums.length; i++) {<br>    if (record_condition) {<br>        nums[k] = nums[i]; // save the valid element<br>        k++;<br>    }<br>}</pre><ul><li>i is our <strong>reader</strong> — it moves forward to examine each number.</li><li>k is our <strong>writer</strong> — it only moves when we find something we want to keep.</li></ul><p>✨ How the Code Works</p><p>In <strong>LeetCode 80: Remove Duplicates from Sorted Array II</strong>, we&#39;re told that each number can appear <strong>at most twice</strong>. That means we want to keep the <strong>first and second</strong> appearances of any number, but skip duplicates beyond that.</p><p>Since the input array is already <strong>sorted in ascending order</strong>, we don’t need to worry about previous elements being greater than the current one. This sorted property is key — it ensures that all duplicates are <strong>grouped together</strong>, making it easier to count them as we iterate.</p><p>Let’s uses our template and see what will the solution looks like:</p><pre>class Solution {<br>    public int removeDuplicates(int[] nums) {<br>       int k = 2;  // start with the third element in the array<br>       <br>       // if current element is larger than the previous 2 elements, record.<br>       for(int i = 2; i &lt; nums.length ; i++) {<br>            if (nums[i] != nums[k-2]) {<br>                nums[k] = nums[i];<br>                k++;<br>            }<br>       }<br>       return k;<br>    }<br>}</pre><p>Simple and elegant!</p><h3>🧠 A Mindset Shift That Helped Me</h3><p>The trick is to <strong>focus on the condition for keeping elements</strong> rather than overthinking how to skip them.</p><p>When I first saw this kind of question, I got overwhelmed by all the “what ifs.” Thoughts like:</p><blockquote><em>“What if the current number is the same as the last two?”<br> “Do I need to move the pointer manually?”<br> “Will the for-loop skip it for me?”</em></blockquote><p>All of those doubts are normal! But once you realize that you’re only responsible for deciding <strong>what to keep</strong>, and the for-loop naturally moves things along, it becomes way more manageable.</p><h3>🧩 Related Problems (Practice Makes Patterns Stick)</h3><p>If you understood this problem, you’re well on your way to mastering the <strong>Two Pointers</strong> pattern. Here are a few related problems that build on the same core ideas:</p><h4>⚙️ Intermediate</h4><ul><li>283. Move Zeroes<br> ➤ Shift all zeroes to the end while maintaining the relative order of the other elements.</li><li>167. Two Sum II — Input Array is Sorted<br> ➤ Classic Two Pointers in a sorted array to find a target sum.</li></ul><h4>🧠 Advanced</h4><ul><li>75. Sort Colors<br> ➤ Also called the Dutch National Flag problem. Another pointer-heavy, in-place sort.</li><li>986. Interval List Intersections<br> ➤ A Two Pointers problem in disguise, working with two arrays of intervals.</li><li>3. Longest Substring Without Repeating Characters<br> ➤ Uses a <strong>sliding window</strong> variation of the Two Pointers pattern.</li></ul><h3>💬 Final Thoughts</h3><p>Array problems can look scary, especially with all the index juggling. But once you recognize the <strong>pattern</strong>, things get easier.</p><p>The <strong>Two Pointers</strong> technique appears in so many array questions — once it “clicks,” you’ll start seeing it everywhere. Focus on clearly assigning <strong>roles to your pointers</strong> (reader vs writer), and ask:</p><blockquote><em>What am I trying to keep? What’s my condition for recording?</em></blockquote><p>Mastering that mindset is how I started gaining confidence in LeetCode — and you can too. 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ad6a40322c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>