<?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 Gikunda Mbiriri on Medium]]></title>
        <description><![CDATA[Stories by Gikunda Mbiriri on Medium]]></description>
        <link>https://medium.com/@petermbiriri8957?source=rss-29d3db56ce9b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*brx8RHpDE6aI-Ez7.jpg</url>
            <title>Stories by Gikunda Mbiriri on Medium</title>
            <link>https://medium.com/@petermbiriri8957?source=rss-29d3db56ce9b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:57:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@petermbiriri8957/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[Count and Say ‍♂️ Typescript Algorithm]]></title>
            <link>https://medium.com/@petermbiriri8957/count-and-say-%EF%B8%8F-typescript-algorithm-93ec65f8f8e8?source=rss-29d3db56ce9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/93ec65f8f8e8</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gikunda Mbiriri]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 07:14:59 GMT</pubDate>
            <atom:updated>2023-08-18T07:14:59.169Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x0dE1Y6FhemFaAiRsvxzhQ.jpeg" /></figure><p><strong>Challenge Description</strong></p><p>The <strong>count-and-say</strong> sequence is a sequence of digit strings defined by the recursive formula:</p><ul><li>countAndSay(1) = &quot;1&quot;</li><li>countAndSay(n) is the way you would &quot;say&quot; the digit string from countAndSay(n-1), which is then converted into a different digit string.</li></ul><p>To determine how you “say” a digit string, split it into the <strong>minimal</strong> number of substrings such that each substring contains exactly <strong>one</strong> unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.</p><p>For example, the saying and conversion for digit string &quot;3322251&quot;:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/0*BaqqwlKBsbaoAg-Y.jpg" /></figure><p>Given a positive integer n, return <em>the </em>nth<em> term of the </em><strong><em>count-and-say</em></strong><em> sequence</em>.</p><p><strong>Example 1</strong></p><pre>Input: n = 1<br>Output: &quot;1&quot;<br>Explanation: This is the base case.</pre><p><strong>Example 2</strong></p><pre>Input: n = 4<br>Output: &quot;1211&quot;<br>Explanation:<br>countAndSay(1) = &quot;1&quot;<br>countAndSay(2) = say &quot;1&quot; = one 1 = &quot;11&quot;<br>countAndSay(3) = say &quot;11&quot; = two 1&#39;s = &quot;21&quot;<br>countAndSay(4) = say &quot;21&quot; = one 2 + one 1 = &quot;12&quot; + &quot;11&quot; = &quot;1211&quot;</pre><p><strong>Typescript Solution</strong></p><pre>function countAndSay(n: number): string {<br>    if (n === 1) {<br>        return &quot;1&quot;;<br>    }<br>    if (n === 2) {<br>        return &quot;11&quot;;<br>    }<br><br>    let nm: string = &quot;11&quot;;<br>    for (let i = 3; i &lt;= n; i++) {<br>        let kk: string = task(nm);<br>        nm = kk;<br>    }<br><br>    return nm;<br>}<br><br>function task(s: string): string {<br>    let count: number = 1;<br>    let nm: string = &quot;&quot;;<br><br>    for (let i = 0; i &lt; s.length - 1; i++) {<br>        if (s.charAt(i) === s.charAt(i + 1)) {<br>            count++;<br>        } else {<br>            nm += count + s.charAt(i);<br>            count = 1;<br>        }<br>    }<br>    nm += count + s.charAt(s.length - 1);<br><br>    return nm;<br>}</pre><ol><li>The countAndSay function takes an integer n as input and returns a string that represents the nth term of the &quot;Count and Say&quot; sequence.</li><li>The function first checks if n is 1 or 2. If so, it returns &quot;1&quot; or &quot;11&quot; respectively, which are the base cases of the sequence.</li><li>If n is greater than 2, the function initializes the variable nm with the value &quot;11&quot; to represent the second term of the sequence.</li><li>A loop runs from i = 3 up to n. This loop generates subsequent terms of the sequence using the task function and updates the value of nm with each new term.</li><li>The task function takes a string s as input and constructs the next term of the sequence according to the &quot;Count and Say&quot; rules.</li><li>Inside the task function, there&#39;s a loop that iterates through the characters of the input string s.</li><li>For each character, it checks if the current character is the same as the next character. If they are the same, the count variable is incremented.</li><li>If the current character is different from the next one, it appends the count followed by the current character to the nm string. Then, it resets the count to 1.</li><li>After the loop, the final character is appended to the nm string with its respective count.</li><li>The nm string now represents the next term of the sequence and is returned by the task function.</li><li>After iterating through the loop in the countAndSay function, the final value of nm will represent the nth term of the &quot;Count and Say&quot; sequence.</li><li>The function returns this value as a string, which is the desired output.</li></ol><p>Here’s an example of how the countAndSay function works:</p><ul><li>For n = 1, the output is &quot;1&quot;.</li><li>For n = 2, the output is &quot;11&quot;.</li><li>For n = 3, the output is &quot;21&quot; (read as &quot;one 1, one 2&quot;).</li><li>For n = 4, the output is &quot;1211&quot; (read as &quot;one 1, one 2, two 1s&quot;).</li><li>For n = 5, the output is &quot;111221&quot; (read as &quot;three 1s, two 2s, one 1&quot;).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93ec65f8f8e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Will these Asteroids Collide?]]></title>
            <link>https://medium.com/@petermbiriri8957/will-these-asteroids-collide-b9597429d037?source=rss-29d3db56ce9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9597429d037</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gikunda Mbiriri]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 07:36:13 GMT</pubDate>
            <atom:updated>2023-08-17T07:36:13.112Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*--pQwjFKGr3cpdkAraTFBQ.jpeg" /></figure><p><strong>Challenge Description</strong></p><p>We are given an array asteroids of integers representing asteroids in a row.</p><p>For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.</p><p>Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.</p><p><strong>Example 1</strong></p><pre>Input: asteroids = [5,10,-5]<br>Output: [5,10]<br>Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.</pre><p><strong>Example 2</strong></p><pre>Input: asteroids = [8,-8]<br>Output: []<br>Explanation: The 8 and -8 collide exploding each other.</pre><p><strong>Example 3</strong></p><pre>Input: asteroids = [10,2,-5]<br>Output: [10]<br>Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.</pre><p><strong>Intuition</strong></p><p>In this problem, we need to find out the state of the asteroids after all collisions. So for each asteroid, we check if it can collide destructively with the asteroids currently in the stack. If the asteroid’s size is negative (moving to the left) and there are positive-sized asteroids in the stack (moving to the right), they will collide destructively. In such cases, we pop the positive-sized asteroids from the stack until no more collisions are possible or until the negative-sized asteroid is destroyed.</p><p><strong>Approach</strong></p><ul><li>Here’s a short explanation of the code:</li></ul><ol><li>The function “asteroidCollision” iterates through the asteroids in the input vector.</li><li>For each asteroid, it checks if it can collide destructively with the asteroids on the top of the stack.</li><li>If the asteroid collides destructively with the top asteroid(s) in the stack, it removes those asteroids from the stack.</li><li>If the asteroid does not collide destructively with any asteroid in the stack, it is added to the stack.</li><li>Finally, the function constructs a vector “ans” containing the non-colliding asteroids from the stack and returns it as the result.</li></ol><p><strong>Complexity</strong></p><ul><li>Time complexity: O(N)</li><li>Space complexity: O(N)</li></ul><pre>function asteroidCollision(asteroids: number[]): number[] {<br>  const stack: number[] = [];<br><br>  for (const it of asteroids) {<br>    let flag = 1;<br><br>    while (stack.length &gt; 0 &amp;&amp; stack[stack.length - 1] &gt; 0 &amp;&amp; it &lt; 0) {<br>      if (Math.abs(stack[stack.length - 1]) &lt; Math.abs(it)) {<br>        stack.pop();<br>        continue;<br>      } else if (Math.abs(stack[stack.length - 1]) === Math.abs(it)) {<br>        stack.pop();<br>      }<br><br>      flag = 0;<br>      break;<br>    }<br><br>    if (flag) {<br>      stack.push(it);<br>    }<br>  }<br><br>  const ans: number[] = new Array(stack.length);<br>  for (let i = ans.length - 1; i &gt;= 0; i--) {<br>    ans[i] = stack.pop()!;<br>  }<br><br>  return ans;<br>}<br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9597429d037" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is It a Valid Game — Typescript Algorithm]]></title>
            <link>https://medium.com/@petermbiriri8957/is-it-a-valid-game-typescript-algorithm-edaac296c8d5?source=rss-29d3db56ce9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/edaac296c8d5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Gikunda Mbiriri]]></dc:creator>
            <pubDate>Wed, 16 Aug 2023 05:53:50 GMT</pubDate>
            <atom:updated>2023-08-16T05:53:50.012Z</atom:updated>
            <content:encoded><![CDATA[<h3>Is It a Valid Game — Typescript Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m4C0i7oHSQ4VQbvQCUWBpQ.jpeg" /></figure><p><strong>Challenge Description</strong></p><p>Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated <strong>according to the following rules</strong>:</p><ol><li>Each row must contain the digits 1-9 without repetition.</li><li>Each column must contain the digits 1-9 without repetition.</li><li>Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.</li></ol><p><strong>Note:</strong></p><ul><li>A Sudoku board (partially filled) could be valid but is not necessarily solvable.</li><li>Only the filled cells need to be validated according to the mentioned rules.</li></ul><p><strong>Example 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*KQAX70gjAwj5FqXM.png" /></figure><pre>Input: board = <br>[[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;]<br>,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;]<br>,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;]<br>,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;]<br>,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;]<br>,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;]<br>,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;]<br>,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;]<br>,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]]<br>Output: true</pre><p><strong>Example 2:</strong></p><pre>Input: board = <br>[[&quot;8&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;]<br>,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;]<br>,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;]<br>,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;]<br>,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;]<br>,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;]<br>,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;]<br>,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;]<br>,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]]<br>Output: false<br>Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8&#39;s in the top left 3x3 sub-box, it is invalid.</pre><p><strong>Solution :</strong></p><p>Collect the set of things we see, encoded as strings. For example:</p><ul><li>&#39;4&#39; in row 7 is encoded as &quot;(4)7&quot;.</li><li>&#39;4&#39; in column 7 is encoded as &quot;7(4)&quot;.</li><li>&#39;4&#39; in the top-right block is encoded as &quot;0(4)2&quot;.</li></ul><p>Scream false if we ever fail to add something because it was already added (i.e., seen before).</p><p><strong>Code Explanation</strong></p><ul><li>For each cell in the Sudoku board, three keys (rowKey, colKey, and blockKey) are created to uniquely identify the value in its respective row, column, and block.</li><li>The seen set&#39;s has method is used to check if any of the keys are already present in the set, indicating a duplicate value.</li><li>If any of the keys are found in the seen set, the function returns false.</li><li>If none of the keys are found, the keys are added to the seen set for future reference.</li><li>The function returns true if no duplicate values are found.</li></ul><pre>function isValidSudoku(board: string[][]): boolean {<br>  const seen = new Set&lt;string&gt;();<br><br>  for (let i = 0; i &lt; 9; ++i) {<br>    for (let j = 0; j &lt; 9; ++j) {<br>      const number = board[i][j];<br>      if (number !== &quot;.&quot;) {<br>        const rowKey = number + &quot; in row &quot; + i;<br>        const colKey = number + &quot; in column &quot; + j;<br>        const blockKey =<br>          number + &quot; in block &quot; + Math.floor(i / 3) + &quot;-&quot; + Math.floor(j / 3);<br><br>        if (seen.has(rowKey) || seen.has(colKey) || seen.has(blockKey)) {<br>          return false;<br>        }<br><br>        seen.add(rowKey);<br>        seen.add(colKey);<br>        seen.add(blockKey);<br>      }<br>    }<br>  }<br><br>  return true;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edaac296c8d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minimum Shots with Typescript Greedy Algorithm]]></title>
            <link>https://medium.com/@petermbiriri8957/minimum-shots-with-typescript-greedy-algorithm-7603986781c4?source=rss-29d3db56ce9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7603986781c4</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gikunda Mbiriri]]></dc:creator>
            <pubDate>Tue, 15 Aug 2023 08:30:18 GMT</pubDate>
            <atom:updated>2023-08-15T08:30:18.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_lBp3mcpqd141m7SQcX2Q.jpeg" /></figure><p><strong>Challenge Description</strong></p><p>There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose <strong>horizontal diameter</strong> stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.</p><p>Arrows can be shot up <strong>directly vertically</strong> (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is <strong>burst</strong> by an arrow shot at x if xstart &lt;= x &lt;= xend. There is <strong>no limit</strong> to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.</p><p>Given the array points, return <em>the </em><strong><em>minimum</em></strong><em> number of arrows that must be shot to burst all balloons</em>.</p><p><strong>Example 1</strong></p><pre>Input: points = [[10,16],[2,8],[1,6],[7,12]]<br>Output: 2<br>Explanation: The balloons can be burst by 2 arrows:<br>- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].<br>- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].</pre><p><strong>Example 2</strong></p><pre>Input: points = [[1,2],[3,4],[5,6],[7,8]]<br>Output: 4<br>Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows.</pre><p><strong>Example 3</strong></p><pre>Input: points = [[1,2],[2,3],[3,4],[4,5]]<br>Output: 2<br>Explanation: The balloons can be burst by 2 arrows:<br>- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].<br>- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].</pre><p><strong>Intuition</strong></p><p>If we look at problems related to intervals , first thing we do is sorting but how and by which column.</p><p>Firstly, look at the interval we can solve the problem either reverse order strategy or ascending order. Here I solve using reverse order.</p><p><strong>Approach</strong></p><ol><li>Sort the points according to start points.</li><li>Traverse the points from last start points and check whether my last interval is end before curr_start interval. If so then update new curr_start interval to last interval start point and count the arrows.</li><li>Repeat the step — 2 for all points in points array.</li><li>Return the count of arrow.</li></ol><h3>Complexity</h3><ul><li>Time complexity:<br>O(NlogN)</li><li>Space complexity:<br>O(1)</li></ul><pre>function findMinArrowShots(points: number[][]): number {<br>  // Sort the points in descending order based on the first coordinate (x) of each point<br>  points.sort((a, b) =&gt; b[0] - a[0]);<br><br>  // Initialize the answer with 1 (at least one arrow is needed to start)<br>  let ans = 1;<br>  // Initialize the current position with the x-coordinate of the first point<br>  let currPos = points[0][0];<br><br>  // Loop through each point (x, y) in the sorted array<br>  for (const [x, y] of points) {<br>    // If the y-coordinate of the current point is less than the current position,<br>    // it means the current arrow cannot burst this balloon, so we need a new arrow.<br>    if (y &lt; currPos) {<br>      // Update the current position with the x-coordinate of the current point<br>      currPos = x;<br>      // Increment the answer (a new arrow is needed)<br>      ans++;<br>    }<br>  }<br><br>  // Return the minimum number of arrows needed<br>  return ans;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7603986781c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Container with the most water — Typescript Algorithm]]></title>
            <link>https://medium.com/@petermbiriri8957/container-with-the-most-water-typescript-algorithm-8e3b35aa0b56?source=rss-29d3db56ce9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e3b35aa0b56</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[data-structures-algorithm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Gikunda Mbiriri]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 06:29:34 GMT</pubDate>
            <atom:updated>2023-08-14T06:29:34.090Z</atom:updated>
            <content:encoded><![CDATA[<h3>Container with the most water — Typescript Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qGklfDdlPg0QJyosmAC3Q.jpeg" /></figure><p><strong>Challenge Description</strong></p><p>You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).</p><p>Find two lines that together with the x-axis form a container, such that the container contains the most water.</p><p>Return <em>the maximum amount of water a container can store</em>.</p><p><strong>Notice</strong> that you may not slant the container.</p><p><strong>Example 1</strong></p><pre>Input: height = [1,8,6,2,5,4,8,3,7]<br>Output: 49<br>Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.</pre><p><strong>Example 2</strong></p><pre>Input: height = [1,1]<br>Output: 1</pre><p><strong>Intuition</strong></p><p>The two-pointer technique starts with the widest container and moves the pointers inward based on the comparison of heights.<br>Increasing the width of the container can only lead to a larger area if the height of the new boundary is greater. By moving the pointers towards the center, we explore containers with the potential for greater areas.</p><h3>Explanation:</h3><ol><li>Initialize the variables:</li></ol><ul><li>left to represent the left pointer, starting at the beginning of the container (index 0).</li><li>right to represent the right pointer, starting at the end of the container (index height.size() - 1).</li><li>maxArea to keep track of the maximum area found, initially set to 0.</li></ul><p>2. Enter a loop using the condition left &lt; right, which means the pointers have not crossed each other yet.</p><p>3. Calculate the current area:</p><ul><li>Use the min function to find the minimum height between the left and right pointers.</li><li>Multiply the minimum height by the width, which is the difference between the indices of the pointers: (right - left).</li><li>Store this value in the currentArea variable.</li></ul><p>4. Update the maximum area:</p><ul><li>Use the max function to compare the currentArea with the maxArea.</li><li>If the currentArea is greater than the maxArea, update maxArea with the currentArea.</li></ul><p>5. Move the pointers inward: (Explained in detail below)</p><ul><li>Check if the height at the left pointer is smaller than the height at the right pointer.</li><li>If so, increment the left pointer, moving it towards the center of the container.</li><li>Otherwise, decrement the right pointer, also moving it towards the center.</li></ul><p>6. Repeat steps 3 to 5 until the pointers meet (left &gt;= right), indicating that all possible containers have been explored.</p><p>7. Return the maxArea, which represents the maximum area encountered among all the containers.</p><p><strong>Update the maximum area:</strong></p><p>The purpose of this condition is to determine which pointer to move inward, either the left pointer (i) or the right pointer (j), based on the comparison of heights at their respective positions.</p><p>Imagine you have two containers represented by the heights at the left and right pointers. The condition checks which container has a smaller height and moves the pointer corresponding to that container.</p><ol><li>If height[i] &gt; height[j]:</li></ol><ul><li>This means that the height of the left container is greater than the height of the right container.</li><li>Moving the right pointer (j) would not increase the potential area because the height of the right container is the limiting factor.</li><li>So, to explore containers with the possibility of greater areas, we need to move the right pointer inward by decrementing j.</li></ul><p>2. If height[i] &lt;= height[j]:</p><ul><li>This means that the height of the left container is less than or equal to the height of the right container.</li><li>Moving the left pointer (i) would not increase the potential area because the height of the left container is the limiting factor.</li><li>So, to explore containers with the possibility of greater areas, we need to move the left pointer inward by incrementing i.</li></ul><p>By making these pointer movements, we ensure that we are always exploring containers with the potential for larger areas. The approach is based on the observation that increasing the width of the container can only lead to a larger area if the height of the new boundary is greater.<br>By following this condition and moving the pointers accordingly, the algorithm explores all possible containers and finds the one with the maximum area.</p><pre>function maxArea(height: number[]): number {<br>  let left = 0;<br>  let right = height.length - 1;<br>  let maxArea = 0;<br><br>  while (left &lt; right) {<br>    const currentArea = Math.min(height[left], height[right]) * (right - left);<br>    maxArea = Math.max(maxArea, currentArea);<br><br>    if (height[left] &lt; height[right]) {<br>      left++;<br>    } else {<br>      right--;<br>    }<br>  }<br><br>  return maxArea;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e3b35aa0b56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Longest Common Prefix (TS algorithm)]]></title>
            <link>https://medium.com/@petermbiriri8957/longest-common-prefix-ts-algorithm-731263147942?source=rss-29d3db56ce9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/731263147942</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Gikunda Mbiriri]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 06:18:16 GMT</pubDate>
            <atom:updated>2023-08-11T06:18:16.788Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smvxNq_LCt3_rB9saU6Zjw.jpeg" /></figure><p><strong>Challenge Description</strong></p><p>Write a function to find the longest common prefix string amongst an array of strings.</p><p>If there is no common prefix, return an empty string &quot;&quot;.</p><p><strong>Example 1</strong></p><pre>Input: strs = [&quot;flower&quot;,&quot;flow&quot;,&quot;flight&quot;]<br>Output: &quot;fl&quot;</pre><p><strong>Example 2</strong></p><pre>Input: strs = [&quot;dog&quot;,&quot;racecar&quot;,&quot;car&quot;]<br>Output: &quot;&quot;<br>Explanation: There is no common prefix among the input strings.</pre><p><strong>Approach</strong></p><p>This code is used to find the longest common prefix of an array of strings, which is defined as the longest string that is a prefix of all the strings in the array. By sorting the array and then comparing the first and last elements, the code is able to find the common prefix that would be shared by all strings in the array.</p><ol><li>Sort the elements of an array of strings called “strs” in lexicographic (alphabetical) order using the Arrays.sort(strs) method.</li><li>Assign the first element of the sorted array (the lexicographically smallest string) to a string variable s1.</li><li>Assign the last element of the sorted array (the lexicographically largest string) to a string variable s2.</li><li>Initialize an integer variable idx to 0.</li><li>Start a while loop that continues while idx is less than the length of s1 and s2.</li><li>Within the while loop, check if the character at the current index in s1 is equal to the character at the same index in s2. If the characters are equal, increment the value of idx by 1.</li><li>If the characters are not equal, exit the while loop.</li><li>Return the substring of s1 that starts from the first character and ends at the idxth character (exclusive).</li></ol><p><strong>Complexity</strong></p><ul><li>Time complexity:</li></ul><ol><li>Sorting the array of strings takes O(Nlog(N)) time. This is because most of the common sorting algorithms like quicksort, mergesort, and heapsort have an average time complexity of O(Nlog(N)).</li><li>Iterating over the characters of the first and last strings takes O(M) time. This is because the code compares the characters of the two strings until it finds the first mismatch.</li></ol><p>Therefore, the total time complexity is O(Nlog(N) + M).</p><ul><li>Space complexity:<br>The space used by the two string variables s1 and s2 is proportional to the length of the longest string in the array. Therefore, the space complexity is O(1) as it does not depend on the size of the input array.</li></ul><p><strong>Reason for Sorting</strong></p><p>The reason why we sort the input array of strings and compare the first and last strings is that the longest common prefix of all the strings must be a prefix of the first string and a prefix of the last string in the sorted array. This is because strings are ordered based on their alphabetical order (Lexicographical order).<br>For example, consider the input array of strings {“flower”, “flow”, “flight”}. After sorting the array, we get {“flight”, “flow”, “flower”}. The longest common prefix of all the strings is “fl”, which is located at the beginning of the first string “flight” and the second string “flow”. Therefore, by comparing the first and last strings of the sorted array, we can easily find the longest common prefix.</p><pre>function longestCommonPrefix(strs: string[]): string {<br>  strs.sort();<br>  const s1 = strs[0];<br>  const s2 = strs[strs.length - 1];<br>  let idx = 0;<br><br>  while (idx &lt; s1.length &amp;&amp; idx &lt; s2.length) {<br>    if (s1.charAt(idx) === s2.charAt(idx)) {<br>      idx++;<br>    } else {<br>      break;<br>    }<br>  }<br><br>  return s1.substring(0, idx);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=731263147942" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building The Square Root Function with TS.]]></title>
            <link>https://medium.com/@petermbiriri8957/building-the-square-root-function-with-ts-f7575db41236?source=rss-29d3db56ce9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7575db41236</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Gikunda Mbiriri]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 06:59:31 GMT</pubDate>
            <atom:updated>2023-08-10T06:59:31.174Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e55vRXDPXOsSAmhnDke4-Q.jpeg" /></figure><p><strong>Challenge Description</strong></p><p>Given a non-negative integer x, return <em>the square root of </em>x<em> rounded down to the nearest integer</em>. The returned integer should be <strong>non-negative</strong> as well.</p><p>You <strong>must not use</strong> any built-in exponent function or operator.</p><ul><li>For example, do not use pow(x, 0.5) or x ** 0.5 .</li></ul><p><strong>Example 1</strong></p><pre>Input: x = 4<br>Output: 2<br>Explanation: The square root of 4 is 2, so we return 2.</pre><p><strong>Example 2</strong></p><pre>Input: x = 8<br>Output: 2<br>Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.</pre><p><strong>Intuition</strong></p><p>We want to find the square root of a given non-negative integer x. Instead of using a traditional approach like repeatedly subtracting numbers until we reach 0 or using a library function, we’ll use a smarter method called “Binary Search.” Binary Search helps us quickly find the square root by repeatedly narrowing down the search range.</p><h3>Approach</h3><ol><li>We first check if x is 0 or 1. If it is, we know that the square root of 0 and 1 is 0 and 1 respectively, so we directly return x.</li><li>For any other value of x, we set up a search range between 1 and x. We initialize two variables start and end to represent the range.</li><li>Now comes the clever part: We use a while loop to repeatedly divide the search range in half (Binary Search) to find the square root.</li><li>In each iteration of the loop, we calculate the middle value mid using the formula <strong>start + (end — start) / 2</strong>. This formula ensures that we don’t encounter any integer overflow when dealing with large values of x.</li><li>Next, we calculate the square of mid and compare it with x.</li><li>If the square of mid is greater than x, we know the square root lies in the lower half of the search range. So, we move the end pointer to the left to narrow down the search range.</li><li>If the square of mid is equal to x, we have found the square root! So, we return mid as the answer.</li><li>If the square of mid is less than x, we know the square root lies in the upper half of the search range. So, we move the start pointer to the right to continue the search.</li><li>We repeat steps 4 to 8 until the start pointer becomes greater than the end pointer. At this point, we have found the floor value of the square root, and end holds that value.</li><li>To ensure that we return the correct floor value of the square root, we round down the value of end to the nearest integer using the Math.round() method.</li></ol><p><strong>Complexity</strong></p><ul><li><strong>Time complexity:</strong><br>The time complexity of this approach is O(logN). It’s very efficient because Binary Search reduces the search range by half in each iteration, making the search faster.</li><li><strong>Space complexity:</strong><br>The space complexity is O(1), which means the amount of extra memory used is constant, regardless of the input. We only use a few variables to store the search range and the middle value during the computation.</li></ul><pre>function mySqrt(x: number): number {<br>  // For special cases when x is 0 or 1, return x.<br>  if (x === 0 || x === 1) return x;<br><br>  // Initialize the search range for the square root.<br>  let start = 1;<br>  let end = x;<br>  let mid = -1;<br><br>  // Perform binary search to find the square root of x.<br>  while (start &lt;= end) {<br>    // Calculate the middle point using &quot;start + Math.floor((end - start) / 2)&quot; to avoid integer overflow.<br>    mid = start + Math.floor((end - start) / 2);<br><br>    // If the square of the middle value is greater than x, move the &quot;end&quot; to the left (mid - 1).<br>    if (mid * mid &gt; x) end = mid - 1;<br>    else if (mid * mid === x)<br>      // If the square of the middle value is equal to x, we found the square root.<br>      return mid;<br>    // If the square of the middle value is less than x, move the &quot;start&quot; to the right (mid + 1).<br>    else start = mid + 1;<br>  }<br><br>  // The loop ends when &quot;start&quot; becomes greater than &quot;end&quot;, and &quot;end&quot; is the integer value of the square root.<br>  // However, since we might have been using integer division in the calculations,<br>  // we round down the value of &quot;end&quot; to the nearest integer to get the correct square root.<br>  return Math.floor(end);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7575db41236" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Search with TS — O(logn) Time Complexity]]></title>
            <link>https://medium.com/@petermbiriri8957/binary-search-with-ts-o-logn-time-complexity-dd6ee7fe35a5?source=rss-29d3db56ce9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd6ee7fe35a5</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Gikunda Mbiriri]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 04:50:56 GMT</pubDate>
            <atom:updated>2023-08-09T04:50:56.006Z</atom:updated>
            <content:encoded><![CDATA[<h3>Binary Search with TS — O(logn) Time Complexity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O3UuzyE724kYVshXnlcddA.jpeg" /></figure><p><strong>Challenge Description</strong></p><p>Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.</p><p>You must write an algorithm with O(log n) runtime complexity.</p><p><strong>Example 1:</strong></p><pre>Input: nums = [-1,0,3,5,9,12], target = 9<br>Output: 4<br>Explanation: 9 exists in nums and its index is 4</pre><p><strong>Example 2:</strong></p><pre>Input: nums = [-1,0,3,5,9,12], target = 2<br>Output: -1<br>Explanation: 2 does not exist in nums so return -1</pre><p><strong>Intuition</strong></p><p>Binary search is an efficient algorithm for searching for a specific target value within a sorted array. The basic idea is to repeatedly divide the search interval in half until the target value is found or the interval is empty. By using this approach, we can quickly eliminate half of the remaining search space at each iteration, resulting in a time complexity of O(log n).</p><p><strong>Approach</strong></p><p>The algorithm starts by comparing the target value to the middle element of the sorted array. If the target is equal to the middle element, we return the index of the middle element. If the target is less than the middle element, we repeat the search on the left half of the array. If the target is greater than the middle element, we repeat the search on the right half of the array. We continue this process until either the target is found or the search interval is empty.</p><ul><li>Initialize left and right pointers to the beginning and end of the array, respectively.</li><li>While the left pointer is less than or equal to the right pointer:</li><li>a. Calculate the middle index as the average of the left and right pointers.<br>b. If the middle element is equal to the target, return the index of the middle element.<br>c. If the middle element is less than the target, update the left pointer to mid + 1.<br>d. If the middle element is greater than the target, update the right pointer to mid — 1.</li><li>If the target is not found, return -1.</li></ul><p><strong>Complexity</strong></p><ul><li>Time complexity: O(logn) — Since binary search reduces the search space by half at each step, the maximum number of iterations required to find the target is log base 2 of n, where n is the size of the array. Therefore, the time complexity of binary search is O(logn).</li><li>Space complexity: O(1) — Binary search only uses a constant amount of additional space for the two pointers and the middle index variable, so the space complexity is O(1).</li></ul><p>Note that the above complexity analysis assumes that the array is already sorted. If the array needs to be sorted first, then the time complexity would be dominated by the sorting algorithm, which is typically O(nlogn)for comparison-based sorts.</p><pre>function search(nums: number[], target: number): number {<br>  let left = 0; // initialize left pointer to 0<br>  let right = nums.length - 1; // initialize right pointer to the last index of the array<br><br>  while (left &lt;= right) {<br>    // continue the loop till left pointer is less than or equal to right pointer<br>    const mid = left + Math.floor((right - left) / 2); // calculate the middle index of the array<br><br>    if (nums[mid] === target) {<br>      // check if the middle element is equal to target<br>      return mid; // return the middle index<br>    } else if (nums[mid] &lt; target) {<br>      // check if the middle element is less than target<br>      left = mid + 1; // move the left pointer to the right of middle element<br>    } else {<br>      // if the middle element is greater than target<br>      right = mid - 1; // move the right pointer to the left of middle element<br>    }<br>  }<br><br>  return -1; // target not found in the array<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd6ee7fe35a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Plus One with TS]]></title>
            <link>https://medium.com/@petermbiriri8957/plus-one-with-ts-2e27d2193236?source=rss-29d3db56ce9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e27d2193236</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Gikunda Mbiriri]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 05:45:17 GMT</pubDate>
            <atom:updated>2023-08-08T05:45:17.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueJaS5SU6v3fFeShA_Xu8g.jpeg" /></figure><p><strong>Challenge Description</strong></p><p>You are given a <strong>large integer</strong> represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0&#39;s.</p><p>Increment the large integer by one and return <em>the resulting array of digits</em>.</p><p><strong>Example 1:</strong></p><pre>Input: digits = [1,2,3]<br>Output: [1,2,4]<br>Explanation: The array represents the integer 123.<br>Incrementing by one gives 123 + 1 = 124.<br>Thus, the result should be [1,2,4].</pre><p><strong>Example 2:</strong></p><pre>Input: digits = [4,3,2,1]<br>Output: [4,3,2,2]<br>Explanation: The array represents the integer 4321.<br>Incrementing by one gives 4321 + 1 = 4322.<br>Thus, the result should be [4,3,2,2].</pre><p><strong>Example 3:</strong></p><pre>Input: digits = [9]<br>Output: [1,0]<br>Explanation: The array represents the integer 9.<br>Incrementing by one gives 9 + 1 = 10.<br>Thus, the result should be [1,0].</pre><p><strong>Solution Explanation</strong></p><ol><li>The function starts by iterating through the digits array from right to left using a for loop.</li><li>If the current digit is less than 9, it means we can simply add one to it without causing a carry. So, the current digit is incremented, and the modified digits array is returned immediately.</li><li>If the current digit is 9, it means adding one will cause a carry. In this case, the current digit is set to 0, and the loop continues to check the previous digit.</li><li>If the loop completes and we haven’t returned, it means all digits were 9, and adding one would carry over to the leftmost digit. In this case, we prepend a new digit 1 at the beginning of the array to represent the carry.</li></ol><p>This function effectively handles adding one to a number represented by an array of digits, considering cases where a carry needs to be propagated.</p><pre>function plusOne(digits: number[]): number[] {<br>  for (let i = digits.length - 1; i &gt;= 0; i--) {<br>    if (digits[i] &lt; 9) {<br>      digits[i]++;<br>      return digits;<br>    }<br>    digits[i] = 0;<br>  }<br><br>  // If we reach here, it means we need to add a new digit<br>  digits.unshift(1);<br>  return digits;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e27d2193236" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving away from the Ancient Rome with TS]]></title>
            <link>https://medium.com/@petermbiriri8957/moving-away-from-the-ancient-rome-with-ts-d471690710e2?source=rss-29d3db56ce9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d471690710e2</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Gikunda Mbiriri]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 03:42:30 GMT</pubDate>
            <atom:updated>2023-08-07T03:42:30.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BH2ge8C9kWbANfk5_W-Ybw.jpeg" /></figure><p><strong>Challenge Description</strong></p><p>Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.</p><pre>Symbol       Value<br>I             1<br>V             5<br>X             10<br>L             50<br>C             100<br>D             500<br>M             1000</pre><p>For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.</p><p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:</p><ul><li>I can be placed before V (5) and X (10) to make 4 and 9.</li><li>X can be placed before L (50) and C (100) to make 40 and 90.</li><li>C can be placed before D (500) and M (1000) to make 400 and 900.</li></ul><p>Given a roman numeral, convert it to an integer.</p><p><strong>Example 1</strong></p><pre>Input: s = &quot;III&quot;<br>Output: 3<br>Explanation: III = 3.</pre><p><strong>Example 2</strong></p><pre>Input: s = &quot;LVIII&quot;<br>Output: 58<br>Explanation: L = 50, V= 5, III = 3.</pre><p><strong>Example 3</strong></p><pre>Input: s = &quot;MCMXCIV&quot;<br>Output: 1994<br>Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.</pre><h3>Solution</h3><p><strong>Intuition:</strong></p><p>The key intuition lies in the fact that in Roman numerals, when a smaller value appears before a larger value, it represents subtraction, while when a smaller value appears after or equal to a larger value, it represents addition.</p><p><strong>Explanation:</strong></p><ol><li>The unordered map m is created and initialized with mappings between Roman numeral characters and their corresponding integer values. For example, &#39;I&#39; is mapped to 1, &#39;V&#39; to 5, &#39;X&#39; to 10, and so on.</li><li>The variable ans is initialized to 0. This variable will accumulate the final integer value of the Roman numeral string.</li><li>The for loop iterates over each character in the input string s.<br><strong>For the example &quot;IX&quot;:</strong></li></ol><ul><li>When i is 0, the current character s[i] is &#39;I&#39;. Since there is a next character (&#39;X&#39;), and the value of &#39;I&#39; (1) is less than the value of &#39;X&#39; (10), the condition m[s[i]] &lt; m[s[i+1]] is true. In this case, we subtract the value of the current character from ans.</li><li>ans -= m[s[i]];<br>ans -= m[&#39;I&#39;];<br>ans -= 1;<br>ans becomes -1.</li><li>When i is 1, the current character s[i] is &#39;X&#39;. This is the last character in the string, so there is no next character to compare. Since there is no next character, we don&#39;t need to evaluate the condition. In this case, we add the value of the current character to ans.</li><li>ans += m[s[i]];<br>ans += m[&#39;X&#39;];<br>ans += 10;<br>ans becomes 9.</li></ul><p><strong>For the example “XI”:</strong></p><ul><li>When i is 0, the current character s[i] is &#39;X&#39;. Since there is a next character (&#39;I&#39;), and the value of &#39;X&#39; (10) is greater than the value of &#39;I&#39; (1), the condition m[s[i]] &lt; m[s[i+1]] is false. In this case, we add the value of the current character to ans.</li><li>ans += m[s[i]];<br>ans += m[&#39;X&#39;];<br>ans += 10;<br>ans becomes 10.</li><li>When i is 1, the current character s[i] is &#39;I&#39;. This is the last character in the string, so there is no next character to compare. Since there is no next character, we don&#39;t need to evaluate the condition. In this case, we add the value of the current character to ans.</li><li>ans += m[s[i]];<br>ans += m[&#39;I&#39;];<br>ans += 1;<br>ans becomes 11.</li></ul><p>4. After the for loop, the accumulated value in ans represents the integer conversion of the Roman numeral string, and it is returned as the result.</p><pre>function romanToInt(s: string): number {<br>  const m: { [key: string]: number } = {<br>    I: 1,<br>    V: 5,<br>    X: 10,<br>    L: 50,<br>    C: 100,<br>    D: 500,<br>    M: 1000,<br>  };<br><br>  let ans: number = 0;<br><br>  for (let i = 0; i &lt; s.length; i++) {<br>    if (m[s[i]] &lt; m[s[i + 1]]) {<br>      ans -= m[s[i]];<br>    } else {<br>      ans += m[s[i]];<br>    }<br>  }<br><br>  return ans;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d471690710e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>