<?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 Navaneeth Krishnan on Medium]]></title>
        <description><![CDATA[Stories by Navaneeth Krishnan on Medium]]></description>
        <link>https://medium.com/@navaneethrvce?source=rss-1579de875125------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rOPRFs6Hzb5CjXm6.</url>
            <title>Stories by Navaneeth Krishnan on Medium</title>
            <link>https://medium.com/@navaneethrvce?source=rss-1579de875125------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:19:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@navaneethrvce/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[The 221g Operating System]]></title>
            <link>https://medium.com/@navaneethrvce/the-221g-operating-system-ea6d49164b2b?source=rss-1579de875125------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea6d49164b2b</guid>
            <dc:creator><![CDATA[Navaneeth Krishnan]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 20:22:18 GMT</pubDate>
            <atom:updated>2024-06-18T20:22:18.042Z</atom:updated>
            <content:encoded><![CDATA[<p>What was supposed to be a vacation, basically is turning into a anxiety wait for my passport to come back. But long story short, i am going to be using this time to build an operating system from scratch. I am going to be following this Github repo.</p><p><a href="https://github.com/cfenollosa/os-tutorial">GitHub - cfenollosa/os-tutorial: How to create an OS from scratch</a></p><p>Development Environment</p><ol><li>A Virtual Machine running Ubuntu 64 bit 18.04.1on my MAC<br>(Virtual Machine config, 8GB Ram, 4 processor cores )</li></ol><p>Thats pretty much it. :-p</p><p>I did a repo install of the following<br><em>sudo apt-get install build-essential git</em></p><p>Now for building the operating system, i am going to be using Qemu emulator within the Virtual machine.<br>The first thing to do is to install NASM<br>At the time of this writing , i used this link to download NASM<br><a href="https://www.nasm.us/pub/nasm/releasebuilds/2.13.03/">https://www.nasm.us/pub/nasm/releasebuilds/2.13.03/</a></p><p>Download the tar.gz file on to your ubuntu Machine and then do a <br><em>./configure<br>make <br>make install</em></p><p>Now if you type in whereis nasm on the terminal <br>You will see the following <br><em>root@ubuntu:/home/nyadunan/Downloads/nasm-2.13.03# whereis nasm<br>nasm: /usr/local/bin/nasm<br>root@ubuntu:/home/nyadunan/Downloads/nasm-2.13.03#</em></p><p>After this lets get the QEMU installed <br> <em>sudo apt-get install qemu-kvm qemu virt-manager virt-viewer libvirt-bin</em></p><p>Ok after we set up all this lets start developing the OS.</p><p>When the computer first boots, the CPU does not where the operating system is present. So the CPU’s firmware loads a bootloader into the RAM.<br>Now here are certain facts that we need to consider about the bootloader</p><ol><li>Its always present at the first sector of the hard disk</li><li>A sector is 512 bytes long and is considered to be bootable if the last two bytes are 0x55AA. Else the BIOS would treat the drive as unbootable.<br>(x86 is always little endian, so the actual values of the last two bytes in human readable form is 0xAA55)</li><li>The BIOS takes this sector and places this at the RAM address 0000:7C00. <br>After the BIOS does a jump to 0000:7C00.</li></ol><p>Time to write the bootloader then :-)</p><pre>loop:<br> jmp loop</pre><pre>;$ dentoes the current address of the statement<br>;$$ dentotes the address of the start of the section<br>;$-$$ tell us how much bytes of instruction is executed<br>;510-($-$$) db 0zeros out everything between the range of addresses</pre><pre>times 510-($ - $$) db 0<br>dw 0xaa55</pre><p>I am just creating a simple bootloader, which has an infinite loop , the code comments are inline</p><p>I store this as simple_boot_sector.asm</p><p>Now lets create a bin file.</p><p><em>nasm -f bin simple_boot_sector.asm</em></p><p>Time to run our os.<br> <em>qemu-system-x86_64 simple_boot_sector</em></p><p>You should see something of this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOMpgDNKQOJkjm2u0fsLcg.png" /></figure><p>Ok now that we have atleast made something work . Lets try to get our concepts clean :-) . Time from uncle sam should not go for a waste right ;)</p><p>What happens when you press the power button on your laptop? Isnt this a question we have always asked ourselves?<br>Once the motherboard receives a good power signal, it tries to start the CPU, the CPU now defaults its registers to pre defined values.<br>The x86 defaults to the following values</p><pre>IP          0xfff0<br>CS selector 0xf000<br>CS base     0xffff0000</pre><p>IP — Instruction Pointer</p><p>CS — Code Segment Register — Points to the location of the code base</p><p>The old 8086 processor had a 20 bit address bus, which means it could work from 0–0xFFFFF( 2 ^ 20 = 1048576 bytes = 1M ), meaning it could work with 1 Megabyte of Address. This also means the size of the memory address is 20 bits</p><p>But the registers are of 16 bits in size, so the catch now is we cannot store the a memory address in the 8086 register. The only way out is through memory segmentation. <br>Now since the register is of 16 bits in length, it can hold address 16 bits long. With 16 bit addresses, the x86 could address memory from 0–0xFFFF (2 ^ 16 = 65536 bytes = 64KB of memory). <br>Now with memory segmentation we divide the 1 MB of memory into multiple 64K regions.</p><p>Now to access memory the way 8086 processor used to do it was, it had a segment selector address and an offset within the segment.</p><p>So to get any physical address , the formula would be</p><p>Segment Selector address * 16 + offset address (Why 16? Because each memory segment is 64KB, 64KB * 16 is 1 M)</p><p>Another simple calculation</p><p>Segment selector address &lt;&lt; 4 + offset address</p><p>(Each left shift is multiplication by 2 , so 4 left shifts, 2⁴ = 16)</p><p>So when we left off we were still talking about in the past tense, how the old 8086 processor did memory segmentation and stuff. <br>Now when an x86 processor is reset, The CS register will have 0xffff0000 and EIP (Extended Instruction pointer) will have 0xfff0. <br>So the processor executes its first instruction at <br>CS register + EIP address = 0xfffffff0</p><p>This address 0xfffffff0 translates into 4095.99998474 MB , which is like 16 bytes below the 4 GB point.</p><p>This point is called the reset vector.</p><p>The reset vector is where the CPU expects to find the first instruction after power on.</p><p>Usually at the reset vector there is always a JMP command to the address where the BIOS resides.</p><p>The bios after initializing and checking the hardware, starts to look for storage devices which have an MBR partition (Master boot record partition ) on them in a particular configured order .(Remember the screen where you configure which device to boot first, CD-DVD, HDD etc)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hzOkYK8QBeHKqKEWX4U4wA.png" /><figcaption>A screenshot of the BIOS boot order from an old system</figcaption></figure><p>So now the question what exactly is a MBR(Master boot record ) , remember when we were writing the bootloader, i told you that the last two bytes must be 0xAA55 . That exactly is an MBR.</p><p>Since we have already written the bootloader and given it a run. When you type the file command against the bin file we created this is what you will see</p><p><em>nyadunan@ubuntu:~/os_dev$ file simple_boot_sector<br>simple_boot_sector: DOS/MBR boot sector<br>nyadunan@ubuntu:~/os_dev$</em></p><p>Now that we have a simple bootlader ready, its time to start tweaking it. The BIOS already has some basic skeleton source code for interrupts. Giving us access to keyboard and the monitor. Lets make the bootloader print something on the screen rather than making it spin around in an infinite loop.(Well we will make it spin on an infinite loop but we will make it print something first)</p><pre>;Writing 0x0e into AH basically asks interrupt to write AL contents onto TTY<br>mov ah, 0x0e</pre><pre>mov al, &#39;2&#39;</pre><pre>;0x10 is the video interrupt<br>int 0x10</pre><pre>int 0x10<br>mov al, &#39;1&#39;<br>int 0x10<br>mov al, &#39;g&#39;<br>int 0x10<br>mov al, &#39; &#39;<br>int 0x10<br>mov al, &#39;O&#39;<br>int 0x10<br>mov al, &#39;S&#39;<br>int 0x10<br>;The infinite loop,it does a JMP to the current address and encounters the JMP instruction again  lol :D</pre><pre>jmp $</pre><pre>;The usual drill<br>times 510 - ($-$$) db 0<br>dw 0xaa55</pre><p>Made the code super self explanatory as possible, any questions feel free to give me a ping or comment down below :) . Will try to answer as much as i can</p><p>After this its the usual<br><em>nasm -f bin 221g_boot_sector.asm<br>qemu-system-x86_64 221g_boot_sector</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kgj4NJg5FL3p4Zwc8nbmzA.png" /></figure><p>So like i mentioned the 8086 processor(the old one remember ) , has an address size of 20 bits. Therefore its got 20 address lines . Which like we discussed before has 1 MB memory.<br>Now this 1 MB memory is organized as follows</p><p>0x00000000 - 0x000003FF - Real Mode Interrupt Vector Table<br>0x00000400 - 0x000004FF - BIOS Data Area<br>0x00000500 - 0x00007BFF - Unused<br>0x00007C00 - 0x00007DFF - Our Bootloader<br>0x00007E00 - 0x0009FFFF - Unused<br>0x000A0000 - 0x000BFFFF - Video RAM (VRAM) Memory<br>0x000B0000 - 0x000B7777 - Monochrome Video Memory<br>0x000B8000 - 0x000BFFFF - Color Video Memory<br>0x000C0000 - 0x000C7FFF - Video ROM BIOS<br>0x000C8000 - 0x000EFFFF - BIOS Shadow Area<br>0x000F0000 - 0x000FFFFF - System BIOS</p><p>Huh ? Something seems off now right?</p><p>Didnt we say that after reset / poweron the process will start executing at 0xfffffff0 ? Isnt that more than the 1 MB space? (its like 16 bytes less than the 4GB right)</p><p>Thats because the address of 0xfffffff0 is not RAM, but its ROM and this is what is called IO Mapped memory :) . Which means that the BIOS Is in the ROM and not in the RAM</p><p>The BIOS has its own data structures and code present in some parts of the 1 MB of memory as described above, so the BIOS does not load the bootsector at 0, instead it loads the bootsector at 0x7c00.</p><p>Now all the code written in bootsector should be offset off 0x7c00. Calculating the offsets and putting the code would be hard. Therefore the assembler gives us an option of mentioning where this code would be loaded and therefore addresses would be computed as an offset off 0x7c00. The way we would do this is by writing</p><pre>[org 0x7c00]</pre><p>To make this explanation more clear, consider this code(Copied directly from the github repo mentioned above)</p><pre>mov ah, 0x0e</pre><pre>; attempt 1<br>; Fails because it tries to print the memory address (i.e. pointer)<br>; not its actual contents<br>mov al, &quot;1&quot;<br>int 0x10<br>mov al, the_secret<br>int 0x10</pre><pre>; attempt 2<br>; It tries to print the memory address of &#39;the_secret&#39; which is the correct approach.<br>; However, BIOS places our bootsector binary at address 0x7c00<br>; so we need to add that padding beforehand. We&#39;ll do that in attempt 3<br>mov al, &quot;2&quot;<br>int 0x10<br>mov al, [the_secret]<br>int 0x10</pre><pre>; attempt 3<br>; Add the BIOS starting offset 0x7c00 to the memory address of the X<br>; and then dereference the contents of that pointer.<br>; We need the help of a different register &#39;bx&#39; because &#39;mov al, [ax]&#39; is illegal.<br>; A register can&#39;t be used as source and destination for the same command.<br>mov al, &quot;3&quot;<br>int 0x10<br>mov bx, the_secret<br>add bx, 0x7c00<br>mov al, [bx]<br>int 0x10</pre><pre>; attempt 4<br>; We try a shortcut since we know that the X is stored at byte 0x2d in our binary<br>; That&#39;s smart but ineffective, we don&#39;t want to be recounting label offsets<br>; every time we change the code<br>mov al, &quot;4&quot;<br>int 0x10<br>mov al, [0x7c2d]<br>int 0x10</pre><pre>jmp $ ; infinite loop</pre><pre>the_secret:<br>    ; ASCII code 0x58 (&#39;X&#39;) is stored just before the zero-padding.<br>    ; On this code that is at byte 0x2d (check it out using &#39;xxd file.bin&#39;)<br>    db &quot;X&quot;</pre><pre>; zero padding and magic bios number<br>times 510-($-$$) db 0<br>dw 0xaa55</pre><p>In assembly, mov al,[bx] basically means that you are moving the contents present at the memory location stored in bx into al. (Think about dereferencing a pointer)<br>If we have not told the assembler that the contents of the bootloader are stored starting at 0x7c00. The assembler is going to start with address values of 0. Therefore attempt 2 in the above code snippet will fail</p><p>See the output of what happens when i ran this code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KfDqZteAYGOULPlXL7yv8A.png" /></figure><p>Only the 3 and 4th attempt passed.</p><p>Now also see the binary output of the assembled file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbWoDNKBiTVI95jHViEwzQ.png" /><figcaption>Binary output of the assembled file referenced above(X is 0x58)</figcaption></figure><p>Here from the binary output we can see X(hex value of 0x58) is stored at address 0x20 , therefore when we use the command mov al, [the_secret] in attempt 2 . The al register will now have 0x2d in it, instead of (0x7c00 + 0x2d)</p><p>Now that you got a basic hold of the BIOS and how to have some fun with assembly, its time to start off by initializing the stack for our bootsector, which will help us to load our kernel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea6d49164b2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding the first 0 bit]]></title>
            <link>https://medium.com/@navaneethrvce/finding-the-first-0-bit-b0b08e825972?source=rss-1579de875125------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0b08e825972</guid>
            <dc:creator><![CDATA[Navaneeth Krishnan]]></dc:creator>
            <pubDate>Fri, 05 Jun 2020 18:15:07 GMT</pubDate>
            <atom:updated>2020-06-05T18:15:07.571Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bit Operations: find first zero bit</h3><ol><li>Invert the number</li><li>Compute the two’s complement of the inverted number</li><li>AND the results of (1) and (2)</li><li>Find the position by computing the binary logarithm of (3)</li></ol><p>e.x.<br>For the number 10110111</p><ol><li>01001000</li><li>10111000</li><li>01001000 AND 10111000 = 00001000</li><li>log2(00001000) = 3</li></ol><p>But in a x86 processor environment there is a more simple way to do this since Intel provides a specific assembly instruction for this purpose called bsfl. This instruction return the position (index) of the least significant bit set to 1 in a 32-bit word. By using inline assembly, someone can easily create a function that finds the first zero bit by inverting a number and feeding it to this instruction. For 8-bit numbers, the code for this in gcc would look like this:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0b08e825972" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Problem Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree]]></title>
            <link>https://medium.com/@navaneethrvce/leetcode-problem-check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree-c9f5565251f6?source=rss-1579de875125------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9f5565251f6</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <dc:creator><![CDATA[Navaneeth Krishnan]]></dc:creator>
            <pubDate>Fri, 01 May 2020 05:51:52 GMT</pubDate>
            <atom:updated>2020-05-01T05:51:52.897Z</atom:updated>
            <content:encoded><![CDATA[<p>Given a binary tree where each path going from the root to any leaf form a <strong>valid sequence</strong>, check if a given string is a <strong>valid sequence</strong> in such binary tree.</p><p>We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a <strong>sequence</strong> in the given binary tree.</p><p><strong>Example 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*5qDcD3wEF7pzDLAo.png" /></figure><pre><strong>Input:</strong> root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1]<br><strong>Output:</strong> true<br><strong>Explanation: <br></strong>The path 0 -&gt; 1 -&gt; 0 -&gt; 1 is a valid sequence (green color in the figure). <br>Other valid sequences are: <br>0 -&gt; 1 -&gt; 1 -&gt; 0 <br>0 -&gt; 0 -&gt; 0</pre><p><strong>Example 2:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*K7MojmrpniH5uwNX.png" /></figure><pre><strong>Input:</strong> root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,0,1]<br><strong>Output:</strong> false <br><strong>Explanation:</strong> The path 0 -&gt; 0 -&gt; 1 does not exist, therefore it is not even a sequence.</pre><p><strong>Example 3:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*_Aa4NThunQ8OAISU.png" /></figure><pre><strong>Input:</strong> root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,1]<br><strong>Output:</strong> false<br><strong>Explanation: </strong>The path 0 -&gt; 1 -&gt; 1 is a sequence, but it is not a valid sequence.</pre><p><strong>Constraints:</strong></p><ul><li>1 &lt;= arr.length &lt;= 5000</li><li>0 &lt;= arr[i] &lt;= 9</li><li>Each node’s value is between [0–9].</li></ul><p>Code</p><pre>class Solution {<br>public:<br>    bool helper(TreeNode *root, vector&lt;int&gt;&amp; arr, int index)<br>    {<br>        if(root == NULL || arr.size() ==0 || index &gt;= arr.size())<br>            return false;<br>        <br>        //LAST NODE<br>        if(root-&gt;val == arr[index] &amp;&amp; (root-&gt;left ==NULL) &amp;&amp; (root-&gt;right == NULL) &amp;&amp; (index == arr.size()-1))<br>        {<br>            index = index +1;<br>            return true;<br>        }<br>        if(root-&gt;val == arr[index] &amp;&amp; helper(root-&gt;left,arr,(index+1)))<br>            return true;<br>        if(root-&gt;val == arr[index] &amp;&amp; helper(root-&gt;right,arr,(index+1)))<br>            return true;<br>        return false;<br>    }<br>    bool isValidSequence(TreeNode* root, vector&lt;int&gt;&amp; arr) {<br>        return helper(root,arr,0);<br>    }<br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9f5565251f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Problem 55 Jump game]]></title>
            <link>https://medium.com/@navaneethrvce/leetcode-problem-55-jump-game-2425435f9469?source=rss-1579de875125------2</link>
            <guid isPermaLink="false">https://medium.com/p/2425435f9469</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <dc:creator><![CDATA[Navaneeth Krishnan]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 04:36:50 GMT</pubDate>
            <atom:updated>2020-04-26T04:36:50.078Z</atom:updated>
            <content:encoded><![CDATA[<p>Given an array of non-negative integers, you are initially positioned at the first index of the array.</p><p>Each element in the array represents your maximum jump length at that position.</p><p>Determine if you are able to reach the last index.</p><p><strong>Example 1:</strong></p><pre><strong>Input:</strong> [2,3,1,1,4]<br><strong>Output:</strong> true<br><strong>Explanation:</strong> Jump 1 step from index 0 to 1, then 3 steps to the last index.</pre><p><strong>Example 2:</strong></p><pre><strong>Input:</strong> [3,2,1,0,4]<br><strong>Output:</strong> false<br><strong>Explanation:</strong> You will always arrive at index 3 no matter what. Its maximum<br>             jump length is 0, which makes it impossible to reach the last index.</pre><p>Code</p><pre>class Solution {<br>public:<br>    bool canJump(vector&lt;int&gt;&amp; nums) {<br>        int max_index = 0;<br>        for(int i =0 ;i&lt;nums.size();i++)<br>        {<br>            if(max_index &lt; i)<br>                return false;<br>            max_index = max(max_index, nums[i]+i);<br>        }<br>        if(max_index &gt;= nums.size()-1)<br>            return true;<br>        else<br>            return false;<br>    }<br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2425435f9469" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Problem 560- Subarray Sum equals k]]></title>
            <link>https://medium.com/@navaneethrvce/leetcode-problem-560-subarray-sum-equals-k-815d53f267ea?source=rss-1579de875125------2</link>
            <guid isPermaLink="false">https://medium.com/p/815d53f267ea</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <dc:creator><![CDATA[Navaneeth Krishnan]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 02:39:55 GMT</pubDate>
            <atom:updated>2020-04-23T02:39:55.480Z</atom:updated>
            <content:encoded><![CDATA[<p>560. Subarray Sum Equals K</p><p>Medium</p><p>3899123Add to ListShare</p><p>Given an array of integers and an integer <strong>k</strong>, you need to find the total number of continuous subarrays whose sum equals to <strong>k</strong>.</p><p><strong>Example 1:</strong></p><pre><strong>Input:</strong>nums = [1,1,1], k = 2<br><strong>Output:</strong> 2</pre><p><strong>Note:</strong></p><ol><li>The length of the array is in range [1, 20,000].</li><li>The range of numbers in the array is [-1000, 1000] and the range of the integer <strong>k</strong> is [-1e7, 1e7].</li></ol><p>Code</p><p>You have a hashmap with key as prefix sums for each element and the value as the number of times you see the prefix sum. This is easier to explain with an example</p><p>Consider this input array</p><p>1,2,2,3,1,6 and k is 4</p><p>let us say we are at array index — 2 . Then the prefix sum till now is [1+2 +2 ] 5 . If we do 5 minus k = 1 . This basically means that to reach 4 , we need to remove 1 from 5. <br>Now we will see if we have encountered 1 before in the hashmap, if we have encountered 1 before in the hashmap then we know that a sequence before the current index exists where the sum is equal to 4.</p><pre>class Solution {<br>public:<br>    int subarraySum(vector&lt;int&gt;&amp; nums, int k) {<br>        unordered_map &lt;int,int&gt;mp ;<br>        int sum = 0;<br>        int res = 0;<br>        int rem = 0;<br>        for(int i = 0 ; i &lt;nums.size();i++)<br>        {<br>            sum = sum + nums[i];<br>            if(sum == k)<br>                res +=1;<br>            rem = sum -k;<br>            if(mp[rem])<br>                res = res + mp[rem];<br>            mp[sum]++;<br>        }<br>        return res;<br>    }<br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=815d53f267ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode problem Leftmost Column with at Least a One]]></title>
            <link>https://medium.com/@navaneethrvce/leetcode-problem-leftmost-column-with-at-least-a-one-1167fd3b8e35?source=rss-1579de875125------2</link>
            <guid isPermaLink="false">https://medium.com/p/1167fd3b8e35</guid>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Navaneeth Krishnan]]></dc:creator>
            <pubDate>Wed, 22 Apr 2020 01:45:47 GMT</pubDate>
            <atom:updated>2020-04-22T01:45:47.095Z</atom:updated>
            <content:encoded><![CDATA[<p><em>(This problem is an </em><strong><em>interactive problem</em></strong><em>.)</em></p><p>A binary matrix means that all elements are 0 or 1. For each <strong>individual</strong> row of the matrix, this row is sorted in non-decreasing order.</p><p>Given a row-sorted binary matrix binaryMatrix, return leftmost column index(0-indexed) with at least a 1 in it. If such index doesn&#39;t exist, return -1.</p><p><strong>You can’t access the Binary Matrix directly.</strong> You may only access the matrix using a BinaryMatrix interface:</p><ul><li>BinaryMatrix.get(x, y) returns the element of the matrix at index (x, y) (0-indexed).</li><li>BinaryMatrix.dimensions() returns a list of 2 elements [n, m], which means the matrix is n * m.</li></ul><p>Submissions making more than 1000 calls to BinaryMatrix.get will be judged <em>Wrong Answer</em>. Also, any solutions that attempt to circumvent the judge will result in disqualification.</p><p>For custom testing purposes you’re given the binary matrix mat as input in the following four examples. You will not have access the binary matrix directly.</p><p><strong>Example 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/81/0*kBxfDGse2XWWDZdF.jpg" /></figure><pre><strong>Input:</strong> mat = [[0,0],[1,1]]<br><strong>Output:</strong> 0</pre><p><strong>Example 2:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/81/0*a-R0CY5EL7k2ONfY.jpg" /></figure><pre><strong>Input:</strong> mat = [[0,0],[0,1]]<br><strong>Output:</strong> 1</pre><p><strong>Example 3:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/81/0*4zLCQYqVMO7sgJlD.jpg" /></figure><pre><strong>Input:</strong> mat = [[0,0],[0,0]]<br><strong>Output:</strong> -1</pre><p><strong>Example 4:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/0*Em7ln_LmeyyLgWUL.jpg" /></figure><pre><strong>Input:</strong> mat = [[0,0,0,1],[0,0,1,1],[0,1,1,1]]<br><strong>Output:</strong> 1</pre><p><strong>Constraints:</strong></p><ul><li>1 &lt;= mat.length, mat[i].length &lt;= 100</li><li>mat[i][j] is either 0 or 1.</li><li>mat[i] is sorted in a non-decreasing way.</li></ul><p>We start from the top right most element , since it is row sorted. If it is 1 then we go to the left, if it is 0, we go down. We also have a variable res which is updated whenever we see 1 and the col value is lesser than the value of res</p><p>Code</p><pre>/**<br> * // This is the BinaryMatrix&#39;s API interface.<br> * // You should not implement it, or speculate about its implementation<br> * class BinaryMatrix {<br> *   public:<br> *     int get(int x, int y);<br> *     vector&lt;int&gt; dimensions();<br> * };<br> */</pre><pre>class Solution {<br>public:<br>    int leftMostColumnWithOne(BinaryMatrix &amp;binaryMatrix) {<br>        vector &lt;int&gt;r = binaryMatrix.dimensions();<br>        int rows = r[0];<br>        int cols = r[1];<br>        int r_iter= 0, c_iter =cols-1;<br>        int found_flag = 0;<br>        int res = INT_MAX;<br>        while(r_iter &lt; rows &amp;&amp; c_iter &lt; cols &amp;&amp; r_iter &gt;=0 &amp;&amp; c_iter &gt;= 0)<br>        {<br>            if(binaryMatrix.get(r_iter,c_iter) == 1)<br>            {<br>                if(c_iter&lt;res){<br>                    res = c_iter;<br>                    found_flag =1;<br>                }<br>                cout&lt;&lt;res&lt;&lt;endl;<br>                c_iter-=1;<br>                continue;<br>            }<br>            r_iter ++;<br>            <br>        }<br>        if(found_flag)<br>            return res;<br>        else<br>            return -1;<br>    }<br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1167fd3b8e35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Problem 1008. Construct Binary Search Tree from Preorder Traversal]]></title>
            <link>https://medium.com/@navaneethrvce/leetcode-problem-1008-construct-binary-search-tree-from-preorder-traversal-52b0b2adf176?source=rss-1579de875125------2</link>
            <guid isPermaLink="false">https://medium.com/p/52b0b2adf176</guid>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Navaneeth Krishnan]]></dc:creator>
            <pubDate>Tue, 21 Apr 2020 04:02:48 GMT</pubDate>
            <atom:updated>2020-04-21T04:02:48.909Z</atom:updated>
            <content:encoded><![CDATA[<p>eturn the root node of a binary <strong>search</strong> tree that matches the given preorder traversal.</p><p><em>(Recall that a binary search tree is a binary tree where for every node, any descendant of </em><em>node.left has a value </em><em>&lt; </em><em>node.val, and any descendant of </em><em>node.right has a value </em><em>&gt; </em><em>node.val. Also recall that a preorder traversal displays the value of the </em><em>node first, then traverses </em><em>node.left, then traverses </em><em>node.right.)</em></p><p><strong>Example 1:</strong></p><pre><strong>Input: </strong>[8,5,1,7,10,12]<br><strong>Output: </strong>[8,5,10,1,7,null,12]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*aNxkiM0qm-zLtn0f.png" /></figure><p><strong>Note:</strong></p><ol><li>1 &lt;= preorder.length &lt;= 100</li><li>The values of preorder are distinct.</li></ol><p>The way we would solve this is all the values between the range of MiN in the array to the value of the root element would go to the left subtree</p><p>Left_sub_tree — &gt; [MinValue, rootval]</p><p>Right subtree — -&gt; [rootVal, MaxVal]</p><p>We have to go over in a recursion until we exhaust the array</p><p>code</p><pre>/**<br> * Definition for a binary tree node.<br> * struct TreeNode {<br> *     int val;<br> *     TreeNode *left;<br> *     TreeNode *right;<br> *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}<br> * };<br> */<br>class Solution {<br>public:<br>    TreeNode* bst_helper(vector&lt;int&gt; &amp;preorder,int &amp;index, int min, int max)<br>    {<br>        if(index &gt;=preorder.size())<br>            return NULL;<br>        if(preorder[index] &lt; min || preorder[index]&gt;max)<br>            return NULL;<br>        TreeNode *root = new TreeNode(preorder[index]);<br>        index+=1;<br>        root-&gt;left = bst_helper(preorder, index ,min, root-&gt;val);<br>        root-&gt;right = bst_helper(preorder, index , root-&gt;val,max);<br>        return root;<br>    }<br>    TreeNode* bstFromPreorder(vector&lt;int&gt;&amp; preorder) {<br>        int index =0;<br>        return bst_helper(preorder,index,INT_MIN,INT_MAX);<br>        <br>    }<br>};<br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52b0b2adf176" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Problem 64 — Minimum Path sum]]></title>
            <link>https://medium.com/@navaneethrvce/leetcode-problem-64-minimum-path-sum-cdeae81a274?source=rss-1579de875125------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdeae81a274</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <dc:creator><![CDATA[Navaneeth Krishnan]]></dc:creator>
            <pubDate>Sat, 18 Apr 2020 18:04:11 GMT</pubDate>
            <atom:updated>2020-04-18T18:04:11.956Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode Problem 64 — Minimum Path sum</h3><p>Given a <em>m</em> x <em>n</em> grid filled with non-negative numbers, find a path from top left to bottom right which <em>minimizes</em> the sum of all numbers along its path.</p><p><strong>Note:</strong> You can only move either down or right at any point in time.</p><p><strong>Example:</strong></p><pre><strong>Input:</strong><br>[<br>  [1,3,1],<br>  [1,5,1],<br>  [4,2,1]<br>]<br><strong>Output:</strong> 7<br><strong>Explanation:</strong> Because the path 1→3→1→1→1 minimizes the sum.</pre><p>We have to use DP for this</p><pre>class Solution {<br>public:<br>    int minPathSum(vector&lt;vector&lt;int&gt;&gt;&amp; grid) {<br>        int r_s = grid.size();<br>        int c_s = grid[0].size();<br>        vector&lt;vector&lt;int&gt;&gt; grid_sum(r_s,vector&lt;int&gt;(c_s,0));<br>        grid_sum[0][0] = grid[0][0];<br>        int i=0,j=0;<br>        for( i =1;i&lt;r_s;i++)<br>        {<br>            grid_sum[i][0] = grid_sum[i-1][0] + grid[i][0];<br>        }<br>        for( j=1;j&lt;c_s;j++)<br>        {<br>            grid_sum[0][j] = grid_sum[0][j-1] + grid[0][j];<br>        }<br>        for( i=1;i&lt;r_s;i++)<br>        {<br>            for( j=1;j&lt;c_s;j++)<br>            {<br>                grid_sum[i][j] = min(grid_sum[i-1][j],grid_sum[i][j-1]) + grid[i][j];<br>            }<br>        }<br>        return grid_sum[i-1][j-1];<br>    }<br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdeae81a274" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Problem 200 Number of Islands]]></title>
            <link>https://medium.com/@navaneethrvce/leetcode-problem-200-number-of-islands-9832c79a589?source=rss-1579de875125------2</link>
            <guid isPermaLink="false">https://medium.com/p/9832c79a589</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <dc:creator><![CDATA[Navaneeth Krishnan]]></dc:creator>
            <pubDate>Sat, 18 Apr 2020 02:57:44 GMT</pubDate>
            <atom:updated>2020-04-18T02:57:44.896Z</atom:updated>
            <content:encoded><![CDATA[<p>Given a 2d grid map of &#39;1&#39;s (land) and &#39;0&#39;s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p><p><strong>Example 1:</strong></p><pre><strong>Input:</strong><br>11110<br>11010<br>11000<br>00000</pre><pre><strong>Output:</strong> 1</pre><p><strong>Example 2:</strong></p><pre><strong>Input:</strong><br>11000<br>11000<br>00100<br>00011</pre><pre><strong>Output: </strong>3</pre><p>Basically DFS whenever you see a 1, Finally find the number of times we did DFS</p><pre>class Solution {<br>public:<br>    void dump_matrix(vector&lt;vector&lt;int&gt;&gt; &amp;visited_arr)<br>    {<br>        int i,j;<br>        for(i=0;i&lt;visited_arr.size();i++)<br>        {<br>            for(j=0;j&lt;visited_arr[i].size();j++)<br>            {<br>                cout&lt;&lt; visited_arr[i][j] &lt;&lt;&quot; &quot;;<br>            }<br>            cout&lt;&lt;endl;<br>        }<br>            <br>    }<br>    void dfs(vector&lt;vector&lt;char&gt;&gt;&amp; grid, int i, int j, vector&lt;vector&lt;int&gt;&gt; &amp;visited_arr)<br>    {<br>        if((i &gt; grid.size()-1) || (j&gt;grid[0].size()-1) || (i&lt; 0) || (j &lt;0))<br>            return;<br>        if((visited_arr[i][j] ==1) || (grid[i][j]==&#39;0&#39;))<br>         return;<br>        visited_arr[i][j] =1;<br>        <br>        dfs(grid,i+1,j,visited_arr);<br>        dfs(grid,i,j+1,visited_arr);<br>        dfs(grid,i-1,j,visited_arr);<br>        dfs(grid,i,j-1,visited_arr);<br>    }<br>    int numIslands(vector&lt;vector&lt;char&gt;&gt;&amp; grid) {<br>        int i=0,j=0;<br>        int dfs_count = 0;<br>        if(grid.size() == 0)<br>            return 0;<br>        if(grid[0].size() == 0)<br>            return 0;<br>        vector&lt;vector&lt;int&gt;&gt; visited_arr(grid.size(),<br>                                        vector&lt;int&gt;(grid[0].size(),0));<br>        for(i=0;i&lt;grid.size();i++)<br>        {<br>            for(j=0;j&lt;grid[i].size();j++)<br>            {<br>               visited_arr[i][j] = 0;<br>            }<br>        }<br>        for(i=0;i&lt;grid.size();i++)<br>        {<br>            for(j=0;j&lt;grid[i].size();j++)<br>            {<br>                if(visited_arr[i][j] == 1)<br>                    continue;<br>                <br>                if(grid[i][j] == &#39;0&#39;)<br>                    visited_arr[i][j] =1;<br>                else{<br>                    <br>                    dfs(grid,i,j,visited_arr)<br>                    dfs_count ++;<br>                }<br>            }<br>        <br>        }<br>        return dfs_count;<br>    }<br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9832c79a589" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Problem 678 — Valid Parenthesis String]]></title>
            <link>https://medium.com/@navaneethrvce/leetcode-problem-678-valid-parenthesis-string-ac72697c49eb?source=rss-1579de875125------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac72697c49eb</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <dc:creator><![CDATA[Navaneeth Krishnan]]></dc:creator>
            <pubDate>Fri, 17 Apr 2020 04:23:44 GMT</pubDate>
            <atom:updated>2020-04-17T04:23:44.630Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode Problem 678 — Valid Parenthesis String</h3><p>Given a string containing only three types of characters: ‘(‘, ‘)’ and ‘*’, write a function to check whether this string is valid. We define the validity of a string by these rules:</p><ol><li>Any left parenthesis &#39;(&#39; must have a corresponding right parenthesis &#39;)&#39;.</li><li>Any right parenthesis &#39;)&#39; must have a corresponding left parenthesis &#39;(&#39;.</li><li>Left parenthesis &#39;(&#39; must go before the corresponding right parenthesis &#39;)&#39;.</li><li>&#39;*&#39; could be treated as a single right parenthesis &#39;)&#39; or a single left parenthesis &#39;(&#39; or an empty string.</li><li>An empty string is also valid.</li></ol><p><strong>Example 1:</strong></p><pre><strong>Input:</strong> &quot;()&quot;<br><strong>Output:</strong> True</pre><p><strong>Example 2:</strong></p><pre><strong>Input:</strong> &quot;(*)&quot;<br><strong>Output:</strong> True</pre><p><strong>Example 3:</strong></p><pre><strong>Input:</strong> &quot;(*))&quot;<br><strong>Output:</strong> True</pre><p><strong>Note:</strong></p><ol><li>The string size will be in the range [1, 100].</li></ol><p>First look at this problem ,looks simple to solve. I literally struggled on this one.</p><p>The best way to solve this is to use a 2 pointer greedy approach. From the left of the array keep counting the number of open brackets ‘(‘ and * , if you find any closed brackets ‘)’ decrement this open bracket counter.<br>From the right of the array keep counting the number of closed brackets and * , if you find any open brackets decrement this closed bracket counter.Now at any instance in the for loop if the open bracket counter or closed bracket counter falls below 0 (i.e becomes negative) its a false. Otherwise its true</p><pre>class Solution {<br>public:<br>    bool checkValidString(string s) {<br>        int open_count = 0, close_count =0;<br>        int len= s.length()-1;<br>        for(int i=0;i&lt;=len;i++)<br>        {<br>            if(s[i] == &#39;(&#39; || s[i] == &#39;*&#39;)<br>                open_count ++;<br>            else <br>                open_count --;<br>            if(s[len-i] == &#39;)&#39; || s[len-i] == &#39;*&#39;)<br>                close_count ++;<br>            else<br>                close_count --;<br>            if(open_count &lt; 0 || close_count &lt;0)<br>                return false;<br>        }<br>        return true;<br>    }<br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac72697c49eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>