<?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 44y4755 on Medium]]></title>
        <description><![CDATA[Stories by 44y4755 on Medium]]></description>
        <link>https://medium.com/@44y4755?source=rss-9668da936277------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ja571PflYoFmc0ePs0gikw.jpeg</url>
            <title>Stories by 44y4755 on Medium</title>
            <link>https://medium.com/@44y4755?source=rss-9668da936277------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:32:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@44y4755/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[Algorithm #6: Minimum Swap 2]]></title>
            <link>https://44y4755.medium.com/algorithm-6-minimum-swap-2-195d4825e957?source=rss-9668da936277------2</link>
            <guid isPermaLink="false">https://medium.com/p/195d4825e957</guid>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[greedy-algorithms]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding-test]]></category>
            <dc:creator><![CDATA[44y4755]]></dc:creator>
            <pubDate>Wed, 03 Sep 2025 13:38:40 GMT</pubDate>
            <atom:updated>2025-09-03T13:39:35.434Z</atom:updated>
            <content:encoded><![CDATA[<h4>2D Array, Greedy</h4><p>The following problem is sourced from HackerRank. You can find and attempt it at the link below:</p><p><a href="https://www.hackerrank.com/challenges/minimum-swaps-2/problem?isFullScreen=true&amp;h_l=interview&amp;playlist_slugs%5B%5D=interview-preparation-kit&amp;playlist_slugs%5B%5D=arrays">Minimum Swaps 2 | HackerRank</a></p><h3>Problem</h3><p>You are given an array arr, which is a permutation of integers from 1 to n.</p><p>Your task is to determine the <strong>minimum number of swaps</strong> required to sort the array in ascending order.</p><ul><li>You can swap <strong>any two elements</strong>.</li><li>The array always contains all integers 1..n exactly once (no duplicates).</li></ul><h4>Function Signature</h4><pre>def minimumSwaps(arr: List[int]) -&gt; int</pre><h4>Parameters</h4><p>arr[n]: an unordered permutation of integers 1..n</p><h4>Returns</h4><p>int: the minimum number of swaps to sort the array</p><h4>Input Format</h4><ul><li>First line: integer n, the size of the array</li><li>Second line: n space-separated integers (the array arr)</li></ul><h4>Constraints</h4><ul><li>1 ≤ n ≤ 10⁵</li><li>arr is always a valid permutation of 1..n</li></ul><h4>Sample Input</h4><pre>4<br>4 3 1 2</pre><h4>Sample Output</h4><pre>3</pre><p><strong>Explanation:</strong></p><ul><li>Initial: [4, 3, 1, 2]</li><li>swap(0,2) → [1, 3, 4, 2]</li><li>swap(1,3) → [1, 2, 4, 3]</li><li>swap(2,3) → [1, 2, 3, 4]</li><li>Total = 3 swaps</li></ul><h3>Solution</h3><p>Always place the current value into its target index (v → v−1).</p><p>Count the swap, and only move on when the current index is correct.</p><pre>def minimumSwaps(arr):<br>  length = len(arr)<br>  step = 0<br>  counter = 0<br>  <br>  while step &lt; length:<br>    correct_index = arr[step] - 1<br>    if arr[step] != arr[correct_index]<br>      arr[step], arr[correct_index] = arr[correct_index], arr[step]<br>      counter += 1<br><br>    else:<br>      step += 1<br><br>  return counter</pre><p>Thank you! :))</p><p><a href="https://github.com/doyun-gu/coding-test-prep/blob/main/01-arrays/04_minimum-swap2.py">coding-test-prep/01-arrays/04_minimum-swap2.py at main · doyun-gu/coding-test-prep</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WjSf2TTCTO3wGwVl081kAg.jpeg" /><figcaption>My lovely Camera!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=195d4825e957" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithm #5: New Year Chaos]]></title>
            <link>https://44y4755.medium.com/algorithm-5-new-year-chaos-dbb74e4f132e?source=rss-9668da936277------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbb74e4f132e</guid>
            <category><![CDATA[greedy-algorithms]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[counting]]></category>
            <category><![CDATA[coding-test]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[44y4755]]></dc:creator>
            <pubDate>Wed, 03 Sep 2025 03:48:26 GMT</pubDate>
            <atom:updated>2025-09-03T03:48:26.339Z</atom:updated>
            <content:encoded><![CDATA[<h4>2D Array, Greedy, Counting Problem</h4><p>The following problem is sourced from HackerRank. You can find and attempt it at the link below:</p><p><a href="https://www.hackerrank.com/challenges/new-year-chaos/problem?isFullScreen=true&amp;h_l=interview&amp;playlist_slugs%5B%5D=interview-preparation-kit&amp;playlist_slugs%5B%5D=arrays">New Year Chaos | HackerRank</a></p><h3>Problem</h3><p>It’s New Year’s Day and people are in line for the Wonderland rollercoaster ride.</p><p>Each person has a sticker with their <strong>initial position</strong> (1 to n).</p><h4><strong>Rules:</strong></h4><ul><li>A person can bribe the one directly in front to swap positions.</li><li>A person can bribe <strong>at most two others</strong>.</li><li>Stickers (original positions) never change.</li></ul><h4><strong>Task:</strong></h4><p>Given the final state of the queue, determine the <strong>minimum number of bribes</strong> that took place.</p><p>If someone must have bribed more than 2 others, print &quot;Too chaotic&quot;.</p><h4>Function Signature</h4><pre>def minimumBribes(q: List[int]) -&gt; None</pre><h4>Parameters</h4><p>q[n]: list of integers representing the final state of the queue</p><h4>Input Format</h4><ul><li>First line: integer t (number of test cases)</li><li>For each test case:</li><li>One line: integer n (size of queue)</li><li>One line: n space-separated integers (final queue state)</li></ul><h4>Constraints</h4><ul><li>1 ≤ t ≤ 10</li><li>1 ≤ n ≤ 10⁵</li></ul><h4>Sample Input</h4><pre>2<br>5<br>2 1 5 3 4<br>5<br>2 5 1 3 4</pre><h4>Sample Output</h4><pre>3<br>Too chaotic</pre><p><strong>Explanation:</strong></p><ul><li>Test Case 1:</li><li>Person 5 bribed 4 and 3</li><li>Person 2 bribed 1</li><li>Total = 3 bribes</li><li>Test Case 2:</li><li>Person 5 appears to have bribed 3 people → impossible</li><li>Print &quot;Too chaotic&quot;</li></ul><h3>Solution — LEVEL:MEDIUM</h3><p>As a person who haven’t done this kind of algorithm solving problem, it was a bit tricky to me I can’t lie. But I realised that it was not that complex question if how this question can be approached.</p><h4>Understand the point of question</h4><p>In the given array, the rule is, each person can give a bribe to a person adjacent. In other words, everyone can swap with the people in a both right and left side.</p><p>So there are some information that we can remind as below:</p><ul><li>If more than two bride (bribe_counter &gt;= 3), no need to process anymore =&gt; print (&quot;Too Chaotic&quot;)</li><li>Each person has their own original seat number in a ascending order.</li><li>But the given number is in the resulted array <br>(After all bribe giving are made)</li></ul><p>From these given information we could get the following idea:</p><pre>Before<br>|index|0|1|2|3|4|...<br>|before|1|2|3|4|5|...<br><br>After<br>|index|0|1|2|3|4|...<br>|after|2|1|5|3|4|...</pre><p>From the above simple view of tables, the original seat can be get by index-1. If after-index &gt; 2, then it will be too chaotic.</p><p>Then, if it’s within 2, then it will be able to count the number of chaotic.</p><h4>Brief Coding</h4><pre>bribe_counter = 0<br><br># Find the original seat<br>for index, value in enumerate(q):<br>  if value - (index+1) &gt; 2:<br>    print(&quot;Too Chaotic&quot;)<br><br>  # Count the number of bribe<br>  start_pos = max(value-2, 1)<br>  <br>  for person in range(start_pos-1, index):<br>    if q[person] &gt; value:<br>      bribe_counter += 1<br><br>return bribe_counter<br>      </pre><h4>Full Code</h4><pre>def minimumBribes(q):<br><br>  bribe_counter = 0<br>  <br>  for index, value in enumerate(q):<br>    if value - (index+1) &gt; 2:<br>      print(&quot;Too Chaotic&quot;)<br><br>    start_pos = max(value-2, 1)<br><br>    for person in range(start_pos-1, index):<br>      if q[person] &gt; value:<br>        bribe_counter += 1<br><br>  return bribe_counter</pre><p>Thank you! :))</p><p><a href="https://github.com/doyun-gu/coding-test-prep/blob/main/01-arrays/03_new-year_chaos.py">coding-test-prep/01-arrays/03_new-year_chaos.py at main · doyun-gu/coding-test-prep</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3cbMH1oALVfmhUJiMYvhg.jpeg" /><figcaption>Back to Manchester!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbb74e4f132e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithm #4: Repeated Strings]]></title>
            <link>https://44y4755.medium.com/algorithm-4-repeated-strings-8922e91ba632?source=rss-9668da936277------2</link>
            <guid isPermaLink="false">https://medium.com/p/8922e91ba632</guid>
            <dc:creator><![CDATA[44y4755]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 20:09:41 GMT</pubDate>
            <atom:updated>2025-09-02T22:49:24.013Z</atom:updated>
            <content:encoded><![CDATA[<h4>String, Counting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*waZ5dd4FqnX3AvogwAI0vA.jpeg" /><figcaption>Aston Martin Valkyrie!</figcaption></figure><p>The following problem is sourced from HackerRank. You can find and attempt it at the link below:</p><p><a href="https://www.hackerrank.com/challenges/repeated-string/problem?isFullScreen=true&amp;h_l=interview&amp;playlist_slugs%5B%5D=interview-preparation-kit&amp;playlist_slugs%5B%5D=warmup">Repeated String | HackerRank</a></p><h3>Problem</h3><p>There is a string s of lowercase English letters that is repeated infinitely many times.</p><p>Given an integer n, determine the number of occurrences of the letter &#39;a&#39; in the first n characters of this infinite string.</p><h4>Function Signature</h4><p>repeatedString(s: str, n: int) -&gt; int</p><h4>Parameters</h4><ul><li>s (string): the base string to repeat</li><li>n (int): the number of characters to consider</li></ul><h4>Returns</h4><ul><li>int: the frequency of &#39;a&#39; in the first n characters</li></ul><h4>Input Format</h4><ul><li>First line: a string s</li><li>Second line: an integer n</li></ul><h4>Constraints</h4><ul><li>1 ≤ |s| ≤ 100</li><li>1 ≤ n ≤ 10¹²</li><li>For 25% of test cases, n ≤ 10⁶</li></ul><h4>Sample Input</h4><pre>aba<br>10</pre><h4>Sample Output</h4><pre>7</pre><h4><strong>Explanation:</strong></h4><p>Infinite string: &quot;abaabaabaa...&quot;</p><p>First 10 characters: &quot;abaabaabaa&quot;</p><p>Occurrences of &#39;a&#39;: 7</p><h3>Solution</h3><p>For this problem, unlike the previous ones, the constraints force us to think about complexity. Since n can be as large as 10¹², building the repeated string or a list is infeasible. Instead, we use a simple arithmetic approach.</p><h4><strong>Method with a tiny example</strong></h4><p>Assume s = &quot;abc&quot; and n = 5. The first five characters of the infinite string are abcab.</p><p>We can see:</p><ul><li>Number of full cycles: 5 // 3 = 1</li><li>Remainder length: 5 % 3 = 2 → we only take &quot;ab&quot; from the next cycle.<br> Total &#39;a&#39; count = 1 * count(&quot;a&quot; in &quot;abc&quot;) + count(&quot;a&quot; in &quot;ab&quot;) = 1 * 1 + 1 = 2.</li></ul><h4><strong>Formula</strong></h4><p>Let L = len(s), q = n // L, r = n % L.<br><strong>Answer</strong> = q * count_a(s) + count_a(s[:r]).</p><h4><strong>Complexity</strong></h4><p>Time <strong>O(L)</strong>, Space <strong>O(1)</strong>.</p><h4>Code</h4><pre>def repeatedString(s: str, n: int) -&gt; int:<br>    L = len(s)<br>    full_cycles = n // L          <br>    remainder = n % L             <br><br>    a_in_s = s.count(&#39;a&#39;)        <br>    a_in_prefix = s[:remainder].count(&#39;a&#39;)  <br><br>    return full_cycles * a_in_s + a_in_prefix</pre><p>Thank you! :))</p><p><a href="https://github.com/doyun-gu/coding-test-prep/blob/main/00-warm-up/test_case4.py">coding-test-prep/00-warm-up/test_case4.py at main · doyun-gu/coding-test-prep</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8922e91ba632" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithm #3: Jumping Clouds]]></title>
            <link>https://44y4755.medium.com/algorithm-3-jumping-clouds-2b78c3dcf3fd?source=rss-9668da936277------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b78c3dcf3fd</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding-test]]></category>
            <category><![CDATA[greedy-algorithms]]></category>
            <dc:creator><![CDATA[44y4755]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 17:28:36 GMT</pubDate>
            <atom:updated>2025-09-02T17:28:36.986Z</atom:updated>
            <content:encoded><![CDATA[<h4>Greedy</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Br00y48Z_In0D2UlEwxGVg.jpeg" /><figcaption>At Aston Martin!</figcaption></figure><p>The following problem is sourced from HackerRank. You can find and attempt it at the link below:</p><p><a href="https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem?isFullScreen=true&amp;h_l=interview&amp;playlist_slugs%5B%5D=interview-preparation-kit&amp;playlist_slugs%5B%5D=warmup">Jumping on the Clouds | HackerRank</a></p><h3>Problem — LEVEL:EASY</h3><p>A game is played on consecutively numbered clouds.</p><ul><li>Safe clouds are represented by 0 (cumulus).</li><li>Dangerous clouds are represented by 1 (thunderheads).</li><li>The player starts at the first cloud (index 0) and must reach the last cloud.</li></ul><h4><strong>Rules:</strong></h4><ul><li>The player can jump from cloud i to i+1 or i+2.</li><li>The player can only land on safe clouds (0).</li><li>It is always possible to win the game.</li></ul><h4>Task</h4><p>Determine the <strong>minimum number of jumps</strong> needed to get from the start to the last cloud.</p><h4>Function Signature</h4><p>jumpingOnClouds(c: List[int]) -&gt; int</p><h4>Parameters</h4><ul><li>c[n]: list of integers (0 = safe, 1 = thunderhead)</li></ul><h4>Returns</h4><ul><li>An integer: the minimum number of jumps required</li></ul><h4>Input Format</h4><ul><li>First line: integer n (the number of clouds)</li><li>Second line: n space-separated integers c[i] (0or 1)</li></ul><h4>Output Format</h4><ul><li>Print the minimum number of jumps</li></ul><h4>Constraints</h4><ul><li>2 ≤ n ≤ 100</li><li>c[i] ∈ {0, 1}</li><li>c[0] = c[n-1] = 0 (first and last clouds are always safe)</li></ul><h4>Sample Input</h4><pre>7<br>0 0 1 0 0 1 0</pre><h4>Sample Output</h4><pre>4</pre><h3>Solution</h3><p>For this question, it asks to return the minimum number of jumps to get to the end of the cloud.</p><p>We aim to minimise jumps by always taking a 2-cloud jump when possible. Otherwise, we take a 1-cloud jump.</p><h4>Logic</h4><ul><li>Set Variables properly → <strong>Initialise variables</strong></li><li>Use while loop</li><li>Check the next two positions are safe before jumping two steps</li><li>Update the index (i) and increment jumps after each move</li></ul><pre>jump_count = 0<br>on_cloud = 0<br>n = len(c)</pre><p>Then I made a for loop to get a set of integers to check the cloud and go:</p><pre>while on_cloud &lt; n:<br>  # Check the Range<br>  if on_cloud + 2 &lt; n and c[on_cloud+2] == 0:<br>    on_cloud += 2<br>  <br>  else:<br>    on_cloud += 1<br><br>  jump_count += 1</pre><h4>Code</h4><pre>def jumpingOnClouds(c):<br>  jump_count = 0   # Jump Count &lt;- what to return<br>  on_cloud = 0     # Current step-on-cloud<br>  n = len(c)       # Length<br><br>  while on_cloud &lt; n:<br>    if on_cloud + 2 &lt; n and c[on_cloud+2]==0:<br>      on_cloud += 2<br><br>    else:<br>      on_cloud += 1<br><br>  jump_counter += 1<br><br>  return jumpt_counter</pre><p>Thank you! :))</p><p><a href="https://github.com/doyun-gu/coding-test-prep/blob/main/00-warm-up/test_case3.py">coding-test-prep/00-warm-up/test_case3.py at main · doyun-gu/coding-test-prep</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b78c3dcf3fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithm #2: Counting Valley]]></title>
            <link>https://44y4755.medium.com/algorithm-2-counting-valley-b56f56ae9d2c?source=rss-9668da936277------2</link>
            <guid isPermaLink="false">https://medium.com/p/b56f56ae9d2c</guid>
            <category><![CDATA[coding-test]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[counting]]></category>
            <dc:creator><![CDATA[44y4755]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 16:53:42 GMT</pubDate>
            <atom:updated>2025-09-02T16:53:42.179Z</atom:updated>
            <content:encoded><![CDATA[<h4>Couting Problem, Prefixsum</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ja571PflYoFmc0ePs0gikw.jpeg" /><figcaption>Gaython Gathering August 2025</figcaption></figure><p>The following problem is sourced from HackerRank. You can find and attempt it at the link below:</p><p><a href="https://www.hackerrank.com/challenges/counting-valleys/problem?isFullScreen=true&amp;h_l=interview&amp;playlist_slugs%5B%5D=interview-preparation-kit&amp;playlist_slugs%5B%5D=warmup">Counting Valleys | HackerRank</a></p><h3>Problem — LEVEL:EASY</h3><p>An avid hiker records each step of a hike as uphill (U) or downhill (D). Starting at sea level (0), each step changes altitude by ±1.</p><p>A <strong>valley</strong> is any sequence of consecutive steps <strong>below sea level</strong>, starting with a step down from sea level and ending when returning to sea level.</p><p>Given the sequence of steps, determine how many valleys were traversed.</p><h4>Function Signature</h4><p>countingValleys(steps: int, path: str) -&gt; int</p><h4>Parameters</h4><ul><li>steps — the number of steps in the hike</li><li>path — a string of length steps consisting only of &#39;U&#39; and &#39;D&#39;</li></ul><h4>Output</h4><ul><li>An integer: the number of valleys walked through</li></ul><h4>Input Format</h4><ul><li>First line: integer steps</li><li>Second line: string path of steps characters (&#39;U&#39;/&#39;D&#39;)</li></ul><h4>Constraints</h4><ul><li>2 ≤ steps ≤ 10^6</li><li>path[i] ∈ {&#39;U&#39;, &#39;D&#39;}</li><li>The hike starts and ends at sea level</li></ul><h4>Sample Input</h4><pre>8<br>UDDDUDUU</pre><h4>Sample Output</h4><pre>1</pre><h4>Explanation (visual)</h4><p>Sea level _ , uphill /, downhill /:</p><pre>_/\      _<br>   \    /<br>    \/\/</pre><p>The hiker enters and exits exactly one valley.</p><h3>Solution</h3><h4>Methodologies:</h4><ul><li>Set Variables properly</li></ul><pre>valley_count = 0<br>level = 0</pre><ul><li>Use while loop</li><li>Check the path type on each step</li><li>When it’s uphill, check it reaches to the sea level</li><li>After every step, increase step_tracker</li></ul><h4>Main Idea &amp; Code</h4><pre>for step in path:<br>  if step == &quot;U&quot;:<br>    # Increase level<br>    level += 1<br><br>    # Check and Count Valley<br>    if level == 0:<br>      valley_count += 1<br><br>  else:<br>    # Decrease level<br>    level -= 1</pre><p>We track altitude with level, starting at 0. For each character in path, we increment on &#39;U&#39; and decrement on &#39;D&#39;. A valley is completed precisely when an uphill step brings us back to sea level (level becomes 0). Each time that happens, we increment valley_count.</p><pre>def countingValleys(steps, path):<br>    level = 0           # current altitude relative to sea level<br>    valley_count = 0<br><br>    for step in path:<br>        if step == &#39;U&#39;:<br>            level += 1<br>            # If we just came UP to sea level, a valley ended<br>            if level == 0:<br>                valley_count += 1<br>        else:  # step == &#39;D&#39;<br>            level -= 1<br><br>    return valley_count</pre><p>Thank you! :))</p><p><a href="https://github.com/doyun-gu/coding-test-prep/blob/main/00-warm-up/test_case2.py">coding-test-prep/00-warm-up/test_case2.py at main · doyun-gu/coding-test-prep</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b56f56ae9d2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithm #1: Sales by Match]]></title>
            <link>https://44y4755.medium.com/algorithm-1-sales-by-match-72fb0f8ab5a9?source=rss-9668da936277------2</link>
            <guid isPermaLink="false">https://medium.com/p/72fb0f8ab5a9</guid>
            <category><![CDATA[counting]]></category>
            <category><![CDATA[coding-test]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[44y4755]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 15:40:25 GMT</pubDate>
            <atom:updated>2025-09-02T16:25:53.151Z</atom:updated>
            <content:encoded><![CDATA[<h4>Counting Problem, Dictionary &amp; Hashmap</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fz0x1WUSCfEUxvYZOyL0Q.jpeg" /><figcaption>Back to Manchester!</figcaption></figure><h3>Introduction</h3><p>I’m not really a “software person,” but I recently decided to start preparing for coding online assessments. That means I need to review, memorise, and practice some Data Structures and Algorithms (DSA) in the short term.</p><p>Even though my main focus has been on firmware and other areas, programming always shares some common ground, so I believe this practice will definitely help me.</p><p>The following problem is sourced from HackerRank. You can find and attempt it at the link below:</p><p><a href="https://www.hackerrank.com/interview/interview-preparation-kit/warmup/challenges">Solve Warm-up Challenges Interview Questions | HackerRank</a></p><h3>Problem — LEVEL: EASY</h3><p>There is a pile of socks, each sock identified by its colour. Given an array of integers representing the colours, <strong>determine how many pairs of socks with matching colours can be formed</strong>.</p><h4>Input Format</h4><ul><li>The first line: an integer n (the number of socks)</li><li>The second line: n space-separated integers ar[i] (the colous of the socks)</li></ul><h4>Output Format</h4><ul><li>An integer representing the total number of matching pairs of socks</li></ul><h4>Constraints</h4><ul><li>1 ≤ n ≤ 100</li><li>1 ≤ ar[i] ≤ 100</li></ul><h4>Sample Input</h4><pre>9<br>10 20 20 10 10 30 50 10 20</pre><h4>Sample Output</h4><pre>3</pre><h3>Solution</h3><h4>Methodologies</h4><ul><li>What method can I use to count the number of socks by colour?</li><li>number_of_socks // 2 gives the number of pairs</li></ul><h4>Main idea</h4><blockquote>This will store the count of socks by colour in the array. The format will look like this:</blockquote><pre>n = len(arr)<br>counter = [0] * 101 # From the constraints<br><br>for colour in arr:<br>  counter[colour] += 1</pre><p>This will store the count of socks by colour in the array. The format will look like this:</p><pre>| colour | 10 | 20 | 30 | 40 | ... |<br>|--------|----|----|----|----|-----|<br>| count  | 4  | 2  | 1  | 4  | ... |</pre><p>Then, for each colour, we can simply divide the count by 2 to get the number of pairs.</p><pre>pairs = 0<br>for colour, count in enumerate(counter):<br>  pairs += count//2</pre><h4>Code</h4><pre>def sockMerchant (n, ar):<br>  <br>  # Create empty counter array<br>  counter = [0]*101<br><br>  # Get the count for each colour<br>  for colour in ar:<br>    counter[colour] += 1<br><br>  # Get the number of pairs<br>  pairs = 0<br>  <br>  for colour, count in enumerate(counter):<br>    pairs += count//2<br><br>  return pairs</pre><p><a href="https://github.com/doyun-gu/coding-test-prep/blob/main/00-warm-up/test_case1.py">coding-test-prep/00-warm-up/test_case1.py at main · doyun-gu/coding-test-prep</a></p><p>Thank you! :))</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72fb0f8ab5a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[enum Vs struct in C]]></title>
            <link>https://44y4755.medium.com/enum-vs-struct-in-c-79949db1605c?source=rss-9668da936277------2</link>
            <guid isPermaLink="false">https://medium.com/p/79949db1605c</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[44y4755]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 09:22:21 GMT</pubDate>
            <atom:updated>2024-10-25T09:22:21.305Z</atom:updated>
            <content:encoded><![CDATA[<h4>My Programming Cheat Sheet #6</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OY3TpBPc_e_EdGEOzpyW-A.jpeg" /><figcaption>2024–10–25</figcaption></figure><p>In C programming, both struct and enum are user-defined data types, but they serve different purposes:</p><h3>struct (Structure)</h3><ul><li><strong>Purpose</strong>: Used to group multiple variables of different data types under a single name, forming a complex data structure.</li><li><strong>How it Works</strong>: A struct allows you to create a data structure that can hold various types of information. For example, a struct representing a &quot;person&quot; might hold both char (for name) and int (for age).</li><li><strong>When to Use</strong>: Use struct when you need to represent an entity or record that has multiple related properties (fields) of potentially different data types.</li></ul><pre>#include &lt;stdio.h&gt;<br><br>// Define a structure to represent a person<br>struct Person {<br>    char name[50];<br>    int age;<br>    float height;<br>};<br><br>int main() {<br>    // Create an instance of the struct<br>    struct Person person1;<br>    <br>    // Assign values<br>    person1.age = 30;<br>    person1.height = 5.9;<br>    sprintf(person1.name, &quot;Alice&quot;);<br><br>    // Accessing struct values<br>    printf(&quot;Name: %s\n&quot;, person1.name);<br>    printf(&quot;Age: %d\n&quot;, person1.age);<br>    printf(&quot;Height: %.1f\n&quot;, person1.height);<br><br>    return 0;<br>}</pre><h3>enum (Enumeration)</h3><ul><li><strong>Purpose</strong>: Used to define a collection of related constants (integral values), making code more readable and easier to manage.</li><li><strong>How it Works</strong>: Each item in an enum represents a unique constant with an integer value (by default, starting from 0).</li><li><strong>When to Use</strong>: Use enum when you need a set of named constants, especially if they represent discrete states or categories (e.g., days of the week, colours, modes).</li></ul><pre>#include &lt;stdio.h&gt;<br><br>// Define an enum for days of the week<br>enum Weekday {<br>    MONDAY,<br>    TUESDAY,<br>    WEDNESDAY,<br>    THURSDAY,<br>    FRIDAY,<br>    SATURDAY,<br>    SUNDAY<br>};<br><br>int main() {<br>    // Define a variable of enum type<br>    enum Weekday today = WEDNESDAY;<br><br>    // Using enum values in code<br>    if (today == WEDNESDAY) {<br>        printf(&quot;It&#39;s the middle of the week!\n&quot;);<br>    }<br><br>    return 0;<br>}</pre><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zn_WuKBChr6YgYNMA8v4A.png" /></figure><ul><li>Use <strong>struct</strong> when you need to store multiple properties of a real-world entity, each potentially of a different type.</li><li>Use <strong>enum</strong> when you need a set of named constants that represent specific, predefined values or states.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79949db1605c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blocking, Non-Blocking, Interrupt, and Polling Modes in HAL C]]></title>
            <link>https://44y4755.medium.com/blocking-non-blocking-interrupt-and-polling-modes-in-hal-c-201d67340899?source=rss-9668da936277------2</link>
            <guid isPermaLink="false">https://medium.com/p/201d67340899</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[stm32]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[hardware]]></category>
            <dc:creator><![CDATA[44y4755]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 08:49:04 GMT</pubDate>
            <atom:updated>2024-10-25T08:49:17.438Z</atom:updated>
            <content:encoded><![CDATA[<h4>My Programming Cheat Sheet #5</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j38xM3cpsS9rkvUi4-ITVw.jpeg" /><figcaption>2024–10–25</figcaption></figure><h3>Introduction</h3><p>In STM32 programming with HAL (Hardware Abstraction Layer), <strong>blocking</strong>, <strong>non-blocking</strong>, <strong>interrupt</strong> and <strong>polling</strong> modes control how functions interact with hardware peripherals like UART, I2C, and timers.</p><h3>Blocking Mode</h3><ul><li><strong>Description:</strong> In blocking mode, a function waits (or “blocks”) until the operation completes. For example, if you’re sending data over UART in blocking mode, the CPU will wait until the data is fully transmitted before moving on to the next instruction.</li><li><strong>Use Case:</strong> Useful for quick, simple operations where the system can afford to wait for the peripheral to complete. It’s straightforward to use and doesn’t require complex setup.</li><li><strong>Downside:</strong> Not efficient for lengthy operations, as it ties up the CPU, preventing it from executing other tasks.</li></ul><h3>Non-Blocking Mode</h3><ul><li><strong>Description</strong>: In non-blocking mode, a function initiates the operation but does not wait for it to complete. The function returns immediately, and the operation continues in the background.</li><li><strong>Use Case</strong>: Suitable for applications needing to perform other tasks concurrently without waiting, like in multi-tasking systems.</li><li><strong>Downside</strong>: Requires additional mechanisms to check the completion status (such as polling or interrupt handling) and may need complex state management.</li></ul><h3>Interrupt Mode</h3><ul><li><strong>Description</strong>: In interrupt mode, the CPU initiates an operation and goes on to perform other tasks. When the operation completes (or encounters an event), it triggers an interrupt, which temporarily halts other tasks to handle the event.</li><li><strong>Use Case</strong>: Ideal for applications needing immediate response to events without constant monitoring, such as receiving data over UART or handling button presses.</li><li><strong>Downside</strong>: If interrupts are too frequent, they can overload the CPU, potentially leading to missed events or delayed responses.</li></ul><h3>Polling Mode</h3><ul><li><strong>Description</strong>: In interrupt mode, the CPU initiates an operation and goes on to perform other tasks. When the operation completes (or encounters an event), it triggers an interrupt, which temporarily halts other tasks to handle the event.</li><li><strong>Use Case</strong>: Ideal for applications needing immediate response to events without constant monitoring, such as receiving data over UART or handling button presses.</li><li><strong>Downside</strong>: If interrupts are too frequent, they can overload the CPU, potentially leading to missed events or delayed responses.</li></ul><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Al0usd8LT2V04DQBPIZnAA.png" /><figcaption>Summary of Table</figcaption></figure><h3>Example</h3><ul><li><strong>UART</strong>: Use interrupt mode for receiving continuous data (like a stream) without blocking the CPU. Use blocking mode if you only need to send a small packet occasionally.</li><li><strong>I2C</strong>: Non-blocking or interrupt mode is effective for data reading/writing while handling other tasks. Polling can be suitable for very short transfers or where frequent data is not required.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=201d67340899" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HAL_Delay Vs Interrupt]]></title>
            <link>https://44y4755.medium.com/hal-delay-vs-interrupt-78281988a099?source=rss-9668da936277------2</link>
            <guid isPermaLink="false">https://medium.com/p/78281988a099</guid>
            <category><![CDATA[hardware]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[c-language]]></category>
            <dc:creator><![CDATA[44y4755]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 19:44:11 GMT</pubDate>
            <atom:updated>2024-10-24T19:44:11.469Z</atom:updated>
            <content:encoded><![CDATA[<h4>My Programming Cheat Sheet #4</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zr2nMYDN2z2DlIA5NYkj4A.jpeg" /><figcaption>2024–10–24</figcaption></figure><h3>Introduction</h3><p>It is important to understand the difference between how HAL_Delay() works and how <strong>interrupts</strong> work. Although HAL_Delay() can make your main program pause, <strong>interrupts</strong> are handled differently by the microcontroller and will continue to run even when the main code is waiting inside HAL_Delay().</p><h3>How it works?</h3><h4>Interrupt</h4><p>Interrupts are <strong>hardware mechanisms</strong> that allow the microcontroller to pause whatever it is doing in the <strong>main code</strong> to handle a special event, and then resume the main program after the event has been handled.</p><ul><li>Interrupts, like the SysTick interrupt, are handled by the Nested Vectored Interrupt Controller (NVIC) in the STM32.</li><li>Even when the main program is paused (e.g. inside HAL_Dealy()), the interrupt system is still active. When an interrupt event occurs (like the SysTick timer reaching zero), the microcontroller <strong>pauses</strong> whatever it is doing (including a HAL_Delay() call), jumps to the interrupt service routine (ISR), executes the ISR code, and then returns to continue the main program where it left off.</li></ul><h4>Why HAL_Delay() doesn’t block Interrupts?</h4><p>HAL_Dealy() <strong>does not disable interrupts</strong>. What it does is create a delay in the <strong>main code </strong>by making the program wait for a certain number of milliseconds. But this does not stop the SysTick Interrupt (or any other interrupts) from occurring.</p><h4><strong>HAL_Delay() uses the SysTick timer</strong></h4><ul><li>When you call HAL_Delay(), the function <strong>relies on the SysTick interrupt</strong> to know when the delay has passed. For example, if you call HAL_Delay(50), it waits for 50 SysTick interrupts (1 ms each) to count up to 50 milliseconds.</li></ul><h4><strong>Interrupts still occur during the delay</strong></h4><ul><li>While the HAL_Delay() function makes the <strong>main program wait</strong>, interrupts (like the SysTick interrupt) continue to occur in the background. This is because the microcontroller is designed to handle interrupts even when the main code is paused or delayed.</li><li>Every 1 millisecond, the SysTick timer will trigger an interrupt, and the microcontroller will pause the HAL_Delay() execution to run the <strong>SysTick interrupt service routine (ISR)</strong>.</li></ul><h4><strong>SysTick Interrupt Handler is Called</strong></h4><ul><li>When the SysTick interrupt occurs, the microcontroller will execute the <strong>SysTick_Handler()</strong> (or HAL_SYSTICK_Callback() if you have defined it).</li><li>Inside this interrupt handler, you can process other tasks, like reading sensor data, updating timers, or handling events in real time. After the ISR finishes, the microcontroller resumes the HAL_Delay() or any other task it was performing in the main code.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78281988a099" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Static Vs. Const Vs. Extern in C]]></title>
            <link>https://44y4755.medium.com/static-vs-const-vs-extern-in-c-eda4279134fb?source=rss-9668da936277------2</link>
            <guid isPermaLink="false">https://medium.com/p/eda4279134fb</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computers]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[44y4755]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 19:32:56 GMT</pubDate>
            <atom:updated>2024-10-24T19:32:56.404Z</atom:updated>
            <content:encoded><![CDATA[<h4>My Programming Cheat Sheet #3</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mKd15IRZlQ5tUFh0fIrzWw.jpeg" /><figcaption>2024–10–24</figcaption></figure><h3>Introduction</h3><p>When working with multiple files in C project for me, STM32 HAL C Project, understanding the difference between static, constant, and extern is crucial because they control how variables and functions are shared and accessed different source files. This programming cheat sheet will explain each of keyword and example of usage.</p><h3>static — Internal Linkage</h3><p>The static keyword can be applied to variables and functions to limit their scope to the current file (also called file scope or internal linkage). This means that if you declare a function or a variable as static in one file, it cannot be accessed from other files. It only exists within the file where it is declared.</p><h4>Usage of static</h4><p><strong>Static Global Variables:</strong> If a global variable is declared as static, it can only be used inside the file where it’s declared, preventing conflicts with variables of the same name in other files.</p><pre>// @file: example_1.c<br>static int counter = 0; // Can only be used inside example_1.c</pre><p><strong>Static Functions: </strong>A static function can only be called from within the same file, which is helpful to prevent exposing utility functions that don’t need to be accessed elsewhere.</p><pre>// @file: example_1.c<br>static void hello (void) {<br> // Only accessible within example_1.c<br>}</pre><h4>When to use static?</h4><ul><li>When you want to <strong>limit the visibility</strong> of a variable or function to a specific file, especially if the same names might be used in multiple files.</li><li>To encapsulate helper functions and avoid polluting the global namespace.</li></ul><h3>const — Constant Value</h3><p>The const keyword indicates that the variable’s value cannot be modified after it is initialised. This can be used for both global and local variables, but it does not affect the linkage (visibility) of the variable.</p><h4>Use of const</h4><p><strong>Global const Variables:</strong> By default, a const global variable has external linkage (can be accessed by other files), unless static is used. To share a constant value across multiple files, you can declare it with extern in the header file.</p><pre>// File: example_2.c<br>const int max_value = 100; // Other files can read this value, but can&#39;t change it<br><br>// File: main.c<br>extern const int max_value; // Declare in another file to access it</pre><p><strong>Local const Variables:</strong> Local const variables are like any other local variable, but they cannot be modified after they are initialised.</p><pre>void some_function() {<br>    const int threshold = 50; // Can only be set once, can&#39;t be changed<br>}</pre><h4>When to use const?</h4><ul><li>When you want to declare a <strong>read-only value</strong> that can’t be modified, like configuration constants or fixed values.</li><li>Use const for variables that should not change during program execution to improve readability and safety.</li></ul><h3>extern — External Linkage</h3><p>The extern keyword is used to <strong>declare</strong> a variable or function that is <strong>defined in another file</strong>. It allows different source files to share the same global variable or function without duplicating it.</p><h4>Usage of extern</h4><p><strong>Extern Global Variables:</strong> When a variable is defined in one file and you want to access it from another file, you use extern in the second file to tell the compiler that this variable exists elsewhere.</p><pre>// @file: example_3.c<br>int shared_variable = 10; // Define a global variable<br><br>// @file: example_4.c<br>extern int shared_variable; // Declare the variable so it can be used in example_4.c</pre><p><strong>Extern Functions:</strong> In C, by default, functions have external linkage, so extern is rarely needed for functions. However, if you want to <strong>explicitly declare</strong> a function defined in another file, you can use extern.</p><pre>// @file: example_5.c<br>void shared_function(void); // Declare it in example_5.h (or use extern)<br><br>// @file: example_6.c<br>extern void shared_function(void); // Use in example_6.c</pre><h4>When to use extern?</h4><ul><li>When you want to <strong>share variables or functions between files</strong>.</li><li>Use extern to <strong>declare</strong> global variables and functions that are <strong>defined in another file</strong>.</li></ul><h4>How to use extern?</h4><p>First, define a variable (once, without extern): In one source file (usually the one where you want to “own” the variable), you <strong>define</strong> the variable <strong>without</strong> extern. This is where the variable is actually created in memory.</p><pre>// File: config.c<br>int shared_variable = 10;  // Definition (creates the variable)</pre><p>This is the<strong> definition</strong> of shared_variable, and memory is allocated for it here. You do not use extern here because this is where the variable is actually being defined.</p><p>Next, declaring the variable in other files (with extern): In any other source files that need to access this variable, you need to declare it using extern. The extern keyword tells the compiler, “This variable exists, but it’s defined in another file.”</p><pre>// File: main.c<br>extern int shared_variable;  <br>         // Declaration (no memory allocated, just informs the compiler)</pre><p>With extern, you are telling the compiler that shared_variable exists, and it should look for its definition elsewhere (in this case, in config.c). The actual memory for the variable is still only in config.c.</p><h4>Important Rules</h4><ul><li>You can declare a variable with extern multiple times in different files (as long as you don’t redeclare in the same file).</li><li>You can only define the variable once (without extern), usually in a single .c file.</li></ul><h3>Summary</h3><p><strong>static</strong></p><ul><li>Limits the scope of a variable or function to the current file (internal linkage).</li><li>Used for encapsulation and avoiding name conflicts between files.</li></ul><p><strong>const</strong></p><ul><li>Marks a variable as read-only (its value cannot be modified).</li><li>Does not affect the linkage but ensures that the value of the variable cannot change.</li><li>Can be used with extern to share constants between files.</li></ul><p><strong>extern</strong></p><ul><li>Declares a variable or function that is defined in another file (external linkage).</li><li>Allows different files to access the same global variable or function.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eda4279134fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>