<?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 Santanu Das on Medium]]></title>
        <description><![CDATA[Stories by Santanu Das on Medium]]></description>
        <link>https://medium.com/@iamsantanu?source=rss-9dfdf3906bca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-39dDcvyHzFHtLz1dDVZNA.jpeg</url>
            <title>Stories by Santanu Das on Medium</title>
            <link>https://medium.com/@iamsantanu?source=rss-9dfdf3906bca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:00:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamsantanu/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[Moving Average from Data Stream]]></title>
            <link>https://medium.com/root-node/moving-average-from-data-stream-774aefb72a2c?source=rss-9dfdf3906bca------2</link>
            <guid isPermaLink="false">https://medium.com/p/774aefb72a2c</guid>
            <dc:creator><![CDATA[Santanu Das]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 10:45:21 GMT</pubDate>
            <atom:updated>2021-02-07T10:45:21.266Z</atom:updated>
            <content:encoded><![CDATA[<p>Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.</p><p>Implement the MovingAverage class:</p><ul><li>MovingAverage(int size) Initializes the object with the size of the window size.</li><li>double next(int val) Returns the moving average of the last size values of the stream.</li></ul><p><strong>Example 1:</strong></p><pre><strong>Input</strong><br>[&quot;MovingAverage&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;]<br>[[3], [1], [10], [3], [5]]<br><strong>Output</strong><br>[null, 1.0, 5.5, 4.66667, 6.0]</pre><pre><strong>Explanation</strong><br>MovingAverage movingAverage = new MovingAverage(3);<br>movingAverage.next(1); // return 1.0 = 1 / 1<br>movingAverage.next(10); // return 5.5 = (1 + 10) / 2<br>movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3<br>movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3</pre><p><strong>Constraints:</strong></p><ul><li>1 &lt;= size &lt;= 1000</li><li>-105 &lt;= val &lt;= 105</li><li>At most 104 calls will be made to next.</li></ul><h3>Solution</h3><h4>Approach 1: Array or List</h4><p><strong>Intuition</strong></p><p>Following the description of the problem, we could simply keep track of all the incoming values with the data structure of <em>Array</em> or <em>List</em>. Then from the data structure, later we retrieve the necessary elements to calculate the average.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t6B7iTWoq-0rRJv7.png" /></figure><p><strong>Algorithm</strong></p><ul><li>First, we initialize a variable queue to store the values from the data stream, and the variable n for the size of the moving window.</li><li>At each invocation of next(val), we first append the value to the queue. We then retrieve the last n values from the queue, in order to calculate the average.</li></ul><pre>class MovingAverage {<br>  int size;<br>  List queue = new ArrayList&lt;Integer&gt;();<br>  public MovingAverage(int size) {<br>    this.size = size;<br>  }</pre><pre>public double next(int val) {<br>    queue.add(val);<br>    // calculate the sum of the moving window<br>    int windowSum = 0;<br>    for(int i = Math.max(0, queue.size() - size); i &lt; queue.size(); ++i)<br>      windowSum += (int)queue.get(i);</pre><pre>return windowSum * 1.0 / Math.min(queue.size(), size);<br>  }<br>}</pre><p><strong>Complexity</strong></p><ul><li>Time Complexity: \mathcal{O}(N)O(<em>N</em>) where N<em>N</em> is the size of the moving window, since we need to retrieve N<em>N</em> elements from the queue at each invocation of next(val) function.</li><li>Space Complexity: \mathcal{O}(M)O(<em>M</em>), where M<em>M</em> is the length of the queue which would grow at each invocation of the next(val) function.</li></ul><h4>Approach 2: Double-ended Queue</h4><p><strong>Intuition</strong></p><p>We could do better than the first approach in both time and space complexity.</p><blockquote><em>First of all, one might notice that we do not need to keep all values from the data stream, but rather the last </em><em>n values which falls into the moving window.</em></blockquote><p>By definition of the moving window, at each step, we add a new element to the window, and at the same time we remove the oldest element from the window. Here, we could apply a data structure called <em>double-ended queue</em> (<em>a.k.a</em> deque) to implement the moving window, which would have the constant time complexity (\mathcal{O}(1)O(1)) to add or remove an element from both its ends. With the deque, we could reduce the space complexity down to \mathcal{O}(N)O(<em>N</em>) where N<em>N</em> is the size of the moving window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pbDZTEbVhoL3CpbP.png" /></figure><blockquote><em>Secondly, to calculate the sum, we do not need to reiterate the elements in the moving window.</em></blockquote><p>We could keep the sum of the previous moving window, then in order to obtain the sum of the new moving window, we simply add the new element and deduce the oldest element. With this measure, we then can reduce the time complexity to constant.</p><p><strong>Algorithm</strong></p><p>Here is the definition of the <em>deque</em> from Python. We have similar implementation of deque in other programming languages such as Java.</p><blockquote><em>Deques are a generalization of stacks and queues (the name is pronounced </em><em>deck and is short for </em><em>double-ended queue). Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.</em></blockquote><p>Follow the intuition, we replace the queue with the <em>deque</em> and add a new variable window_sum in order to calculate the sum of moving window in constant time.</p><pre>class MovingAverage {<br>  int size, windowSum = 0, count = 0;<br>  Deque queue = new ArrayDeque&lt;Integer&gt;();</pre><pre>public MovingAverage(int size) {<br>    this.size = size;<br>  }</pre><pre>public double next(int val) {<br>    ++count;<br>    // calculate the new sum by shifting the window<br>    queue.add(val);<br>    int tail = count &gt; size ? (int)queue.poll() : 0;</pre><pre>windowSum = windowSum - tail + val;</pre><pre>return windowSum * 1.0 / Math.min(size, count);<br>  }<br>}</pre><p><strong>Complexity</strong></p><ul><li>Time Complexity: \mathcal{O}(1)O(1), as we explained in intuition.</li><li>Space Complexity: \mathcal{O}(N)O(<em>N</em>), where N<em>N</em> is the size of the moving window.</li></ul><h4>Approach 3: Circular Queue with Array</h4><p><strong>Intuition</strong></p><p>Other than the <em>deque</em> data structure, one could also apply another fun data structure called circular queue, which is basically a queue with the circular shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ed5z4EXbTxc77JHs.png" /></figure><ul><li>The major advantage of circular queue is that by adding a new element to a full circular queue, it automatically discards the oldest element. Unlike deque, we do not need to explicitly remove the oldest element.</li><li>Another advantage of circular queue is that a single index suffices to keep track of both ends of the queue, unlike deque where we have to keep a pointer for each end.</li></ul><p><strong>Algorithm</strong></p><p>No need to resort to any library, one could easily implement a circular queue with a fixed-size array. The key to the implementation is the correlation between the index of head and tail elements, which we could summarize in the following formula:</p><p>\text{tail} = (\text{head} + 1) \mod \text{size}tail=(head+1)modsize</p><p>In other words, the tail element is right next to the head element. Once we move the head forward, we would overwrite the previous tail element.</p><pre>class MovingAverage {<br>  int size, head = 0, windowSum = 0, count = 0;<br>  int[] queue;<br>  public MovingAverage(int size) {<br>    this.size = size;<br>    queue = new int[size];<br>  }</pre><pre>public double next(int val) {<br>    ++count;<br>    // calculate the new sum by shifting the window<br>    int tail = (head + 1) % size;<br>    windowSum = windowSum - queue[tail] + val;<br>    // move on to the next head<br>    head = (head + 1) % size;<br>    queue[head] = val;<br>    return windowSum * 1.0 / Math.min(size, count);<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=774aefb72a2c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/root-node/moving-average-from-data-stream-774aefb72a2c">Moving Average from Data Stream</a> was originally published in <a href="https://medium.com/root-node">Root Node</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design In-Memory File System]]></title>
            <link>https://medium.com/root-node/design-in-memory-file-system-96ee6c484616?source=rss-9dfdf3906bca------2</link>
            <guid isPermaLink="false">https://medium.com/p/96ee6c484616</guid>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Santanu Das]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 10:23:03 GMT</pubDate>
            <atom:updated>2021-02-07T10:23:03.293Z</atom:updated>
            <content:encoded><![CDATA[<p>Design an in-memory file system to simulate the following functions:</p><p>ls: Given a path in string format. If it is a file path, return a list that only contains this file&#39;s name. If it is a directory path, return the list of file and directory names <strong>in this directory</strong>. Your output (file and directory names together) should in <strong>lexicographic order</strong>.</p><p>mkdir: Given a <strong>directory path</strong> that does not exist, you should make a new directory according to the path. If the middle directories in the path don&#39;t exist either, you should create them as well. This function has void return type.</p><p>addContentToFile: Given a <strong>file path</strong> and <strong>file content</strong> in string format. If the file doesn&#39;t exist, you need to create that file containing given content. If the file already exists, you need to <strong>append</strong> given content to original content. This function has void return type.</p><p>readContentFromFile: Given a <strong>file path</strong>, return its <strong>content</strong> in string format.</p><p><strong>Example:</strong></p><pre><strong>Input:</strong> <br>[&quot;FileSystem&quot;,&quot;ls&quot;,&quot;mkdir&quot;,&quot;addContentToFile&quot;,&quot;ls&quot;,&quot;readContentFromFile&quot;]<br>[[],[&quot;/&quot;],[&quot;/a/b/c&quot;],[&quot;/a/b/c/d&quot;,&quot;hello&quot;],[&quot;/&quot;],[&quot;/a/b/c/d&quot;]]</pre><pre><strong>Output:</strong><br>[null,[],null,null,[&quot;a&quot;],&quot;hello&quot;]</pre><p><strong>Note:</strong></p><ol><li>You can assume all file or directory paths are absolute paths which begin with / and do not end with / except that the path is just &quot;/&quot;.</li><li>You can assume that all operations will be passed valid parameters and users will not attempt to retrieve file content or list a directory or file that does not exist.</li><li>You can assume that all directory names and file names only contain lower-case letters, and same names won’t exist in the same directory.</li></ol><h3>Solution</h3><h4>Approach #1 Using separate Directory and File List[Accepted]</h4><p>We start our discussion by looking at the directory structure used. The root directory acts as the base of the directory structure. Each directory contains two hashmaps namely dirs<em>dirs</em> and files<em>files</em>. The dirs<em>dirs</em> contains data in the form [(subdirectory_1\_name: subdirectory_{1\_structure}), (subdirectory_2\_name: subdirectory_{2\_structure})…][(<em>subdirectory</em>1​_<em>name</em>:<em>subdirectory</em>1_<em>structure</em>​),(<em>subdirectory</em>2​_<em>name</em>:<em>subdirectory</em>2_<em>structure</em>​)…]. The files<em>files</em> contains data in the form [(file_1: file_{1\_contents}), (file_2: file_{2\_contents})…][(<em>file</em>1​:<em>file</em>1_<em>contents</em>​),(<em>file</em>2​:<em>file</em>2_<em>contents</em>​)…]. This directory structure is shown below with a sample showing just the first two levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*omT9rBM02S1Em3xx-caM4Q.png" /></figure><p>Now, we’ll discuss how we implement the various commands required.</p><ol><li>ls: In this case, we start off by initializing t<em>t</em>, a temporary directory pointer, to the root directory. We split the input directory path based on / and obtain the individual levels of directory names in a d<em>d</em> array. Then, we traverse over the tree directory structure based on the individual directories found and we keep on updating the t<em>t</em> directory pointer to point to the new level of directory(child) as we go on entering deeper into the directory structure. At the end, we will stop at either the end level directory or at the file name depending upon the input given. If the last level in the input happens to be a file name, we simply need to return the file name. So, we directly return the last entry in the d<em>d</em> array. If the last level entry happens to be a directory, we can obtain its subdirectory list from the list of keys in its dirs<em>dirs</em> hashmap. Similarly, we can obtain the list of files in the last directory from the keys in the corresponding files<em>files</em> hashmap. We append the two lists obtained, sort them and return the sorted appended list.</li><li>mkdir: In response to this command, as in case of ls, we start entering the directory structure level by level. Whenever we reach a state where a directory mentioned in the path of mkdir doesn&#39;t exist, we create a new entry in the last valid directory&#39;s dirs<em>dirs</em> structure and initialize its subdirectory list as an empty list. We keep on doing so till we reach the end level directory.</li><li>addContentToFile: In response to this command as well, as in case of ls, we start entering the directory structure level by level. When we reach the level of the file name, we check if the file name already exists in the files<em>files</em> keys. If it exists, we concatenate the current contents to the contents of the file(in the value section of the corresponding file). If it doesn&#39;t exist, we create a new entry in the current directory&#39;s files<em>files</em> and initialize its contents with the current contents.</li><li>readContentFromFile: As the previous cases, we reach the last directory level by traversing through the directory structure level by level. Then, in the last directory, we search for the file name entry in the corresponding files<em>files</em>&#39; keys and return its corresponding value as the contents of the file.</li></ol><pre>public class FileSystem {<br>    class Dir {<br>        HashMap &lt; String, Dir &gt; dirs = new HashMap &lt; &gt; ();<br>        HashMap &lt; String, String &gt; files = new HashMap &lt; &gt; ();<br>    }<br>    Dir root;<br>    public FileSystem() {<br>        root = new Dir();<br>    }<br>    public List &lt; String &gt; ls(String path) {<br>        Dir t = root;<br>        List &lt; String &gt; files = new ArrayList &lt; &gt; ();<br>        if (!path.equals(&quot;/&quot;)) {<br>            String[] d = path.split(&quot;/&quot;);<br>            for (int i = 1; i &lt; d.length - 1; i++) {<br>                t = t.dirs.get(d[i]);<br>            }<br>            if (t.files.containsKey(d[d.length - 1])) {<br>                files.add(d[d.length - 1]);<br>                return files;<br>            } else {<br>                t = t.dirs.get(d[d.length - 1]);<br>            }<br>        }<br>        files.addAll(new ArrayList &lt; &gt; (t.dirs.keySet()));<br>        files.addAll(new ArrayList &lt; &gt; (t.files.keySet()));<br>        Collections.sort(files);<br>        return files;<br>    }</pre><pre>public void mkdir(String path) {<br>        Dir t = root;<br>        String[] d = path.split(&quot;/&quot;);<br>        for (int i = 1; i &lt; d.length; i++) {<br>            if (!t.dirs.containsKey(d[i]))<br>                t.dirs.put(d[i], new Dir());<br>            t = t.dirs.get(d[i]);<br>        }<br>    }</pre><pre>public void addContentToFile(String filePath, String content) {<br>        Dir t = root;<br>        String[] d = filePath.split(&quot;/&quot;);<br>        for (int i = 1; i &lt; d.length - 1; i++) {<br>            t = t.dirs.get(d[i]);<br>        }<br>        t.files.put(d[d.length - 1], t.files.getOrDefault(d[d.length - 1], &quot;&quot;) + content);<br>    }</pre><pre>public String readContentFromFile(String filePath) {<br>        Dir t = root;<br>        String[] d = filePath.split(&quot;/&quot;);<br>        for (int i = 1; i &lt; d.length - 1; i++) {<br>            t = t.dirs.get(d[i]);<br>        }<br>        return t.files.get(d[d.length - 1]);<br>    }<br>}</pre><pre>/**<br> * Your FileSystem object will be instantiated and called as such:<br> * FileSystem obj = new FileSystem();<br> * List&lt;String&gt; param_1 = obj.ls(path);<br> * obj.mkdir(path);<br> * obj.addContentToFile(filePath,content);<br> * String param_4 = obj.readContentFromFile(filePath);<br> */</pre><h4>Approach #2 Using unified Directory and File List[Accepted]</h4><p>This design differs from the first design in that the current data structure for a Directory contains a unified files<em>files</em> hashmap, which contains the list of all the files and subdirectories in the current directory. Apart from this, we contain an entry isfile<em>isfile</em>, which when True indicates that the current files<em>files</em> entry is actually corresponding to a file, otherwise it represents a directory. Further, since we are considering the directory and files’ entries in the same manner, we need an entry for content<em>content</em>, which contains the contents of the current file(if isfile<em>isfile</em> entry is True in the current case). For entries corresponding to directories, the content<em>content</em> field is kept empty.</p><p>The following figure shows the directory structure for the same example as in the case above, for the first two levels of the hierarchical structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*Urt2Xs4OwqJYxRx1CecKkQ.png" /></figure><p>The implementation of all the commands remains the same as in the last design, except that we need to make entries in the same files<em>files</em> hashmap for both files and directories, corresponding to addContentToFile and mkdir respectively. Further, for ls, we need not extract entries separately for the files and directories, since they are unified in the current case, and can be obtained in a single go.</p><p><strong>Performance Analysis</strong></p><ul><li>The time complexity of executing an ls command is O\big(m+n+klog(k)\big)<em>O</em>(<em>m</em>+<em>n</em>+<em>klog</em>(<em>k</em>)). Here, m<em>m</em> refers to the length of the input string. We need to scan the input string once to split it and determine the various levels. n<em>n</em> refers to the depth of the last directory level in the given input for ls. This factor is taken because we need to enter n<em>n</em> levels of the tree structure to reach the last level. k<em>k</em> refers to the number of entries(files+subdirectories) in the last level directory(in the current input). We need to sort these names giving a factor of klog(k)<em>klog</em>(<em>k</em>).</li><li>The time complexity of executing an mkdir command is O(m+n)<em>O</em>(<em>m</em>+<em>n</em>). Here, m<em>m</em> refers to the length of the input string. We need to scan the input string once to split it and determine the various levels. n<em>n</em> refers to the depth of the last directory level in the mkdir input. This factor is taken because we need to enter n<em>n</em> levels of the tree structure to reach the last level.</li><li>The time complexity of both addContentToFile and readContentFromFile is O(m+n)<em>O</em>(<em>m</em>+<em>n</em>). Here, m<em>m</em> refers to the length of the input string. We need to scan the input string once to split it and determine the various levels. n<em>n</em> refers to the depth of the file name in the current input. This factor is taken because we need to enter n<em>n</em> levels of the tree structure to reach the level where the files&#39;s contents need to be added/read from.</li><li>The advantage of this scheme of maintaining the directory structure is that it is expandable to include even more commands easily. For example, rmdir to remove a directory given an input directory path. We need to simply reach to the destined directory level and remove the corresponding directory entry from the corresponding dirs<em>dirs</em> keys.</li><li>Renaming files/directories is also very simple, since all we need to do is to create a temporary copy of the directory structure/file with a new name and delete the last entry.</li><li>Relocating a hierarchichal subdirectory structure from one directory to the other is also very easy, since, all we need to do is obtain the address for the corresponding subdirectory class, and assign the same at the new positon in the new directory structure.</li><li>If the number of directories is very large, we waste redundant space for isfile<em>isfile</em> and content<em>content</em>, which wasn&#39;t needed in the first design.</li><li>A problem with the current design could occur if we want to list only the directories(and not the files), on any given path. In this case, we need to traverse over the whole contents of the current directory, check for each entry, whether it is a file or a directory, and then extract the required data.</li></ul><pre>public class FileSystem {<br>    class File {<br>        boolean isfile = false;<br>        HashMap &lt; String, File &gt; files = new HashMap &lt; &gt; ();<br>        String content = &quot;&quot;;<br>    }<br>    File root;<br>    public FileSystem() {<br>        root = new File();<br>    }</pre><pre>public List &lt; String &gt; ls(String path) {<br>        File t = root;<br>        List &lt; String &gt; files = new ArrayList &lt; &gt; ();<br>        if (!path.equals(&quot;/&quot;)) {<br>            String[] d = path.split(&quot;/&quot;);<br>            for (int i = 1; i &lt; d.length; i++) {<br>                t = t.files.get(d[i]);<br>            }<br>            if (t.isfile) {<br>                files.add(d[d.length - 1]);<br>                return files;<br>            }<br>        }<br>        List &lt; String &gt; res_files = new ArrayList &lt; &gt; (t.files.keySet());<br>        Collections.sort(res_files);<br>        return res_files;<br>    }</pre><pre>public void mkdir(String path) {<br>        File t = root;<br>        String[] d = path.split(&quot;/&quot;);<br>        for (int i = 1; i &lt; d.length; i++) {<br>            if (!t.files.containsKey(d[i]))<br>                t.files.put(d[i], new File());<br>            t = t.files.get(d[i]);<br>        }<br>    }</pre><pre>public void addContentToFile(String filePath, String content) {<br>        File t = root;<br>        String[] d = filePath.split(&quot;/&quot;);<br>        for (int i = 1; i &lt; d.length - 1; i++) {<br>            t = t.files.get(d[i]);<br>        }<br>        if (!t.files.containsKey(d[d.length - 1]))<br>            t.files.put(d[d.length - 1], new File());<br>        t = t.files.get(d[d.length - 1]);<br>        t.isfile = true;<br>        t.content = t.content + content;<br>    }</pre><pre>public String readContentFromFile(String filePath) {<br>        File t = root;<br>        String[] d = filePath.split(&quot;/&quot;);<br>        for (int i = 1; i &lt; d.length - 1; i++) {<br>            t = t.files.get(d[i]);<br>        }<br>        return t.files.get(d[d.length - 1]).content;<br>    }<br>}</pre><pre>/**<br> * Your FileSystem object will be instantiated and called as such:<br> * FileSystem obj = new FileSystem();<br> * List&lt;String&gt; param_1 = obj.ls(path);<br> * obj.mkdir(path);<br> * obj.addContentToFile(filePath,content);<br> * String param_4 = obj.readContentFromFile(filePath);<br> */</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96ee6c484616" width="1" height="1" alt=""><hr><p><a href="https://medium.com/root-node/design-in-memory-file-system-96ee6c484616">Design In-Memory File System</a> was originally published in <a href="https://medium.com/root-node">Root Node</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coding Question #3: Level Order Traversal]]></title>
            <link>https://medium.com/root-node/coding-question-3-level-order-traversal-f0e9a5eec2ec?source=rss-9dfdf3906bca------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0e9a5eec2ec</guid>
            <category><![CDATA[coding-question]]></category>
            <dc:creator><![CDATA[Santanu Das]]></dc:creator>
            <pubDate>Sat, 27 Jun 2020 13:51:13 GMT</pubDate>
            <atom:updated>2020-06-27T13:51:13.222Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CDOd1XoG2OqicjG_Sge3sQ.jpeg" /></figure><p><strong>Question: </strong>Given a tree, return its level order traversal, nodes of the same level in separate line.</p><p><strong>Approach:</strong> You use Queue to do a level order traversal. But how do you print nodes of a particular level on each line? You use the size of the queue for that. Below is the code.</p><p><strong>Code:</strong></p><pre>vector&lt;vector&lt;int&gt;&gt; levelOrder(TreeNode* root) {<br>        if(root==NULL) return {};<br>        vector&lt;vector&lt;int&gt;&gt; result; <br>        vector&lt;int&gt; row; queue&lt;TreeNode*&gt; queue;<br>        queue.push(root); <br>        result.push_back({root-&gt;val});<br>        int count = queue.size();<br>        while(!queue.empty()) {<br>            TreeNode* current = queue.front(); <br>            queue.pop();<br>            if(current-&gt;left != NULL) {<br>                queue.push(current-&gt;left);<br>                row.push_back(current-&gt;left-&gt;val);<br>            }<br>            if(current-&gt;right != NULL) {<br>                queue.push(current-&gt;right); <br>                row.push_back(current-&gt;right-&gt;val);<br>            }<br>            if(--count == 0) {<br>                result.push_back(row); <br>                row.clear(); <br>                count = queue.size();<br>            }<br>        }<br>        result.pop_back();<br>        return result;<br>    }</pre><p><strong>Complexity Analysis:</strong></p><ul><li>Time complexity : O(<em>N</em>) since each node is processed exactly once.</li><li>Space complexity :O(<em>N</em>) to keep the output structure which contains N node values.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0e9a5eec2ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/root-node/coding-question-3-level-order-traversal-f0e9a5eec2ec">Coding Question #3: Level Order Traversal</a> was originally published in <a href="https://medium.com/root-node">Root Node</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coding Question #2: Flood Fill]]></title>
            <link>https://medium.com/root-node/coding-question-2-flood-fill-abf985b0aab1?source=rss-9dfdf3906bca------2</link>
            <guid isPermaLink="false">https://medium.com/p/abf985b0aab1</guid>
            <category><![CDATA[coding-question]]></category>
            <dc:creator><![CDATA[Santanu Das]]></dc:creator>
            <pubDate>Sat, 27 Jun 2020 13:19:26 GMT</pubDate>
            <atom:updated>2020-06-27T13:19:26.327Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*8s2SgvvMdiplQsTXe_Olbw.jpeg" /></figure><p><strong>Question:</strong> Given an image represented by a 2D matrix where each cell represents a color in range 0 to 65535, a target cell (row, col) and a target color. You have to return the image after flood fill.</p><p>What is Flood Fill here? Consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.</p><p><strong>Approach: </strong>Basically we just have to traverse the matrix and perform a straight ahead depth first search and change the matrix in our way.</p><p><strong>Code:</strong></p><pre>void dfs(vector&lt;vector&lt;int&gt;&gt; &amp;image, int row, int col, int oldColor, int newColor){<br>        if(row&lt;0||row&gt;=image.size() || col&lt;0||col&gt;=image[0].size() || image[row][col]!= oldColor) return;<br>        <br>        image[row][col] = newColor;<br>        <br>        dfs(image, row+1,col, oldColor, newColor);<br>        dfs(image, row-1,col, oldColor, newColor);<br>        dfs(image, row,col+1, oldColor, newColor);<br>        dfs(image, row,col-1, oldColor, newColor);<br>        <br>    }<br>    <br>    vector&lt;vector&lt;int&gt;&gt; floodFill(vector&lt;vector&lt;int&gt;&gt;&amp; image, int sr, int sc, int newColor) {<br>        int oldColor = image[sr][sc];<br>        if(oldColor == newColor) return image;<br>        dfs(image, sr,sc, oldColor, newColor);<br>        return image;<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abf985b0aab1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/root-node/coding-question-2-flood-fill-abf985b0aab1">Coding Question #2: Flood Fill</a> was originally published in <a href="https://medium.com/root-node">Root Node</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Question #1: Next Greater Element]]></title>
            <link>https://medium.com/root-node/question-1-next-greater-element-934046e816e8?source=rss-9dfdf3906bca------2</link>
            <guid isPermaLink="false">https://medium.com/p/934046e816e8</guid>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Santanu Das]]></dc:creator>
            <pubDate>Fri, 26 Jun 2020 21:41:32 GMT</pubDate>
            <atom:updated>2020-06-26T21:47:42.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*rpJOIejscHo7JhZOxSAmPA.jpeg" /></figure><p>Question: Given an array, return the next greater number than the current number for every element. If there is no greater number you can return -1.</p><p>Example:</p><p>Given array: 4 3 5 2 7 1</p><p>Output: 5 5 7 7 -1</p><p>The Algorithm:</p><ul><li>Push the first element to stack.</li><li>Pick rest of the elements one by one and follow the following steps in loop.</li></ul><ol><li>Mark the current element as <em>next</em>.</li><li>If stack is not empty, compare top element of stack with <em>next</em>.</li><li>If next is greater than the top element,Pop element from stack. <em>next </em>is the next greater element for the popped element.</li><li>Keep popping from the stack while the popped element is smaller than <em>next</em>. <em>next</em> becomes the next greater element for all such popped elements</li></ol><ul><li>Finally, push the next in the stack.</li><li>After the loop in step 2 is over, pop all the elements from stack and print -1 as next element for them.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=934046e816e8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/root-node/question-1-next-greater-element-934046e816e8">Question #1: Next Greater Element</a> was originally published in <a href="https://medium.com/root-node">Root Node</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Welcome fellow dreamer.]]></title>
            <link>https://medium.com/root-node/welcome-fellow-dreamer-c2dc7bd0e8d9?source=rss-9dfdf3906bca------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2dc7bd0e8d9</guid>
            <category><![CDATA[crack-coding-interview]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Santanu Das]]></dc:creator>
            <pubDate>Fri, 26 Jun 2020 21:18:25 GMT</pubDate>
            <atom:updated>2020-06-26T21:18:25.140Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Welcome, dreamer." src="https://cdn-images-1.medium.com/max/1000/1*OM1J5C9OOxR9CMOgi5s0iw.jpeg" /><figcaption>Welcome, dreamer.</figcaption></figure><p>Hi, I am starting this publication to post mostly coding questions. Yeah that’s it. But it will be s lot more than just another coding blog. The most important reason for this blog to exist is to prepare its regular readers to coding interviews for the most prestigious organizations in the world. You can fill that spot with your most favorite company.</p><p>I will keep updating this particular post with more details on this. For now, lets grab a pen and paper and write some code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2dc7bd0e8d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/root-node/welcome-fellow-dreamer-c2dc7bd0e8d9">Welcome fellow dreamer.</a> was originally published in <a href="https://medium.com/root-node">Root Node</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating the Process, not the destinatio]]></title>
            <link>https://medium.com/@iamsantanu/creating-the-process-not-the-destinatio-af6f5f2db99?source=rss-9dfdf3906bca------2</link>
            <guid isPermaLink="false">https://medium.com/p/af6f5f2db99</guid>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[hard-work]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[motivation]]></category>
            <dc:creator><![CDATA[Santanu Das]]></dc:creator>
            <pubDate>Wed, 25 Sep 2019 11:49:11 GMT</pubDate>
            <atom:updated>2019-09-25T11:49:11.851Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating the Process, not the destination</h3><p>Don’t worry I ain’t gonna bust your head with one of those ‘Follow your passion’ type of things. I am gonna talk something really practical.</p><p>So I was browsing through Youtube today. I saw tons of videos about motivation and making money. Making money is a topic every one of us is crazy about right? I bet everyone wants to make a shit ton of money no matter how. We want to live that expensive life we see in hollywood movies and TV shows. Who doesn’t wants to drive a Lambo and chill on the beach. And I respect that. Its not a bad thing to have a desire to make money. Actually, very few people can earn the amount of money they want.</p><p>Now lets fast forward your time a bit and think about something. What do you actually want to do with the money you earn? I hope you not gonna keep that whole amount in a bank and die right? Then what you gonna spend that at? Yeah you can buy that expensive car. You can ride that everyday. You can buy that expensive iPhone. You can have parties everyday. Now ask yourself. <strong>‘Then what?’</strong></p><p>Was that your final destination? Was that where you wanted to go in your life? Most people think that they will work hard for few years, earn a million dollars somehow which they don’t know, and then enjoy the expensive life. That is the worst thinking your brain can allow you to think.</p><p>Do you think people who made it big stopped working hard after earning their first million or first billion? Couldn’t have they stopped working and spent the rest of their lives like a king? Are they stupid? No. The only thing why they are so big because they are in love with the process and not the destination. Their process is their destination. They found what they loved and managed to do something to make that work their everyday job.</p><p>We also need to stop thinking about money and start thinking of the things that amazes us. Something you would do when you are procrastinating. You might have a debt. I respect that. Then get a job, work hard, pay off your debts and while in that also do what you love. Find that thing which you will be wanting to do when you will have no abundance of money. And trust me, no matter what your passion is, you can find ways to monetize that.</p><p>The role of money in your life should be keeping you alive and feeding your passion. When you start doing what you love, your work becomes your play. Being able to do that stuff you love everyday for the rest of your lives, that should be your reward, and not the money that will come with it anyway.</p><p>See you soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af6f5f2db99" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>