<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ coding interview - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ coding interview - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 12 May 2026 20:31:59 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/coding-interview/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Visualization for Leetcode's Two Sum Problem – HTML, CSS, & JavaScript Project ]]>
                </title>
                <description>
                    <![CDATA[ With the current state of the job market, there are a lot of people grinding out LeetCode as a way to prepare for technical interviews.  But sometimes it would be nice if there were a visualization showing the algorithms behind these problems.  In th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-a-visualization-for-leetcode-two-sum-problem/</link>
                <guid isPermaLink="false">66b8d935d482a18d3e028263</guid>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data visualization ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ leetcode ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jessica Wilkins ]]>
                </dc:creator>
                <pubDate>Tue, 21 Nov 2023 21:08:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/nubelson-fernandes--Xqckh_XVU4-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>With the current state of the job market, there are a lot of people grinding out <a target="_blank" href="https://leetcode.com/">LeetCode</a> as a way to prepare for technical interviews. </p>
<p>But sometimes it would be nice if there were a visualization showing the algorithms behind these problems. </p>
<p>In this tutorial, we will build out a <a target="_blank" href="https://codepen.io/Jessica-Wilkins-the-decoder/full/eYxVyKN">visualization</a> showing a couple of approaches to a popular LeetCode problem called <a target="_blank" href="https://leetcode.com/problems/two-sum/">Two Sum</a>. We will use vanilla HTML, CSS, and JavaScript to build this project out. </p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#heading-project-setup">Project Setup</a></li>
<li><a class="post-section-overview" href="#heading-how-to-solve-leetcodes-two-sum-problem">How to Solve LeetCode's Two Sum Problem</a><ul>
<li><a class="post-section-overview" href="#heading-description">Description</a></li>
<li><a class="post-section-overview" href="#heading-brute-force-approach">Brute Force Approach</a></li>
<li><a class="post-section-overview" href="#heading-brute-force-javascript-solution-and-time-complexity">Brute Force JavaScript Solution and Time Complexity</a></li>
<li><a class="post-section-overview" href="#heading-map-approach-and-solution">Map Approach and Solution</a></li>
<li><a class="post-section-overview" href="#heading-time-complexity-for-the-map-solution">Time Complexity for the Map Solution</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-overview-for-the-two-sum-visualization">Overview  for the Two Sum Visualization</a></li>
<li><a class="post-section-overview" href="#heading-adding-the-brute-force-visualization">Adding the Brute Force Visualization</a><ul>
<li><a class="post-section-overview" href="#heading-creating-the-const-and-let-variables">Creating the const and let Variables</a></li>
<li><a class="post-section-overview" href="#heading-creating-the-getclassname-function">Creating the getClassName Function</a></li>
<li><a class="post-section-overview" href="#heading-creating-the-bruteforceapproach-function">Creating the bruteForceApproach Function</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-disable-the-bruteforcesolutionbtn-when-the-animation-is-in-progress">How to Disable the bruteForceSolutionBtn When the Animation is in Progress</a></li>
<li><a class="post-section-overview" href="#heading-adding-the-map-solution-visualization">Adding the Map Solution Visualization</a><ul>
<li><a class="post-section-overview" href="#heading-creating-the-const-variables">Creating the const Variables</a></li>
<li><a class="post-section-overview" href="#heading-creating-the-optimalapproach-async-function">Creating the optimalApproach Async Function</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-reset-the-table-output-for-the-map-solution">How to Reset the Table Output for the Map Solution</a></li>
<li><a class="post-section-overview" href="#heading-final-solution-code-and-live-example">Final Solution Code and Live Example</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>This tutorial assumes that you have basic knowledge of HTML, CSS and JavaScript. If you haven't gone through a beginner course in any of those languages, then I would suggest starting with these resources:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/learn/2022/responsive-web-design/">freeCodeCamp's Responsive Web Design Certification</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/">freeCodeCamp's JavaScript Algorithms and Data Structures Certification</a></li>
</ul>
<p>This tutorial also assumes that you have some basic knowledge of how to work with a code editor or IDE. If not, then I would suggest looking into these resources:</p>
<ul>
<li><a target="_blank" href="https://www.youtube.com/watch?v=WPqXP_kLzpo">Visual Studio Code Crash Course</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-codepen/">How to Use CodePen</a> </li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-replit/">How to Use Replit</a></li>
</ul>
<h2 id="heading-project-setup">Project Setup</h2>
<p>You are free to build out this project in either your local code editor of choice, or through an online IDE or editor like <a target="_blank" href="https://codepen.io/">CodePen</a>, <a target="_blank" href="https://codesandbox.io/">CodeSandbox</a>, or <a target="_blank" href="https://replit.com/">Replit</a>. </p>
<p>This project will consist of three files: <code>index.html</code>, <code>index.js</code>, and <code>styles.css</code>. Since this project is going to mainly focus on JavaScript, I have supplied all of the HTML and CSS in <a target="_blank" href="https://github.com/jdwilkin4/leetcode-two-sum-starter-code">this GitHub repo here</a>. </p>
<p>You are free to <a target="_blank" href="https://www.freecodecamp.org/news/how-to-fork-a-github-repository/">fork</a> and <a target="_blank" href="https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository">clone</a> the repository, or you can copy the code found in the HTML and CSS files and add it to your project.</p>
<p>Once you get your project environment setup, then you should start the local server and see this result on the screen:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/Screenshot-2023-11-19-at-4.18.24-PM.png" alt="Image" width="600" height="400" loading="lazy">
<em>Visualization styles for Leetcode's Two Sum problem</em></p>
<h2 id="heading-how-to-solve-leetcodes-two-sum-problem">How to Solve LeetCode's Two Sum problem</h2>
<p>Before we can build out the visualization for this problem, we need to first understand and solve the problem.</p>
<h3 id="heading-description">Description</h3>
<p>For this problem, you will be given a list of numbers in any order and a target number. The goal is to find the pair of numbers that adds up to the target and return an array of indices for that pair of numbers.</p>
<p>In this example, we have the following list and target number:</p>
<pre><code class="lang-js">[<span class="hljs-number">2</span>,<span class="hljs-number">7</span>,<span class="hljs-number">11</span>,<span class="hljs-number">15</span>]
<span class="hljs-attr">target</span>: <span class="hljs-number">9</span>
</code></pre>
<p>The numbers 2 and 7 equal 9 so we would return <code>[0,1]</code> because that represents the indices for where the pair of numbers can be found in the array. </p>
<p>For this problem, you can assume there will be at least two numbers or more in the array and there will only be <strong>one</strong> possible solution. </p>
<p>So for example you can not have this input here which produces no solution because there are no two numbers in that list that add up to the target.</p>
<pre><code class="lang-js">[<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]
<span class="hljs-attr">target</span>: <span class="hljs-number">55</span>
</code></pre>
<p>You will also not get an input with multiple solutions. The following input has two answers of <code>[0,1]</code> and <code>[1,2]</code> which goes against the rules of this problem. </p>
<pre><code class="lang-js">[<span class="hljs-number">3</span>,<span class="hljs-number">3</span>,<span class="hljs-number">3</span>]
<span class="hljs-attr">target</span>: <span class="hljs-number">6</span>
</code></pre>
<h3 id="heading-brute-force-approach">Brute Force Approach</h3>
<p>The more intuitive approach would be to start at the beginning of the list of numbers and compare each possible pair of numbers until we find the pair that adds up to the target. </p>
<p>Let's take a look at this example here:</p>
<pre><code class="lang-js">[<span class="hljs-number">11</span>, <span class="hljs-number">15</span>, <span class="hljs-number">2</span>, <span class="hljs-number">7</span>]
<span class="hljs-attr">target</span>:<span class="hljs-number">9</span>
</code></pre>
<p>We can start with the first number in the list (11) and check each possible pair and see if it adds up to the target number (9).</p>
<pre><code><span class="hljs-number">11</span> + <span class="hljs-number">15</span> = <span class="hljs-number">9</span>? NO
<span class="hljs-number">11</span> + <span class="hljs-number">2</span> = <span class="hljs-number">9</span>? NO
<span class="hljs-number">11</span> + <span class="hljs-number">7</span> = <span class="hljs-number">9</span>? NO
</code></pre><p>Since none of those pairs equal the target (9), then we move to the second number in the list (15) and check all possible pairs. There is no need to check 11+15 because we already checked that earlier.</p>
<pre><code><span class="hljs-number">15</span> + <span class="hljs-number">2</span> = <span class="hljs-number">9</span>? NO
<span class="hljs-number">15</span> + <span class="hljs-number">7</span> = <span class="hljs-number">9</span>? NO
</code></pre><p>Since none of those pairs equal the target (9), then we move to the third number in the list (2) and check all possible pairs.</p>
<pre><code><span class="hljs-number">2</span> + <span class="hljs-number">7</span> = <span class="hljs-number">9</span>? YES!!!
</code></pre><p>Now, we have found the pair that adds up to the target we would return <code>[2,3]</code> because that represents the indices for where the pair of numbers can be found in the array. </p>
<h3 id="heading-brute-force-javascript-solution-and-time-complexity">Brute Force JavaScript Solution and Time Complexity</h3>
<p>This solution uses a nested <code>for</code> loop which would be an O(n²) time complexity. The outer loop is used to get the current number in the list and the inner loop is used to check if the sum of the current number and other numbers in the list add up to the target.</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * <span class="hljs-doctag">@param <span class="hljs-type">{number[]}</span> <span class="hljs-variable">nums</span></span>
 * <span class="hljs-doctag">@param <span class="hljs-type">{number}</span> <span class="hljs-variable">target</span></span>
 * <span class="hljs-doctag">@return <span class="hljs-type">{number[]}</span></span>
 */</span>

<span class="hljs-keyword">var</span> twoSum = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">nums, target</span>) </span>{
  <span class="hljs-keyword">if</span> (nums.length === <span class="hljs-number">2</span>) <span class="hljs-keyword">return</span> [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>];

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; nums.length; i++) {
    <span class="hljs-keyword">const</span> currentNum = nums[i];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = i + <span class="hljs-number">1</span>; j &lt; nums.length; j++) {
      <span class="hljs-keyword">if</span> (currentNum + nums[j] === target) <span class="hljs-keyword">return</span> [i, j];
    }
  }
};
</code></pre>
<p><strong>Note:</strong> I have added an additional check in my solution to check if the input array has only two numbers. In that case, we immediately return <code>[0,1]</code> because those are the only possible indices for that test case. </p>
<pre><code class="lang-js"> <span class="hljs-keyword">if</span> (nums.length === <span class="hljs-number">2</span>) <span class="hljs-keyword">return</span> [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>];
</code></pre>
<p>So far, our input arrays have been very small. But if we had an input array of 100, 500, or 1000+ numbers, then it could take a while to find the pair that adds up to the target. </p>
<p>In the next section, we are going to take a look at a solution that utilizes JavaScript's <code>Map</code> object and runs in linear time O(n).</p>
<h3 id="heading-map-approach-and-solution">Map Approach and Solution</h3>
<p>In the brute force approach, we started at the beginning of the array and compared all possible pairs of numbers until we found the pair that added up to the target. But in this approach we can use JavaScript's <code>Map</code> object and one <code>for</code> loop to find that pair.</p>
<p>JavaScript's <code>Map</code> object is a collection of key-value pairs that allows for quick lookups and has built in methods like <code>set()</code>, <code>get()</code> and <code>has()</code>.</p>
<p>Let's work with the same example from earlier:</p>
<pre><code class="lang-js">[<span class="hljs-number">11</span>, <span class="hljs-number">15</span>, <span class="hljs-number">2</span>, <span class="hljs-number">7</span>]
<span class="hljs-attr">target</span>:<span class="hljs-number">9</span>
</code></pre>
<p>We can start looping through the array and look at the current number in the list which would be <code>nums[i]</code>. We also want to create a new <code>map</code> object which will be empty to start.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i=<span class="hljs-number">0</span>; i&lt;nums.length; i++){

}
</code></pre>
<p>Inside our loop, we need to calculate the difference which will be the target minus the current number.</p>
<pre><code class="lang-js">    <span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i=<span class="hljs-number">0</span>; i&lt;nums.length; i++){
        <span class="hljs-keyword">const</span> difference = target - nums[i]
    }
</code></pre>
<p>Since we know there can only be two numbers that add up to the target, we can check if the difference is in the <code>map</code>. If so, we have found the pair and can return the indices. Otherwise, we can add that current number to the <code>map</code> along with its index.</p>
<pre><code class="lang-js">    <span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i=<span class="hljs-number">0</span>; i &lt; nums.length; i++) {
        <span class="hljs-keyword">const</span> difference = target - nums[i]

        <span class="hljs-keyword">if</span>(map.has(difference)) {
            <span class="hljs-keyword">return</span> [map.get(difference), i]
        } <span class="hljs-keyword">else</span> {
            map.set(nums[i], i)
        }
    }
</code></pre>
<p>In the following code, the <code>has()</code> method is used to check if the following <code>key</code> is in the <code>map</code> object. This method will return a boolean of true or false. </p>
<pre><code class="lang-js">map.has(difference)
</code></pre>
<p>The <code>get()</code> method is used to return that element from the <code>map</code>. </p>
<pre><code class="lang-js"> <span class="hljs-keyword">if</span>(map.has(difference)) {
   <span class="hljs-keyword">return</span> [map.get(difference), i]
 }
</code></pre>
<p>The <code>set()</code> method will add or update an entry in the <code>map</code> with a key and value.</p>
<pre><code class="lang-js"><span class="hljs-keyword">else</span> {
  map.set(nums[i], i)
}
</code></pre>
<p>Here is the complete code for this approach:</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * <span class="hljs-doctag">@param <span class="hljs-type">{number[]}</span> <span class="hljs-variable">nums</span></span>
 * <span class="hljs-doctag">@param <span class="hljs-type">{number}</span> <span class="hljs-variable">target</span></span>
 * <span class="hljs-doctag">@return <span class="hljs-type">{number[]}</span></span>
 */</span>
<span class="hljs-keyword">var</span> twoSum = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">nums, target</span>) </span>{
    <span class="hljs-keyword">if</span>(nums.length === <span class="hljs-number">2</span>) <span class="hljs-keyword">return</span> [<span class="hljs-number">0</span>,<span class="hljs-number">1</span>]

    <span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; nums.length; i++) {
        <span class="hljs-keyword">const</span> difference = target - nums[i]

        <span class="hljs-keyword">if</span> (map.has(difference)) {
            <span class="hljs-keyword">return</span> [map.get(difference), i]
        } <span class="hljs-keyword">else</span> {
            map.set(nums[i], i)
        }
    }

};
</code></pre>
<h3 id="heading-time-complexity-for-the-map-solution">Time Complexity for the Map Solution</h3>
<p>This solution would be a linear time complexity O(n). Since we are only using one loop instead of two, we have improved on the time complexity and no longer running in quadratic time O(n²) like we were earlier.</p>
<p>In the next few sections, we are going to start to build out the visualizations for each of these approaches. </p>
<h2 id="heading-overview-for-the-two-sum-visualization">Overview for the Two Sum Visualization</h2>
<p>The goal of this project is to create visualizations for both the map and brute force solutions. </p>
<p>For the brute force solution, we will show what is it like to walk through each pair of numbers until we find the pair that adds up to the target.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/Screenshot-2023-11-20-at-8.43.08-AM.png" alt="Image" width="600" height="400" loading="lazy">
<em>Brute Force approach visualization</em></p>
<p>For the map solution, we will show the map being built out and checking for the pair that adds up to the target. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/Screenshot-2023-11-20-at-8.51.40-AM.png" alt="Image" width="600" height="400" loading="lazy">
<em>Map solution visualization</em></p>
<h2 id="heading-adding-the-brute-force-visualization">Adding the Brute Force Visualization</h2>
<h3 id="heading-creating-the-const-and-let-variables">Creating the <code>const</code> and <code>let</code> Variables</h3>
<p>We first need to create <code>const</code> variables and assign them the result of accessing the HTML elements responsible for displaying the brute force solution button and output.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bruteForceSolutionBtn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"brute-force-visual-btn"</span>);
<span class="hljs-keyword">const</span> bruteForceNumbersOutput = <span class="hljs-built_in">document</span>.querySelector(
  <span class="hljs-string">"#brute-force-output &gt; .numbers-array"</span>
);
<span class="hljs-keyword">const</span> bruteForceTextOutput = <span class="hljs-built_in">document</span>.querySelector(
  <span class="hljs-string">"#brute-force-output &gt; .result-text"</span>
);
</code></pre>
<p>The next step is to create <code>const</code> variables for the test case array and target that will be used for both visualizations. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> testCaseArray = [<span class="hljs-number">11</span>, <span class="hljs-number">15</span>, <span class="hljs-number">2</span>, <span class="hljs-number">7</span>];
<span class="hljs-keyword">const</span> target = <span class="hljs-number">9</span>;
</code></pre>
<p>Then, we need to create the <code>let</code> variables that will represent the current number we are looking at in the outer loop and the compliment number we are looking at in the inner loop. </p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> currentNum;
<span class="hljs-keyword">let</span> currentCompliment;
</code></pre>
<h3 id="heading-creating-the-getclassname-function">Creating the <code>getClassName</code> Function</h3>
<p>In our visualization we want to show the user the current pair of numbers we are checking by applying different colored borders around them. The current number will have a green border around it and the current compliment number will have a blue border around it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/Screenshot-2023-11-20-at-10.02.46-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In order to dynamically update these styles over time, we need to create a function that will be responsible for adding the appropriate classes to the current number and it compliment. </p>
<p>First, start by creating a new <code>getClassName</code> function that takes in a <code>num</code> parameter.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getClassName = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> {

};
</code></pre>
<p>Inside that function, create a <code>switch</code> statement that has the <code>num</code> for the expression we are checking for. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getClassName = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (num) {

  }
};
</code></pre>
<p>The first <code>case</code> should check for <code>currentNum</code> and return a string for the <code>current-num</code> class.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getClassName = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (num) {
    <span class="hljs-keyword">case</span> currentNum:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"class='current-num'"</span>;
  }
};
</code></pre>
<p>The second <code>case</code> should check for the <code>currentCompliment</code> and return a string for the <code>compliment-num</code> class. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getClassName = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (num) {
    <span class="hljs-keyword">case</span> currentNum:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"class='current-num'"</span>;
    <span class="hljs-keyword">case</span> currentCompliment:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"class='compliment-num'"</span>;
  }
};
</code></pre>
<p>For the <code>default</code> case, it should return an empty string because we are not going to apply any classes for that element. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getClassName = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (num) {
    <span class="hljs-keyword">case</span> currentNum:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"class='current-num'"</span>;
    <span class="hljs-keyword">case</span> currentCompliment:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"class='compliment-num'"</span>;
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>;
  }
};
</code></pre>
<h3 id="heading-creating-the-bruteforceapproach-function">Creating the <code>bruteForceApproach</code> Function</h3>
<p>This function will be responsible for executing the brute force solution and displaying the visualization on the page. </p>
<p>We first need to create the <code>bruteForceApproach</code> function which will be an <code>async</code> function. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bruteForceApproach = <span class="hljs-keyword">async</span> () =&gt; {

};
</code></pre>
<p>Then, we need to add the outer loop for our test case array.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bruteForceApproach = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {

  }
};
</code></pre>
<p>Inside the <code>for</code> loop, update the <code>currentNum</code> to assign it the value of the current number we are looking at in the test case array.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bruteForceApproach = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {
    currentNum = testCaseArray[i];
  }
};
</code></pre>
<p>Next, create the inner <code>for</code> loop.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bruteForceApproach = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {
    currentNum = testCaseArray[i];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = i + <span class="hljs-number">1</span>; j &lt; testCaseArray.length; ++j) {

    }
  }
};
</code></pre>
<p>Inside the inner <code>for</code> loop, update the <code>currentCompliment</code> number and assign it the value of <code>testCaseArray[j]</code>. This is meant to represent each number to the right of the current number. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bruteForceApproach = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {
    currentNum = testCaseArray[i];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = i + <span class="hljs-number">1</span>; j &lt; testCaseArray.length; ++j) {
      currentCompliment = testCaseArray[j];
    }
  }
};
</code></pre>
<p>Next, we need to add a <code>setTimeout</code> which will delay the visual changes made to the markup by one second. This is what is going to help create the animated effect of showing the different pairs of numbers. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bruteForceApproach = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {
    currentNum = testCaseArray[i];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = i + <span class="hljs-number">1</span>; j &lt; testCaseArray.length; ++j) {
      currentCompliment = testCaseArray[j];
      <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">1000</span>));
    }
  }
};
</code></pre>
<p>Then we need to update the HTML for the output. Start by assigning the test case array to <code>bruteForceNumbersOutput.innerHTML</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bruteForceApproach = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {
    currentNum = testCaseArray[i];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = i + <span class="hljs-number">1</span>; j &lt; testCaseArray.length; ++j) {
      currentCompliment = testCaseArray[j];
      <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">1000</span>));

      bruteForceNumbersOutput.innerHTML = testCaseArray;
    }
  }
};
</code></pre>
<p>Then, we want to use the <code>map</code> method on the array, to create a new array of <code>span</code> elements which represents each number in the array along with the styles. We also need to chain the <code>join</code> method on that to remove the commas that the <code>map</code> method adds when the new array is created.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bruteForceApproach = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {
    currentNum = testCaseArray[i];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = i + <span class="hljs-number">1</span>; j &lt; testCaseArray.length; ++j) {
      currentCompliment = testCaseArray[j];
      <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">1000</span>));

      bruteForceNumbersOutput.innerHTML = testCaseArray
        .map(
          <span class="hljs-function">(<span class="hljs-params">num, index</span>) =&gt;</span>
            <span class="hljs-string">`
            &lt;span <span class="hljs-subst">${getClassName(num)}</span>&gt;
            <span class="hljs-subst">${testCaseArray[index]}</span>
            &lt;/span&gt;
          `</span>
        )
        .join(<span class="hljs-string">""</span>);
    }
  }
};
</code></pre>
<p>If we don't find a pair that adds up to the target, then we want to display a message to the user. Update the text content for the <code>bruteForceTextOutput</code> and assign it the following message:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bruteForceApproach = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {
    currentNum = testCaseArray[i];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = i + <span class="hljs-number">1</span>; j &lt; testCaseArray.length; ++j) {
      currentCompliment = testCaseArray[j];
      <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">1000</span>));

      bruteForceNumbersOutput.innerHTML = testCaseArray
        .map(
          <span class="hljs-function">(<span class="hljs-params">num, index</span>) =&gt;</span>
            <span class="hljs-string">`
            &lt;span <span class="hljs-subst">${getClassName(num)}</span>&gt;
            <span class="hljs-subst">${testCaseArray[index]}</span>
            &lt;/span&gt;
          `</span>
        )
        .join(<span class="hljs-string">""</span>);

      bruteForceTextOutput.textContent = <span class="hljs-string">`Does the sum of <span class="hljs-subst">${currentNum}</span> + <span class="hljs-subst">${currentCompliment}</span> equal <span class="hljs-subst">${target}</span>? NO!`</span>;
    }
  }
};
</code></pre>
<p>The last piece is to add a condition that checks if we found the pair of numbers that adds up to the target. If so, then we can display that final indices array and <code>return</code> from the function. </p>
<pre><code class="lang-js">  <span class="hljs-keyword">if</span> (currentNum + currentCompliment === target) {
      bruteForceTextOutput.textContent = <span class="hljs-string">`Final indices: [<span class="hljs-subst">${i}</span>, <span class="hljs-subst">${j}</span>]`</span>;
      <span class="hljs-keyword">return</span>;
  }
</code></pre>
<p>To test out the brute force visualization, we will need to add an event listener to the <code>bruteForceSolutionBtn</code>. The event listener should listen for a <code>"click"</code> event and should reference the <code>bruteForceApproach</code> function.</p>
<pre><code class="lang-js">bruteForceSolutionBtn.addEventListener(<span class="hljs-string">"click"</span>, bruteForceApproach);
</code></pre>
<p>This should be your complete code so far:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bruteForceSolutionBtn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"brute-force-visual-btn"</span>);
<span class="hljs-keyword">const</span> bruteForceNumbersOutput = <span class="hljs-built_in">document</span>.querySelector(
  <span class="hljs-string">"#brute-force-output &gt; .numbers-array"</span>
);
<span class="hljs-keyword">const</span> bruteForceTextOutput = <span class="hljs-built_in">document</span>.querySelector(
  <span class="hljs-string">"#brute-force-output &gt; .result-text"</span>
);
<span class="hljs-keyword">const</span> testCaseArray = [<span class="hljs-number">11</span>, <span class="hljs-number">15</span>, <span class="hljs-number">2</span>, <span class="hljs-number">7</span>];
<span class="hljs-keyword">const</span> target = <span class="hljs-number">9</span>;
<span class="hljs-keyword">let</span> currentNum;
<span class="hljs-keyword">let</span> currentCompliment;

<span class="hljs-keyword">const</span> getClassName = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (num) {
    <span class="hljs-keyword">case</span> currentNum:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"class='current-num'"</span>;
    <span class="hljs-keyword">case</span> currentCompliment:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"class='compliment-num'"</span>;
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>;
  }
};

<span class="hljs-keyword">const</span> bruteForceApproach = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {
    currentNum = testCaseArray[i];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = i + <span class="hljs-number">1</span>; j &lt; testCaseArray.length; ++j) {
      currentCompliment = testCaseArray[j];
      <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">1000</span>));

      bruteForceNumbersOutput.innerHTML = testCaseArray
        .map(
          <span class="hljs-function">(<span class="hljs-params">num, index</span>) =&gt;</span>
            <span class="hljs-string">`
            &lt;span <span class="hljs-subst">${getClassName(num)}</span>&gt;
            <span class="hljs-subst">${testCaseArray[index]}</span>
            &lt;/span&gt;
          `</span>
        )
        .join(<span class="hljs-string">""</span>);

      bruteForceTextOutput.textContent = <span class="hljs-string">`Does the sum of <span class="hljs-subst">${currentNum}</span> + <span class="hljs-subst">${currentCompliment}</span> equal <span class="hljs-subst">${target}</span>? NO!`</span>;

      <span class="hljs-keyword">if</span> (currentNum + currentCompliment === target) {
        bruteForceTextOutput.textContent = <span class="hljs-string">`Final indices: [<span class="hljs-subst">${i}</span>, <span class="hljs-subst">${j}</span>]`</span>;
        <span class="hljs-keyword">return</span>;
      }
    }
  }
};

bruteForceSolutionBtn.addEventListener(<span class="hljs-string">"click"</span>, bruteForceApproach);
</code></pre>
<p>Try out your visualization by clicking on the "Show Visualization" button for the Brute force approach. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/Screenshot-2023-11-20-at-10.42.51-AM.png" alt="Image" width="600" height="400" loading="lazy">
<em>Result of clicking the "show visualization" button for brute force approach</em></p>
<h2 id="heading-how-to-disable-the-bruteforcesolutionbtn-when-the-animation-is-in-progress">How to Disable the <code>bruteForceSolutionBtn</code> When the Animation is in Progress</h2>
<p>If you try to click on the <code>bruteForceSolutionBtn</code> multiple times in a row, you will see glitches in the animation. To fix that, we should disable the button when the animation is running and then re-enable it when the animation is complete. </p>
<p>Inside the <code>bruteForceApproach</code> function, set the disabled attribute for the <code>bruteForceSolutionBtn</code>. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bruteForceApproach = <span class="hljs-keyword">async</span> () =&gt; {
  bruteForceSolutionBtn.setAttribute(<span class="hljs-string">"disabled"</span>, <span class="hljs-string">""</span>);
</code></pre>
<p>Inside the <code>if</code> statement, remove the disabled attribute for the <code>bruteForceSolutionBtn</code>.</p>
<pre><code class="lang-js">   <span class="hljs-keyword">if</span> (currentNum + currentCompliment === target) {
        bruteForceTextOutput.textContent = <span class="hljs-string">`Final indices: [<span class="hljs-subst">${i}</span>, <span class="hljs-subst">${j}</span>]`</span>;
        bruteForceSolutionBtn.removeAttribute(<span class="hljs-string">"disabled"</span>);
        <span class="hljs-keyword">return</span>;
   }
</code></pre>
<p>Here is the complete code with the fix:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bruteForceSolutionBtn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"brute-force-visual-btn"</span>);
<span class="hljs-keyword">const</span> bruteForceNumbersOutput = <span class="hljs-built_in">document</span>.querySelector(
  <span class="hljs-string">"#brute-force-output &gt; .numbers-array"</span>
);
<span class="hljs-keyword">const</span> bruteForceTextOutput = <span class="hljs-built_in">document</span>.querySelector(
  <span class="hljs-string">"#brute-force-output &gt; .result-text"</span>
);
<span class="hljs-keyword">const</span> testCaseArray = [<span class="hljs-number">11</span>, <span class="hljs-number">15</span>, <span class="hljs-number">2</span>, <span class="hljs-number">7</span>];
<span class="hljs-keyword">const</span> target = <span class="hljs-number">9</span>;
<span class="hljs-keyword">let</span> currentNum;
<span class="hljs-keyword">let</span> currentCompliment;

<span class="hljs-keyword">const</span> getClassName = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (num) {
    <span class="hljs-keyword">case</span> currentNum:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"class='current-num'"</span>;
    <span class="hljs-keyword">case</span> currentCompliment:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"class='compliment-num'"</span>;
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>;
  }
};

<span class="hljs-keyword">const</span> bruteForceApproach = <span class="hljs-keyword">async</span> () =&gt; {
  bruteForceSolutionBtn.setAttribute(<span class="hljs-string">"disabled"</span>, <span class="hljs-string">""</span>);

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {
    currentNum = testCaseArray[i];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = i + <span class="hljs-number">1</span>; j &lt; testCaseArray.length; ++j) {
      currentCompliment = testCaseArray[j];
      <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">1000</span>));

      bruteForceNumbersOutput.innerHTML = testCaseArray
        .map(
          <span class="hljs-function">(<span class="hljs-params">num, index</span>) =&gt;</span>
            <span class="hljs-string">`
            &lt;span <span class="hljs-subst">${getClassName(num)}</span>&gt;
            <span class="hljs-subst">${testCaseArray[index]}</span>
            &lt;/span&gt;
          `</span>
        )
        .join(<span class="hljs-string">""</span>);

      bruteForceTextOutput.textContent = <span class="hljs-string">`Does the sum of <span class="hljs-subst">${currentNum}</span> + <span class="hljs-subst">${currentCompliment}</span> equal <span class="hljs-subst">${target}</span>? NO!`</span>;

      <span class="hljs-keyword">if</span> (currentNum + currentCompliment === target) {
        bruteForceTextOutput.textContent = <span class="hljs-string">`Final indices: [<span class="hljs-subst">${i}</span>, <span class="hljs-subst">${j}</span>]`</span>;
        bruteForceSolutionBtn.removeAttribute(<span class="hljs-string">"disabled"</span>);
        <span class="hljs-keyword">return</span>;
      }
    }
  }
};

bruteForceSolutionBtn.addEventListener(<span class="hljs-string">"click"</span>, bruteForceApproach);
</code></pre>
<p>Try out the visualization again, and now you should see that the button is disabled when the animation is running.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/Screenshot-2023-11-20-at-10.56.36-AM.png" alt="Image" width="600" height="400" loading="lazy">
<em>Image showing how button is disabled when animation is showing</em></p>
<h2 id="heading-adding-the-map-solution-visualization">Adding the Map Solution Visualization</h2>
<h3 id="heading-creating-the-const-variables">Creating the <code>const</code> Variables</h3>
<p>We are going to create some new <code>const</code> variables which represent the optimal solution button element, output, and table elements for the animation.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> optimalSolutionBtn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"optimal-visual-btn"</span>);
<span class="hljs-keyword">const</span> currentValueOutput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"current-value-output"</span>);
<span class="hljs-keyword">const</span> finalOptimalSolutionResult = <span class="hljs-built_in">document</span>.getElementById(
  <span class="hljs-string">"final-optimal-result"</span>
);
<span class="hljs-keyword">const</span> table = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"table-output"</span>);
<span class="hljs-keyword">const</span> tableBodyOutput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"map-table-body"</span>);
</code></pre>
<p>Here is the complete list of variable declarations for both visualizations:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bruteForceSolutionBtn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"brute-force-visual-btn"</span>);
<span class="hljs-keyword">const</span> bruteForceNumbersOutput = <span class="hljs-built_in">document</span>.querySelector(
  <span class="hljs-string">"#brute-force-output &gt; .numbers-array"</span>
);
<span class="hljs-keyword">const</span> bruteForceTextOutput = <span class="hljs-built_in">document</span>.querySelector(
  <span class="hljs-string">"#brute-force-output &gt; .result-text"</span>
);
<span class="hljs-keyword">const</span> optimalSolutionBtn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"optimal-visual-btn"</span>);
<span class="hljs-keyword">const</span> currentValueOutput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"current-value-output"</span>);
<span class="hljs-keyword">const</span> finalOptimalSolutionResult = <span class="hljs-built_in">document</span>.getElementById(
  <span class="hljs-string">"final-optimal-result"</span>
);
<span class="hljs-keyword">const</span> table = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"table-output"</span>);
<span class="hljs-keyword">const</span> tableBodyOutput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"map-table-body"</span>);

<span class="hljs-keyword">const</span> testCaseArray = [<span class="hljs-number">11</span>, <span class="hljs-number">15</span>, <span class="hljs-number">2</span>, <span class="hljs-number">7</span>];
<span class="hljs-keyword">const</span> target = <span class="hljs-number">9</span>;
<span class="hljs-keyword">let</span> currentNum;
<span class="hljs-keyword">let</span> currentCompliment;
</code></pre>
<h3 id="heading-creating-the-optimalapproach-async-function">Creating the <code>optimalApproach</code> Async Function</h3>
<p>The first step is to create the new <code>optimalApproach</code> function which will be an <code>async</code> function. You can add this below your <code>bruteForceApproach</code> function.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> optimalApproach = <span class="hljs-keyword">async</span> () =&gt; {

};
</code></pre>
<p>Just like the <code>bruteForceApproach</code> function, we want to disable the button when the animation starts to prevent users from clicking it multiple times and breaking the animation.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> optimalApproach = <span class="hljs-keyword">async</span> () =&gt; {
  optimalSolutionBtn.setAttribute(<span class="hljs-string">"disabled"</span>, <span class="hljs-string">""</span>);
};
</code></pre>
<p>When the page first loads, the table is hidden by default. We want to show the table element when the animation starts.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> optimalApproach = <span class="hljs-keyword">async</span> () =&gt; {
  optimalSolutionBtn.setAttribute(<span class="hljs-string">"disabled"</span>, <span class="hljs-string">""</span>);
  table.style.display = <span class="hljs-string">"block"</span>;
};
</code></pre>
<p>Each time we run this animation, we want to display messages to the user on if we have found the correct pair or not. At the beginning of the animation, we want to clear the previous output. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> optimalApproach = <span class="hljs-keyword">async</span> () =&gt; {
  optimalSolutionBtn.setAttribute(<span class="hljs-string">"disabled"</span>, <span class="hljs-string">""</span>);
  table.style.display = <span class="hljs-string">"block"</span>;
  currentValueOutput.innerHTML = <span class="hljs-string">""</span>;
};
</code></pre>
<p>Then, we need to create an empty <code>map</code> object which will eventually be updated over time in the <code>for</code> loop.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> optimalApproach = <span class="hljs-keyword">async</span> () =&gt; {
  optimalSolutionBtn.setAttribute(<span class="hljs-string">"disabled"</span>, <span class="hljs-string">""</span>);
  table.style.display = <span class="hljs-string">"block"</span>;
  currentValueOutput.innerHTML = <span class="hljs-string">""</span>;
  <span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();
};
</code></pre>
<p>Next, we need to create a <code>for</code> loop which will be responsible for looping through each number in the array and updating the animation overtime. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> optimalApproach = <span class="hljs-keyword">async</span> () =&gt; {
  optimalSolutionBtn.setAttribute(<span class="hljs-string">"disabled"</span>, <span class="hljs-string">""</span>);
  table.style.display = <span class="hljs-string">"block"</span>;
  currentValueOutput.innerHTML = <span class="hljs-string">""</span>;
  <span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {

  }
};
</code></pre>
<p>Inside the loop, we need to add the expression for calculating the difference.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> optimalApproach = <span class="hljs-keyword">async</span> () =&gt; {
  optimalSolutionBtn.setAttribute(<span class="hljs-string">"disabled"</span>, <span class="hljs-string">""</span>);
  table.style.display = <span class="hljs-string">"block"</span>;
  currentValueOutput.innerHTML = <span class="hljs-string">""</span>;
  <span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {
    <span class="hljs-keyword">const</span> difference = target - testCaseArray[i];
  }
};
</code></pre>
<p>Then, we need to add a <code>setTimeout</code> which will delay the changes by 2 seconds in the HTML markup and help with the animation effect.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> optimalApproach = <span class="hljs-keyword">async</span> () =&gt; {
  optimalSolutionBtn.setAttribute(<span class="hljs-string">"disabled"</span>, <span class="hljs-string">""</span>);
  table.style.display = <span class="hljs-string">"block"</span>;
  currentValueOutput.innerHTML = <span class="hljs-string">""</span>;
  <span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {
    <span class="hljs-keyword">const</span> difference = target - testCaseArray[i];

    <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">2000</span>));
  }
};
</code></pre>
<p>We then need to add an <code>if</code> statement to check if the map has the difference value.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> optimalApproach = <span class="hljs-keyword">async</span> () =&gt; {
  optimalSolutionBtn.setAttribute(<span class="hljs-string">"disabled"</span>, <span class="hljs-string">""</span>);
  table.style.display = <span class="hljs-string">"block"</span>;
  currentValueOutput.innerHTML = <span class="hljs-string">""</span>;
  <span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {
    <span class="hljs-keyword">const</span> difference = target - testCaseArray[i];

    <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">2000</span>));

    <span class="hljs-keyword">if</span> (map.has(difference)) {

    }
  }
};
</code></pre>
<p>Inside the <code>if</code> statement, we need to update the text content to show the final indices array result on the screen. We will use the <code>get</code> method to get the index value from the <code>map</code>. </p>
<pre><code class="lang-js"> <span class="hljs-keyword">if</span> (map.has(difference)) {
      finalOptimalSolutionResult.textContent = <span class="hljs-string">`Final indices: [<span class="hljs-subst">${map.get(
        difference
      )}</span>, <span class="hljs-subst">${i}</span>]`</span>;
 }
</code></pre>
<p>We also need to update the output for displaying a message that shows we have found the pair of numbers that adds up to the target. </p>
<pre><code class="lang-js">  <span class="hljs-keyword">if</span> (map.has(difference)) {
      finalOptimalSolutionResult.textContent = <span class="hljs-string">`Final indices: [<span class="hljs-subst">${map.get(
        difference
      )}</span>, <span class="hljs-subst">${i}</span>]`</span>;
      currentValueOutput.innerHTML = <span class="hljs-string">`
      &lt;p&gt;Difference(<span class="hljs-subst">${difference}</span>) = target(<span class="hljs-subst">${target}</span>) - current number(<span class="hljs-subst">${testCaseArray[i]}</span>)&lt;/p&gt;
      &lt;p&gt;Is the difference(<span class="hljs-subst">${difference}</span>) in our map? YES, we found that pair of numbers that add up to the target.&lt;/p&gt;
    `</span>;
  }
</code></pre>
<p>We also need to remove the disabled attribute from the <code>optimalSolutionBtn</code> and return from the function. </p>
<pre><code class="lang-js">  <span class="hljs-keyword">if</span> (map.has(difference)) {
      finalOptimalSolutionResult.textContent = <span class="hljs-string">`Final indices: [<span class="hljs-subst">${map.get(
        difference
      )}</span>, <span class="hljs-subst">${i}</span>]`</span>;
      currentValueOutput.innerHTML = <span class="hljs-string">`
      &lt;p&gt;Difference(<span class="hljs-subst">${difference}</span>) = target(<span class="hljs-subst">${target}</span>) - current number(<span class="hljs-subst">${testCaseArray[i]}</span>)&lt;/p&gt;
      &lt;p&gt;Is the difference(<span class="hljs-subst">${difference}</span>) in our map? YES, we found that pair of numbers that add up to the target.&lt;/p&gt;
    `</span>;
      optimalSolutionBtn.removeAttribute(<span class="hljs-string">"disabled"</span>);
      <span class="hljs-keyword">return</span>;
  }
</code></pre>
<p>If the pair has not been found, then we need to add an <code>else</code> clause.</p>
<pre><code class="lang-js">  <span class="hljs-keyword">if</span> (map.has(difference)) {
      finalOptimalSolutionResult.textContent = <span class="hljs-string">`Final indices: [<span class="hljs-subst">${map.get(
        difference
      )}</span>, <span class="hljs-subst">${i}</span>]`</span>;
      currentValueOutput.innerHTML = <span class="hljs-string">`
      &lt;p&gt;Difference(<span class="hljs-subst">${difference}</span>) = target(<span class="hljs-subst">${target}</span>) - current number(<span class="hljs-subst">${testCaseArray[i]}</span>)&lt;/p&gt;
      &lt;p&gt;Is the difference(<span class="hljs-subst">${difference}</span>) in our map? YES, we found that pair of numbers that add up to the target.&lt;/p&gt;
    `</span>;
      optimalSolutionBtn.removeAttribute(<span class="hljs-string">"disabled"</span>);
      <span class="hljs-keyword">return</span>;
  } <span class="hljs-keyword">else</span> {

  }
</code></pre>
<p>Inside the <code>else</code> clause, we need to update the message to show that we have not found the pair and that the current number <code>testCaseArray[i]</code> is going to be added to the <code>map</code> along with its index value.</p>
<pre><code class="lang-js"><span class="hljs-keyword">else</span> {
      currentValueOutput.innerHTML = <span class="hljs-string">`
        &lt;p&gt;Difference(<span class="hljs-subst">${difference}</span>) = target(<span class="hljs-subst">${target}</span>) - current number(<span class="hljs-subst">${testCaseArray[i]}</span>)&lt;/p&gt;
        &lt;p&gt;Is the difference(<span class="hljs-subst">${difference}</span>) in our map? No.&lt;/p&gt;
        &lt;p&gt;Add the current number <span class="hljs-subst">${testCaseArray[i]}</span> to our map.&lt;/p&gt;
      `</span>;
}
</code></pre>
<p>We then need to update the table output with the current number and its index value.</p>
<pre><code class="lang-js"><span class="hljs-keyword">else</span> {
      currentValueOutput.innerHTML = <span class="hljs-string">`
        &lt;p&gt;Difference(<span class="hljs-subst">${difference}</span>) = target(<span class="hljs-subst">${target}</span>) - current number(<span class="hljs-subst">${testCaseArray[i]}</span>)&lt;/p&gt;
        &lt;p&gt;Is the difference(<span class="hljs-subst">${difference}</span>) in our map? No.&lt;/p&gt;
        &lt;p&gt;Add the current number <span class="hljs-subst">${testCaseArray[i]}</span> to our map.&lt;/p&gt;
      `</span>;
      tableBodyOutput.innerHTML += <span class="hljs-string">`
      &lt;tr&gt;
        &lt;td&gt;<span class="hljs-subst">${testCaseArray[i]}</span>&lt;/td&gt;
        &lt;td&gt;<span class="hljs-subst">${i}</span>&lt;/td&gt;
      &lt;/tr&gt;
    `</span>;
}
</code></pre>
<p>Lastly, use the <code>set</code> method to set the current number and index value in the <code>map</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">else</span> {
      currentValueOutput.innerHTML = <span class="hljs-string">`
        &lt;p&gt;Difference(<span class="hljs-subst">${difference}</span>) = target(<span class="hljs-subst">${target}</span>) - current number(<span class="hljs-subst">${testCaseArray[i]}</span>)&lt;/p&gt;
        &lt;p&gt;Is the difference(<span class="hljs-subst">${difference}</span>) in our map? No.&lt;/p&gt;
        &lt;p&gt;Add the current number <span class="hljs-subst">${testCaseArray[i]}</span> to our map.&lt;/p&gt;
      `</span>;
      tableBodyOutput.innerHTML += <span class="hljs-string">`
      &lt;tr&gt;
        &lt;td&gt;<span class="hljs-subst">${testCaseArray[i]}</span>&lt;/td&gt;
        &lt;td&gt;<span class="hljs-subst">${i}</span>&lt;/td&gt;
      &lt;/tr&gt;
    `</span>;
      map.set(testCaseArray[i], i);
}
</code></pre>
<p>Here is the complete code for your <code>optimalApproach</code> function.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> optimalApproach = <span class="hljs-keyword">async</span> () =&gt; {
  optimalSolutionBtn.setAttribute(<span class="hljs-string">"disabled"</span>, <span class="hljs-string">""</span>);
  table.style.display = <span class="hljs-string">"block"</span>;
  currentValueOutput.innerHTML = <span class="hljs-string">""</span>;
  <span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {
    <span class="hljs-keyword">const</span> difference = target - testCaseArray[i];

    <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">2000</span>));

    <span class="hljs-keyword">if</span> (map.has(difference)) {
      finalOptimalSolutionResult.textContent = <span class="hljs-string">`Final indices: [<span class="hljs-subst">${map.get(
        difference
      )}</span>, <span class="hljs-subst">${i}</span>]`</span>;
      currentValueOutput.innerHTML = <span class="hljs-string">`
      &lt;p&gt;Difference(<span class="hljs-subst">${difference}</span>) = target(<span class="hljs-subst">${target}</span>) - current number(<span class="hljs-subst">${testCaseArray[i]}</span>)&lt;/p&gt;
      &lt;p&gt;Is the difference(<span class="hljs-subst">${difference}</span>) in our map? YES, we found that pair of numbers that add up to the target.&lt;/p&gt;
    `</span>;
      optimalSolutionBtn.removeAttribute(<span class="hljs-string">"disabled"</span>);
      <span class="hljs-keyword">return</span>;
    } <span class="hljs-keyword">else</span> {
      currentValueOutput.innerHTML = <span class="hljs-string">`
        &lt;p&gt;Difference(<span class="hljs-subst">${difference}</span>) = target(<span class="hljs-subst">${target}</span>) - current number(<span class="hljs-subst">${testCaseArray[i]}</span>)&lt;/p&gt;
        &lt;p&gt;Is the difference(<span class="hljs-subst">${difference}</span>) in our map? No.&lt;/p&gt;
        &lt;p&gt;Add the current number <span class="hljs-subst">${testCaseArray[i]}</span> to our map.&lt;/p&gt;
      `</span>;
      tableBodyOutput.innerHTML += <span class="hljs-string">`
      &lt;tr&gt;
        &lt;td&gt;<span class="hljs-subst">${testCaseArray[i]}</span>&lt;/td&gt;
        &lt;td&gt;<span class="hljs-subst">${i}</span>&lt;/td&gt;
      &lt;/tr&gt;
    `</span>;
      map.set(testCaseArray[i], i);
    }
  }
};
</code></pre>
<p>To test out this visualization, add an event listener to the <code>optimalSolutionBtn</code> and pass in the <code>"click"</code> event and <code>optimalApproach</code> function reference. </p>
<pre><code class="lang-js">optimalSolutionBtn.addEventListener(<span class="hljs-string">"click"</span>, optimalApproach);
</code></pre>
<p>When you click on the "Show Visualization" button for the map solution, you should see the animation, as shown below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/Screenshot-2023-11-20-at-12.05.05-PM.png" alt="Image" width="600" height="400" loading="lazy">
<em>Visualization for map solution</em></p>
<h2 id="heading-how-to-reset-the-table-output-for-the-map-solution">How to Reset the Table Output for the Map Solution</h2>
<p>If you try to run the animation multiple times, then you will see that the table shows the results from the previous run.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/Screenshot-2023-11-20-at-12.09.35-PM.png" alt="Image" width="600" height="400" loading="lazy">
<em>Table showing results from the previous run</em></p>
<p>To fix this, we can reset the table before each run of the animation. Start by creating a <code>resetTable</code> function above your <code>optimalApproach</code> function.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> resetTable = <span class="hljs-function">() =&gt;</span> {

};

<span class="hljs-keyword">const</span> optimalApproach = <span class="hljs-keyword">async</span> () =&gt; {
    .........
</code></pre>
<p>Inside that function, clear out the table and final text results. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> resetTable = <span class="hljs-function">() =&gt;</span> {
  tableBodyOutput.innerHTML = <span class="hljs-string">""</span>;
  finalOptimalSolutionResult.textContent = <span class="hljs-string">""</span>;
};
</code></pre>
<p>Call the <code>resetTable</code> function inside your <code>optimalApproach</code> function in order to see the results of resetting the table.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> optimalApproach = <span class="hljs-keyword">async</span> () =&gt; {
  resetTable();
  optimalSolutionBtn.setAttribute(<span class="hljs-string">"disabled"</span>, <span class="hljs-string">""</span>);
    ...........
</code></pre>
<p>Test out your animation again, and now you should see that the table results reset before each new animation run. </p>
<h2 id="heading-final-solution-code-and-live-example">Final Solution Code and Live Example</h2>
<p>Here is the complete JavaScript solution code for both visualizations:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bruteForceSolutionBtn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"brute-force-visual-btn"</span>);
<span class="hljs-keyword">const</span> bruteForceNumbersOutput = <span class="hljs-built_in">document</span>.querySelector(
  <span class="hljs-string">"#brute-force-output &gt; .numbers-array"</span>
);
<span class="hljs-keyword">const</span> bruteForceTextOutput = <span class="hljs-built_in">document</span>.querySelector(
  <span class="hljs-string">"#brute-force-output &gt; .result-text"</span>
);
<span class="hljs-keyword">const</span> optimalSolutionBtn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"optimal-visual-btn"</span>);
<span class="hljs-keyword">const</span> currentValueOutput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"current-value-output"</span>);
<span class="hljs-keyword">const</span> finalOptimalSolutionResult = <span class="hljs-built_in">document</span>.getElementById(
  <span class="hljs-string">"final-optimal-result"</span>
);
<span class="hljs-keyword">const</span> table = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"table-output"</span>);
<span class="hljs-keyword">const</span> tableBodyOutput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"map-table-body"</span>);

<span class="hljs-keyword">const</span> testCaseArray = [<span class="hljs-number">11</span>, <span class="hljs-number">15</span>, <span class="hljs-number">2</span>, <span class="hljs-number">7</span>];
<span class="hljs-keyword">const</span> target = <span class="hljs-number">9</span>;
<span class="hljs-keyword">let</span> currentNum;
<span class="hljs-keyword">let</span> currentCompliment;

<span class="hljs-keyword">const</span> getClassName = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (num) {
    <span class="hljs-keyword">case</span> currentNum:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"class='current-num'"</span>;
    <span class="hljs-keyword">case</span> currentCompliment:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"class='compliment-num'"</span>;
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>;
  }
};

<span class="hljs-keyword">const</span> bruteForceApproach = <span class="hljs-keyword">async</span> () =&gt; {
  bruteForceSolutionBtn.setAttribute(<span class="hljs-string">"disabled"</span>, <span class="hljs-string">""</span>);

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {
    currentNum = testCaseArray[i];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = i + <span class="hljs-number">1</span>; j &lt; testCaseArray.length; ++j) {
      currentCompliment = testCaseArray[j];
      <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">1000</span>));

      bruteForceNumbersOutput.innerHTML = testCaseArray
        .map(
          <span class="hljs-function">(<span class="hljs-params">num, index</span>) =&gt;</span>
            <span class="hljs-string">`
              &lt;span <span class="hljs-subst">${getClassName(num)}</span>&gt;
              <span class="hljs-subst">${testCaseArray[index]}</span>
              &lt;/span&gt;
            `</span>
        )
        .join(<span class="hljs-string">""</span>);

      bruteForceTextOutput.textContent = <span class="hljs-string">`Does the sum of <span class="hljs-subst">${currentNum}</span> + <span class="hljs-subst">${currentCompliment}</span> equal <span class="hljs-subst">${target}</span>? NO!`</span>;

      <span class="hljs-keyword">if</span> (currentNum + currentCompliment === target) {
        bruteForceTextOutput.textContent = <span class="hljs-string">`Final indices: [<span class="hljs-subst">${i}</span>, <span class="hljs-subst">${j}</span>]`</span>;
        bruteForceSolutionBtn.removeAttribute(<span class="hljs-string">"disabled"</span>);
        <span class="hljs-keyword">return</span>;
      }
    }
  }
};

<span class="hljs-keyword">const</span> resetTable = <span class="hljs-function">() =&gt;</span> {
  tableBodyOutput.innerHTML = <span class="hljs-string">""</span>;
  finalOptimalSolutionResult.textContent = <span class="hljs-string">""</span>;
};

<span class="hljs-keyword">const</span> optimalApproach = <span class="hljs-keyword">async</span> () =&gt; {
  resetTable();
  optimalSolutionBtn.setAttribute(<span class="hljs-string">"disabled"</span>, <span class="hljs-string">""</span>);
  table.style.display = <span class="hljs-string">"block"</span>;
  currentValueOutput.innerHTML = <span class="hljs-string">""</span>;
  <span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; testCaseArray.length; ++i) {
    <span class="hljs-keyword">const</span> difference = target - testCaseArray[i];

    <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">2000</span>));

    <span class="hljs-keyword">if</span> (map.has(difference)) {
      finalOptimalSolutionResult.textContent = <span class="hljs-string">`Final indices: [<span class="hljs-subst">${map.get(
        difference
      )}</span>, <span class="hljs-subst">${i}</span>]`</span>;
      currentValueOutput.innerHTML = <span class="hljs-string">`
      &lt;p&gt;Difference(<span class="hljs-subst">${difference}</span>) = target(<span class="hljs-subst">${target}</span>) - current number(<span class="hljs-subst">${testCaseArray[i]}</span>)&lt;/p&gt;
      &lt;p&gt;Is the difference(<span class="hljs-subst">${difference}</span>) in our map? YES, we found that pair of numbers that add up to the target.&lt;/p&gt;
    `</span>;
      optimalSolutionBtn.removeAttribute(<span class="hljs-string">"disabled"</span>);
      <span class="hljs-keyword">return</span>;
    } <span class="hljs-keyword">else</span> {
      currentValueOutput.innerHTML = <span class="hljs-string">`
        &lt;p&gt;Difference(<span class="hljs-subst">${difference}</span>) = target(<span class="hljs-subst">${target}</span>) - current number(<span class="hljs-subst">${testCaseArray[i]}</span>)&lt;/p&gt;
        &lt;p&gt;Is the difference(<span class="hljs-subst">${difference}</span>) in our map? No.&lt;/p&gt;
        &lt;p&gt;Add the current number <span class="hljs-subst">${testCaseArray[i]}</span> to our map.&lt;/p&gt;
      `</span>;
      tableBodyOutput.innerHTML += <span class="hljs-string">`
        &lt;tr&gt;
          &lt;td&gt;<span class="hljs-subst">${testCaseArray[i]}</span>&lt;/td&gt;
          &lt;td&gt;<span class="hljs-subst">${i}</span>&lt;/td&gt;
        &lt;/tr&gt;
      `</span>;
      map.set(testCaseArray[i], i);
    }
  }
};

bruteForceSolutionBtn.addEventListener(<span class="hljs-string">"click"</span>, bruteForceApproach);
optimalSolutionBtn.addEventListener(<span class="hljs-string">"click"</span>, optimalApproach);
</code></pre>
<p>Here is a <a target="_blank" href="https://codepen.io/Jessica-Wilkins-the-decoder/full/eYxVyKN">link</a> again to the final live result on CodePen.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope you enjoyed that project and learned a little bit more about how the Two Sum problem works. </p>
<p>I encourage you to play around with the project and maybe add some new features on your own like testing out different numbers or asking for user inputs for the numbers array and targets. 👍🏾</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ AWS Lambda Interview Questions and Answers ]]>
                </title>
                <description>
                    <![CDATA[ By Mugilan Ragupathi In this article, I'll go over some of the most commonly asked questions that come up in interviews about AWS Lambda.  Note that this is not an exhaustive list – but you can use this guide as a reference to refresh your knowledge ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/aws-lambda-interview-questions/</link>
                <guid isPermaLink="false">66d46040d7a4e35e3843498f</guid>
                
                    <category>
                        <![CDATA[ aws lambda ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 07 Dec 2022 20:54:49 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/12/AWS-Lambda-Interview-Questions.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Mugilan Ragupathi</p>
<p>In this article, I'll go over some of the most commonly asked questions that come up in interviews about AWS Lambda. </p>
<p>Note that this is not an exhaustive list – but you can use this guide as a reference to refresh your knowledge and get pointers for further study.</p>
<p>Most of the questions will be based on your experience or on certain scenarios. The questions are in the headings and you'll find the notes for the rationale behind asking the questions just below them.</p>
<h2 id="heading-explain-your-last-project-involving-aws-lambda">Explain your last project involving AWS Lambda</h2>
<p><em>The interviewer wants to know about your real-life experience using AWS Lambda. Don't bluff here, as the interviewer may ask further questions based on the answers to this question.</em> </p>
<p>You might have built a serverless API, systems involving microservices, image/video conversion, log analysis, and many more. Just explain your project in detail and tell about the business benefits of that project so that the interviewer knows you're seeing the big picture.</p>
<h2 id="heading-what-services-have-you-integrated-with-aws-lambda">What services have you integrated with AWS Lambda?</h2>
<p><em>This is an extension of the previous question. This is not a laundry list of all event sources that can connect to AWS Lambda. Only tell about the services that you've really used.</em> </p>
<p>You may have used S3, SNS, SQS, Kinesis, DynamoDB, SES, or others. Not all projects will be completely serverless. </p>
<p>If you've used any non-serverless component along with AWS Lambda, mention those too. For example, you might've used AWS Lambda with RDS. If you've used such a configuration,  you can explain about that along with your reasoning.</p>
<h2 id="heading-explain-the-concept-of-cold-and-warm-starts-in-aws-lambda">Explain the concept of cold and warm starts in AWS Lambda</h2>
<p><em>There are 2 reasons for asking this question. They want to know the runtimes that you've used, and they want to know if you know the other runtimes that could cause a cold start.</em></p>
<p>Lambda services receive a request to run a lambda function. The service prepares the execution environment by downloading the handler function code and by allocating memory along with other configuration. </p>
<p>Even though you're not billed for this <code>execution environment</code> preparation time, you'll have to face the delay in invoking your lambda function. This delay is called a "cold start".</p>
<p>The cold start timing is less significant for TypeScript and Python runtime environments, whereas it's a bit higher for Java or C# runtime environments.</p>
<p>To improve performance, the lambda service will keep the execution environment for some time. When you receive the request for the same lambda function again during this period, your handler can start executing immediately. This type of invocation is called a "<em>warm start</em>".</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/image-18.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://aws.amazon.com/blogs/compute/operating-lambda-performance-optimization-part-1/">Image source</a></em></p>
<h2 id="heading-whats-the-difference-between-synchronous-and-asynchronous-invocation-in-aws-lambda">What's the difference between synchronous and asynchronous invocation in AWS Lambda?</h2>
<p><em>Even though this seems to be straightforward question, this has many implications for your design and error handling.</em> </p>
<p>In synchronous invocation, the caller will wait for the execution to complete. But in asynchronous invocation, the caller will put the event in an internal queue which will later be processed in the lambda function.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/image-19.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html">Image source</a></em></p>
<p>An important point to note here is that you can't dictate the type of invocation and it depends on the service that you use with AWS Lambda.</p>
<p>For example, if you're building serverless APIs using API Gateway, it'll be a synchronous invocation. But if you're using S3, it'll be an asynchronous invocation.</p>
<h2 id="heading-how-do-you-implement-error-handling-and-retry-logic-in-lambda">How do you implement error handling and retry logic in Lambda?</h2>
<p><em>Any component in event driven system that may fail will fail. So interviewer wants to know how you've handled the error and how you retried in your previous projects. Below are some examples. Always explain with concrete examples.</em></p>
<p>This depends on the service that you're using with AWS Lambda. Let's discuss this with some examples.</p>
<p>If you're building a serverless API, it is better to return that error to the calling client (could be a front end app in this case). Then you let your front end logic decide what to display to the user based on the type of the error.</p>
<p>If you're using Lambda with SQS, it is better to use a Dead Letter Queue so that you know what messages have failed to process. For this same reason, many of the systems that use SNS may use SQS, too.</p>
<p>In the below code, we're using a dead letter queue. If any message fails to process after a certain number of times (as specified by <code>maxReceiveCount</code>), it's sent to the dead letter queue. This behaviour is specific to lambda when used along with queues.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> queue = <span class="hljs-keyword">new</span> sqs.Queue(<span class="hljs-built_in">this</span>, <span class="hljs-string">'AwsLambdaSqsQueue'</span>, {
      visibilityTimeout: cdk.Duration.seconds(<span class="hljs-number">300</span>),
      receiveMessageWaitTime: cdk.Duration.seconds(<span class="hljs-number">20</span>),
      deadLetterQueue: {
        queue: <span class="hljs-keyword">new</span> sqs.Queue(<span class="hljs-built_in">this</span>, <span class="hljs-string">'AwsLambdaDlq'</span>),
        maxReceiveCount: <span class="hljs-number">5</span>,
      },
    });
</code></pre>
<p>When lambda is invoked with any other services, you can configure the number of retries with a maximum value of 2. This means that you can have maximum of 2 retries apart from the initial invocation. For example, you want to trigger based on the S3 object upload and your lambda will try at most 3 times.</p>
<h2 id="heading-explain-your-workflows-for-development-and-deployment-of-aws-lambda-functions">Explain your workflows for development and deployment of AWS Lambda functions</h2>
<p><em>Talk about the frameworks that you've used. The interviewer may expect you to talk about testing lambda functions as well.</em> </p>
<p>You can explain which framework(s) you've used to develop and deploy lambda functions. You can also talk about any IaC (Infrastructure as Code) tool that you've used. </p>
<p>Below is non-exhaustive list of the most commonly used frameworks:</p>
<ul>
<li>Serverless</li>
<li>AWS CDK</li>
<li>AWS SAM</li>
<li>CloudFormation</li>
<li>Pulumi</li>
</ul>
<p>If you've used Terraform, you can talk about that as well.</p>
<h2 id="heading-can-lambda-be-invoked-when-you-get-an-email-to-a-particular-support-email-address-if-yes-design-that-system-if-not-explain-why">Can Lambda be invoked when you get an email to a particular support email address? If yes, design that system. If not, explain why.</h2>
<p>Yes, you can. You can create receipt rule set and add a rule which triggers the lambda function.</p>
<p>You should store the email to S3 and trigger the lambda after that so that you can have the copy of the email for any further reference.</p>
<p>You can refer to <a target="_blank" href="https://www.freecodecamp.org/news/how-to-receive-emails-via-your-sites-contact-us-form-with-aws-ses-lambda-api-gateway/">this article</a> on how to receive emails from a contact form.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/image-20.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.freecodecamp.org/news/how-to-receive-emails-via-your-sites-contact-us-form-with-aws-ses-lambda-api-gateway/">Image source</a></em></p>
<h2 id="heading-can-one-lambda-function-call-another-lambda-function">Can one lambda function call another lambda function?</h2>
<p><em>The interviewer wants to know whether you know this anti-pattern.</em></p>
<p>You can do this, but it is not recommended. If you want to design a workflow which involves multiple lambda functions, you can use step functions. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/image-21.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://aws.amazon.com/step-functions/">Image source</a></em></p>
<p>You can read more about step functions <a target="_blank" href="https://aws.amazon.com/step-functions/">here</a>.</p>
<p>Another standard approach is to emit an event and trigger a lambda based on the event. You can use SQS, SNS, or EventBridge as intermediary for these events.</p>
<h2 id="heading-can-you-execute-queries-on-an-rds-instance-in-a-private-subnet-using-lambda">Can you execute queries on an RDS instance (in a private subnet) using Lambda?</h2>
<p>Yes, you can execute the query in RDS using AWS Lambda. For that you can have your lambda inside the same VPC. </p>
<p>There may be some performance implications if you use AWS Lambda directly with RDS because of the database connection creation time. To avoid those, you can use an RDS Proxy.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/image-22.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.freecodecamp.org/news/aws-lambda-rds/">Image source</a></em></p>
<p>Here's a <a target="_blank" href="https://www.freecodecamp.org/news/aws-lambda-rds/">detailed step by step guide</a> that shows you how to do that.</p>
<h2 id="heading-aws-lambda-provides-many-benefits-what-are-the-cons-of-using-aws-lambda">AWS Lambda provides many benefits. What are the cons of using AWS Lambda?</h2>
<p><em>The interviewer wants to know about your thought process. Don't say AWS Lambda solves all the problems :-)</em> </p>
<p>Yeah, Lambda provides many benefits such as cost and scalability without any need to maintain the servers. But it's not the answer to everything – like any service, it has its own problems (and you should be able to discuss them):</p>
<ul>
<li>Debugging: If you're using serverless architectures using Lambda, you might have to rely on logging to find the root cause of the issue. This is because your application will be distributed across many services/ lambda functions. </li>
<li>Testing: You can mock AWS services in your local testing. But it is better to have a separate environment in AWS to test your lambdas. This makes testing a bit complex.</li>
<li>Background jobs: Lambda has a timeout limit of 15 minutes. If you want any particular task to take more than 15 minutes, you might have to move to Fargate or some other solution.</li>
<li>Cost: If you're running a high traffic application which processes the requests 24/7, using lambda can be expensive. It is better to use Fargate, EC2 or other services, if you have constant high traffic.</li>
</ul>
<h2 id="heading-how-do-you-manage-concurrency-and-scaling-in-aws-lambda">How do you manage concurrency and scaling in AWS Lambda?</h2>
<p><em>Bonus points if you talk about the issues that you've faced in these situations.</em></p>
<p>Concurrency is the ability to execute multiple lambda functions at the same time. Scaling is the process of increasing the number of copies of your lambda function to handle the incoming requests.</p>
<p>You can control concurrency by setting the value of <code>reserved concurrency</code> so that only the mentioned number of lambda functions will be invoked.</p>
<p>Below is the high level diagram of how lambda scales in accordance with number of messages in the queue.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/image-23.png" alt="AWS Lambda with SQS" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.cloudtechsimplified.com/aws-lambda-sqs/">Image source</a></em></p>
<p>Note: There is some <a target="_blank" href="https://www.cloudtechsimplified.com/aws-lambda-sqs/#weird-behavior">weird behavior</a> if you try to throttle AWS Lambda when used with SQS standard queue. You can use a FIFO queue to solve that issue.</p>
<h2 id="heading-how-do-you-pass-environment-variables-to-aws-lambda">How do you pass environment variables to AWS Lambda?</h2>
<p><em>The interviewer might want to know how you pass sensitive information, for example.</em></p>
<p>There are different ways to pass environment variables to AWS Lambda, and it depends on the type of value is getting passed.</p>
<p><strong>Non-sensitive data</strong>: If you want to pass any non-sensitive information, you can pass the values directly to your lambda function environment variables. But these values would be visible in the AWS console in the Lambda service.  </p>
<p>In the below code example, we're passing the name of the DynamoDB table directly as environment variable, as it is not sensitive data:</p>
<pre><code>   <span class="hljs-keyword">const</span> readDDBLambdaFn = <span class="hljs-keyword">new</span> NodejsFunction(<span class="hljs-built_in">this</span>, <span class="hljs-string">'readDDBLambdaFn'</span>, {
      <span class="hljs-attr">entry</span>: path.join(__dirname, <span class="hljs-string">'../src/lambdas'</span>, <span class="hljs-string">'read-ddb.ts'</span>),
      ...nodeJsFunctionProps,
      <span class="hljs-attr">functionName</span>: <span class="hljs-string">'readDDBLambdaFn'</span>,
      <span class="hljs-attr">environment</span>: {
        <span class="hljs-attr">tableName</span>: table.tableName,
      },
    });
</code></pre><p><strong>Sensitive data</strong>: If you want to pass sensitive data such as passwords and API keys, you can use either a Secret Manager or Parameter store. But, you need to make sure you provide necessary roles to Lambda for accessing and decrypting secrets from the respective services.</p>
<p>In the below code snippet, we're NOT passing the actual secret. Instead, we're just passing the ARN (Amazon Resource Name) of the secret.  </p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> rdsLambdaFn = <span class="hljs-keyword">new</span> NodejsFunction(<span class="hljs-built_in">this</span>, <span class="hljs-string">'rdsLambdaFn'</span>, {
      entry: path.join(__dirname, <span class="hljs-string">'../src/lambdas'</span>, <span class="hljs-string">'rds-lambda.ts'</span>),
      ...nodeJsFunctionProps,
      functionName: <span class="hljs-string">'rdsLambdaFn'</span>,
      environment: {
        DB_ENDPOINT_ADDRESS: dbInstance.dbInstanceEndpointAddress,
        DB_NAME: databaseName,
        DB_SECRET_ARN: dbInstance.secret?.secretFullArn || <span class="hljs-string">''</span>,
      },
      vpc,
      vpcSubnets: vpc.selectSubnets({
        subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
      }),
    });
</code></pre>
<p>Then, in lambda you can get the actual secret dynamically within the lambda function as shown below:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> handler = <span class="hljs-keyword">async</span> (event: <span class="hljs-built_in">any</span>, context: <span class="hljs-built_in">any</span>): <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-built_in">any</span>&gt; =&gt; {
    <span class="hljs-keyword">const</span> host = process.env.DB_ENDPOINT_ADDRESS || <span class="hljs-string">''</span>;
    <span class="hljs-keyword">const</span> database = process.env.DB_NAME || <span class="hljs-string">''</span>;
    <span class="hljs-keyword">const</span> dbSecretArn = process.env.DB_SECRET_ARN || <span class="hljs-string">''</span>;
    <span class="hljs-keyword">const</span> secretManager = <span class="hljs-keyword">new</span> AWS.SecretsManager({
      region: <span class="hljs-string">'us-east-1'</span>,
    });
    <span class="hljs-keyword">const</span> secretParams: AWS.SecretsManager.GetSecretValueRequest = {
      SecretId: dbSecretArn,
    };
    <span class="hljs-keyword">const</span> dbSecret = <span class="hljs-keyword">await</span> secretManager.getSecretValue(secretParams).promise();
    <span class="hljs-keyword">const</span> secretString = dbSecret.SecretString || <span class="hljs-string">''</span>;

    <span class="hljs-keyword">const</span> { password } = <span class="hljs-built_in">JSON</span>.parse(secretString);

}
</code></pre>
<p>I've written a detailed tutorial <a target="_blank" href="https://www.cloudtechsimplified.com/environment-variables-secrets-database-password-aws-lambda/">here</a> on the same topic.</p>
<h2 id="heading-say-you-have-a-windows-dependent-executable-sometoolexe-you-can-upload-it-into-an-s3-bucket-can-you-execute-this-binary-with-some-parameters-using-aws-lambda">Say you have a Windows-dependent executable sometool.exe. You can upload it into an S3 bucket. Can you execute this binary with some parameters using AWS Lambda?</h2>
<p><em>This is more of a question to make sure you understand the AWS Lambda execution environment – specifically the operating system it uses.</em></p>
<p>No, you would not be able to do that as AWS Lambda uses Linux as its operating system. Linux would not be able to execute a Windows-dependent binary.</p>
<h2 id="heading-how-do-you-re-use-code-across-aws-lambda-functions">How do you re-use code across AWS Lambda functions?</h2>
<p>There are 2 ways to re-use code across many AWS Lambda functions:</p>
<ul>
<li>Use Lambda Layers: You can store your code or logic in lambda layers, which you can re-use across different lambda functions. </li>
</ul>
<p>Below is some high level code for creating and consuming lambda layers using <code>aws cdk</code>:</p>
<pre><code>    <span class="hljs-keyword">const</span> logicLayer = <span class="hljs-keyword">new</span> lambda.LayerVersion(<span class="hljs-built_in">this</span>, <span class="hljs-string">'logic-layer'</span>, {
      <span class="hljs-attr">compatibleRuntimes</span>: [
        lambda.Runtime.NODEJS_14_X,
        lambda.Runtime.NODEJS_16_X,
      ],
      <span class="hljs-attr">layerVersionName</span>: <span class="hljs-string">'business-logic-layer'</span>,
      <span class="hljs-attr">code</span>: lambda.Code.fromAsset(<span class="hljs-string">'src/layers/business-logic'</span>),
      <span class="hljs-attr">description</span>: <span class="hljs-string">'Business logic layer'</span>,
    });


    <span class="hljs-keyword">const</span> lambdaWithLayer = <span class="hljs-keyword">new</span> NodejsFunction(<span class="hljs-built_in">this</span>, <span class="hljs-string">'lambdaWithLayer'</span>, {
      <span class="hljs-attr">entry</span>: path.join(__dirname, <span class="hljs-string">'../src/lambdas'</span>, <span class="hljs-string">'lambda.ts'</span>),
      ...nodeJsFnProps,
      <span class="hljs-attr">functionName</span>: <span class="hljs-string">'lambdaWithLayer'</span>,
      <span class="hljs-attr">handler</span>: <span class="hljs-string">'handler'</span>,
      <span class="hljs-attr">layers</span>: [logicLayer, utilsLayer],
    });
</code></pre><ul>
<li>Use <code>monorepo</code>: You can use mono repo and dynamically build packages at deploy time.</li>
</ul>
<h2 id="heading-what-happens-to-your-lambda-functions-if-you-delete-a-lambda-layer">What happens to your lambda functions if you delete a Lambda Layer?</h2>
<p><em>In this question, the interviewer wants to see how well you understand lambda layers.</em> </p>
<p>Existing lambda functions which use that deleted layer will continue to work – as lambda layers are merged with lambda functions at deployment time. </p>
<p>But you can't create a new lambda function using that deleted lambda layer.</p>
<p>You can learn more about Lambda layers <a target="_blank" href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">here</a> and I've written a guide on the same topic <a target="_blank" href="https://www.cloudtechsimplified.com/aws-lambda-layers/">here</a>.</p>
<h2 id="heading-can-you-increase-the-size-of-a-deployment-package-if-you-use-lambda-layers">Can you increase the size of a deployment package if you use Lambda Layers?</h2>
<p>No, you can't increase the size of the deployment package if you use Lambda Layers. The maximum deployment size of 50 MB zipped includes both the size of the lambda function and its associated lambda layers.</p>
<p>If you have a large codebase and want to increase the deployment, you can run containers in AWS Lambda.</p>
<h2 id="heading-can-i-take-my-existing-dockerized-web-application-and-run-it-using-lambda">Can I take my existing dockerized web application and run it using Lambda?</h2>
<p>Nope. You can't take any Express, Springboot, or .NET Core application (or any other application for that matter) as they are and put them inside lambda. </p>
<p>But that being said, there are a few libraries which allow you to put applications that use these web frameworks into AWS Lambda. Internally, those libraries convert those web applications into AWS lambda-compatible APIs. You can see one such example <a target="_blank" href="https://aws.amazon.com/blogs/aws/running-express-applications-on-aws-lambda-and-amazon-api-gateway/">here</a>.</p>
<p>By using these frameworks, the size of your lambda functions will be bigger and will result in longer start up times.</p>
<p>Remember that even when using containers with Lambda, the existing runtime API of Lambda remains the same. Lambda will still:</p>
<ul>
<li>be a single function </li>
<li>be invoked by an event or manually</li>
<li>have a timeout of 15 minutes.</li>
</ul>
<p>As you can see in the below code, there will be no change to the lambda API. The advantage of using Docker is that you would be able to use large packages without worrying about size.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { Context, APIGatewayProxyResult, APIGatewayEvent } <span class="hljs-keyword">from</span> <span class="hljs-string">'aws-lambda'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> handler = <span class="hljs-keyword">async</span> (
  event: APIGatewayEvent,
  context: Context
): <span class="hljs-built_in">Promise</span>&lt;APIGatewayProxyResult&gt; =&gt; {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Event: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(event, <span class="hljs-literal">null</span>, <span class="hljs-number">2</span>)}</span>`</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Context: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(context, <span class="hljs-literal">null</span>, <span class="hljs-number">2</span>)}</span>`</span>);
  <span class="hljs-keyword">return</span> {
    statusCode: <span class="hljs-number">200</span>,
    body: <span class="hljs-built_in">JSON</span>.stringify({
      message: <span class="hljs-string">'Running this handler from docker'</span>,
    }),
  };
};
</code></pre>
<p>And, this is how you use it:</p>
<pre><code> <span class="hljs-keyword">const</span> repo = ecr.Repository.fromRepositoryName(
      <span class="hljs-built_in">this</span>,
      <span class="hljs-string">'dockerLambda'</span>,
      <span class="hljs-string">'docker-lambda'</span>
    );

    <span class="hljs-keyword">const</span> dockerLambda = <span class="hljs-keyword">new</span> lambda.DockerImageFunction(
      <span class="hljs-built_in">this</span>,
      <span class="hljs-string">'DockerLambdaFunction'</span>,
      {
        <span class="hljs-attr">code</span>: lambda.DockerImageCode.fromEcr(repo),
      }
    );
</code></pre><p>I wrote a step-by-step tutorial on running Docker containers for your application in <code>aws lambda</code> <a target="_blank" href="https://www.cloudtechsimplified.com/run-docker-containers-images-from-ecr-in-aws-lambda-along-with-cicd/">here</a>.</p>
<h2 id="heading-how-do-you-share-large-files-between-lambda-functions">How do you share large files between lambda functions?</h2>
<p>You can use the Elastic File System (EFS) to share large files between different functions.  </p>
<p>You can create an <code>access point</code> in the created EFS with the appropriate permissions and use that <code>access point</code> in your <code>mount path</code> in your lambda. </p>
<p>Any files written on that mount path will be accessible to all other lambda functions provided they have the mount path with appropriate permissions.</p>
<p>Below is the high level logical diagram on how to use AWS Lambda with Elastic File System (EFS):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/image-24.png" alt="Using EFS with Lambda" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.cloudtechsimplified.com/elastic-file-system-efs-aws-lambda/">Image source</a></em></p>
<p>You can read about this <a target="_blank" href="https://aws.amazon.com/blogs/compute/using-amazon-efs-for-aws-lambda-in-your-serverless-applications/">here</a> (bit old). I wrote a more recent practical step-by-step guide <a target="_blank" href="https://www.cloudtechsimplified.com/elastic-file-system-efs-aws-lambda/">here</a> on EFS with Lambda functions.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>I hope this article helped you to prepare for interviews involving AWS Lambda.</p>
<p>Thanks for reading to this point. I write about <code>aws</code> and serverless technologies at <a target="_blank" href="https://www.cloudtechsimplified.com/">https://www.cloudtechsimplified.com</a>. If you're interested, you can <a target="_blank" href="https://www.cloudtechsimplified.com/">subscribe</a> to my blog.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Prepare for React Interviews – Front-End Technical Interview Guide ]]>
                </title>
                <description>
                    <![CDATA[ By Manu Arora A front-end technical interview is an opportunity for a potential employer to assess your skills and knowledge in web development.   The interviewer will ask you questions about your experience and skills in HTML, CSS, and JavaScript. T... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/prepare-for-react-technical-interviews/</link>
                <guid isPermaLink="false">66d46021787a2a3b05af43dc</guid>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interviewing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 08 Sep 2022 00:29:16 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/08/Build-a-React-Code-Editor-That-Compiles-and-Executes-in-10--Languages--2-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Manu Arora</p>
<p>A front-end technical interview is an opportunity for a potential employer to assess your skills and knowledge in web development.  </p>
<p>The interviewer will ask you questions about your experience and skills in HTML, CSS, and JavaScript. They'll also likely ask you some framework specific questions about React, Angular, Vue, or whatever framework they use.  </p>
<p>They may also give you a coding challenge to test your abilities in a particular domain.  </p>
<p>Today, we are going to look at the most common problems asked in a front-end technical interview round, focusing on React and JavaScript.</p>
<h2 id="heading-what-interviewers-are-looking-for">What Interviewers Are Looking For</h2>
<p>When interviewing for a front-end web development position, be prepared to discuss your skills and experience with various programming languages, tools, and frameworks.  </p>
<p>Interviewers will also want to see that you have a strong understanding of the latest trends and technologies in web development.  </p>
<p>Be prepared to talk about your past projects and how you approached solving various challenges.  </p>
<p>Be sure to showcase your problem-solving skills by discussing how you tackled various challenges during your development process.  </p>
<p>Finally, don’t forget to highlight your strengths.</p>
<h2 id="heading-most-commonly-asked-questions-in-a-front-end-technical-interview">Most Commonly Asked Questions in a Front-End Technical Interview</h2>
<p>Front-end technical interview problems are pretty straightforward and common. If you have been actively coding for at least 6 months, you will be familiar with most of the concepts that are asked about.</p>
<p>Once you practice the right questions with a time based approach, you should be able to clear the interviews.</p>
<p>Let's look at the most common questions asked.</p>
<h2 id="heading-map-foreach-filter-and-reduce">Map, ForEach, Filter and Reduce</h2>
<p>The most commonly asked questions (generally at the start of the interviews) are about <code>array methods</code>. The interviewer wants to asses how comfortable you are with array manipulation.</p>
<h4 id="heading-the-map-method">The <code>.map()</code> method</h4>
<p>The <code>.map()</code> methods iterates over an array, computes whatever logic you write inside the map body, and returns a <strong>NEW</strong> array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">12</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Manu'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">24</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Quincy'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">22</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Abbey'</span> },
]

<span class="hljs-keyword">let</span> names = arr.map(<span class="hljs-function">(<span class="hljs-params">el</span>) =&gt;</span> el.name)
<span class="hljs-built_in">console</span>.log(names)
<span class="hljs-comment">// Output: [ 'Manu', 'Quincy', 'Abbey' ]</span>
</code></pre>
<h4 id="heading-the-foreach-method">The <code>.forEach()</code> method</h4>
<p>ForEach is similar to <code>.map()</code> but it DOES NOT return an array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">12</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Manu'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">24</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Quincy'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">22</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Abbey'</span> },
]

arr.forEach(<span class="hljs-function">(<span class="hljs-params">el</span>) =&gt;</span> el.age+= <span class="hljs-number">10</span>);
<span class="hljs-built_in">console</span>.log(arr);

<span class="hljs-comment">// Output: 22 32 44</span>
</code></pre>
<h4 id="heading-the-filter-method">The <code>.filter()</code> method</h4>
<p>The filter method, as the name suggests, helps in filtering out the values inside of an array based on a Boolean condition. </p>
<p>If the boolean condition is true, the result will be returned and added in the final array. If not, it will be skipped. Filter also returns an array, just like the <code>.map()</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">12</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Manu'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">24</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Quincy'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">22</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Abbey'</span> },
]

<span class="hljs-keyword">let</span> tooYoung = arr.filter(<span class="hljs-function">(<span class="hljs-params">el</span>) =&gt;</span> el.age &lt;= <span class="hljs-number">14</span>);
<span class="hljs-built_in">console</span>.log(tooYoung);

<span class="hljs-comment">// Output: [ { id: 1, age: 12, name: 'Manu' } ]</span>
</code></pre>
<h4 id="heading-the-reduce-method">The <code>.reduce()</code> method</h4>
<p>In simple terms, the <code>.reduce()</code> method takes into account a <code>previous value</code> , current value and an <code>accumulator</code>. </p>
<p>The return type of the <code>.reduce()</code> method is always a single value. It is useful when you want to process all the values of the array and want to derive some accumulated result.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Calculates the total age of all the three persons.</span>
<span class="hljs-keyword">let</span> arr = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">12</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Manu'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">24</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Quincy'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">22</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Abbey'</span> },
]

<span class="hljs-keyword">let</span> totalAge = arr.reduce(<span class="hljs-function">(<span class="hljs-params">acc, currentObj</span>) =&gt;</span> acc + currentObj.age, <span class="hljs-number">0</span>)
<span class="hljs-built_in">console</span>.log(totalAge)

<span class="hljs-comment">// Output: 57</span>
</code></pre>
<p>Here, the <code>currentObj</code> is the object that is being iterated over. Also, the <code>acc</code> value stores the result and is outputted finally into the totalAge array.</p>
<h2 id="heading-how-to-implement-polyfills">How to Implement Polyfills</h2>
<p>Another important interview question is <a target="_blank" href="https://www.algochurn.com/frontend/polyfills">How to implement polyfills</a> of the map and filter array methods.</p>
<p>A polyfill is a code snippet (in terms of JavaScript web architecture) used for modern world functionalities on older browsers that do not implement it natively.</p>
<p>Simply put, a polyfill is a custom implementation of native JavaScript functions. Sort of a create your own <code>.map()</code> or <code>.filter()</code> method.</p>
<h4 id="heading-how-to-use-the-map-polyfill">How to use the <code>.map()</code> polyfill</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> data = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-built_in">Array</span>.prototype.myMap = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">cb</span>) </span>{
  <span class="hljs-keyword">let</span> arr = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.length; i++) {
    arr.push(cb(<span class="hljs-built_in">this</span>[i], i, <span class="hljs-built_in">this</span>));
  }
  <span class="hljs-keyword">return</span> arr;
};
<span class="hljs-keyword">const</span> mapLog = data.myMap(<span class="hljs-function">(<span class="hljs-params">el</span>) =&gt;</span> el * <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(mapLog);
</code></pre>
<p>the <code>myMap</code> method takes in a <code>callback</code> that gets executed inside the <code>myMap</code> body. We basically have a native <code>for</code> loop inside the myMap body, which iterates over the <code>this.length</code>. This is nothing but the length of the array through which the <code>myMap</code> function is called.</p>
<p>Since the syntax of <code>map()</code> is <code>arr.map(currentElement, index, array)</code>, and the <code>myMap()</code> function takes into account exactly that.</p>
<p>Also since <code>map()</code> returns a new array, we create an empty array and push the results into it. In the end we return it.</p>
<h4 id="heading-how-to-use-the-filter-polyfill">How to use the <code>.filter()</code> polyfill</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> data = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-built_in">Array</span>.prototype.myFilter = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">cb</span>) </span>{
  <span class="hljs-keyword">let</span> arr = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.length; i++) {
    <span class="hljs-keyword">if</span> (cb(<span class="hljs-built_in">this</span>[i], i, <span class="hljs-built_in">this</span>)) {
      arr.push(<span class="hljs-built_in">this</span>[i]);
    }
  }
  <span class="hljs-keyword">return</span> arr;
};
<span class="hljs-keyword">const</span> filterLog = data.myFilter(<span class="hljs-function">(<span class="hljs-params">el</span>) =&gt;</span> el &lt; <span class="hljs-number">4</span>);
<span class="hljs-built_in">console</span>.log(filterLog);
</code></pre>
<p><code>.filter()</code> is very similar to <code>.map()</code> in terms of implementation. But since <code>filter</code> filters out the results based on a boolean value, we have an additional <code>if()</code> condition to filter out results and conditionally push inside the array.</p>
<h2 id="heading-what-is-debouncing">What is Debouncing?</h2>
<p>This is a famous interview question with a lot of practical real world usage and implementations.</p>
<p><code>Debouncing</code> is a method of preventing a function from being invoked too often, and instead waiting a certain amount of time until it was last called before invoking it.  </p>
<p>Think of Amazon in this case. Whenever you type anything in the search bar, when you stop for AT LEAST 0.5 seconds, then the results are fetched. This is exactly what debouncing is.</p>
<p>In order to implement debouncing, let's take an example: Generating a username for a user based on the user input.</p>
<div class="embed-wrapper"><iframe src="https://codesandbox.io/embed/proud-surf-uiu2v?fontsize=14&amp;hidenavigation=1&amp;theme=dark" style="width:100%;height:500px;border:0;border-radius:4px;overflow:hidden" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" title="Embedded content" loading="lazy"></iframe></div>

<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">"./styles.css"</span>;
<span class="hljs-keyword">let</span> inputEle = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"inputElement"</span>);
<span class="hljs-keyword">let</span> username = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"username"</span>);

<span class="hljs-keyword">let</span> generateUsername = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  username.innerHTML = e.target.value.split(<span class="hljs-string">" "</span>).join(<span class="hljs-string">"-"</span>);
};
<span class="hljs-keyword">let</span> debounce = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">cb, delay</span>) </span>{
  <span class="hljs-keyword">let</span> timer;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> context = <span class="hljs-built_in">this</span>;
    <span class="hljs-built_in">clearTimeout</span>(timer);
    timer = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      cb.apply(context, <span class="hljs-built_in">arguments</span>);
    }, delay);
  };
};

inputEle.addEventListener(<span class="hljs-string">"keyup"</span>, debounce(generateUsername, <span class="hljs-number">300</span>));
</code></pre>
<p>Here, we are trying to create a custom username based on the user input. Now if the user starts typing, we don't want to immediately create it, but actually wait for 300 milliseconds before creating the username. We are trying to mimic an API call here, so assume the user types anything and it has to make an API call to the backend and fetch a response.</p>
<p>The <code>debounce()</code> function takes in two values, <code>cb</code> and <code>delay</code> . <code>cb</code> is the callback function that gets executed when the timer runs out.  </p>
<p>We use <code>setTimeout()</code> to create a timeout timer, which means the function inside the setTimeout body will be executed after a certain amount of time.</p>
<p>The <code>apply</code> method is used to call the callback function with the <code>object</code> that it was initially called with, applying the arguments and context to it.</p>
<h2 id="heading-what-are-closures">What are Closures?</h2>
<p>According to the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">mdn docs for closures</a>,</p>
<blockquote>
<p>A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.</p>
</blockquote>
<p>To simplify this, let's take an example and understand how closures work.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">start</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> name = <span class="hljs-string">"Manu"</span>; <span class="hljs-comment">// name is a local variable created by start()</span>
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayName</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// displayName() is the inner function, a `closure`</span>
    alert(name); <span class="hljs-comment">// use variable declared in the parent function</span>
  }
  displayName();
}
start(); <span class="hljs-comment">// "Manu" alert box is displayed</span>
</code></pre>
<p>Here, a closure is formed between the <code>start()</code> and the <code>displayName()</code> function. The <code>displayName()</code> function has access to the <code>name</code> variable present in the <code>start()</code> function.</p>
<p>In simple terms, the inner function will know its surroundings (the lexical environment).</p>
<p>I have written a whole blog on <a target="_blank" href="https://manuarora.in/blog/ace-the-javascript-interview#closures">how to clear JavaScript interviews</a>. Have a look at that if you want to know more about in depth JavaScript interview process.</p>
<h2 id="heading-react-hooks">React Hooks</h2>
<p>The most popular questions asked in a front-end coding interview when it comes to React hooks are:</p>
<ol>
<li><code>useState()</code></li>
<li><code>useReducer()</code></li>
<li><code>useEffect()</code></li>
<li><code>useRef()</code></li>
<li>Custom Hooks and their implementation.</li>
</ol>
<h3 id="heading-how-the-usestate-hook-works">How the <code>useState()</code> hook works</h3>
<p>To manage a state inside of your component, the <code>useState()</code> hook is your go-to hook.  </p>
<p>Let's take an example and understand:</p>
<div class="embed-wrapper"><iframe src="https://codesandbox.io/embed/thirsty-lewin-uo8ylh?fontsize=14&amp;hidenavigation=1&amp;theme=dark" style="width:100%;height:500px;border:0;border-radius:4px;overflow:hidden" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" title="Embedded content" loading="lazy"></iframe></div>

<pre><code class="lang-javscript">import { useState } from "react";
import "./styles.css";

export default function App() {
  const [title, setTitle] = useState("freeCodeCamp");
  const handleChange = () =&gt; {
    setTitle("FCC");
  };
  return (
    &lt;div className="App"&gt;
      &lt;h1&gt;{title} useState&lt;/h1&gt;
      &lt;button onClick={handleChange}&gt;Change Title&lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>The <code>useState()</code> methods gives us two values, the <code>state</code> variable and <code>a function to change</code> that state variable.</p>
<p>In the above code snippet, we are creating a <code>title</code> state to store the title of the page. The initial state is passed as <code>freeCodeCamp</code>.</p>
<p>On button click, we can use the <code>setTitle()</code> method to change the state variable to <code>FCC</code>.</p>
<p><code>useState()</code> method is your go-to resource for state management in a functional component.</p>
<h3 id="heading-how-the-usereducer-hook-works">How the <code>useReducer()</code> hook works</h3>
<p>In simple terms, <code>useReducer()</code> is the cool way of managing state in your application. It is more structured and helps you maintain complex state in your application.</p>
<p>Let's take an example to understand the useReducer hook:</p>
<div class="embed-wrapper"><iframe src="https://codesandbox.io/embed/ecstatic-marco-o8wh00?fontsize=14&amp;hidenavigation=1&amp;theme=dark" style="width:100%;height:500px;border:0;border-radius:4px;overflow:hidden" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" title="Embedded content" loading="lazy"></iframe></div>

<pre><code class="lang-javscript">import "./styles.css";
import { useReducer } from "react";

const initialState = { title: "freeCodeCamp", count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case "change-title":
      return { ...state, title: "FCC" };
    case "increment-counter":
      return { ...state, count: state.count + 1 };
    default:
      throw new Error();
  }
}

export default function App() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    &lt;&gt;
      &lt;div className="App"&gt;
        &lt;h1&gt;{state.title} CodeSandbox&lt;/h1&gt;
        &lt;button onClick={() =&gt; dispatch({ type: "change-title" })}&gt;
          Change Title
        &lt;/button&gt;
        &lt;button onClick={() =&gt; dispatch({ type: "increment-counter" })}&gt;
          Increment Counter
        &lt;/button&gt;
      &lt;/div&gt;
      &lt;p style={{ textAlign: "center" }}&gt;{state.count}&lt;/p&gt;.
    &lt;/&gt;
  );
}
</code></pre>
<p>The <code>useReducer()</code> hook takes two parameters, the <code>reducer</code> function and an <code>initialState</code> value.  </p>
<p>The reducer function is a <code>switch-case</code> based implementation that returns the final state value that <code>useReduer()</code> internally uses to supply back to the component.</p>
<p>The values returned from the <code>useReducer()</code> function are <code>state</code> and <code>dispatch</code>. The <code>state</code> is the actual <code>state</code> value that can be used inside of the component. In our case, the state has two values: <code>title and count</code>. This title and count can be manipulated using the <code>dispatch()</code> method which is returned by the <code>useReducer()</code> method.</p>
<p>In the above case, to change the title, we have written a case of <code>change-title</code> inside the reducer function. This can be triggered with the help of the <code>dispatch({ type: "change-title" })</code> function. This will trigger the change title function and it will change the state of the <code>title</code> attribute.  </p>
<p>Similarly, the same happens for the <code>count</code> part that is there in the application.  </p>
<p>Like I said earlier, it is a cool way of implementing state inside your application. 😉</p>
<h3 id="heading-how-the-useeffect-hook-works">How the <code>useEffect()</code> hook works</h3>
<p>Think of it this way: if you want to have a <code>side effect</code> to a state variable that changes, you can use the <code>useEffect()</code> hook to trigger it.  </p>
<p>For example, let's say if the <code>input value</code> of your input box changes, and you want to call an API after it has changed. You can write the logic of the <code>API handle</code> in the <code>useEffect()</code> block.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, {useState, useEffect} <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> [value, setValue] = useState(<span class="hljs-string">''</span>);
    useEffect(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'value changed: '</span>, value);
    }, [value])
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setValue(e.target.value)} /&gt;
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
}
</code></pre>
<p>Here, we have an <code>input box</code> that has a state value of <code>value</code> attached to it. This value will change when the user tries to input anything.  </p>
<p>Once the value has been updated and has been rendered, the <code>useEffect()</code> block will kick in and the <code>console</code> statement will be triggered, outputting the latest state value which is there.  </p>
<p>Here, one good use case of the <code>useEffect()</code> can be to implement <code>API calls</code>. Let's assume you want to call an API with the input field value. The useEffect function block will be the best way to do it.</p>
<p>Another part of this is the <code>dependency array</code> which is the second argument to the <code>useEffect()</code> hook. In our case, we mentioned <code>[value]</code> as the second argument.</p>
<p>This basically means that EVERY TIME THE <code>value</code> CHANGES, the function inside the useEffect gets triggered. If you don't pass anything in the <code>dependency array</code>, the function block gets triggered once.</p>
<h3 id="heading-how-the-useref-hook-works">How the <code>useRef()</code> hook works</h3>
<p>The useRef hook gives us the ability to mutate the DOM (but this is not the only implication of useRef).</p>
<p>According to the docs:</p>
<blockquote>
<p>useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.</p>
</blockquote>
<p>In simple terms, we are going to useRef if we want to persist the value of something for the entire component lifecycle. The basic implementation of useRef comes with DOM elements. Let's take an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TextInputWithFocusButton</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> inputEl = useRef(<span class="hljs-literal">null</span>);
  <span class="hljs-keyword">const</span> onButtonClick = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// `current` points to the mounted text input element</span>
    inputEl.current.focus();
  };
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputEl}</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onButtonClick}</span>&gt;</span>Focus the input<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre>
<p>Here, we are assigning a <code>ref</code> property to the <code>input</code> block. This will be associated with the <code>inputEl</code> reference that we created.</p>
<p>Now this <code>input</code> element can be manipulated however we want. We can modify the <code>style</code> attribute and make it beautiful, we can take the <code>value</code> property to see what is being help by the input element as the value, and so on.</p>
<p>In the above example, when we click the button, the <code>input</code> is focused and we can immediately start typing. We can do this with the help of <code>inputEl.current.focus()</code> – essentially the <code>focus()</code> method present on the <code>current</code> object.</p>
<h3 id="heading-what-are-custom-hooks">What are custom hooks?</h3>
<p>One of the most commonly asked questions that I've seen in front-end interview rounds is to <a target="_blank" href="https://www.algochurn.com/frontend/usekeypress-custom-hook">create a custom hook for keyboard events</a>.</p>
<p>We saw many different hooks, but the interviewer might ask you to create a hook of your own. This might be challenging for some but with some practice, it becomes much easier.</p>
<p>Let's understand what a <code>Hook</code> is:</p>
<p>The basic usage of a custom hook is to extract a function's logic into its own component.</p>
<p>Imaging what will happen if you have to <code>listen for an enter press</code> inside of each of your components. Instead of writing the logic for <code>listening</code> again and again, we can extract the logic into a component of its own and use it wherever we want (just like we use <code>useState()</code> or <code>useEffect()</code>).</p>
<p>There are a few conditions for a function to be called a <code>Hook</code>:</p>
<ol>
<li>It should always start with the <code>use</code> keyword.</li>
<li>We can decide what it takes as arguments, and what, if anything, it should return.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-comment">// Custom Hook: useAvailable</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useAvailabe</span>(<span class="hljs-params">resource</span>) </span>{
  <span class="hljs-keyword">const</span> [isAvailable, setIsAvailable] = useState(<span class="hljs-literal">null</span>);

  <span class="hljs-comment">// ...</span>

  <span class="hljs-keyword">return</span> isAvailable;
}

<span class="hljs-comment">// Usage:</span>
  <span class="hljs-keyword">const</span> isAvailable = useAvailable(cpu);
</code></pre>
<p>Here, no matter how many times we call <code>useState</code> and <code>useEffects</code> inside the custom hook, they will be completely independent from the function where we use the custom hook.  </p>
<p>Let's take an example of creating a custom hook for <code>storing local storage values</code>.</p>
<h3 id="heading-how-to-create-a-custom-hook-uselocalstorage-example">How to create a custom hook – useLocalStorage example</h3>
<p>The useLocalStorage custom hook is a way to persist data into the local storage. Get and set values inside the local storage using <code>key</code> and <code>value</code> pairs so that whenever the user comes back to your web app, they see the same result they used earlier.</p>
<p>The below implementation is of a simple <code>select</code> tag value that, once changed, persists the data into local storage.</p>
<p><code>useLocalStorage.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Use Local Storage Custom Hook</span>
<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useLocalStorage</span>(<span class="hljs-params">key, initialValue</span>) </span>{
  <span class="hljs-keyword">const</span> [storedValue, setStoredValue] = useState(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">window</span> === <span class="hljs-string">'undefined'</span>) {
      <span class="hljs-keyword">return</span> initialValue;
    }
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> item = <span class="hljs-built_in">window</span>.localStorage.getItem(key);
      <span class="hljs-keyword">return</span> item ? <span class="hljs-built_in">JSON</span>.parse(item) : initialValue;
    } <span class="hljs-keyword">catch</span> (error) {
      <span class="hljs-built_in">console</span>.log(error);
      <span class="hljs-keyword">return</span> initialValue;
    }
  });
  <span class="hljs-keyword">const</span> setValue = <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> valueToStore =
        value <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Function</span> ? value(storedValue) : value;
      setStoredValue(valueToStore);
      <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">window</span> !== <span class="hljs-string">'undefined'</span>) {
        <span class="hljs-built_in">window</span>.localStorage.setItem(key, <span class="hljs-built_in">JSON</span>.stringify(valueToStore));
      }
    } <span class="hljs-keyword">catch</span> (error) {
      <span class="hljs-built_in">console</span>.log(error);
    }
  };
  <span class="hljs-keyword">return</span> [storedValue, setValue] <span class="hljs-keyword">as</span> <span class="hljs-keyword">const</span>;
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> useLocalStorage;
</code></pre>
<p><code>App.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./style.css'</span>;
<span class="hljs-keyword">import</span> useLocalStorage <span class="hljs-keyword">from</span> <span class="hljs-string">'./useLocalStorate'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [storedValue, setStoredValue] = useLocalStorage(
    <span class="hljs-string">'select-value'</span>,
    <span class="hljs-string">'light'</span>
  );

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">select</span>
        <span class="hljs-attr">className</span>=<span class="hljs-string">"select"</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{storedValue}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setStoredValue(e.target.value)}
      &gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"dark"</span>&gt;</span>Dark<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"light"</span>&gt;</span>Light<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"desc"</span>&gt;</span>
        Value from local storage: <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>{storedValue}<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Here, the <code>useLocalStorage</code> hook takes in two parameters, the <code>local storage key name</code> to store, and a <code>default</code> value that has to be there.</p>
<p>The hook returns two values: the <code>local storage value</code> of the key that you're using and a way to <code>change that key value</code> by giving us a <code>setter method</code>. In this case, the <code>setStoredValue</code> method.</p>
<p>In the <code>useLocalStorage.js</code> file, we are trying to first <code>GET</code> the local storage value with that key using <code>localStorage.getItem()</code> method. If that exists, we are setting the value. If found, we <code>JSON.parse()</code> the value and return it. Otherwise, initialValue which was provided is set as the default value.  </p>
<p>The <code>setLocalStorage()</code> function takes into account whether the passed value is a function or a simple variable value. Also it takes care of setting the value of local storage using <code>localStorage.setItem()</code> function.</p>
<h2 id="heading-how-to-stand-out-as-a-developer-by-creating-side-projects">How to Stand Out as a Developer by Creating Side Projects</h2>
<p>The thing that has always worked for me and helped me stand out is my side projects that I've built.  </p>
<p>In my opinion, you don't have to build 10 basic cookie cutter side projects. Instead, try building one or two really good projects where you get to implement all the concepts of React/HTML/CSS/JavaScript and everything that you've been learning.  </p>
<p>Assume the interviewer has 14 interviews in a week and has to review the résumés of 14 candidates. They'll be more likely interested in your profile because you have created a <code>link shortener website that charges $1 after every 1000 link visits</code> instead of an Amazon / Netflix clone.</p>
<p>Again, there's nothing wrong with creating clones and practicing your skills. But it's always good to have at least 1 unique project that helps you stand out from the crowd.  </p>
<p>Also, creating side projects will help you upskill as a developer. It is not likely possible to know everything beforehand when creating a project from scratch. Along the way, you'll have to learn many different skills and get good at that.</p>
<h2 id="heading-practice-practice-practice">Practice, Practice, Practice.</h2>
<p>There's a famous saying that goes like this:</p>
<div class="embed-wrapper">
        <blockquote class="twitter-tweet">
          <a href="https://twitter.com/mannupaaji/status/1566350128767987712"></a>
        </blockquote>
        <script defer="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></div>
<p>and this is true to a great extent. </p>
<p>I myself have failed 100s of times before landing my first job. It's the constant feedback and iterations that you have to make in order to get what you want.  </p>
<p>In our case, getting a front-end job becomes easy when:</p>
<ul>
<li>You have in depth knowledge of your skills – React in this case (along with HTML, CSS, and JS).</li>
<li>You have a set of projects to showcase, making you stand out.</li>
<li>You're willing to put in the time and the effort to learn more and challenge yourself.</li>
<li>You read the freeCodeCamp blog regularly and practice questions there (😉)</li>
</ul>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>There are a lot of questions to practice for a machine-coding round. The interviewer can ask different sets of questions to test your skills.  </p>
<p>You can use <a target="_blank" href="https://algochurn.com"><strong>Algochurn</strong></a> to practice the most popular <a target="_blank" href="https://www.algochurn.com/blog/top-5-react-front-end-questions-to-practice-before-a-technical-interview-round">JavaScript interview questions</a>, <a target="_blank" href="https://algochurn.com/frontend">React Interview Questions</a>, and <a target="_blank" href="https://algochurn.com/problems">algorithmic questions</a> asked in a front-end technical interview round along with their solutions and approaches.</p>
<p>If you have any questions, please reach out to me via <a target="_blank" href="https://twitter.com/mannupaaji">Twitter(@mannupaaji)</a> and/or my <a target="_blank" href="https://manuarora.in">website(manuarora.in)</a></p>
<p>Good luck and Happy Coding! 👑🫡</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Coding Interview Practice – Sample Interview Questions and Solutions ]]>
                </title>
                <description>
                    <![CDATA[ By Damla Erkiner David Goggins is an ultramarathon runner, a public speaker, a retired navy SEAL, and the author of the book 'Can't Hurt Me: Master Your Mind and Defy the Odds'. He's one of my role models because of his physical strength and mental r... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-coding-interview-practice/</link>
                <guid isPermaLink="false">66d45e01d1ffc3d3eb89dda9</guid>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 31 Aug 2022 17:39:28 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/08/david-goggins-quotes-about-hard-work.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Damla Erkiner</p>
<p>David Goggins is an ultramarathon runner, a public speaker, a retired navy SEAL, and the author of the book '<a target="_blank" href="https://www.amazon.com/Cant-Hurt-Me-Master-Your/dp/1544512287"><strong>Can't Hurt Me: Master Your Mind and Defy the Odds</strong></a>'. He's one of my role models because of his physical strength and mental resilience. </p>
<p>You might say: "Wait a second! We get it. This person is obviously the epitome of success. But he has non-technical skills. So why is he relevant to JavaScript coding interviews?" </p>
<p>Well, if you're ready, let's explore this together.</p>
<h3 id="heading-rocky-balboa-as-a-mentor">Rocky Balboa As a Mentor</h3>
<p>In response to a question, David says, 'The Rocky Movie changed my life." In <a target="_blank" href="https://www.youtube.com/watch?v=dse1afiGbx4&amp;t=193s">that pep talk</a>, he refers to <a target="_blank" href="https://www.youtube.com/watch?v=25NmudB2fqg">this scene</a> (min 1.30-1.42) where the fictional character, Rocky - despite being beaten up badly by his opponent in the final boxing round - refuses to give up no matter what. </p>
<p>David describes that particular moment as the time when Rocky - initially depicted as an underdog by the screenwriter - overcomes all the odds and strikes awe in his rival.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-280.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.amazon.com/Eye-Tiger-Rocky/dp/B004GY1FTQ">Illustration Source</a></em></p>
<p>Let's admit it. Being a good programmer is not that easy. And especially if you are at the beginning of your career, technical job interviews can be seriously daunting. In short, it might be nice to reach David's (and Rocky's) mindset. </p>
<p>With that kind of drive and confidence, you're much less likely to consider giving up regardless of the types of challenges you face in your wonderful yet difficult journey of getting a developer job.</p>
<h2 id="heading-why-coding-interviews-are-difficult">Why Coding Interviews Are Difficult</h2>
<p>During coding interviews, you are expected to fix coding problems with some theoretical knowledge. But the caveat is you must do that in real time, which sometimes scares new developers off. </p>
<p>There are several types of coding interviews. But the most challenging one is probably a whiteboard interview. In these types of interviews, you have to code in front of a future employer / a senior software developer.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-319.png" alt="Image" width="600" height="400" loading="lazy">
<em>[Illustration by HackerRank](https://www.hackerrank.com/blog/virtual-whiteboarding-for-system-design-interviews/"&gt;&lt;nr-sentence class="nr-s20" id="nr-s20" page="0)</em></p>
<p>These interviews can be extra stressful because you are typically not allowed to have a computer to google any unknown concepts or to get some code snippets from the internet. You are only given a marker to solve the question on a whiteboard as the name suggests.</p>
<h3 id="heading-do-interviews-reflect-what-youll-do-in-your-job">Do Interviews Reflect What You'll Do in Your Job?</h3>
<p>Not necessarily. So why are they holding these scary coding interviews? Well, the reason is to test your problem solving skills in general. At times, finding the correct answer may not even be that important. </p>
<p>What matters is how you reach that conclusion / solution and which algorithms you prefer to use along the way. In other words, your ability to function well under stress is being tested by tech companies. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-329.png" alt="Image" width="600" height="400" loading="lazy">
_[Image Source](https://www.reddit.com/r/ProgrammerHumor/comments/l6wnvt/interview_vs<em>job/"&gt;&lt;nr-sentence class="nr-s30" id="nr-s30" page="0)</em></p>
<p>Let's face it. You'll come across lots of stressful situations in your future job, and how you deal with certain issues is especially crucial. Therefore, your future employer naturally wants to witness firsthand whether you are the right fit for the job. </p>
<h2 id="heading-what-is-the-purpose-of-this-tutorial">What is the Purpose of This Tutorial?</h2>
<p>In this post, I'll walk you through some popular JavaScript interview concepts through examples. I'll also do my best to show you what recruiters / interviewers might actually be looking for in a candidate while they code in front of them. </p>
<p>To simply put, we'll examine some models and try to solve the related puzzles together. </p>
<p>By the end of this tutorial, you'll hopefully have an idea about a number of important array methods. But most importantly, you'll unlock how to approach some coding challenges in the best way possible.</p>
<h2 id="heading-what-exactly-is-the-memory-palace-method">What Exactly is the Memory Palace Method?</h2>
<p>Before we start, just be aware that in the sample data down below, I've used some late celebrities' names intentionally so that all those details can be catchy in the long run. </p>
<p>An ancient technique called <a target="_blank" href="https://www.wired.co.uk/article/memory-palace-technique-explained">the Memory Palace</a> clearly says that the weirder the details, the easier it is to remember them – and a made-up story / creating context is even more effective. </p>
<p>If you try to visualise the related situation vividly and associate the given programming concepts with some bizarre details in your mind, you might feel less stressed and confused when you see a similar problem next time. This is because it might be easier for you to create specific links and as such remember things easily. This is how our brains work. </p>
<p>Well, even the fictional figure '<a target="_blank" href="https://www.smithsonianmag.com/arts-culture/secrets-sherlocks-mind-palace-180949567/">Sherlock Holmes</a>', the smartest guy on the planet, benefits from this method when solving complicated crimes – so why shouldn't we?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-321.png" alt="Image" width="600" height="400" loading="lazy">
<em>[Illustration by Savanahcat](https://www.deviantart.com/savanahcat/art/Mind-Palace-387601041"&gt;&lt;nr-sentence class="nr-s43" id="nr-s43" page="0)</em></p>
<h2 id="heading-how-to-approach-coding-problems">How to Approach Coding Problems</h2>
<p>In our imaginary interview, you'll see that four extraordinary musicians from the past are listed as passengers on a flight. We have their food choices and the number of connecting flights they need to take after their incredible performances on stage in different parts of the world.</p>
<p>Let's say just for the sake of argument our phenomenal figures (Freddie Mercury, Amy Winehouse, Kurt Cobain, and Michael Jackson) are about to fly from different destinations to Los Angeles just to be able to dine out together at a swanky restaurant, as they enjoy each other's company so much. </p>
<p>After all, this is our own private memory palace, so we can absolutely do whatever we want to do in our minds. Remember unusual details will stick better. That's why I'm trying to add more to spice things up. </p>
<p>This method explicitly suggests describing every single detail with some vivid adjectives so that you can associate them with the things you plan to learn in the long run. </p>
<p><a target="_blank" href="https://www.medicalnewstoday.com/articles/memory-loss#:~:text=Short%2Dterm%20memory%20is%20the,from%20a%20longer%20time%20ago.">Scientists</a> say short term memory and long term memory function very differently. To put it simply, we need a way to put all those core concepts (not necessarily the syntax) about programming in our long term memory. That's why it can be nice to benefit from the memory palace method in our journey.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-326.png" alt="Image" width="600" height="400" loading="lazy">
<em>[Image Source](https://www.nme.com/news/music/producer-goes-viral-for-mixing-nirvana-and-michael-jackson-songs-with-drill-beats-2747204"&gt;&lt;nr-sentence class="nr-s56" id="nr-s56" page="0)</em></p>
<p>Plus, I feel like you get to picture this unusual scenario with a smile on your face. Well, wouldn't it be great if these awesome souls could have seen that they are now helping us / the programming community as the guests of a freeCodeCamp article? </p>
<h3 id="heading-sample-interview-questions">Sample Interview Questions</h3>
<p>Let's get back to the real life now though. Remember you're still in the interview and as you see below, three questions in a row are waiting for you.</p>
<pre><code class="lang-js">
<span class="hljs-comment">// Main Question: Get the passengers' names using the data provided </span>
<span class="hljs-comment">// Bonus Part (a)- Return vegetarians/vegans</span>
<span class="hljs-comment">// Bonus Part (b)- Sort passengers by the number of connected flights in descending order</span>
</code></pre>
<h3 id="heading-the-data">The Data</h3>
<p>To solve the puzzles, you're expected to use the data inside the following array of objects in practical ways. </p>
<p>You'll certainly need to come up with the right algorithms and try to find the most effective solution that can satisfy the interviewer. </p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> passengers = [
  {
    <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">passengerName</span>: <span class="hljs-string">"Freddie Mercury"</span>,
    <span class="hljs-attr">isVegetarianOrVegan</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">connectedFlights</span>: <span class="hljs-number">2</span>,
  },
  {
    <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>,
    <span class="hljs-attr">passengerName</span>: <span class="hljs-string">"Amy Winehouse"</span>,
    <span class="hljs-attr">isVegetarianOrVegan</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">connectedFlights</span>: <span class="hljs-number">4</span>,
  },
    {
    <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>,
    <span class="hljs-attr">passengerName</span>: <span class="hljs-string">"Kurt Cobain"</span>,
    <span class="hljs-attr">isVegetarianOrVegan</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">connectedFlights</span>: <span class="hljs-number">3</span>,
  },
     {
    <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>,
    <span class="hljs-attr">passengerName</span>: <span class="hljs-string">"Michael Jackson"</span>,
    <span class="hljs-attr">isVegetarianOrVegan</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">connectedFlights</span>: <span class="hljs-number">1</span>,
  },
];
</code></pre>
<p>The above questions are in fact not that hard. But, how we'll handle them is a great opportunity to compare alternative solutions for a single problem. At the end of the day, quality is what counts for recruiters / interviewers. </p>
<h3 id="heading-interview-question-1-how-to-get-passengers-names">Interview Question 1: How to Get Passengers' Names</h3>
<p>Let's get the passengers' names as requested. The first solution is through a <a target="_blank" href="https://www.freecodecamp.org/news/javascript-for-loop-how-to-loop-through-an-array-in-js/">'for loop'</a> method. So we first need to use an empty array to push the passengers' names right inside it at the end of the loop. </p>
<p>Below, <code>[i]</code> represents the current passenger and we simply loop through the 'passengers' array to access the names of the passengers. Then, we need to lock them up in our empty array / passengerNames.</p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> passengerNames = [];
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; passengers.length; i++) {
    passengerNames.push(passengers[i].passengerName)
}
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"passengers"</span>, passengerNames);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-331.png" alt="Image" width="600" height="400" loading="lazy">
<em>RESULT - using 'for loop'</em></p>
<p>Alright, we solved the puzzle, but is it enough? Or might the interviewers expect you to come up with a better solution?</p>
<h3 id="heading-alternative-solution-1">Alternative Solution #1:</h3>
<p>We can reach the desired result by using the '<a target="_blank" href="https://www.freecodecamp.org/news/javascript-foreach-how-to-loop-through-an-array-in-js/">forEach</a>' function as well. This solution is even a bit better than the previous one because there is no index expression in this one. </p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> passengerNames = [];
passengers.forEach(<span class="hljs-function">(<span class="hljs-params">passenger</span>) =&gt;</span> {
    passengerNames.push(passenger.passengerName);
})
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-332.png" alt="Image" width="600" height="400" loading="lazy">
<em>RESULT - using 'forEach'</em></p>
<p>To benefit from 'forEach', we need <a target="_blank" href="https://www.freecodecamp.org/news/what-is-a-callback-function-in-javascript-js-callbacks-example-tutorial/">a callback function</a>. With this arrangement, we are able to reach every passenger in the list. However, just like in the previous solution, we first need an empty array to push the items / passengers' names. </p>
<p>Even though the result is the same, this piece of code is shorter. Writing neater codes is what is – in fact – expected from you. </p>
<p>In other words, not only the solution matters, but also how you reach it is being evaluated by the recruiters. For this reason, it is a good idea to plan your action rather than writing the first idea in your mind on the whiteboard.</p>
<h3 id="heading-alternative-solution-2">Alternative Solution 2:</h3>
<p>Here comes the best solution. We can also utilise the '<a target="_blank" href="https://www.freecodecamp.org/news/javascript-map-how-to-use-the-js-map-function-array-method/">map</a>' function to tackle the same problem. Let's see how.</p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> passengerNames = passengers.map(<span class="hljs-function">(<span class="hljs-params">passenger</span>) =&gt;</span> passenger.passengerName);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-333.png" alt="Image" width="600" height="400" loading="lazy">
<em>RESULT - using 'map'</em></p>
<p>The map function also loops through the array and returns a new array for every item in the list. With this set-up, we simply return a single element, not an object. </p>
<p>The result will again be the same in the console, but your code will even be better than the first and second one because this time, we don't need to create an empty array before the actual task. </p>
<p>Here is the food for thought on this topic. Those who say 'less is more' have a point when it comes to writing codes. </p>
<h3 id="heading-interview-question-2-how-to-get-vegetarianvegan-singers">Interview Question 2: How to Get Vegetarian/Vegan Singers</h3>
<p>Let's now take a look at the next challenge. The new task asks us to obtain only the vegetarian / vegan singers from the passengers' list by also keeping the first argument in the main question section. </p>
<h3 id="heading-how-to-solve-with-a-for-loop">How to Solve With a 'For Loop'</h3>
<p>Again, we can use the same old 'for loop' for this one as well. All we need to do is to check whether there are any vegetarian / vegan singers in our passenger list through an 'if' statement inside our existing function.</p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> passengerNames = [];
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; passengers.length; i++) {
    <span class="hljs-keyword">if</span>(passengers[i].isVegetarianOrVegan) {
    passengerNames.push(passengers[i].passengerName)
    }
}
<span class="hljs-built_in">console</span>.log(passengerNames);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-334.png" alt="Image" width="600" height="400" loading="lazy">
<em>RESULT - using 'for loop'</em></p>
<p>We do that with the <code>isVegetarianOrVegan</code> property in our object. Basically, what we say is this: if the relevant statement is true (if there are any vegan / vegetarian passengers in the list), just push those items into our new array. The result will give us three singers' names as those are listed as  'vegetarian or vegan' in the data part. </p>
<h3 id="heading-how-to-solve-with-foreach">How to Solve with 'forEach'</h3>
<p>As a matter of fact, the 'forEach' function handles the problem similarly. But once again, it has too many lines of codes as you see below, so it isn't the ideal version. </p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> passengerNames = [];
passengers.forEach(<span class="hljs-function">(<span class="hljs-params">passenger</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (passenger.isVegetarianOrVegan)
        passengerNames.push(passenger.passengerName);
});

<span class="hljs-built_in">console</span>.log(passengerNames);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-335.png" alt="Image" width="600" height="400" loading="lazy">
<em>RESULT / 'forEach'</em></p>
<h3 id="heading-how-to-solve-with-filter-amp-map">How to Solve with 'Filter' &amp; 'Map'</h3>
<p>To come up with the best option, this time, we will use two different methods. The '<a target="_blank" href="https://www.freecodecamp.org/news/javascript-array-filter-tutorial-how-to-iterate-through-elements-in-an-array/">filter</a>' and the 'map' functions will – in a way – collaborate to create better logic when solving the given problem. Let's examine the following code snippet closely now.</p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> passengerNames = passengers.filter(<span class="hljs-function">(<span class="hljs-params">passenger</span>) =&gt;</span> passenger.isVegetarianOrVegan).map(<span class="hljs-function">(<span class="hljs-params">passenger</span>) =&gt;</span> passenger.passengerName);

<span class="hljs-built_in">console</span>.log(passengerNames);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-336.png" alt="Image" width="600" height="400" loading="lazy">
<em>RESULT / 'filter' + 'map'</em></p>
<p>With the filter method, we only get the vegetarian / vegan passengers from our array in the first place. If it finds some non-vegetarian / vegan passengers (like our beloved 'Freddie'), it will get rid of them automatically. </p>
<p>Briefly, the first part of the equation, the 'filter' method will simply work through 'yes' or 'no' model. </p>
<p>Then, the 'map' function will come in, eventually giving us a brand new array showing the vegetarian / vegan passengers only. </p>
<p>This final solution will prove your future employer that you genuinely know what you're doing and you are really taking the right steps to be a hotshot developer.</p>
<h3 id="heading-interview-question-3-how-to-sort-passengers-by-connecting-flights">Interview Question #3: How to Sort Passengers by Connecting Flights</h3>
<p>The last section asks us to sort the list of our super cool passengers by the number of the connecting flights they'll take to eventually reach LA. Let's see who has more and as such, will be pretty exhausted. </p>
<p>Spoiler alert! Amy with four connecting flights in total might be a bit sleepy in the get-together at that fancy restaurant. But there is no doubt that she will somehow rock where ever she goes. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-322.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://variety.com/2022/music/global/amy-winehouse-freddie-mercury-john-lennon-tupac-shakur-bbc-studios-sales-1235196177/">Image Source</a></em></p>
<p>Anyway, what we need for this task is to know how the '<a target="_blank" href="https://www.freecodecamp.org/news/javascript-array-sort-tutorial-how-to-use-js-sort-methods-with-code-examples/">sort</a>' function operates.</p>
<p>Primarily, it compares items one by one and returns something as a result. In our case, it will be the number of connected flights. But how does it make that comparison? What is the logic behind that?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-343.png" alt="Image" width="600" height="400" loading="lazy">
_[Source Code: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global<em>Objects/Array/sort"&gt;&lt;nr-sentence class="nr-s149" id="nr-s149" page="0)</em></p>
<p>The above lines of code are pretty clear in general. Thanks to the 'sort' function, we list those months in alphabetical order. </p>
<p>Well, here comes the big question. How does the code / system know that 'a' is the first letter of the alphabet and as such, the list starts with the 'd' letter (December)?</p>
<p>The reason is that the 'sort function' lists things in ascending order by default. But can't we change this setting? Perhaps, we need to list items in descending order. Of course, we can. </p>
<p>Let's see how. To achieve what we want, we may utilise 'a' and 'b' letters as parameters leading to different directions.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-338.png" alt="Image" width="600" height="400" loading="lazy">
_[Source Code: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global<em>Objects/Array/sort"&gt;&lt;nr-sentence class="nr-s160" id="nr-s160" page="0)</em></p>
<p>Simultaneously, we can benefit from the assistance of three numbers: -1,+1, 0 as seen above. When sorting items in descending or ascending order or finding the equal values, they can be quite handy. </p>
<h3 id="heading-tricky-bit-of-the-sort-function">Tricky Bit of the 'Sort' Function</h3>
<p>In the following example, the list is sorted in ascending order. Why is it like that? Here is the reason. When we return those 'a' and 'b' parameters, we use this order:  'a - b' . That gives us ascending values by default. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-339.png" alt="Image" width="600" height="400" loading="lazy">
_[Source Code: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global<em>Objects/Array/sort"&gt;&lt;nr-sentence class="nr-s169" id="nr-s169" page="0)</em></p>
<p>However, if we swap them and say 'b - a', the list will be seen in descending order this time. That's the tricky bit when it comes to the 'sort' function.</p>
<p>In the above example, the first version (regular function) and the second one (arrow function) are in essence the same, but just be aware that <a target="_blank" href="https://www.freecodecamp.org/news/arrow-function-javascript-tutorial-how-to-declare-a-js-function-with-the-new-es6-syntax/">arrow functions</a> came with <a target="_blank" href="https://www.freecodecamp.org/news/these-are-the-features-in-es6-that-you-should-know-1411194c71cb/">ES6</a>. </p>
<p>Although arrow functions help developers to write less code, you cannot use them everywhere. (Read <a target="_blank" href="https://www.freecodecamp.org/news/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26/">this</a> to find out when to use them.)</p>
<h3 id="heading-testing-our-new-knowledge">Testing Our New Knowledge</h3>
<p>Shall we now analyse the situation of our passengers through our new perspective? We know that the last task asks us to sort the number of flights in descending order. But the following set-up does the opposite. </p>
<p>It can only give us the list in ascending order. Why? It's simply because of the pre-defined order (passenger1.connectedFlights - passenger2.connectedFlights) as in the case of a - b example.</p>
<pre><code class="lang-js">
 <span class="hljs-keyword">const</span> numberOfFlights = passengers.sort(
  <span class="hljs-function">(<span class="hljs-params">passenger1, passenger2</span>) =&gt;</span>
    passenger1.connectedFlights -  passenger2.connectedFlights 
); 
<span class="hljs-built_in">console</span>.log(numberOfFlights);
</code></pre>
<p>Once we swap the order (passenger2.connectedFlights - passenger1.connectedFlights) as you see in the following code snippet, our problem will be solved and the list will come in descending order. </p>
<pre><code class="lang-js">
 <span class="hljs-keyword">const</span> numberOfFlights = passengers.sort(
  <span class="hljs-function">(<span class="hljs-params">passenger1, passenger2</span>) =&gt;</span>
    passenger2.connectedFlights -  passenger1.connectedFlights 
); 
<span class="hljs-built_in">console</span>.log(numberOfFlights);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-342.png" alt="Image" width="600" height="400" loading="lazy">
<em>RESULT - Descending Order by the Number of Connected Flights / Michael is the luckiest :-)</em></p>
<h3 id="heading-can-we-also-use-for-loop-or-foreach">Can We Also Use 'for loop' or 'forEach'?</h3>
<p>Well, yes and no. Both would be low-level solutions for this question. </p>
<p>We should keep in mind that the sort function mutates an array. This is a kind of side effect which changes the original array and that might be a problem if we use 'for loop' or 'forEach' as a solution. </p>
<p>There are of course <a target="_blank" href="http://www.buginit.com/javascript/javascript-sort-without-mutating-array/">ways</a> to avoid mutation in the sort function, but in our example, it will lead to more lines of codes, which is not practical at all.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>We've started the article with David Goggins, the symbol of resilience and grit, so let's end it with his inspiring presence and ideas. </p>
<p>If you happen to read this modern day hero's book or listen to one of those famous podcast episodes (For example, <a target="_blank" href="https://www.youtube.com/watch?v=5tSTk1083VY">this one</a>) where he was a guest speaker, you'll immediately understand that he wasn't born that way. Rather, his secret lies in the fact that he never gives up, against all odds. </p>
<p>Coding interviews are tough, but if you keep going after your goals by visualising the scene of success in your mind over and over again, it will -  sooner or later - be yours. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-328.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://castromarina.info/david-goggins-inspirational-quotes">Image Source</a></em></p>
<p>Many thanks for reading this post. If you've liked this article, one of the best ways to support me is to share it. Should you have any questions or comments, you can always contact me via <a target="_blank" href="https://www.linkedin.com/in/damla-erkiner-000b76227/">LinkedIn</a>. I'll be more than happy to help you out with your queries.</p>
<p>Happy coding!</p>
<p><strong>“Knowledge is power.” – Francis Bacon</strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Coding Interview Prep for Big Tech (FAANG) – And How I Became A Google Engineer ]]>
                </title>
                <description>
                    <![CDATA[ When I changed careers from lawyer to software engineer at Google, I published 10 big ideas that helped me make that massive transition. Since then I’ve had a ton of questions from people asking me questions about: How I taught myself new skills Ho... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/coding-interview-prep-for-big-tech/</link>
                <guid isPermaLink="false">66d461c933b83c4378a51861</guid>
                
                    <category>
                        <![CDATA[ career advice ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Career Change ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interview tips ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubin Pratap ]]>
                </dc:creator>
                <pubDate>Wed, 13 Jul 2022 14:45:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/Google-Mel.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When I changed careers from lawyer to software engineer at Google, I published <a target="_blank" href="https://www.freecodecamp.org/news/from-lawyer-to-google-engineer/">10 big ideas that helped me</a> make that massive transition. Since then I’ve had a ton of questions from people asking me questions about:</p>
<ul>
<li><p>How I taught myself new skills</p>
</li>
<li><p>How did I know that learning to code at 37 was not “too late”</p>
</li>
<li><p>How I prepared for big tech coding interviews</p>
</li>
<li><p>How I analyzed and minimized the risk of career change</p>
</li>
<li><p>How I worked out that software engineering was “right” for me</p>
</li>
<li><p>What languages I focused on</p>
</li>
<li><p>Whether being a FANG/FAMGA software engineer is right for everybody (hint: tempting to think so but I saw plenty of evidence of it not being right for some people’s goals)</p>
</li>
</ul>
<p>Note: I think “FAANG/FAMGA” is limiting, and prefer to refer to “big tech”since there are many highly prestigious companies other than the usual 4-5 everyone obsesses about.</p>
<h2 id="heading-why-i-wrote-this-article">Why I Wrote This Article</h2>
<p>Each of those questions I listed above deserve their own article, even though I know our contemporary culture prefers “tweet-sized tips”. However, meaningful skills can’t be internalized from a few hundred characters.</p>
<p>So today I am going to share with you my answer to one of those questions – the approach I adopted when:</p>
<ol>
<li><p>I made that first jump in careers from lawyer to coder at 38, and</p>
</li>
<li><p>How I prepared for big tech interviews at the ripe ol’ age of 39, with less than 2 years of coding behind me.</p>
</li>
</ol>
<p>If you want me to write on any of the other questions I always get, please let me know! I’m going to put my contact details in this post somewhere, and the only way to find it will be to go through the article. 😊 That is also to encourage you to carefully read this article rather than skimming for a “quick tip”.</p>
<h2 id="heading-uncovering-the-real-goal">Uncovering the Real Goal</h2>
<p>I hold the following opinions: getting coding interviews is harder than learning to code. Doing well at the interviews is often just as hard as getting the interviews. Behavioral interviews are hard if you don’t have solid experience – but your competition does.</p>
<p>When I made the switch I had zero coding background. Later, when I set my sights on Big Tech, I knew I’d be competing with PhDs, people who’d been coding since their teens (often 20+ years), and folks who'd achieved a lot more technically than I had in my one brief year’s experience as a developer.</p>
<p>And I had the added challenge of applying for big tech from outside the United States.</p>
<p>So I had to develop a plan that went well beyond just “learning to code”.</p>
<p>First, let me explain why I concluded that “learning to code” is the easy part, even though I’d tried and failed to learn to code 4 times, between 2012 and 2018.</p>
<p>This insight came to me in late 2018, when my startup was struggling. I had lost tens of thousands of dollars building my startup. I had no income for over 2 years.</p>
<p>And I decided to pull out over $40K from my mortgage. Why? I got into a top-rated bootcamp in San Francisco.</p>
<p>I left my family behind, and relocated to the US. I was meant to be there for over 14 weeks, but I withdrew from this top-rated bootcamp in week 1, and returned to Australia.</p>
<p>I had been super excited about the adventure (and scared from all the debt). But I developed grave doubts about the bootcamp strategy. I noticed that my instructors and the program were designed to help people "learn to code" rather than "becoming a coder".</p>
<p>From my experience on the hiring side in 3 other industries and 4 countries, I knew this was a mistake.</p>
<p>Learning to code is just a form of “literacy”. And literacy is not skill.</p>
<p>I was living proof: each of the 4 times I focused on “learning to code” I succeeded in a narrow sense. Whether it was HTML or Java or writing a simple Android app from a book, I always succeeded at learning how to read and write the basics. But I had no idea how to actually build anything useful. I was completely hopeless at applying my knowledge – I had no real “skill”.</p>
<p>In this century we don't get hired for what we know. We get hired for skill.</p>
<p>I quickly saw several reasons why a coding bootcamp was the wrong strategy for me.</p>
<p>This expensive bootcamp would likely give me some basic skills, the kind that may even get me an “entry level” job. But I could see things were going to be rushed, standardized, and focused on "getting out the other end".</p>
<p>I didn't want to "tick a box". I wanted skill. Competence. Confidence.</p>
<p>Moreover, bootcamps seemed to prepare everyone for entry level "junior developer" jobs.</p>
<p>I was 37 and I didn’t want to settle for an “entry-level job” mindset. Plus I don't believe anyone with 3 + years of experience is "junior" even if they're a total newbie in the field.</p>
<p>Then I discovered that several instructors and teaching assistants at the bootcamp were former students who hadn’t yet found jobs. They had never changed careers – many had never had a "career" as such. The job-search counselors had never even been on the interviewing side in tech.</p>
<p>How was I going to learn to do something from people who’d never done what I needed to do?</p>
<p>And then there was geography. Students based in San Francisco had advantages, whereas people coming from other parts of the US did not find work that easily and ran out of money in the long months after graduating and before getting their first job. Heck, I was based in Australia...how was this going to work for me?</p>
<p>I looked at my explicit goal. It was not to "learn to code" – it was to build a career that fulfilled me.</p>
<p>Plus, when researching bootcamps, I could see a path to learning “part time”. That seemed like a much more sustainable strategy to me because I could find a job and learn at night and on weekends. After over 2 years of no income, I needed to have cashflow in order to keep fear at bay, and focus on becoming a professional coder.</p>
<p>As the legendary businessman Harvey Firestone said:</p>
<blockquote>
<p><em>“Having a surplus is the greatest aid to business judgment that I know.”</em></p>
</blockquote>
<p>Having income while studying would give me the confidence to make better judgments. Better judgments are important for a career that is fulfilling in the long term.</p>
<p>I had no doubt that I would "learn to code" if I did 3-4 months in the bootcamp.</p>
<p>But would I learn enough for a good team to pay me money for my skills? I no longer believed bootcamps and online coding websites would help me achieve that.</p>
<p>Learning to code would not get me far. I had to be good enough to beat my competitors who had coding degrees, prior experience and networks. I wanted a career in code.</p>
<p>So I left the bootcamp, wrote off about $9,000 and returned to Australia. Sure, I had gained rudimentary coding literacy to pass the entrance test for the bootcamp. But I was very far from competent.</p>
<p>This analysis may be hard to understand if you’re new to the workplace. Another way to truly understand it is to notice that many of us play music, but aren’t in a band. As my mentor said:</p>
<blockquote>
<p><em>"Michael Jordan didn’t want to learn to play basketball. He wanted to be in the NBA. Huge difference."</em></p>
</blockquote>
<h2 id="heading-how-to-use-your-advantages-amp-disadvantages">How to Use Your Advantages &amp; Disadvantages</h2>
<p>That one insight made all the difference. Within 8 months, in 2019, I got all 4 developer jobs I applied for. I simply followed the program I’d developed with the help of my (non-technical!) coach.</p>
<p>Don't be misled though. I had unexpected advantages. I benefited from 2 major advantages that initially appeared to be disadvantages.</p>
<p>This was not my first career change, and for almost a decade, I had been on the hiring side in previous careers. Today I’ve been on the hiring side in engineering too, and the patterns are very similar.</p>
<p>My biggest advantage was that I was no longer thinking about the job market challenge as a candidate. I was thinking about this from the perspective of the hiring manager. That had a significant impact on my plan because I had experience of how hiring managers think – their constraints, priorities, values, business needs, dislikes, red flags...</p>
<p>My experience (age?) helped me understand what impact I could deliver to a team and organization, and to identify the right people that I could learn from, who could help me with ideas, guidance, suggestions and referrals. What was a disadvantage was now an advantage – <a target="_blank" href="https://www.freecodecamp.org/news/why-career-changers-have-an-advantage/">a career changer's advantage</a>.</p>
<p>On the point of advantages, I want to call out something important.</p>
<p>The easiest thing in the world is to dismiss others for having “killer” advantages. It's easy to shrug and say "Of course – that’s why they succeeded". It’s easy to not notice that everyone has very compelling and serious disadvantages.</p>
<p>For me, my “disadvantages” were:</p>
<ul>
<li><p>Geography – I don’t live in the US or one of the other tech hubs</p>
</li>
<li><p>No formal computer science qualifications</p>
</li>
<li><p>Zero technical background</p>
</li>
<li><p>A mortgage and financial responsibilities</p>
</li>
<li><p>My “age” – learning new skills when you’re pushing 40 is harder than when you’re 25</p>
</li>
<li><p>Cultural and social expectations, judgment, negativity</p>
</li>
<li><p>Recruiters and bosses being younger than I was and uncertain of how to deal with me</p>
</li>
<li><p>Compared to other candidates, people viewed my change as very, very “risky”</p>
</li>
<li><p>I was going to earn less in engineering than I would as a lawyer</p>
</li>
</ul>
<p>Every day I hear from people who let any one of these things stop them. While I cannot comment on whether or not they’re real reasons, I <em>can</em> say that if we argue for our limitations, we get to keep them.</p>
<p>Clinging on to our disadvantages does not help us overcome them.</p>
<p>With the help of my coach and a ton of mindset/psychology training, I was able to dig into my disadvantages and convert a few of them (not many!) into major advantages. And that’s when I realized that my experience with how interviewing, recruitment, and resourcing works would help me a lot in formulating a strategy.</p>
<h3 id="heading-priority-one-career-change">Priority one: career change</h3>
<p>When learning to code and intentionally setting the goal of becoming a professional coder, I found that I kept switching to short-term thinking and obsessing about my first role.</p>
<p>I wanted my first role to be glorious, to prove all my critics wrong, to pay me a gazillion dollars and save me from having to deal with self doubt and struggle for the rest of my life.</p>
<p>But I had to train myself to view things differently. My first role must be one that makes me learn and grow, and set me up for future success no matter what happened. It needed to pay fair market rates, but I was happy to take a slightly lower salary if the team was fantastic and the growth/learning was solid. It did <em>not</em> need to be my dream job.</p>
<p>I was very explicit in the tradeoffs I’d make:</p>
<ul>
<li><p>Team matters more than brand</p>
</li>
<li><p>Team matters more than money</p>
</li>
<li><p>Brand matters more than money (as it would set me up for future opportunities)</p>
</li>
<li><p>Money matters more than stock (this was for my first dev role, as this would make my continued learning plan sustainable, even though stock may give me more financial upside)</p>
</li>
<li><p>But, learning mattered more than brand or money – as learning more would save me time which is better than saving me money</p>
</li>
<li><p>I would not trade off between team and learning. I needed both (but I was more likely to get reliable signals on the team than I would on the actual learning/growth I’d get on the job)</p>
</li>
</ul>
<p>“Nailing it” or being comfortable was not a priority. My priority was to successfully change careers.</p>
<p>Accepting a rubbish coding job (and there are plenty of them…) would not be a “successful” career change for me. But equally I didn’t have to get into big tech (ever) for my career change to be “successful”. This was very personal – success to me meant loving the work I do and learning a lot doing it. Period.</p>
<h3 id="heading-how-i-made-a-customized-plan">How I Made a Customized Plan</h3>
<p>After analyzing my advantages and "convertible" disadvantages, the next thing I needed to develop was a customized plan. I needed one that was tailored to me, that I could believe in.</p>
<p>I needed a plan that took into account my specific context, which includes my temperament, experience, beliefs, values, goals and skills.</p>
<p>Note that I’ve still not talked about the technical interviews, the algorithms and data structures, and so on. When developing my plan, I had to focus on all the many pieces that had nothing to do with my coding skills or technical capability.</p>
<p>It would also need to account for my psychological “runway” – how much time was I prepared to invest in this career change, before I’d give up, lose hope, or change my mind? I could not answer that without understanding how long it was going to take me to learn the minimum required skills.</p>
<p>To understand that, I needed to research and analyze what the minimum set of engineering skills that the market would value were.</p>
<p>And to understand that, I needed to analyze the dozens of engineering domains in the market, and which ones would suit my temperament, interest/passion and advantages. And from that analysis I’d need to pick the domains that I would focus on and exclude all others.</p>
<p>I'd have to find the overlap between my interests, my ability and what the market valued.</p>
<p>Again, my experience on the hiring side of the market gave me some (small but important) advantages. I knew that pure technical skill would not be enough – that’s just the starting point. the “invitation to the dance”.</p>
<p>I also knew that good teams don’t just hire for raw technical skill, they hire for essential non-technical attributes as well. What those traits are depend on the technical domain, the team culture, the current composition of the team, and so on.</p>
<p>Yes, you're right. A custom plan is extremely multi-dimensional, and getting things right is only moderately helpful, whereas getting things wrong can result in a giant loss of direction and waste of time.</p>
<p>Since I was almost halfway through my career, I was determined not to repeat past mistakes. I was going to be:</p>
<ul>
<li><p>Highly specific in my goals.</p>
</li>
<li><p>Highly intentional in my choices and actions.</p>
</li>
<li><p>Focused on what I wanted, paying no attention to the things I did not want.</p>
</li>
<li><p>Willing to change myself, my habits and negative beliefs, so that I could change the world around me.</p>
</li>
<li><p>Ready to focus on building a rewarding and fulfilling career rather than just “getting the next job”.</p>
</li>
<li><p>Ready to focus on delivering value for my future team rather than a “what’s in it for me” mindset.</p>
</li>
<li><p>Willing to play the long game – think in 5-10-25 year horizons rather than the next few weeks.</p>
</li>
</ul>
<p>I must confess, doing these things consistently was much harder than I anticipated. I slipped up a lot, especially on the first three. But since I had my custom plan written down, I let that be my guide and the sole source of truth for what I needed to do.</p>
<p>My plan required me to focus on fundamental programming skills, and then narrow it down to the segment that I felt matched my long-term goals and skills. For me, this was web development. This meant completely and ruthlessly avoiding all the “shiny new things” and doing things like Python or Java.</p>
<p>And tutorials and endless videos were not going to make me beat the competition. I calculated that the minimum set of skills I’d need to develop for my city would require 900-1100 hours of focused coding, practicing the right things in the right sequence.</p>
<p>Preparing the plan took several weeks. I kept refining and strengthening it and didn’t rush it artificially. I am very inspired by Abraham Lincoln (another lawyer who changed careers!) and he once said “Give me six hours to chop down a tree and I will spend the first four sharpening the axe”.</p>
<p>I was so tempted to dive right into my plan and get “busy” but I’d learned that being busy was so not the same as being effective. Once the plan felt as complete as it could be with the information I had at my disposal, I turned to executing on that plan, with total focus.</p>
<p>This meant a lot of sacrifice, and many, many days of self doubt, battling the temptation to switch, and learning to manage my energy. I developed some amazing habits during this time, but they were only obvious to me in hindsight. During those 6 months of work, I was constantly assailed by uncertainty, fear and occasional loss of hope.</p>
<p>Later on, I adapted this planning process to create a plan for Big Tech and especially for Google. That plan took another 500-600 hours of intentional study that was completely different from my plan to become a developer. More on that later.</p>
<h2 id="heading-early-results-and-thengoogle-swe">Early Results, and then…Google SWE</h2>
<p>Another lesson I’d learned from 4 years of trial, error, and failure was that I was very likely to change plans midway, switch resources, courses or focus.</p>
<p>This is a much more serious problem than we realize because every time we switch focus or plans we throw out the hard work we’ve done, go back to square 1 and…start…all…over…again.</p>
<p>Imagine if you were driving from A to B and kept taking U-turns and going back and restarting. You’d never get anywhere.</p>
<p>But I’d made myself a promise (it’s easier to keep a single promise than to keep a bunch of them!): I was going to complete my plan and then decide whether I would keep going. This time I wasn’t going to stop until I completed my plan.</p>
<p>I didn’t have to like doing it. I just had to like the possibilities that lay at the end of doing it.</p>
<p>My plan had a specific time when I would start interviewing even if I didn’t feel ready for interviews. But to get to that stage I had to get good at generating interview opportunities.</p>
<p>Again, my past experience in other careers helped me. I applied all my learnings over 18 years and secured 4 interviews within a few weeks, and got all 4 offers even though there were plenty of candidates with more experience, skill, and qualifications than I had.</p>
<p>It wasn’t because I was better at coding. I don’t see how that could be, given that I’d only been in the game for a few months.</p>
<p>I believe I got all 4 offers because <em>during the interview process</em> I demonstrated that I was a better candidate <em>for the hiring manager</em>. This approach was critical in how I presented myself.</p>
<p>Getting the offers is great, but I had an unexpected problem. Since my plan required me to be highly intentional about the kind of work I’d pursue, all 4 roles I’d applied for were the ones I really believed would be a fantastic start to my new career. How was I going to choose?</p>
<p>Yes it’s a great problem to have, but that doesn’t make the decision easy!</p>
<p>To resolve this problem intelligently, I learned to ask myself a very important question:</p>
<blockquote>
<p><em>Do I</em> <strong><em>know</em></strong> <em>this or do I simply</em> <strong><em>think</em></strong> <em>this?</em></p>
</blockquote>
<p>Very often we make decisions based on assumptions and beliefs that are completely untested, and we mistake our opinions or fantasies for reality. What we actually know is way less than what we believe without truly knowing.</p>
<p>Being intentional required me to focus on what I know rather than what I wished, or merely thought. I had to either find evidence to back my thoughts, or disregard thoughts for what I knew.</p>
<p>That framework developed my analytical powers and helped me choose the right first role in early 2019. I turned 39 around that time.</p>
<p>Till today I continue to use this <em>know vs think</em> framework in my personal decision making as well as in my engineering decision making. I find it to be an excellent framework for analyzing tradeoffs in complex decisions.</p>
<p>Looking back, I learned a TON about sticking to my plan, revisiting my goals, self-awareness and practicing being <em>intentional</em>.</p>
<p>A few months into my new role, I noticed that a lot of lawyers were starting to reach out and ask me how I did this. Curiously, many of them were people who insisted I was making a huge mistake and that wanting to learn to code at this stage was immature and foolhardy.</p>
<p>Now they wanted to “learn to code”. And that made me think.</p>
<p>What else have others said is “not possible”? <em>Do they</em> <strong><em>know</em></strong> <em>that or do they just</em> <strong><em>think</em></strong> <em>that</em>?</p>
<p>And my goals hadn’t changed. For me learning, growth, and team were still more important than brand or money. But I was almost 40 and I also wanted to explore life in a way that I’d never had the courage to do in the first half of my career.</p>
<p>So I decided to set myself a stretch goal: I was going to find out what being a software engineer at Big Tech was like. I’d worked in huge companies before and I knew that it isn’t for everyone – that’s the reason I went into startup and smaller companies in the first place.</p>
<p>But wouldn’t I learn and grow SO much by being surrounded by some of the “best” people in their field, from engineering to product and sales? Did I know this? Or did I just think it?</p>
<p>I did the research and found that on average people were happy in Big Tech. But I also found that most people were not as intentional as I was. So I confined my research to people who were very intentional about their careers. And they (almost universally) said they grew a lot from Big Tech, even if they decided to leave. Leaving Big Tech was also intentional, in pursuit of their end goals.</p>
<p>So I decided to try for big tech (including 3 of the FAMGA companies) and several others, in Silicon Valley, New York, and Seattle. I was still based in Australia, so this was a massive challenge.</p>
<p>I re-designed my plan. Several of the steps were the same but the coding curriculum would have to be massively overhauled. I also needed to find out how US big tech recruitment is done, and be worthy of a referral.</p>
<p>About 7 months later, I started generating interviews. I worked very hard to prove myself worthy of referrals for those 7 months, and people offered to give me referrals based on my efforts and proven commitment.</p>
<p>I got referred to Meta (it was called Facebook then) but I didn't get the interview as my skills were not the right match. This was a massive learning for me as I thought I’d been careful to only apply for roles where my skills matched – and I was wrong.</p>
<p>That was when I realized that sometimes the position description is written in ways that mean one thing for the hiring company but means very different things <em>outside that company</em>. This is because different organizations use the same words to mean different things. Both the hiring side and the candidate side can be unaware of this!</p>
<p>All these learnings added up. Within 3 months I got offers from 2 big tech companies, and missed out on a third at the final interview because I just didn’t know how to write a filesystem from scratch (I didn’t understand much about the Linux world at all!).</p>
<p>And then I got an offer from Google.</p>
<p>Again, I was faced with a very difficult decision. Google is a cultural force that is very hard to be objective about. But I really wanted to stay true to my goals, my plan, and my intentions.</p>
<p>Trying to separate what I knew from what I thought was EXTREMELY hard when it came to Google. But I was absolutely sure about one thing: the team I’d interviewed with were amazing people.</p>
<p>And this is where I believe luck matters. No matter what people say about skills, brains, smarts and all that stuff, luck and "magic" have a role in life.</p>
<p>My interviewers from Google were friendly, kind, cheerful and highly focused engineers. They were not looking to prove I sucked. They wanted to help me prove I was good. They answered my questions with enthusiasm, and I felt like collaborators from the first minute.</p>
<p>Is this a Google thing? Maybe. But later, when training to be a technical interviewer at Google, I witnessed a very wide variety of interviewer/hiring manager styles and beliefs. I saw candidates with great skill losing their nerve, struggle to communicate their process, and so on. And I came to appreciate the role of chance in all this.</p>
<p>So yes – I was lucky that I had the kind of interviewers I did, and that on interview day I happened to know how to work through the code.</p>
<p>This is also where my ultra-focused preparation on <em>type of work</em> and <em>relevant</em> skills paid off. There are a very large number of engineering roles at Big Tech that I would never have been suited to (like the one at Meta). Even with my prior experience in other careers, I had no idea how HUGE the engineering world is, and how many flavors and types there are, and how hard it is to tell them apart.</p>
<p>By forcing myself to be highly intentional and not randomly and blindly applying for big tech engineering roles, I improved my chances in small but important ways. I dug deep into each role and researched them carefully by speaking to friends in the industry (again – my age and experience was an asset because I had built relationships over 15+ years never expecting that they’d be so useful later on!).</p>
<p>For each offer I got, I had researched the role deeply, and prepared for the technical interviews well. On interview day the stars were aligned, and things worked out. Though I don’t think I “nailed” my interviews, I did well enough to communicate that I was a suitable candidate <em>for the team’s needs</em>.</p>
<p>Which leads me to the question: How did I prepare for the Big Tech interviews?</p>
<h2 id="heading-how-to-prepare-for-big-tech-interviews">How to Prepare for Big Tech Interviews</h2>
<p>Answer: In two phases that took me over 500 hours to execute.</p>
<h3 id="heading-phase-1-learn-the-realities-and-competitive-landscape">Phase 1: Learn the Realities and Competitive Landscape</h3>
<p>If I wanted to tackle Big Tech, from another country, with less than a year of industry experience, and 15+ years in an unrelated career, with no Computer Science degree, I needed to have a very clear view of the realities, especially the competitive landscape.</p>
<p>This means there was room for informed hope, but no room for dreamy-eyed, pie-in-the-sky magical and wishful thinking.</p>
<p>Hard truths (see my <a target="_blank" href="https://www.youtube.com/playlist?list=PLAPuklwJx5V3XZS19AlJQayZFpiZyDT9C">initial YouTube Videos on this here</a>). Hard realities. Hard work.</p>
<p>I had to fully internalize and appreciate the following:</p>
<ul>
<li><p>Coding is just the starting point. Not the ending point. Learning to code was the first step of many, one small piece of a much larger puzzle. In other words, it is necessary, <em>but not sufficient</em> to get a coding job (and especially at big tech).</p>
</li>
<li><p>My biggest enemy would be my own mind. It would either let the negativity of others get me down, or it would turn against me and undermine my own confidence. I had to build the habits that would help me have a resilient mindset. I focused on recovering from setbacks rather than avoiding them.</p>
</li>
<li><p>My competitors would likely not be career changers. Or if they were, they’d be from closely <a target="_blank" href="https://www.linkedin.com/posts/zubinpratap_software-engineering-computer-engineering-activity-6946411823759810560-VvA-?utm_source=linkedin_share&amp;utm_medium=member_desktop_web">related fields like computer engineering, mechanical engineering, or electronics engineering</a>. The vast majority would have technical qualifications, maybe even PhDs (this turned out to be true!), and several years of industry experience.</p>
</li>
<li><p>As an outlier and a “wildcard”, the hardest part would be getting the interviews. Learning algorithms and data structures would be easier. And “cracking the coding interview” (whatever that means…) would be easier too. Why? Code is deterministic – identical code generally produces identical results. But life is not deterministic, and getting interviews is highly subjective. In the job market, identical actions do not produce identical results.</p>
</li>
<li><p>I needed to shape myself into the <em>kind of person</em> seasoned engineers would want to work with</p>
</li>
<li><p>I assumed most of my competitors would have at least 3 -5 years of experience. I couldn't catch up with them, let alone <em>overtake</em> them. Instead, I needed to outperform them on non-technical skills and compare favorably (if not outperform them) on the technical stuff.</p>
</li>
<li><p>I had to communicate better than the others. If I didn’t know something, I’d need to say so and then communicate how I’d solve it if given the right time and opportunity. I also had to communicate to show interviewers that I understood <em>their business needs</em> and wasn’t just focusing on my selfish dreams.</p>
</li>
<li><p>Which means I had to really work on understanding what the hiring team valued, was looking for, wanted, and needed.</p>
</li>
<li><p>I could not control my competitors (their skill, their performance, how much they knew, and so on), or what my interviewer was thinking, wanting, what they valued, or whether they liked career changers or not. I could not control <em>most</em> things. I could only optimize my effort, my focus, my psychology, and how much learning I extract out of each experience, good or bad. I could only control my choices and actions. So focusing on anything outside that would be a waste of precious energy.</p>
</li>
<li><p>I had to accept the role of luck. Jordan, Tendulkar, Federer – they’ve all had bad days. I would too. Or maybe I'd do great, but on the day someone else would do better. Or someone else would just be a better fit for what the team needed. No harm, no foul. I’ve made those hard decisions on the interviewing side countless times myself, so I know how these things work.</p>
</li>
<li><p>If I was successful at more than 1 offer I would need to <em>pre</em>-think and <em>pre</em>-agree with myself about what signals and factors I would use to decide (I’d learned from my experience of choosing between my first 4 offers!).<br>  If you’re wondering how I knew how to do all this…I didn’t. Not all at once. What you’re reading is a summary in hindsight. But I had to work most of this out in “real time” based on “<a target="_blank" href="https://fs.blog/first-principles/">first principles thinking</a>”. And I worked with my mentor to tighten them up as I went along. It took a lot of time and I was so impatient to “start coding”. But …I knew what advice Abraham Lincoln would give me…</p>
</li>
</ul>
<h3 id="heading-phase-2-how-i-chose-my-learning-resources">Phase 2: How I Chose My Learning Resources</h3>
<p>I know everyone thinks there is a secret “magic bullet” out there. Some blog, video, resource, tutorial, podcast, PDF cheatsheet…_something…_that will unlock the entire “secret” and make us instantly learn things.</p>
<p>Nope.</p>
<p>I’ll bang on about this till the day I die – information is a commodity.</p>
<blockquote>
<p>Learning is hard, but it’s made much harder because there is <em>too much free information</em>.</p>
</blockquote>
<p>We all fall into the trap of thinking there is some missing piece of information. There isn’t.</p>
<p>Why? Because no matter where you live, what language you speak, what color your eyes, skin, or hair are, what gender you identify with – all resources are going to teach you things that “work”. They’re all “the same” at a very fundamental level.</p>
<p>They <em>have</em> to be, because that’s how computers work.</p>
<p>If you and I write an identical function in JavaScript or Python or Java, we are going to get identical results. That’s how computers work – they’re <a target="_blank" href="https://en.wikipedia.org/wiki/Deterministic_algorithm">deterministic</a> <a target="_blank" href="https://en.wikipedia.org/wiki/Deterministic_algorithm">algorithms</a>.</p>
<p>But life (and interviewing) is most decidedly <strong>not</strong> deterministic. Identical effort, grades, skill, intelligence will not produce identical results.</p>
<p>Again, I had to <em>teach myself to</em> <em>learn</em>. I had to teach myself to shift my attention away from resources/blogs/websites/courses and put my attention on building solid mental models, identifying relevant skills, drilling down on concepts rather than code implementations, applying what I already knew in new ways, reasoning, problem solving, and communicating my reasoning <em>while</em> I reasoned.</p>
<p>Now you’re going to be surprised by the resources I used for my Google and other Big Tech interviews.</p>
<p>Yes, I used <a target="_blank" href="http://leetcode.com">Leetcode</a>, <a target="_blank" href="http://algoepxert.io">Algoexpert</a>, <a target="_blank" href="http://interviewcake.com">InterviewCake</a> and <a target="_blank" href="https://www.youtube.com/c/JennyslecturesCSITNETJRF">Jenny’s CS Lectures</a> and perhaps a few others. But I didn’t complete a single one of them.</p>
<p>This wasn’t because I switched or lost focus. I was being intentional. I realized that they all teach the same thing, but with slightly different styles and content. So I used these resources to learn concepts and mixed and matched all these resources based on my analyses of interview <em>patterns</em>.</p>
<p>My reasoning was simple. Having been on the hiring side, I know that every year the quality of candidates (at good companies) improves. I personally think that focusing on the company is a huge mistake – we should focus on the team, people and <em>kind</em> of work.</p>
<p>But the world works a certain way, and because of that, everyone rushes to the big companies. This increases competition which makes it harder for hiring managers to assess candidates.</p>
<p>The only way for hiring managers to deal with this is to raise the bar, making it harder for candidates. The overall number of candidates keeps increasing, but the “pool” of candidates that get invited to the interview stays within a narrow range – usually 2 -10 people. Regardless of how many hundreds apply that’s about the number that will even get a chance to interview.</p>
<p>Therefore, the number of candidates that don’t hear back or meet with rejection increases, especially in bull markets.</p>
<p>If the competition is increasing and the resources on the internet are also increasing, but the shortlisted number stays more or less constant, then “learning more” cannot be the solution. Everyone is “learning more”, so relative to the competition there is no change.</p>
<p>I also realized that Big Tech would have lists of interview questions (this is “efficient” as interviewing is <em>very</em> time consuming, and so it makes sense to save time by having a question bank that interviewers could use). Naturally, they would not use these questions if they were “leaked” – that would defeat the interview process.</p>
<p>So, logically, hiring managers will not ask questions that are available on Leetcode or Algoexpert or other sites. This produces a kind of “arms race” – the more questions are made publicly available, the more questions in the question bank are changed. That results in more innovation and variance in questions and hiring strategies.</p>
<p>This left me only one choice. I had to learn to solve problems using mental models and by classifying them. Chances are I was never going to be asked to sort a Linked List or to implement Dijkstra’s shortest path algorithm. Instead, I would need to know how to apply these sorts of algorithms to “real world”, practical problems.</p>
<p>Often real world problems don’t look, sound, or smell like the practice questions we study. Practice questions and competitive coding questions tend to be “neatly” packaged up with clear constraints.</p>
<p>But as an interviewer, I wanted to know how the candidate thinks, reasons, analyses, interprets information, and collaborates. Solving the problem is a bonus. Often they have the right solution but run out of time – but ask great questions and clearly know how to tackle the problem. These candidates can still get the offer.</p>
<p>Later, as an engineer at Google, I could always tell if someone <em>knew</em> how to solve something even if they were unable to solve it in time. Equally, it’s immediately obvious when a candidate does not know how to solve something (and that's OK – we are all learning).</p>
<p>By adopting my approach of understanding problem types and solutions rather than specific code implementation, I could focus on learning to reason rather than learning to write specific algorithms.</p>
<p>This approach meant that I completed less than 40% of Algoexpert (and back then it had half the questions it has now). I also did maybe 50-60 questions from Leetcode and most of them weren’t the “hard” ones.</p>
<p>I figured that “hard” questions would probably show up in 45 minute interviews about 20% of the time which means 80% of the time they’d be easy or medium questions. So it made sense to optimize for the 80% given I was still relatively new to engineering and the hard problems would get in the way of understanding easy and medium ones.</p>
<p>I used these resources to recognise patterns rather than just “complete” and get a certification. That’s why I didn’t complete any of them. And no, I didn’t use “<a target="_blank" href="https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/0984782850">Cracking the coding interview</a>” either.</p>
<p>Along the way I also started a systematic process of understanding system design questions. I documented system design preparation in a <a target="_blank" href="https://www.freecodecamp.org/news/systems-design-for-interviews/">long form blog on the essential concepts for system design interview questions</a>.</p>
<p>I also decided to focus on one language: JavaScript. It wasn’t the best for interviewing (seasoned engineers discourage it on Quora and elsewhere) but I didn’t see how it mattered. The purpose of the interview was not to test my choice of languages – it was to test my ability to think abstractly and solve complex computer science-y problems.</p>
<p>The language is just a tool (another core belief I hold). In fact, using an untyped language like JS would give me opportunities to talk about its limitations or strengths, which is an opportunity to demonstrate that I understand the tradeoffs in language choices. That way, I could showcase broader knowledge and insight without actually having to implement it all in code.</p>
<p>But a lot of the resources I learned from used Java or C++. These languages are the dominant languages at Google. So being forced to read these languages and understand the principles forced me to not focus too much on “spitting out the code” and more on reasoning through the code so that I could write it.</p>
<p>That was my entire plan. Practice, Pattern Recognition, Mental Models/First Principle Thinking, System Design, doing fewer things really well, and focusing on getting interviews rather than just learning more code.</p>
<h3 id="heading-how-to-stand-out-during-interviews">How to Stand Out During Interviews</h3>
<p>As I mentioned, we all have advantages and disadvantages. And we all think our disadvantages are special and huge and our advantages are common, unremarkable, and probably not of much use.</p>
<p>This is not true. Logically, if we all think our disadvantages are severe, then we should all succumb to them. Yet some people overcome them. Only to find that others had it even worse and overcame <em>those</em>.</p>
<p>It’s way better to focus on what we can do well. For me, I truly believed that I could add a lot of value to the team. I don’t care about being the smartest or the best. But I care about being an outstanding learner, and maintaining my <a target="_blank" href="https://www.youtube.com/watch?v=hiiEeMN7vbQ">growth mindset</a> at all costs.</p>
<p>And so I tried to use this to stand out as best I could. I learned to ask really good questions of recruiters, interviewers, and hiring managers.</p>
<p>But there was a deeper reason for this. Asking good questions was my way of interviewing the company. Like I said, I didn’t want to repeat the mistakes of the first half of my career. So asking really good questions was important for me to assess whether the company was a fit <em>for me</em> and not just the other way around.</p>
<p>Since I had decided that I was going to value the team and the learning over all else, I never asked about the compensation until the recruiter raised it. It was going to be lower than what I earned as a lawyer anyway!</p>
<p>Instead I focused very hard on learning about the team, its dynamics, its group beliefs and values, how the manager solved problems (especially people problems), what the team was interested in, what the company division was interested in, how its balance sheet was doing, what its strategy was, what its resource allocation and budgeting looked like, and so on.</p>
<p>All these things were things I'd learned in other industries, as an individual contributor, as a manager, executive, founder and so on.</p>
<p>And all of these things also showed that I was being highly intentional. I was genuinely interested in the team, and the company, its product and its future. This wasn’t just another job I was applying for. This was active and personal…not passive and opportunistic.</p>
<p>And I believe that helped me stand out. Maybe not for all the roles I interviewed for, but for many of the offers I got.</p>
<p>When I was on the hiring side, I’d always prefer candidates who were genuinely interested in the role, the people, the product and the company. Those that showed up just “to get a job” didn’t have the kind of energy and drive we wanted.</p>
<h3 id="heading-interview-planning-and-strategy">Interview Planning and Strategy</h3>
<p>The last aspect of my roadmap required me to deeply understand the different types of coding interview processes.</p>
<p>This included technical and non-technical interviews, the format of interviews, the way companies organize them, run them, plan them, staff them, evaluate them, and weigh them. But it also required me to understand my strengths and weaknesses.</p>
<p>When going for Big Tech in the US I was aiming for 2-3 interviews per month – a huge goal given that I was not even in the US and was in a timezone that was 17 hours ahead of the west coast.</p>
<p>I had to plan and structure interviews at weird hours so I could accommodate my day job as a developer and also my study time. Some interviews took 6 hours, some took 10 or more. Some were “pair programming for a day” type interviews.</p>
<p>All this took a ton of planning, and mental training. I had to be careful to get the right sleep, the right exercise, maintain my mindset and confidence, deliver on my day job, be there for my family, study and maintain focus on my goals.</p>
<p>For this, I had to be honest with myself at what I was good at. For example, I am not a morning person. But I can endure late nights. So I structured interviews, work, sleep, or even exercise accordingly.</p>
<p>There were some interviews that were scheduled at 2am or after, and I wouldn’t sleep before (as I really am not good at waking up on time!). So I’d do a full workout at 1am to get my energy and focus up, then interview, then sleep till 10 am, then go to work and manage my schedule accordingly.</p>
<p>I would also be careful to plan interviews so that I wasn’t doing two of them back to back unless they were very similar and time bound. For example, doing a take-home test and doing a timed test in the same week require different planning from doing a take-home and a live-coding interview – all while managing work and family.</p>
<p>To schedule the interviews appropriately I’d work closely with the recruiter and be very transparent with them. This had two advantages: I gained credibility and trust with the recruiter for being collaborative and communicative, and they also got to see that I had other opportunities going, which increased the value of my candidacy. Competition is a good thing.</p>
<h2 id="heading-concluding-thoughts">Concluding Thoughts</h2>
<p>I am sure many of you were expecting this article to give “insider” tips and a specific set of languages, and DSA questions to learn. I believe I’ve given you something much better. Rather than giving you fish, I am showing you how to fish.</p>
<p>Apart from the ethics of it, insider tips are of limited value, especially in Big Tech. In huge companies things can be vastly different from team to team and city to city. You need to understand the principles of recruitment and career development, rather than just the specific languages and algorithms. Assuming that all interviews are the same is a big mistake.</p>
<p>And as for our obsession with data structures and algorithms…managing your career is the ultimate algorithm. Your mind is the ultimate data structure. Learn how to work with both and you’ll always do well, despite the occasional failures. <a target="_blank" href="https://twitter.com/ZubinPratap/status/1534341043344252929">Powerful ideas aren’t grandiose – they’re elegantly minimal</a>.</p>
<p>If you have read this article you will have noticed some of the things I linked to include multiple ways to reach me. You can also get invited to my <a target="_blank" href="https://futurecoderstraining.com">webinars, mini-courses and newsletters</a> if you want to go beyond just “learning to code” and learn how to build a career that is <em>right for you</em>.</p>
<p>Perhaps the most important message I can leave you with is that it is a mistake to obsess about big tech. Yes, they’re great to be part of, but if we believe they’re the only thing that is right for us we will miss out on all the other amazing opportunities.</p>
<p>Big Tech has glamor because of cultural trends these days. Sure, it’s nice to work for a great organization, but plenty of great organizations are not well known. Plus what is “great” for one person is pain for another.</p>
<p>Your number one priority is to be happy, fulfilled, and live the life that you want. This is not derived from a company. This comes from the people you spend time with (especially colleagues) and the kind of work you do. Big Tech companies have their share of bad managers, teammates, and work, just like any other company.</p>
<p>If you build skill, stack a great plan on top of the right mindset, and train yourself to set the right goals, you can achieve much more than you dreamed of – with or without Big Tech.</p>
<h3 id="heading-post-script">Post Script</h3>
<p>If you would like to learn more about my journey from lawyer to software engineer, check out <a target="_blank" href="http://podcast.freecodecamp.org/53-zubin-pratap-from-lawyer-to-developer">episode 53</a> of the <a target="_blank" href="http://podcast.freecodecamp.org/">freeCodeCamp podcast</a> and also <a target="_blank" href="https://lessonsfromaquitter.com/episode207/">Episode 207</a> of "Lessons from a Quitter". These provide the blueprint for my career change.</p>
<p>If you are interested in teaching yourself to code, changing careers and becoming a professional coder, or <a target="_blank" href="https://www.freecodecamp.org/news/non-technical-and-looking-for-a-technical-co-founder-2c212c01d6da/">becoming your own technical co-founder</a>, please reach out <a target="_blank" href="http://linktree.com/zubinpratap">here</a>. You can also check out my free webinar on <a target="_blank" href="http://futurecoderstraining.com/">Career Change to Code</a> if that is what you're dreaming of.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Coding Interview Prep – Free Resources to Help You Ace Your Interviews ]]>
                </title>
                <description>
                    <![CDATA[ By Evan SooHoo In the words of RealToughCandy, everyone wants a "one-stop shop" when it comes to learning. She uses this term to describe Educative.io, but Educative.io costs $60 a month unless you choose to commit to its annual plan. So it's not a f... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/coding-interview-preparation/</link>
                <guid isPermaLink="false">66d45edb73634435aafcef9e</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interview tips ]]>
                    </category>
                
                    <category>
                        <![CDATA[ leetcode ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Engineering ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 16 Nov 2021 23:50:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/11/thisisengineering-raeng-LxVzgYjkHp4-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Evan SooHoo</p>
<p>In the words of <a target="_blank" href="https://www.youtube.com/channel/UC54NcJvLCvM2CNaBjd5j6HA">RealToughCandy</a>, everyone wants a "one-stop shop" when it comes to learning.</p>
<p>She uses this term to describe <a target="_blank" href="https://www.educative.io/learn">Educative.io</a>, but Educative.io costs $60 a month unless you choose to commit to its annual plan. So it's not a free resource, which means it's not available to everyone.</p>
<p>If money were not a factor, you might buy a copy of <em>Cracking the Coding Interview</em>, get a LeetCode Premium subscription, and sign up for access to <a target="_blank" href="https://www.educative.io/courses/grokking-the-coding-interview">Grokking the Coding Interview</a> before scheduling some mock interviews. </p>
<p>Now, websites like LeetCode are interesting because they provide an excellent resource for free. A large percentage of LeetCode questions are free, the discussions section provides free solutions where the best code/explanations are voted to the top, and the platform itself can run hundreds of test cases in seconds.</p>
<p>Many people argue that <a target="_blank" href="https://www.youtube.com/watch?v=hhvvTD8SapI">LeetCode premium is not worth it</a>, though writers like Yangshun Tay beg to differ. What interests me about LeetCode is not their premium option, but that they make so much of their service available without it. </p>
<p>All that being said, there are a number of quality free resources you can use to prepare for your coding interviews. Let's go through my favorites now.</p>
<h2 id="heading-best-free-resources-for-coding-interview-prep">Best Free Resources for Coding Interview Prep</h2>
<p>Without further ado, here are the best free resources I have found for coding interview preparation:</p>
<h3 id="heading-freecodecamp-articles">freeCodeCamp articles</h3>
<p><a target="_blank" href="https://www.freecodecamp.org/news/coding-interviews-for-dummies-5e048933b82b/">The 30-minute guide to rocking your next coding interview</a> is a free article available on FreeCodeCamp. Half the value here is in curated lists of LeetCode questions to match every major topic</p>
<p>Here's <a target="_blank" href="https://www.freecodecamp.org/news/javascript-interview-prep-cheatsheet/">another great (and extensive) guide</a> that focuses on JavaScript interviews and goes through all the JS basics you'll need to know. It includes tons of code samples, and moves through the material in an approachable way.</p>
<h3 id="heading-cracking-the-coding-interview">Cracking the Coding Interview</h3>
<p><em>Cracking the Coding Interview</em> is still one of the best resources out there for interview prep, even in 2021. I have heard some people say that it is no longer sufficient, but I have had two coding interviews that were taken out of the book almost verbatim. </p>
<p>Unfortunately, this is not a free resource...but <a target="_blank" href="https://leetcode.com/discuss/general-discussion/1152824/cracking-the-coding-interview-6th-edition-in-leetcode">here is a LeetCode forum that maps every CTCI question to a LeetCode one</a>. </p>
<p>The reason this is acceptable is that they are not perfect mappings. For example, <a target="_blank" href="https://leetcode.com/problems/string-compression/">the LeetCode String Compression problem</a> is not exactly the same as its CTCI equivalent because it has an added constraint. It is actually <em>harder</em> than the CTCI version</p>
<p>If you do choose to purchase <em>Cracking the Coding Interview</em>, the solutions are all freely available on <a target="_blank" href="https://github.com/careercup/CtCI-6th-Edition">GitHub</a>. They are in multiple programming languages, in case you are not a Java developer. </p>
<p>McDowell herself built the repository and committed the Java portion to it, so it is very unlikely the repository will removed due to copyright infringement.</p>
<h3 id="heading-basecs">BaseCS</h3>
<p><a target="_blank" href="https://medium.com/basecs">BaseCS</a> is a great collection of articles that explain computer science fundamentals, from hash tables to sorting algorithms, with custom illustrations, well-written analogies, and light-hearted explanations. </p>
<p>Best of all, every single article is free from the Medium paywall. Had they not been, Joshi probably could have pocketed hundreds, if not thousands of dollars from all her readers.</p>
<h3 id="heading-educativeio">Educative.io</h3>
<p>The Educative.io course on 14 coding patterns is not free, but <a target="_blank" href="https://hackernoon.com/14-patterns-to-ace-any-coding-interview-question-c5bb3357f6ed">a summary</a> is available on HackerNoon and written by an Educative.io cofounder...presumably as either a gesture of goodwill, or a "free sample".</p>
<h3 id="heading-leetcode-questions-sorted-by-programming-pattern">LeetCode questions sorted by programming pattern</h3>
<p>Here is a public <a target="_blank" href="https://leetcode.com/discuss/career/448285/list-of-questions-sorted-by-common-patterns/453408">LeetCode post</a> that maps all 14 coding patterns to respective lists of LeetCode problems.</p>
<h3 id="heading-interviewnoodle-still-in-development">InterviewNoodle – still in development</h3>
<p>Arslan Ahmad is building a consolidated collection of interview preparation articles <a target="_blank" href="https://medium.com/interviewnoodle">on Medium</a> called InterviewNoodle. Just weeks ago, I would have written that this resource is very incomplete, but he has added so much content that I actually think he may now want to divide it into sections.  </p>
<p>This, like Educative.io, is meant to be a “one-stop shop.” That Arslan Ahmad is the founder of <a target="_blank" href="https://designgurus.org/course/grokking-the-system-design-interview?utm_source=google&amp;utm_medium=googAd&amp;utm_campaign=keyword_ad&amp;utm_id=goog1&amp;gclid=CjwKCAiAvriMBhAuEiwA8Cs5lQID0O_VM4qHE-espa4XePw22toAUEPvR2DKp1-s3Vnne9T19JBp1hoCp0sQAvD_BwE">Design Gurus</a> increased my respect for him exponentially, since this means he is attempting to build a free version of an Educative course that makes him money.  </p>
<p>Currently the Medium pages on this publication are not paywall blocked. This could be a coincidence, but for now it's a great resource.</p>
<p>The rest of this article will cover additional resources, though the ones above are my favorites.</p>
<h2 id="heading-additional-coding-interview-prep-resources">Additional Coding Interview Prep Resources</h2>
<h3 id="heading-an-interview-primer">An Interview Primer</h3>
<p>If you don't know what to expect in a coding interview, the "30-minute guide" from freeCodeCamp linked above is a great "primer". Still, it is rather lengthy – even though it takes 30 minutes to just read through it, it would take much longer to actually review and go through its "General tips" section.</p>
<p>This might be just what you're looking for if you want to be really thorough. But what other options do you have?</p>
<p>"Confessions from a Big Tech Hiring Manager" is my single favorite video. It's by "Pragmatic Engineer," and is all about the interview process. </p>
<p>This video has useful and practical advice, but it also conveys the perfect attitude. He argues that you should think of every failed interview as a learning opportunity.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/vFOw_m5zNCs" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h3 id="heading-other-interview-prep-articles">Other Interview Prep articles</h3>
<p>"<a target="_blank" href="https://betterprogramming.pub/if-software-engineering-is-in-demand-why-is-it-so-hard-to-get-a-software-engineering-job-c043a964e463">If software engineering is in demand, why is it so hard to get a software engineering job?</a>" This is a tongue-in-cheek overview of the coding interview process. </p>
<p>If you read it, you should probably ignore the "string compression" story, which does not add much to the article.</p>
<p><a target="_blank" href="https://medium.com/interviewnoodle/the-other-side-of-the-software-engineer-interview-a8772edac0fc">The other side of the software engineer interview</a> is a kind of sequel to the article above, summarizing and responding to Pragmatic Engineer's thoughts.</p>
<p><a target="_blank" href="https://medium.com/illumination/the-responses-i-got-from-a-software-developer-candidate-that-made-me-hire-him-98ff8bf01298">The Responses I Got From A Software Developer Candidate That Made Me Hire Him</a> is an article that provides more insight on the interviewer's perspective, but unlike the two above it is behind Medium's paywall.</p>
<h2 id="heading-whats-the-interview-process-like-in-a-nutshell">What's the Interview Process Like, In a Nutshell?</h2>
<p>If I were asked to summarize all the resources above to you, here's what I would share:</p>
<ul>
<li>I would say that you typically get between 30 minutes to an hour to solve a coding question. </li>
<li>You typically get a choice of programming language like C++, Python, Java, or JavaScript, but not always...in some instances you do not have a choice.</li>
<li>Outside of the coding portion, they are free to ask you pretty much anything, from language-specific questions to favorite projects, but any interview with a coding portion tends to be dominated by it.</li>
</ul>
<p>And here's some general advice to consider: you are going to be dealing with people who may be pretty tired of interviews. Smile if you can. Try to show enthusiasm. Have a conversation, and try to talk to the interviewer the way you might communicate if the two of you were pair programming, but they were more senior.</p>
<h2 id="heading-how-to-start-your-interview-prep">How to Start Your Interview Prep</h2>
<p>I think that for most people starting out in this interview prep process, LeetCode is pretty hard. Here are two possible starting problems, though the best point of entry is admittedly <em>Cracking the Coding Interview.</em></p>
<ul>
<li><a target="_blank" href="https://leetcode.com/problems/fizz-buzz/">FizzBuzz on LeetCode</a>. I recommend it because it should not require any additional interview preparation, and will help you familiarize yourself with the LeetCode platform.</li>
<li><a target="_blank" href="https://medium.com/interviewnoodle/fizzbuzz-68fcdec8d2b2">Here's an article about FizzBuzz</a> on InterviewNoodle so you can learn more what that's about.</li>
<li><a target="_blank" href="https://leetcode.com/problems/jewels-and-stones/">Jewels and Stones on LeetCode</a>. If you are not able to solve this on your first try, then you will have to learn a technique that is useful in many coding interview problems.</li>
</ul>
<h3 id="heading-learn-about-hashmaps">Learn about hashmaps</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/kVgy1GSDHG8" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>There are many more data structures than just hashmaps, but I see these come up in coding interviews so often that I think they deserve their own section.</p>
<ul>
<li><a target="_blank" href="https://leetcode.com/problems/valid-anagram/">Valid Anagram</a> is another good LeetCode "starting point." It does not necessarily require a hashmap, but something that acts like a hashmap</li>
<li>Here is <a target="_blank" href="https://www.youtube.com/watch?v=IRN1VcA8CGc">Nick White solving Valid Anagram</a></li>
<li>This is <a target="_blank" href="https://www.youtube.com/watch?v=70qy6_gw1Hc">Alex Lee</a> using hashmaps in Java. He does not explain the internals of how they actually work, but he provides practical advice on how to actually use them.</li>
</ul>
<h3 id="heading-what-to-do-after-you-cover-the-basics">What to do after you cover the basics</h3>
<p>After you get started preparing and are comfortable with the basics, I would refer back to the resources above. </p>
<p>The 30-Minute Guide and <em>Cracking the Coding Interview</em> (again, there are free LeetCode problem mappings if you do not own <em>Cracking the Coding Interview)</em> both cover computer science fundamentals<em>.</em> And <em>14 coding patterns</em> goes a little bit further.</p>
<h2 id="heading-closing-thoughts">Closing Thoughts</h2>
<p>There is a lot more work to be done when it comes to coding interview preparation resources. It is relatively easy for me to simply point to good resources in an aggregate post, but actually providing comprehensive reviews or my own resource would require an order of magnitude more effort. I haven't gotten there yet.</p>
<p>So for now, there is certainly a gap. The most comprehensive content, in my opinion, can be found in <em>Cracking the Coding Interview</em> and this <a target="_blank" href="https://www.youtube.com/watch?v=70qy6_gw1Hc">Educative.io course</a>. And that's not to mention the plethora of resources someone with a lot of money could afford, from coaches, to coding interview bootcamps, to expensive mock interviews in which the interviewers provide detailed feedback. </p>
<p>That the people <em>behind</em> Educative.io and its "coding interview patterns" course have made efforts to provide free resources, like InterviewNoodle and a HackerNoon article, count for a lot to me.</p>
<p>I personally don't really use sites like GeeksforGeeks or interview resources on Github that are written exclusively in markdown. It would be very useful to build a platform with detailed blog-style explanations <em>and</em> embedded coding platforms, but at that point you would essentially be recreating Educative.io.</p>
<p>Medium provides an interesting case: Some of the best writers can be found here, but they are incentivized to put things behind a paywall. Anyone, in theory, can put up articles without a paywall on Medium the way BaseCS has. But few Medium writers seem to do this anymore.</p>
<p>We need <strong>more</strong> high-quality articles. We need practice problem lists that are continually updated. We need great YouTube content creators, like Nick White, to continue to provide clear problem explanations. </p>
<p>Efforts by BaseCS were largely successful, and my one wish is that it had continued to produce content...but this was all produced by a single person with a full-time job, a podcast, a YouTube channel, and apparently no compensation from Medium.</p>
<p>Not everyone has the same level of access to educational coding interview resources, so I admire the people who have done everything in their power to create free alternatives.</p>
<p>Yangshun Tay, author of "The 30-minute guide to rocking your next coding interview", sent me a personal email a few months after this article was published and shared some more helpful resources.</p>
<ul>
<li>Here's a link to the main <a target="_blank" href="https://www.techinterviewhandbook.org/">Tech Interview Handbook Website</a>, which contains in-depth and structured guides that can really help you prep for interviews. </li>
<li>Additionally, he's published <a target="_blank" href="https://www.techinterviewhandbook.org/grind75">Grind75</a> which generates study plans based on time left, which could also be of interest to your readers.</li>
</ul>
<p>The Tech Interview Handbook currently has about 69,000 stars on GitHub, and the website is the closest thing I have seen to a free, "one-stop-shop" software engineer interview resource.  </p>
<p>Grind75 is designed to be a better version of <a target="_blank" href="https://leetcode.com/discuss/general-discussion/460599/blind-75-leetcode-questions">Blind75</a>, a popular list Yangshun also made that received 3200 upvotes on a LeetCode discussion.</p>
<p>I hope these help you out! Happy prepping.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Implement Binary Tree Algorithms in Technical Interviews ]]>
                </title>
                <description>
                    <![CDATA[ A binary tree is a common data structure used in software development. It is also a frequent topic in technical coding interviews. We just published a course on the freeCodeCamp.org YouTube channel that will teach you all about binary tree algorithms... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-implement-binary-tree-algorithms-in-technical-interviews/</link>
                <guid isPermaLink="false">66b20322297cd6de0bd54648</guid>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Tue, 19 Oct 2021 17:13:24 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/10/binary.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A binary tree is a common data structure used in software development. It is also a frequent topic in technical coding interviews.</p>
<p>We just published a course on the freeCodeCamp.org YouTube channel that will teach you all about binary tree algorithms and prepare you to use them in coding interviews and programming projects.</p>
<p>Alvin Zablan from Structy developed this course. He has created many technical course, including one of the most popular Dynamic Programming courses on the internet.</p>
<p>In this course you will first learn about the theory behind the algorithms and then you will learn how to implement them with code. The algorithms will be taught with images and visualization to help you really understand how they work.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/image-57.png" alt="Image" width="600" height="400" loading="lazy">
<em>This type of binary tree will not be covered in the course.</em></p>
<p>Here are the topics covered in this course:</p>
<ul>
<li>What is a Binary Tree?</li>
<li>Binary Tree Node Class</li>
<li>Depth First Values</li>
<li>Breadth First Values</li>
<li>Tree Includes</li>
<li>Tree Sum</li>
<li>Tree Min Value</li>
<li>Max Root to Leaf Path Sum</li>
</ul>
<p>Watch the full course below or <a target="_blank" href="https://youtu.be/fAAZixBzIAI">on the freeCodeCamp.org YouTube channel</a> (2-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/fAAZixBzIAI" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-transcript">Transcript</h2>
<p>(autogenerated)</p>
<p>Binary tree is a common data structure used in software development.</p>
<p>It's also a frequent topic and technical coding interviews in this course, Alvin will explain binary tree algorithms and prepare you to use them in both interviews and coding projects.</p>
<p>Hey programmers, Hamilton from Shruthi, elk to our course on binary trees, I want to show you how you can do well on those technical interviews that have binary tree problems.</p>
<p>So what I have in store for this course, like usual, we'll go over both the theory pines and binary tree algorithms, as well as of course be more practical and come up with a code implement those algorithms really a one two punch.</p>
<p>For every section, we're going to be sure to draw out a pictures and visualize and truly understand the algorithm on the whiteboard notes are feeling comfortable with that, we'll go over to the code implementation.</p>
<p>So in the description and in the timestamps, you'll be able to find the corresponding exercise, you can practice every algorithm that we go over.</p>
<p>In terms of the prerequisites for this course, I'm going to assume that you're not new to programming.</p>
<p>And maybe you've dabbled in some previous data structures and algorithms.</p>
<p>And you're also familiar with some recursion.</p>
<p>But that being said, I'm going to assume you know nothing about binary trees, and even just trees in general.</p>
<p>with no further ado, let's jump right in.</p>
<p>So first order of businesses, let's actually understand what the word tree even means.</p>
<p>And like the programming concept, right.</p>
<p>So when we visualize a tree, a tree contains many nodes, typically we draw nodes as circles, right.</p>
<p>And these nodes can also point to other nodes.</p>
<p>So here I have one node.</p>
<p>And I could point to some other node, right, I could point to any number of nodes.</p>
<p>So here are the circles, I'm going to refer to them as nodes, and the lines or hours between them, I'm going to call edges, right.</p>
<p>So this is an example of a tree.</p>
<p>And trees can of course, come in many different shapes and sizes.</p>
<p>So here's quite a large tree.</p>
<p>Let's try to understand a few terms we can use during our technical interviews.</p>
<p>And this is something I highly recommend, right? helps if you speak the language, it does show that you have proficiency dealing with the data structure, we could store values within the nodes of our tree.</p>
<p>For now I'm just going to put some letters.</p>
<p>When it comes to your programs, you can store any type you want, you can store integers, numbers, or even other objects.</p>
<p>So because we have a tree, we like to use familial relationships.</p>
<p>In other words, I think of like a family tree, right? So if I look at node B, let's say I call them the parent.</p>
<p>If b is the parent, I know that children of B are just the D nodes, right? their parent and child is like a relative relationship.</p>
<p>Let's say I kind of changed my frame of reference.</p>
<p>And let's say I looked at a as the parent, well, that scenario, then B and C are the children of a.</p>
<p>for the case of the C node, if I think of CSM parent, it only has one child, its lone child being the F node.</p>
<p>So feel free to use that parent child relationship when describing the relationship among nodes within a tree.</p>
<p>Another terminal is a lot in the context of trees is the word root, right? So a root is going to be a node that has no parent.</p>
<p>So in this tree, A is the root because a has no parent, right? There are no arrows going into the a node.</p>
<p>On the flip side of that, if I look at the nodes in DNF, we call them leaf nodes.</p>
<p>A leaf node is a node that has no children, right, so d and f have no outgoing arrows.</p>
<p>Typically, in a binary tree, we're going to have a single root and we could have many leaves.</p>
<p>One thing I want to be sure to do is make sure you generalize your understanding of a leaf, right? So in this particular example, looks like every leaf is two edges away from the root, counting the number of arrows from the roots, any leaf, it could be the case that my leaves occur at different levels, right? So I removed that F node, which case C is now a leaf, right? Although a C is on like a different level than D and E, it's not the bottommost level, it is the case that it's still a leaf, right? a leaf node is just a node that has zero children.</p>
<p>All right.</p>
<p>So with all of those terms out of the way, let's hone in on the real topic here.</p>
<p>Right, I talked a lot about trees.</p>
<p>But really in this course, I want to go over the basics of binary trees.</p>
<p>Right? So let's look at that binary part to begin with.</p>
<p>That's really a dead giveaway.</p>
<p>We know binary has to do with the number two.</p>
<p>A binary tree is a tree where every node has at most two children.</p>
<p>Right? So currently on the screen, I have a binary tree.</p>
<p>If I gave a another child, let's say a third node over here of f, this would be a tree but not a binary tree.</p>
<p>Right? It would be like a ternary tree because I have at most three children.</p>
<p>So let's say I kind of remove that extra node.</p>
<p>Now it's back to a binary tree.</p>
<p>And it could be the case that a node has less than two children but still be a binary tree, right? So if I gave C, just a child of f, this is still a binary tree.</p>
<p>It's if I look at any node within my tree, that node will have 01 or two children, and no one has more than two children, right? So you want to be sure to remember that a node in a binary tree could have less than two children.</p>
<p>All right.</p>
<p>So I'll be the first criteria for understanding what a binary tree is right? It's probably the easiest criteria and most children per node will also want to be sure to add into our definition Have a robust understanding is to also remember that, at least for us in computer science, we think of our binary trees as having exactly one root, meaning there should be only a single node that has no parent, right? Typically when we draw, it would be like the topmost node.</p>
<p>So right now this is definitely so far a binary tree.</p>
<p>If I had some other node in this drawing, like G, right, g also has no parents, I would no longer consider this a classic binary tree, right? So watch out for that.</p>
<p>Let's go on to our final criteria, we also need one more ingredient.</p>
<p>And that's exactly one path between the root and any node, right.</p>
<p>So looking at my example to the left, this is indeed a binary tree that meets all three criteria.</p>
<p>And let's say I chose the root and any node, obviously, there's only one root, so we're definitely considering the a node, let's say I chose some random node like E, this is really a binary tree, then we're guaranteed to have only a single path that connects A to E, a path is really just a series of connected nodes I can travel through, right, so to get from the root a to the node E, I can go from A to B to E, and that would be one path.</p>
<p>And that's the only way to get from A to E.</p>
<p>That's what I mean by exactly one path.</p>
<p>Let's say I chose another node like F.</p>
<p>There is also exactly one way to get from the root to F, and that's just a CF, that would be the only path.</p>
<p>If I added some additional connections or edges within my tree, I can get a scenario like this, this would no longer be a binary tree.</p>
<p>For one, we can see that B has three children, but also does not have a unique path between the route in any node.</p>
<p>For example, if I chose a and the note of f, one way to get there is by going ACF.</p>
<p>But another way to get there would be a, b, c, f, right? And so do watch out for all three criteria when you're considering a binary tree.</p>
<p>Awesome.</p>
<p>So let's look at some smaller examples.</p>
<p>And this is where I think some students tend to struggle with their understanding of binary trees.</p>
<p>So if I took out some nodes over here, this would definitely still be a binary tree, right? Just looking at our different rules, right? Let's say the root node A only had one child would still be a binary tree, right? Because the binary tree only demands that we have at most two children, we still have one root, and we still have only one path from root to any node.</p>
<p>Let's say I have the smallest tree that has a node, which would be the singleton tree, this is still considered a binary tree, right has one route.</p>
<p>And there's not really any pass to be had here except the route to itself.</p>
<p>And every node does have at most two children.</p>
<p>Here we have zero children, right? The final edge case we want to think about is what happens when we have no nodes, right? We consider this as the empty tree.</p>
<p>This is a very special case.</p>
<p>And we should consider any empty tree as actually being a binary tree.</p>
<p>That's going to be very useful when we come up with some algorithms later on, right.</p>
<p>So a common edge case off to consider is what happens when we have an empty tree, that's a tree with zero nodes, right? Let's look at another example.</p>
<p>Let's say I had this structure to take a moment look at it, and see if this meets our criteria.</p>
<p>This would not be considered a binary tree.</p>
<p>So we look at your different criteria.</p>
<p>Looking at the first one, it does have at most two children per node, so that's okay.</p>
<p>But we can't identify exactly one root here.</p>
<p>Remember that a root node is a node that has no parent, right? If you look at every node in this picture, every node has exactly one ingoing arrow.</p>
<p>So that means every node has at least one parent, right? So it doesn't meet that criteria.</p>
<p>And furthermore, there is not exactly one path between the root and any node, because we have a cycle within the structure.</p>
<p>So for example, let's say I was starting at a right and I wanted to travel to see, one way to get there would be to go A, B, C, that'd be one path.</p>
<p>But I could also have another path or I just go around twice and go A, B, C, again, there would actually be an infinite number of paths in this scenario.</p>
<p>Because of that, this is definitely not a binary tree.</p>
<p>And there kind of many reasons for that.</p>
<p>If I had a different example, looking at this one, now I need criteria one and two, right, I have at most two children for every node.</p>
<p>But I also still have exactly one root node here I would consider z the root node.</p>
<p>However, there is not one path between the roots in any node and because I have that cycle.</p>
<p>So these rules are really worth remembering, they're really going to help you solve a much more difficult binary tree problems.</p>
<p>And if you remember these three rules, you can identify different problems in a binary tree framework.</p>
<p>In other words, the hardest problems that you'll encounter in your interviews are problems where they don't tell you straight up what data structure you're dealing with, you're just gonna have to notice the pattern.</p>
<p>In other words, what if I gave you some structure like this, take a moment and figure out if this is a binary tree.</p>
<p>If you look closely, this does meet all of the three criteria to be a binary tree.</p>
<p>I can just treat a as the root because it has no parent.</p>
<p>I can treat nodes D and F as the leaves because they have no children.</p>
<p>I just drew this in a pretty interesting way.</p>
<p>Right? If you really range things in a classical binary tree sense would look like this.</p>
<p>More importantly, this has the same relationships as a previous drawing, I just show it in a top down fashion, right? So no matter what do you understand these three rules for a binary tree, right? Because sometimes may not be as explicit as a nice triangular shaped drawing.</p>
<p>Awesome.</p>
<p>So we've talked a lot about the theory of how to, you know, look at and reason through some binary tree definitions.</p>
<p>Let's go ahead and start to talk about how we could represent binary tree programmatically.</p>
<p>In other words, how can we do this in some code? Well, no matter your programming language of choice, I think you're going to represent these as objects.</p>
<p>In other words, every node here is going to be some objects.</p>
<p>So it could be like an instance of a class, the properties only to store within this object would be the current value.</p>
<p>So I need something to store like the A of my current node.</p>
<p>But I also need to refer to some children.</p>
<p>So we'll also need some left and right pointers to the children, right, those are just going to be some properties on that object.</p>
<p>In a classic binary tree is very common to refer to the two children using a left and right direction.</p>
<p>Notice that some nodes here, like the C node, they're only going to have one child, right? c only has a node dot, right? It does not have a left.</p>
<p>So we're gonna have to use some empty value, like null or undefined.</p>
<p>To represent a child that doesn't exist, right? Especially for a node like he, he has no left and also no, right.</p>
<p>So here's what we'll do, let's go ahead and hop into my text editor.</p>
<p>And I'll show you how you could represent a binary tree programmatically.</p>
<p>So transition, here we are in my text editor.</p>
<p>Let's start by creating our node class, right.</p>
<p>So you'll be able to follow along any language that you choose, I'm going to do mine in JavaScript, right.</p>
<p>So I think the best way to present a node is just to use some class.</p>
<p>So hopefully familiar with some classic class syntax, let's create a node class, there's going to be a quick constructor, I think would be valuable to take in the initial value that's going to be stored within the notes, I'll take the ns a constructor argument, I can just set this dot Val to that value, and also need two more properties, one for my left, so I can say this dot left, I'm gonna initialize it to null, that means by default, a node will have no left child the same way.</p>
<p>By default, a node will have no right child, right? So when you use no to represent children that don't exist over here, awesome.</p>
<p>That's all you need to create, you know, a baseline binary tree, right, we're going to use this class a lot during the course to test our algorithms.</p>
<p>So I'm going to create a node and eventually wire up a tree.</p>
<p>Well, I'll just call my constructor few times, I'll create different nodes, I'll just store them to some variable names.</p>
<p>And of course, a new node to create new instance of node, and I'll store some value inside, I'm going to store some characters inside, I'll create a bunch of these different nodes, what we'll want to be sure to do is make sure that you also set their pointers properly.</p>
<p>So I'll give each of these some different values ABC, D, E, also do F.</p>
<p>And then I'll just manually for now set their pointers properly.</p>
<p>So what if I did syntax like this is since I'm in JavaScript, I can easily assign these pointers, I can say, A's left is going to be B.</p>
<p>I can say A's right? is C can also say B's left D.</p>
<p>and then B's right is E.</p>
<p>And maybe Finally I can say C's right is F.</p>
<p>So by doing these assignments, I'm connecting some nodes together, I should end up with a structure like this right? Have a as a root, because nothing points to a it has no parent.</p>
<p>But a has two children of the NC.</p>
<p>And then along with that, B has two children of D and E.</p>
<p>Finally, C just has a right child of f, this is actually the same tree that we looked at a lot during the whiteboard session, right? And that's how you can represent that same tree programmatically, right? So I always think it's valuable to also try to visualize your trees, right? Obviously, we created this tree in a very manual way, probably in the long run will create applications to just maintain and create trees dynamically during some input.</p>
<p>But for now, we'll start by creating all of our trees in this very kind of static way.</p>
<p>Right? And so with that, now that we have an understanding of how to represent a binary tree, let's go head back to the whiteboard.</p>
<p>And I can show us our very first algorithm.</p>
<p>Hey, programmers, Alvin here, right? Now I want to go over this depth first values problem.</p>
<p>So this will be a good review of the depth first traversal algorithm.</p>
<p>So what do you want to do in this problem? Well, what we want to do is take in a binary tree, and in particular, your function is going to take in the root of the binary tree.</p>
<p>And just recall that given the root node of a binary tree, we know that that node is going to have pointers to its left and right children, which may point to other nodes.</p>
<p>However, if let's say a node does not have left or right child, then its point is going to be set to No.</p>
<p>So that's how I represent our binary tree programmatically.</p>
<p>But for now, let's just stick to the visual represent of our tree.</p>
<p>So for a depth first traversal, we could start with the root node of a, what we'll do is we'll just add that to some collection.</p>
<p>And we're going to have to maintain these in a very particular order.</p>
<p>And then from there, according to a depth first traversal, I could go to B.</p>
<p>And here's where we make our really important decision, right, we can either go to C, or D, if I'm doing a depth first traversal, I need to go deeper in the tree before I move laterally.</p>
<p>So that means I go from B to D.</p>
<p>And once I bought them out at D, there's nowhere deeper, I can go from D.</p>
<p>And so now I move laterally to the E node.</p>
<p>And this pattern continues, right? I don't have anything deeper from E.</p>
<p>So now I go to C.</p>
<p>And then from C, I go to f.</p>
<p>So this would be a depth first traversal on this binary tree.</p>
<p>Notice that it goes A, B, D, E, C, F, and again, the really important characteristic is we must go deeper in the tree until we can't anymore and then we can go across the tree.</p>
<p>That being said, How can we actually managed to implement this algorithm.</p>
<p>If you're familiar with depth first, traditionally, then we know that it's going to use a data structure like a stack.</p>
<p>So let's get situated over here.</p>
<p>So we'll trace through that again.</p>
<p>But this time, taking a really close look at how we can use a stack to accomplish that direct order.</p>
<p>And so just recall that a stack is a sequential data structure where we can only add things to the top of the stack and remove things from the top of the stack.</p>
<p>So a really important characteristic is we can't really insert or remove elements from anywhere but the top of the stack.</p>
<p>So when I add things to the stack, I was added to the top like this.</p>
<p>When I remove things, it's also from the top like this.</p>
<p>Alright, so when I begin at this depth first traversal algorithm, I'm going to start with the root node of a.</p>
<p>And by default, I really just take that root node and I just store it on my stack.</p>
<p>So it's the only thing on my stack right now, I'll use these rectangles represent my different stack frames.</p>
<p>And really in my program, that would just mean storing the actual instance of node or some pointer to it.</p>
<p>Cool.</p>
<p>And then from there, I actually begin my main algorithm.</p>
<p>So the main flow of a depth first traversal, we'll check if the stack is empty.</p>
<p>Right now the stack is not empty, because I have at least one element.</p>
<p>And so what I do is I start by removing or popping the top element of my stack.</p>
<p>So I'm gonna remove the A, and I'll label that as my current node being explored.</p>
<p>And when something leaves the stack, then I can consider it being visited right now.</p>
<p>So I need to list out my values, because that's the whole point of this problem, right? So by now I've just visited the a node.</p>
<p>At this point, I can look at that nodes children now.</p>
<p>So I look at the a node in the tree, and I see that it has a B child on its left and a C child on its right.</p>
<p>And from there, I push or add those two children to my stack.</p>
<p>So I'm going to put c first, and I put B afterwards.</p>
<p>And notice if I push my right child first, followed by my left child, that makes it such that my left child is at the top of my stack, which means that I would hit them next.</p>
<p>And that actually ends on my first iteration of this depth first traversal.</p>
<p>And now I asked that same question is my stack empty, it's not.</p>
<p>So I removed the top of my stack, I'll call it B, my current, which means I could print it out or insert it into my values list.</p>
<p>Nice.</p>
<p>From there, I consider B's children, B has two children.</p>
<p>So I add them both, I push E, followed by pushing D.</p>
<p>That ends that iteration.</p>
<p>Now something interesting happens, my stack is still not empty.</p>
<p>So I know I removed the top, so I call D, my current, I add D to my list of values.</p>
<p>But if I look at these children, it actually has no children, right, and so there's nothing to add to the stack from here.</p>
<p>And so technically, I finished this iteration.</p>
<p>And now I still have stuff on my stack.</p>
<p>So now I pop he off the top of my stack.</p>
<p>Same thing as before, right, I add to my values, he has no children.</p>
<p>So I'm done with that iteration.</p>
<p>Finally FC, I removed C from the stack, and I printed out in my values.</p>
<p>And then at this point, I see that the C node only has one child, so I'm just going to push the children that exists so I would push the F node onto my stack.</p>
<p>And that's a really important thing to remember when it comes to implementing your depth first traversal you're going to have to check if your children exist before you add them to your stack.</p>
<p>And now on the final final iteration, we have the F node we remove it from the stack, we add it to our list of values f has no children.</p>
<p>And so I finish this iteration and now my stack is empty and I will just exit right once the stack is empty.</p>
<p>I know that I must have traveled through the entire binary tree.</p>
<p>So there we have it and we do get the correct output over here.</p>
<p>So just by using a stack and just obeying the rules of the stack, that is we got pushed to the top and removed from the top we will get the correct order.</p>
<p>important thing to remember is you should add your values into your like values list whenever something leaves the stack.</p>
<p>That being said, What can we say about the time and space complexity of this algorithm? Well, it's actually pretty straightforward.</p>
<p>Let's say we define n as the number of nodes in this binary tree, then we can say that the time complexity of this is O of n.</p>
<p>And why do I say that? Well, we're just going to add that every node eventually to our stack.</p>
<p>And that nodes also going to leave the stack exactly once.</p>
<p>So it's not like we're double visiting any of the nodes.</p>
<p>So I'm guaranteed to just run in O of n steps.</p>
<p>In a similar way, we can see that the space complexity is O of n, the only thing we stored was really the stack, which is a linear data structure.</p>
<p>And we know that we're not going to put ever more than n things on the stack.</p>
<p>So overall, we have a linear time and space solution for this depth first traversal problem.</p>
<p>All right, I think we have a good understanding about the approach for a depth first traversal.</p>
<p>Now let's go ahead to the walkthrough video.</p>
<p>And we'll implement this one in a few ways together.</p>
<p>Hey, programmers, Alvin here, right.</p>
<p>And I want to go over a JavaScript solution for this depth first values problem.</p>
<p>And so we're going to do here is really just implement that same strategy that we traced through in the approach video, pretty much to the tee.</p>
<p>And we'll start with the iterative version.</p>
<p>And that means of course, we will solve this one in two different ways, right, we're gonna solve it iteratively first, and afterwards, we'll go ahead and solve it recursively.</p>
<p>Alright, so let's jump right in over here.</p>
<p>Like we said, in the approach video, we know that the iterative version really relies on us creating a stack.</p>
<p>And for most of your programming languages, you can just go ahead and use your like array data structure for that.</p>
<p>So I'm going to use just a plain old JavaScript array, I'll go ahead and name this one stack.</p>
<p>And we can just use an array to represent a stack as long as we stick to two particular methods, right, I'm going to use array push, which adds to the end of an array, and also array pop, which removes from the end of the array as well.</p>
<p>So I'm going to consider the end of my array to represent the top of my stack.</p>
<p>Cool, we'll go ahead and do is initialize the stack with the root node on top of it.</p>
<p>Nice, then I can have my main loop for the algorithm.</p>
<p>So we know that we need to keep running the algorithm while there's stuff on our stack.</p>
<p>So I can just check while stack dot length is greater than zero.</p>
<p>So while I have at least one element on my stack, there is some work to be done here.</p>
<p>And that will step through a single iteration of this algorithm, we know that we start interation by just removing the top of our stack, in other words, stack dot pop in JavaScript, that will also return us the element that we just removed.</p>
<p>So I'll call that my current const current.</p>
<p>And that is going to be an instance of nodes, it's going to be one of these objects.</p>
<p>Cool.</p>
<p>So now that I remove this element from the top of my stack, let's say for now, I just I don't know, print it out, maybe we'll kind of debug this one as we go.</p>
<p>So console dot log, current dot Val, because I know that every instance of node has a dot Val prop on the inside.</p>
<p>And then from there, I need to add this nodes children.</p>
<p>So you might go ahead and guess that to do that, we could just do stacked up push, I'm going to push the left child, one out here, so node or current dot left, followed by the right child.</p>
<p>But we also need to make sure that these children exist, right? Look at the prompt.</p>
<p>There could be instances, for example, like this C node over here, this C node only has a right child, but has no left child, right.</p>
<p>So what I don't want to do is push C's left, because that'd be pushing no onto my stack, which would give me an error later on.</p>
<p>Right? So I want to only push the children if they exist.</p>
<p>And I need to individually check if the left exists and push it and also if the right exists and push it, I'm just going to add some guard statements for both of these.</p>
<p>So we'll go ahead and insert will say, all right, if the current has a left and right side, current dot left, called justice for the right hand side, cool, maybe we can inline this, if you prefer.</p>
<p>Alright, so I'm going to only push the children if they exist.</p>
<p>And that should actually be the heart of our depth first algorithm.</p>
<p>So we're not putting our values inside of an array like the problem asks, but we should at least be able to see the correct order of printing here, because I'm going to print a nodes value as soon as it is removed from my stack.</p>
<p>So I'll go ahead and actually maybe bring in maybe one literal test case, so I could just steal this little stub over here.</p>
<p>And this will just print out the values.</p>
<p>Right, so I'll test this I can hit Run, if I hit Run, it's just going to execute this file just like a script.</p>
<p>So it's not going to run any automatic test cases, just going to run my file as is.</p>
<p>So if you want to test it in this way, kind of in a manual way, you're gonna have to be sure to call your function.</p>
<p>I do have a console dot log on the inside.</p>
<p>So I'll just run Run this manually.</p>
<p>And when I do that should see some output here looks like node is not defined because I forgot to bring in my class definition.</p>
<p>So I'll do that.</p>
<p>give that a go.</p>
<p>Alright, so looking at our output, we didn't get our exact depth first traversal, like we expected, right? I got ACF, B, D, if you take a look at what we really printed out, we technically did print out a depth first print, but we favored the right hand side.</p>
<p>So we did a, c, f, and then B, E, D.</p>
<p>So let's say we really wanted the left to right version of this, and all you have to do is flip the order that you push the children, right, it should be clear by looking at these two lines, right? When I add my children looks like I push the left child, and then the right child.</p>
<p>If you push the left child first, and then you push the right child afterwards, that means that the right child's going to be on top for the next iteration.</p>
<p>So if you do it like this, this will favor the right hand side and travel through it first.</p>
<p>But if you did it like this, now you'd be actually iterating to the left branch first, toward the right.</p>
<p>So with that small change, let's just see what our print is.</p>
<p>And there we have a nice AB de ECF.</p>
<p>However, in this problem, they want us to actually return those values in an array.</p>
<p>So I can kind of get rid of this little Manual Test over here, I don't need this class definition anymore.</p>
<p>And now instead, I'll just gather up all of my values in some results array.</p>
<p>So I'll say, maybe result over here starts as an empty array.</p>
<p>And then as I pop elements from the top of my stack, instead of logging them, I'll go ahead and do result dot push, and I'll push that value into the result array.</p>
<p>Once I'm done with this while loop, that means my entire tree has been explored.</p>
<p>which case I can return, make sure I spell it right, return my results.</p>
<p>Cool.</p>
<p>So this should be a nice solution, it's actually run the test cases on this.</p>
<p>give that a go.</p>
<p>So it looks like we're doing pretty good.</p>
<p>But for this very last example, looks like we're getting can't read property Val of na, and that's running test case 04.</p>
<p>So if you actually go into the prompt, those test cases are actually laid out explicitly over here.</p>
<p>So I want to go to zero for now let's look at the zero for test case.</p>
<p>They go ahead and they pass my function, no, right kind of representing like an empty tree or an empty node.</p>
<p>And we can kind of trace it what happens here for our code.</p>
<p>Let's say that root was null.</p>
<p>That means when we initialize our stack, our stack literally contains like a null value.</p>
<p>So it's not even an instance of note just now.</p>
<p>So that means when I entered this while we're going to check, you know, Do I have anything in my stack, and I do because my stack length is one.</p>
<p>And then when I pop, the top element of my stack current is going to be no, then on this line 14 it says null dot Val.</p>
<p>And that's actually where our code explodes, right on line 14, right? You can't reference property Val, of null.</p>
<p>And so to handle this scenario, we want to make sure that we actually never allow anything No, to enter the stack.</p>
<p>It's kind of why we had this guard over here.</p>
<p>mentioned also be true for even the top level route, in case they give us the empty tree.</p>
<p>kind of seems like a corny, you know edge case.</p>
<p>But this is a pretty common one, when you actually go into your interviews, right? What happens if you have an empty input.</p>
<p>And so I'll just guard that explicitly, I'll go ahead and check, hey, if my route, so if my entire tree is empty.</p>
<p>So if route equals null, then what I'll do is just return an empty array, right? Because that means there are no values inside of it.</p>
<p>And that actually is the expected answer, according to this, right should return an empty array.</p>
<p>So let's give it a go now should be pretty good.</p>
<p>Nice.</p>
<p>And there, we have our nice iterative solution for this depth first values problem.</p>
<p>Alright, so here's what we'll do.</p>
<p>That was one solution.</p>
<p>Let me show you another way.</p>
<p>let's implement this.</p>
<p>And that would be our recursive flavor.</p>
<p>So I'll just kind of redefine it down below.</p>
<p>And I actually recommend practicing both versions, because they're going to serve as like the basis for which you solve a lot of different tree problems.</p>
<p>And so when I think about the recursive version, like all of our recursive code, I must think about the simplest case of my input, and that will act as my base case, right? So in the case of a binary tree, the simplest tree you can be given is going to be the empty tree or just a no root, right? So it's not even going to be about a node that's single node right inside of a binary tree.</p>
<p>It's going to be about an empty tree, right, a tree with zero nodes.</p>
<p>I'm going to check if my route is no, and I have an empty tree.</p>
<p>And I think about this base case, as if it's its own input, because it really is right and so if someone They asked me to give them back in array of all the values in the empty tree, it's still the case that this must be an empty array, right? Because there are no values, there's even any nodes and the empty tree.</p>
<p>And then from there, I can generate my actual recursive call, right.</p>
<p>And I know what I call my stuff recursively.</p>
<p>That means I have to reference a function and again, go ahead and invoke it.</p>
<p>And I'm going to call upon root dot left, as well as root dot, right? So this would, this call over here would give me back an array containing all of the values in the left subtree.</p>
<p>And this will give me an array of all the values in the right subtree.</p>
<p>And so let's say I see these into their own variables respectively, you don't have to do this part.</p>
<p>But I'm kind of a fan of it, especially if it's the first time implementing this.</p>
<p>So I'll call this my left values.</p>
<p>I'll call this one my right values.</p>
<p>And here's how I'm able to kind of quickly create recursive codes all about taking when I call is a recursive leap of faith here.</p>
<p>So let's say we're stepping through test 00.</p>
<p>And so this is our tree visual, right? So we know that our root is going to be a node.</p>
<p>So when I actually make this top level call, this base case does not fire.</p>
<p>And so I make my recursive calls, right? I know when I do depth first value, or values, rather, let me fix that depth first values of root dot left, that means I'm going to be passing in the B node, right, and here's how I have to actually pretend my code behaves, I'm just going to get back the correct result from this call, right? So if I passed in the B node into this call, what I expect back is the full array representing the depth first traversal of that subtree, starting at B, right.</p>
<p>So if I got correct data over here, what it would look like is just B, D, and E.</p>
<p>That would actually be the full depth first traversal, from this subtree, right.</p>
<p>And I'm kind of doing that just mentally, or I know the expectation for this algorithm, it's going to be a similar story for my right call, right? If I'm at a So A is still my route, and I passed in my right child See, to this call, what I expect back is just an array of CF, which would be the depth first traversal of that left subtree.</p>
<p>And now that I have, you know, my left subtree values and my right subtree values, I have to think about how to combine it all together, right? How do I work myself into that output by combining both of the results from my children, right, what I need to do is really just take myself put it in the array, followed by my left children, followed by my right children.</p>
<p>So I can do some nice JavaScript syntax for that whenever returning the right when I throw myself in there, so I'm going to throw in a root dot Val, that's myself.</p>
<p>So that'd be like the a node that I just take all the values in my left result, put them in here and just use the spread operator to unpack that array.</p>
<p>And I'll do the same thing for the right values of CF, right.</p>
<p>So dot dot, dot, spread out right values just so I return a single array, and this pattern itself does match this output, right, kind of taking the leap of faith and assuming correctness from these recursive calls over here, right, I have a, and I plug in substitute B, D, E, and then for the right, I have CF.</p>
<p>And even before we run this, I'm not going to, you know, assume too much JavaScript knowledge.</p>
<p>So maybe you're kind of new to this spread operator.</p>
<p>So in general, super quick aside over here, let's say had an array of some stuff.</p>
<p>So I'll say, peeps there and some people over here.</p>
<p>So we'll throw in fleabay, we'll throw in Jason, throw in Raj, throw in heavy.</p>
<p>And what I can do is whenever I have an array, I can just use a spread operator to kind of unpack that array.</p>
<p>So for example, I can say const will say new peeps.</p>
<p>And I'll create a new literal array.</p>
<p>So whenever I say square brackets, it gives me a new array literal.</p>
<p>And what I'll do is, I don't know, put an element at the front, we'll call it Alvin.</p>
<p>That'll spread out the elements of peeps, right? So just imagine I took all of the elements here and just remove the brackets.</p>
<p>That way I don't add any initial nesting.</p>
<p>And then at the end, I don't know I can add someone else.</p>
<p>Like, right? Well, console dot log, what new peeps looks like so I'm not gonna run the test cases, we're just gonna run this file as a script, just so we can review this spreads index.</p>
<p>So if I give that a go, we kind of make this bigger.</p>
<p>Notice that I have correctly spread things out right? Have Alvin at the front, and I have all of the things from peeps in the middle, right, followed by Brian at the end.</p>
<p>So you can do this.</p>
<p>You can also use like the concat method on arrays.</p>
<p>You're probably going to see me use this spread syntax a lot because I'm kind of a fan, right.</p>
<p>But with that in mind, let's go ahead and actually test this code.</p>
<p>So we'll run all the test cases.</p>
<p>Nice.</p>
<p>And this is another working solution for our depth first values.</p>
<p>And it should be pretty natural that we can solve this problem also recursively.</p>
<p>So I know that the iterative solution for this depth first traversal requires a stack data structure.</p>
<p>And I know whenever I write recursive code, under the hood, your programming language is actually going to track all those recursive calls, using the call stack, right? That call stack behavior gives you the same type of ordering, which is really convenient.</p>
<p>Cool.</p>
<p>All right.</p>
<p>So before I send you off on the next problem, I want you to actually practice both solutions for this depth first values code, it's going to be very necessary to actually master some later concepts that are coming right up.</p>
<p>So do spend some time on this practice makes perfect, right, and I'll catch you in the next one.</p>
<p>Hey, programmers, Alan here, right? Now I want to go over this breadth first values problem.</p>
<p>So it's really just going to be a little variation off of the depth first one we just did, of course, but it's really important that moving forward for all of our tree algorithms and other data structures, that we have both versions down pat.</p>
<p>So in this problem, we're going to take in a binary tree, once again, very classic binary tree structure, this time, I want to return an array or a list of all the values according to a breadth first traversal order.</p>
<p>So a breadth first traversal starts with the root node of a, so that's nothing new.</p>
<p>And then from there, I could go to B.</p>
<p>So right now I have my a node, and also my B node.</p>
<p>And here is where we diverged from our previous problem in a breadth first traversal.</p>
<p>And breadth just refers to like the width of something I travel across before I go deeper.</p>
<p>So in our breadth first traversal, I'm gonna move to C and not D for now.</p>
<p>So I add my C node c value to my list.</p>
<p>And then from here, once I finished this entire level, and there's nowhere to go across the tree anymore, now I could go downward to the next level.</p>
<p>Now I have D, and then E, and then F.</p>
<p>So they're really important distinction here is the breadth first traversal starts with ABC, whereas the depth first traversal would have started A, B, D.</p>
<p>That's a really, really important distinction.</p>
<p>And so how can we go about implementing the breadth first version of this? Well recall that the depth first used a stack data structure, well is the case that the breadth first is now going to use the queue data structure, really just the partnering version of that structure.</p>
<p>And so let's kind of step through that in a more programmatic way.</p>
<p>So I'm going to use and track my queue.</p>
<p>And just recall that a queue has no sense of direction to have the back of my queue and the front of my queue, things enter the back of the queue, and they leave the front of the queue.</p>
<p>Right.</p>
<p>And so no one gets a skip line either.</p>
<p>So this gives me a nice fair ordering, think of a queue as just like waiting in line at checkout at a grocery store or something.</p>
<p>So how do I begin my algorithm, I'm going to start by initializing my queue with the root node.</p>
<p>So I'm just gonna start with a on my queue.</p>
<p>And then from here, now I can begin my main algorithm.</p>
<p>So my main algorithm should check on every iteration is my queue empty, right now it's not because I have at least one element.</p>
<p>And so I remove the front element of my queue.</p>
<p>And so we know that a would be removed, and we label it as our current.</p>
<p>A node being explored when something leaves the queue and is marked as our current will say that now it's being visited.</p>
<p>So I would add a to the running list of my values.</p>
<p>Then from here, I need to look at his children.</p>
<p>He has two children B and C, I need to go ahead and add them into my queue.</p>
<p>And so let's say I added B into the queue first, followed by C.</p>
<p>Notice that C must enter behind B, right.</p>
<p>And now I finished this iteration.</p>
<p>At this point, I have the next iteration of my algorithm, I take the front element of my queue, and it leaves, right So b is now my current, I add B to my running list, then I look at B's children of D, I push D followed by he behind it.</p>
<p>At this point, I have another iteration to do right.</p>
<p>And it's so on so forth.</p>
<p>From here, see leaves the front of my queue, I add it to my list of values, and I look at sees children see only has one child.</p>
<p>So for that child that exists, I go ahead and add them to the back of my queue.</p>
<p>And it's really important that I added to the back right at this point had my next iteration.</p>
<p>At this point I continue, my queue is still not empty, so I still have some stuff to remove.</p>
<p>So D leaves in front of my queue, I add it to my list of values.</p>
<p>Since D has no children, there's nothing to add here.</p>
<p>next iteration, he leaves the front of my queue, I added to my list of values, no children, so I don't need to add anything.</p>
<p>And finally f leaves the front of my queue, I just add it to my list of values and again, f has no children.</p>
<p>So by now my queue is empty, which must mean that, hey, I must have completed the algorithm, right? There are no more nodes to explored, I explored and added every single node to my list of values.</p>
<p>All right, and this output actually looks correct, right, I get abcdef, just like we say.</p>
<p>But what about the complexity of this algorithm.</p>
<p>So let's take a closer look over here.</p>
<p>Well, we know from the get go, that n is going to be the number of nodes in this binary tree.</p>
<p>So that will be the term for our sides of input.</p>
<p>And we can say that the time complexity is simply just O of n, roughly, because we know when it comes to visiting these nodes, and you know, using our loop, we're going to add every node to the queue once, which also means that that node is going to leave the queue also wants, so it's not like we're double adding a node to the queue, right, we're not going to double visit any of these.</p>
<p>In a similar way, the space complexity is going to be O of n at most, because, you know, we're just going to add at most to all of the nodes into our queue.</p>
<p>And in general, it's probably going to be less than Oh, event space in terms of how much space we use in our queue.</p>
<p>An important thing I'll just mention right now that in regards to the time complexity of this one, here, we're going to say that the time complexity is O of n.</p>
<p>And that's if we can assume that adding something now to the queue runs in constant time.</p>
<p>And removing something from the queue occurs in constant time.</p>
<p>So depending on how you implement this, if you use actually, a built in an efficient queue data structure, you will get this O of n time complexity for our breadth first.</p>
<p>But if you use a less optimal, like data structure, maybe not a perfect queue, then you might have an actual worse complexity.</p>
<p>So again, this time complexity of O of n assumes that we have a maximally efficient queue that has o of one add and remove operations.</p>
<p>With that being said, I feel pretty good about coding this one up.</p>
<p>I'll catch you in the walkthrough video, and I'll show you a few different ways that's implement this one.</p>
<p>Hey, programmers, Alvin here, right now I want to walk through the JavaScript solution for this breadth first values function.</p>
<p>So hopefully, you just finished the depth first version, in which case, this one should be pretty much a cakewalk.</p>
<p>But of course, we will still go through the motions of it, because it's going to be useful to solve much harder problems later on, as you always hear me say, Alright, so to tackle this one, we'll start with our queue data structure, right? So nothing fancy in JavaScript, what I would do is just use an array and just stick to using very specific methods, right? So I'm going to create an array, I'll call it my cube.</p>
<p>And we're going to initialize that queue with the route on it by default.</p>
<p>And we'll also guard against upfront is imagine they gave us an empty tree to begin with.</p>
<p>So in other words, the initial route is no, which case it would be like this test 04.</p>
<p>And they just want us to return an empty array.</p>
<p>So I'm going to guard for that explicitly.</p>
<p>So I'll check Hey, is my route No.</p>
<p>And if it is, just go ahead and return an empty array like that.</p>
<p>Nice.</p>
<p>Then from here, I need to start in my main loop from algorithm.</p>
<p>So I iterate a while my queue is not empty, just like we spoke about in the approach video, right? So while q dot length is greater than zero, then keep on going.</p>
<p>Now I begin a single iteration of this algorithm by just removing the front of my queue, right? So it's really up to you which methods you use, you just need to make sure you remove from one end and add to the opposite end.</p>
<p>So for me, I'm going to treat index zero as if it's the front of my array, I'm going to treat the last index as if it's the back of my array, right? So if I want to remove the front and say, array dot shift, or for me right now, Q dot shift, that removes the front also returns to me, that element, so I'll call that my current note, x.</p>
<p>And then from here, I need to add this node children into my queue.</p>
<p>And that'll give me my main flow for this breadth first traversal.</p>
<p>Right.</p>
<p>So I'm going to go ahead and check, hey, if my left child exists, so if, let's say current dot left, that is not know, then what I should do is go ahead and push that into my queue.</p>
<p>So I'll say q dot push my current dot left, and it's just going to be symmetric for the right hand side, of course.</p>
<p>So if the right exists, then push the right into the queue.</p>
<p>Just like that.</p>
<p>Awesome.</p>
<p>And so that looks pretty good.</p>
<p>And then from there, I actually want to store the nodes I visit in an array for the final return just like the problem asks, so nothing too fancy.</p>
<p>I really want to insert some code over here about and so I'll create a result array, I'll call it values, sort of empty whenever something leaves the queue.</p>
<p>I'll just take that and push it into my values.</p>
<p>So I say values dot push.</p>
<p>I'll push that current Val into my queue.</p>
<p>And do note that, what you can't do is just take like the queue and treat it like your final return value, it must be a totally separate thing, right, I use the queue just for the sake of traveling through in a breadth first order.</p>
<p>And the order that you visit is actually derived from the order in which things lead the queue.</p>
<p>So that's why I'm doing it over here, right, as soon as something leaves a queue, that's what I considered visited.</p>
<p>So I added to my values list.</p>
<p>Nice.</p>
<p>And after my while it's done running, I'll go ahead and return my entire values array.</p>
<p>So let's give this a test.</p>
<p>I'm gonna run all the test cases, what we get, have a few test cases to pass.</p>
<p>And there we have it.</p>
<p>Here's a nice iterative solution for our breadth first traversal.</p>
<p>Just something I want to mention, by the way, let's look at the prompt.</p>
<p>So looking at, I don't know, like the very first example, in this kind of rendition of breadth first, what they asked us to do is really give us a breadth first traversal, that moves from left to right, so notice it goes A, B, C in terms of the resulting output, and not a CB, right, those would both be technically correct, start to a breath first.</p>
<p>And then you can kind of choose depending on what problem you're solving, whether you want to go left to right or right to left.</p>
<p>For me, because I push the left followed by the right, that means the left is going to leave the queue first, right, because remember, the queue is just like a line and checkout.</p>
<p>So if someone enters first, that is the left enters first, they going to be served before the right go.</p>
<p>And you can just flip these around.</p>
<p>And I'll give you the right to left universal goal.</p>
<p>So depending on what your problem warrants, you can always manipulate that code a little bit.</p>
<p>And this is actually probably like the only solution you can have.</p>
<p>You know, maybe aside from just some superficial changes to like the code style, this is going to be your go to and only go to solution for a breadth first traversal on a binary tree, right? A common mistake I see people try to do a lot is there is not really a straightforward way to implement a breadth first traversal recursively.</p>
<p>And that should make some sense, because a breadth first traversal needs a queue order right needs to use a queue.</p>
<p>If you write any recursive code, you know, under the hood, it's using a stack.</p>
<p>And so that stack versus queue is really just going to fight against you.</p>
<p>And you're going to have a really tough time trying to implement the correct ordering.</p>
<p>So always just writes the iterative version for your breadth first traversal.</p>
<p>Alright, so I recommend before you hop into the next video, make sure you're able to write this code on your own, because we are going to level up difficulty a little bit, but I'll catch you in the next one.</p>
<p>Hey programmers, Alvin here, right now I want to walk through the approach for this tree includes problem.</p>
<p>So the premise of this problem is I'm going to give you a binary tree, and also a target value to look for.</p>
<p>I just want you to tell me True or false? Is that target value found within the binary tree? So for this particular example input, the answer is obviously true or Yes, right, you could definitely find e within this binary tree for give you another target value like j, you would respond with false, right? Because that value j is nowhere to be found within the binary tree.</p>
<p>And really what I'm asking you to do here is we're stepping through the canonical like breadth first search and depth first search problems.</p>
<p>And I think I'll walk through both approaches for you right now.</p>
<p>So let's say I was testing or I wanted to trace through rather of the input where target was IE, how can I go about attacking this one, right? We know that in most of these problems, when they give you a binary tree as input, they're only going to give you really the root node.</p>
<p>But that being said, if you have access to the root node, then you know you have access to all nodes that comprise of the tree, right.</p>
<p>So what I can do is just perform any of my traversal algorithms.</p>
<p>So maybe to get going.</p>
<p>Now let's just do either the breadth first search or the depth first search iterative style.</p>
<p>So I think for this trace, I'll stick to the breadth first version, which means we're going to use a queue, right? So as we trace through this, I'm thinking about this one iteratively.</p>
<p>Right now, hopefully you recall from our previous problems when it comes to your breadth first traversal, you start with your root node on your queue.</p>
<p>And when something leaves the queue, you mark it as your current right.</p>
<p>And here's where I work in the new logic for this, this particular problem.</p>
<p>When something leaves the front of my queue, I'm going to check Hey, is that current value the same as my target value, so is a the same as E.</p>
<p>It's not.</p>
<p>So I have not found the thing I'm looking for, right? And what I can do is now consider his children.</p>
<p>Right? So I look at his children.</p>
<p>They both exist, I add them to the queue.</p>
<p>So I'd be to my queue that I add see to my queue.</p>
<p>And now I'm on to my next iteration right? The front end element B leaves a queue, and I have to check, hey, is B, my target, it's not right my target t.</p>
<p>So I keep running, I look at B's children.</p>
<p>So I take that D and added it, I take the E and also add it.</p>
<p>And this process just continues, see leaves front of my queue is see my target, it's not.</p>
<p>So keep going, I would add C's children to my queue.</p>
<p>So I just add F to my queue.</p>
<p>And this process continues.</p>
<p>And so d leaves the front of my queue I check is d my target, it's not, and D has no children to add, right? Recall that in our breadth first traversal, I only add the children if they exist, because I don't want to add any, like null pointers into my queue.</p>
<p>And so I just continue my algorithm, right, I still have stuff in my queue to check.</p>
<p>And finally, when he leaves the front of my queue, I check Is he my target.</p>
<p>And indeed it is right at this point, I've just confirmed that he is found inside of my binary tree.</p>
<p>So what I can do is just end my algorithm by like returning the true value, right? There's no point of actually looking through the rest of the tree, because I already figured out that, hey, my target value is indeed within the tree.</p>
<p>Right? One thing you might notice is, it looks like I only checked for IE once it left the front of my queue, and not when it was initially added to my queue.</p>
<p>Technically, you could have returned early when you added it to the queue.</p>
<p>But we'll kind of see when I walked through the full code for this one, it would end up with cleaner code if you just checked for your target value when something leaves your queue.</p>
<p>So we'll see that when we go through the code.</p>
<p>It's just a small implementation detail.</p>
<p>That being said, for this iterative breadth first strategy, what can we say about the complexity? Well, if we define n as the number of nodes, then we know that the time complexity is just O of n, it's really just a classic breadth first traversal.</p>
<p>So nodes are going to enter the queue once and leave the queue once that's open, right.</p>
<p>And again, that's considering if we use a efficient queue, right, where our queue add and remove operations run an O of one constant time.</p>
<p>So we have linear time.</p>
<p>And for the space complexity, it's also going to be O of n linear, right? Because we're just going to store our nodes within the queue.</p>
<p>And so we just looked at the approach for a nice iterative breadth first solution, not to this problem, but I want to show you the depth first version, and the depth first version, that would be recursive, right? So obviously, you could write the iterative debt per solution, which case you just use basically the same code we just spoke about, but just use a stack instead of the queue.</p>
<p>But let's try to solve this one.</p>
<p>recursively, right.</p>
<p>And the reason I think it's really important to expose yourself to recursion like this is, as we move to more complex topics, you're going to find this style of recursion.</p>
<p>Very, very useful, right? So we have the same input, right? Let's say My target is E, and I have the same binary tree.</p>
<p>And now I want to check recursively is E within this tree? And so how do we start attacking this? Well, we're going to need to think about our base cases, right? So we're gonna have really two types of base cases, we'll have like the affirmative base case, meaning Hey, we found a match.</p>
<p>And so whenever I counter a node, whose value is he, or whose value matches my target, then I'm gonna have that node or that recursive call, return true, right? So that's my, like, affirmative base case.</p>
<p>So I'm just gonna plug that return value in visually in my tree, you know that this II nodes gonna return true.</p>
<p>And now I'll think about my negatory base case, right? Four times where I call upon an empty node, or the null node, I should return false.</p>
<p>And recall from our previous lectures, we said that we're going to sometimes represent explicitly our null nodes.</p>
<p>So I'm going to fill those in, for example, the C node in my picture would have a left child that is null.</p>
<p>So I'll kind of draw that one explicitly.</p>
<p>And I know that a node like that is going to return false.</p>
<p>Because logically, I shouldn't be able to think about all of my recursive calls as if they're their own subproblems.</p>
<p>Right? So if someone asked me, Hey, can you find this E value within an empty tree? Right? a null node represents an empty tree? The answer to be no, I can't find the value in an empty tree, because there's nothing there.</p>
<p>And so from there, I'm also going to draw explicitly all of those similar null nodes, null pointers, right? So it looks something like this.</p>
<p>Notice that from the E node, I don't need to give it a null left and right, because I already said that that node is going to return true, right? So that's why I draw my tree like this.</p>
<p>And I have all of those false return values.</p>
<p>Cool.</p>
<p>So we just labeled all of the base cases, right as the leaves of our tree, and recall that a leaf is just a node with with no children, right? And from here, how do I actually combine all of these Boolean values to get the true at the very top, I know for my top level color, that is at the a node, or the a recursive call, I need to get back that value of true, right? And the logic we should use is really just to the logical OR so how does this one work.</p>
<p>So let's start evaluating our return values and combining them at the parent.</p>
<p>So this should be somewhat of a similar pattern to like the tree sum problem I showed you.</p>
<p>And so what you could do is focus on this D node over here, this node has values ready on its left and right has two falses.</p>
<p>And when it actually gets those falses returned to it, it just should do the logical OR so it's doing false or false, which evaluates to false, right? Which means that hey, in this subtree rooted in D, I cannot find the value, which makes sense.</p>
<p>That's why it's false.</p>
<p>I'll continue this process.</p>
<p>If I look at this B node, now this B node has values ready on its left and right.</p>
<p>And they're going to bubble up a little bit.</p>
<p>And I take the order of them so I do false or true, which evaluates to true.</p>
<p>And this process continues everywhere in the tree, right? So at this f node, false or false, is me false.</p>
<p>At the C node, false or false gives me false.</p>
<p>Finally, at the top level root of A, I do true or false, give me back a final true, which is indeed the correct answer.</p>
<p>So hopefully, you realize how similar the solution is to our previous tree some problem right in the tree, some problem, I combined my left and right, child return values by doing the arithmetic addition.</p>
<p>But this time around, I just need to use the Boolean operation of or right, so by just adjusting the type to Boolean, we have a very, very elegant solution that shout out George Boole.</p>
<p>And so with that, I think let's go ahead and implement this one in some code, and I'll show you it using the interest of flavor or using maybe a breath for us, and also the recursive version, which is my personal favorite, using this recursive tree structure.</p>
<p>Hey, programmers, welcome back.</p>
<p>Alright, and I want to go over a JavaScript solution for this tree includes problem, right? Well solve this both depth first, and also breadth first.</p>
<p>And I think we'll start with the iterative breadth first version.</p>
<p>And so this is really just going to be implementation of the classic breadth first search algorithm, I'm just gonna lay down my classic a breadth first traversal code, and then just add some conditional logic afterwards, right? So you should be familiar with it by now.</p>
<p>But for my breadth first traversal, I'm going to use a cube.</p>
<p>So I'll say const, q equals an empty array, are really an array with the route thrown on the inside.</p>
<p>And from there, I have my main algorithm, right, so I loop while my queue is not empty.</p>
<p>So while queue length is bigger than zero, and keep on going.</p>
<p>And on a single iteration of this traversal, what I do is Q dot shift, so remove from the front of my queue, the front of my array, remove the first element.</p>
<p>And I'll save that into a variable called current.</p>
<p>So that will be just an instance of node.</p>
<p>And for now all why don't I just build up my solution slowly, I'll just, I don't know, console dot log, what current dot Val is.</p>
<p>But once I consider this node, what I want to do is really add its children into my queue only if they exist, though, right? So in general, I'm going to write like q dot push, I'm going to add to the back of my queue, so I get a nice cue order, push the left child, so current left, likewise, the right child.</p>
<p>But imagine that I have an asymmetric node or just a leaf node, right? Something like C would only have a right child, so it's left would be no.</p>
<p>So if current is see, then I'd be pushing No, into my queue as the left, which is no good, right.</p>
<p>And so I need to guard here and only push the children if they exist.</p>
<p>So something like this, hey, if the current has that, corresponding left and right, then I can go ahead and push it.</p>
<p>So this is looking pretty good.</p>
<p>And that should actually be the main traversal part of the code.</p>
<p>So I'll just test this manually.</p>
<p>So very manually, so maybe just this call, so I'm not gonna return Booleans yet.</p>
<p>We'll build up to that.</p>
<p>But I should at least see my values printed.</p>
<p>If I kind of run this manual test case, I'll bring in my node class, I should see the values printed in a correct breadth first orders, that means A, B, C, D, E, F, recall that breadth first traversal travels across our tree before going lower, so I must finish a level before traveling to the next level.</p>
<p>So let's just run this manually as a script.</p>
<p>See what we get here.</p>
<p>A, B, C, D, E, F, nice, so I'm getting the right order of traversal.</p>
<p>And now I can work in I think, the conditional logic because they want us to return Booleans over here.</p>
<p>So pretty straightforward stuff.</p>
<p>We'll go ahead and check once something leaves the queue.</p>
<p>I can check If the current nodes value is equal to my target, then I've found the thing I'm looking for.</p>
<p>So just return true, right, you're done, you don't need to travel through the rest of the tree because you can return true.</p>
<p>But on the flip side, if my value that I'm currently at is not the target value, that I must continue looking through the rest of the tree, right.</p>
<p>So if I finished the entire while loop, that means I've traveled through the entire tree.</p>
<p>And I never found the thing I'm looking for, I should return false.</p>
<p>So I need a late return false over here are really common mistake people tend to make is, what you don't want to do is just do like, else return false here.</p>
<p>So this is going to be wrong.</p>
<p>Right? Because this would only check like the very first notice normally check the root, and then check if the root is not equal to the value.</p>
<p>If it's not, you just return false, which is not really useful, because it could be somewhere else in the tree.</p>
<p>So you're gonna need that late return false pattern over here.</p>
<p>But with that, I think we're going to pass some of the test cases, as well run the test cases by hitting that test button.</p>
<p>And there's probably one scenario we did not for C.</p>
<p>Cool, and there it is, right? Can I read property value? No, we're failing tests.</p>
<p>055, look at that spec.</p>
<p>Test five gives us a null node as a root, right? So just the empty tree, you cannot find the B character inside of the empty tree.</p>
<p>So return looks like false over here.</p>
<p>And so I can just handle that one explicitly.</p>
<p>I'll go ahead and check at the top.</p>
<p>If my route is no, right, if that's the case, then just return false.</p>
<p>I can't possibly find any target in an empty tree.</p>
<p>Right? The reason our code was failing before is if root is null, then I initialize my queue with no.</p>
<p>And when that thing is pop, and that null is popped, or rather shifted from the queue in the first iteration, then I check null dot Val, which is an illegal JavaScript operation.</p>
<p>So I'll run all these test cases now.</p>
<p>Nice.</p>
<p>And there, we have our breadth first solution for this tree includes problem.</p>
<p>All right, now let's work on the recursive depth first version of this, it's actually my personal favorite, because it utilizes a pattern that I think is quite elegant, and one I use a lot for much more difficult problems.</p>
<p>So like we said, in the approach video, if you haven't watched the approach, you definitely want to check it out.</p>
<p>For this recursive version, right? what I should do is check Hey, if my root is null, if I have the empty tree, basically, then just return false, right, because I can't possibly find my target and empty tree, right, that's just a given.</p>
<p>And from there, I know I'm going to have the general shape of some just depth first traversal code, which means you call the same function because it's recursive.</p>
<p>That's what recursive means.</p>
<p>And you pass along your route dot left and a separate call your route, right.</p>
<p>And when I should be sure to do is Don't forget to pass in your target, write the target that you're looking for, it never changes.</p>
<p>And I know that these two these two calls are going to give me back boolean data.</p>
<p>And I know that the Boolean I get back from like this call would represent whether or not I found the target and that subtree, right.</p>
<p>So this gives me the result of if I found it in the left subtree.</p>
<p>Or the result if I found it in the right subtree.</p>
<p>And I can just do the logical OR on both of these, right.</p>
<p>So if I find it in either subtree then return true.</p>
<p>So I could just write in line return true over here, right? So let's say it's in my right subtree, then this left hand side invites to false.</p>
<p>And this is true, in which case, this entire thing evaluates to true.</p>
<p>And let's say in a bad scenario, let's say it's not found in either subtree.</p>
<p>So this evaluates to false.</p>
<p>this right hand side also evaluates to false, false or false gives me false.</p>
<p>However, one thing I need to be sure to add is also an additional base case, after I check if my route is no, what I want to do is then also check, hey, maybe this route I'm currently at, maybe it actually has the target, right? So if route value is equal to the target, then you're also done, except you can return true.</p>
<p>Cool, and that was very reminiscent of our approach video.</p>
<p>So let's give this a shot.</p>
<p>You should be able to pass nice, and I love how clean this code is.</p>
<p>I will admit, you know, it's pretty tricky.</p>
<p>If you're not a fan of writing recursion, in which case, I'll totally convinced you into being a fan of recursion.</p>
<p>But notice how kind of clean this code is really leverages recursion.</p>
<p>One very important thing I want to bring up is it's really keen that I put this base case on line 26 after the null check, right? So let's say I flipped the order of these.</p>
<p>Let's say you did this.</p>
<p>I believe that would not work out always because it assumes that you even have a route Alright, so I'm feeling a test 00.</p>
<p>But in general, if you look at this code, let's say that route was no, right? You're gonna start by checking null dot Val, and I'll throw an error, right? Can I read property valve? No.</p>
<p>So you want to actually always lead with your base case that checks if your root is null, right? Because that should guard really the entirety of our code.</p>
<p>So this is actually the code you want.</p>
<p>Over here.</p>
<p>Alright, programmers.</p>
<p>So that's all I got for this tree includes solution, I want you to practice both versions, and I'll catch you in the next one.</p>
<p>Hey, programmers, Alvin here, right? Now I want to go over the approach for this tree sum problem.</p>
<p>And so in this problem, I want to take in a binary tree, just like we've been doing as of late, this time, the values within the nodes of this binary tree are going to be numbers, right, what I want you to do is compute the total sum of all the values in this tree.</p>
<p>So for this example, we should end up with 25.</p>
<p>And so hopefully, you're kind of gathering how to attack this problem, especially given you know, the algorithms I've been showing you as of late.</p>
<p>So if you've been studying our problems, and are there hopefully, you know, a straightforward solution to solve this one, we could of course, just use any type of traversal algorithm.</p>
<p>So we can use either a breadth first or a depth first traversal.</p>
<p>And we can just add all these values into a running sum.</p>
<p>And of course, we probably initialize that sum to zero, right? So the iterative breadth first or depth first solution, I think, is very straightforward, right.</p>
<p>And I'm not going to really step through that approach with you over here, I think you have that one down pat, especially if you've done the previous two problems.</p>
<p>But what I will show you here is actually how to solve this one recursively, which would be a type of depth first traversal, because we know that hey, depth first traversal relies on a stack.</p>
<p>And if you do something recursive, it is utilizing the underlying call stack.</p>
<p>So I will get a similar type of ordering.</p>
<p>And so when we trace through this type of solution, this recursive solution for this tree, some problem we're going to do is try to be very explicit, I think this is really helpful, especially if you struggle with recursion, right? So given this binary tree, I know that for particular nodes of my tree, like the four node, it does not have a left child, right.</p>
<p>And I know like programmatically, what that means is like that nodes dot left pointer points to like, no, or it's a null pointer.</p>
<p>And so I'm just going to draw that explicitly, sort of like this.</p>
<p>Again, they'll just help us really understand how our recursive code performs on this type of input.</p>
<p>And so if I know that I can put like an unknown load to the left of four, then it could be the case that other nodes like the leaves have to in one, they also have both left and right children that are also know.</p>
<p>So if I drew all of my null pointers explicitly, it would look something like this.</p>
<p>Cool.</p>
<p>And this is really something that helped me really get comfortable with recursive problems, especially those on binary trees.</p>
<p>And what we're doing now is, we know that when it comes to solving any problem recursively, it's about writing a base case, that is like the simplest version of our input.</p>
<p>And here, I'm going to argue that our base case needs to be about the null node, right? The null node basically represents no node at all, or represents the empty tree in a sense.</p>
<p>In other words, if someone asked me to calculate the sum of a null node or the sum of an empty tree, then to me that some would just be zero, to write elegant recursive code to try to think about your base case as a problem in itself, right? So if someone gave me an empty tree, that is a null node, I would return the total sum of zero.</p>
<p>And what that means is I know that all of these null nodes, they would return zero as their computed sums.</p>
<p>Nice.</p>
<p>And then from there, how can I use this information to actually build up my main solution? Right? So let's go ahead and target this for node to the left.</p>
<p>And what I have to do is figure out Hey, know what is this subtrees total sun, and I can compute that given the values to the left and right.</p>
<p>In other words, if I return those two null values returns to zero.</p>
<p>Now I just have to do zero plus four plus zero, which just equates to four, right? And that is actually correct in itself, right? So what green number above a node represents the total sum of that subtree.</p>
<p>And so it is a case that, hey, the total sum of that four node is just four.</p>
<p>And I would do something similar for this node over here, right? When these base cases return to their color or return to their parent, I just have to add my left and right child together along with myself.</p>
<p>So zero plus two plus zero, gives me to not do that same thing.</p>
<p>For this note 11 We're here.</p>
<p>And now things get interesting, right? It's a calculate the total sum rooted at this 11 subtree, I would just return these values to the top.</p>
<p>And now I do four plus 11 plus two, which gives me an answer of 17.</p>
<p>And if you do a quick spot check, right, this 17 does represent the total sum, just in this subtree, right, and we'll carry on over at this one node, we know that this is going to return just a value of one.</p>
<p>And now at this four node, I can compute its total sum.</p>
<p>And recall that this four node had a left child of zero, right? Because it has a null node.</p>
<p>And so when I compute the sum, I get five, which is perfect.</p>
<p>And finally, at the main route, now I bring up these two values.</p>
<p>And I compute 17 plus three plus five.</p>
<p>And that gives me a final answer of 25.</p>
<p>Which is indeed the correct answer.</p>
<p>Right? So that's how we should really think about our recursive algorithms for our binary trees, right? I kind of draw it out, I think about the base case, which is typically not always but typically about the null node.</p>
<p>And then from there, I figured out how a parents can compute its result given its children's answers.</p>
<p>Alright, so if we take a look at the complexity of this, it's pretty straightforward.</p>
<p>We'll go ahead and define n as the number of nodes in our input tree, in which case, I can see that my time complexity is just O of n, right? We know that we're going to make a recursive call just for every node of the tree.</p>
<p>And we're not going to call duplicate nodes, right, we're going to have just one call for every single node.</p>
<p>And within any single node, we're just going to do some simple arithmetic, right, we just had roughly three numbers together.</p>
<p>So it's not like we're going to have like a loop inside of our calls at all.</p>
<p>In a similar way, we'll say the space complexity is O of n, just because we have that implicit, a call stack space, because we are going to solve this one recursively.</p>
<p>And so we're solving this one in O of n time and space, which would be actually a maximum efficient a solution for this problem.</p>
<p>And so with that, I think, let's head over to the walkthrough video, and I'll show you how to code this one up.</p>
<p>Hey, programmers, Alvin here, right? Now I want to walk through the JavaScript solution for this tree some problem, I think this time around, and I'll jump right into the recursive version, right? So we'll start recursively.</p>
<p>And we'll begin with our base case, right? My base case is always about the simplest version of the input, where I just know the answer without needing any additional calculations, right? I know that the simplest tree here that I could be given is going to be the empty tree, right? I have the empty tree.</p>
<p>That means my root is no.</p>
<p>And if your root is no, you have the empty tree.</p>
<p>What is the sum of the empty tree? Well, kind of inherently, it's just zero.</p>
<p>So I'll be my base case.</p>
<p>Nice.</p>
<p>And then from there, I'll think about how I can compute my answer, given my children results.</p>
<p>So I need to find the results of the some of my left subtree.</p>
<p>And also the some of my right subtree.</p>
<p>So just call recursively.</p>
<p>So tree, some of root left, as well as tree some of root.</p>
<p>Right? Cool.</p>
<p>And I know that these two calls, they return numbers, right, representing the sum of my left subtree.</p>
<p>And the sum of my right subtree.</p>
<p>As the parent that is so rude, how can I find my total sum? Well, it just is myself.</p>
<p>So root out value, plus everything in my left subtree plus everything in my right subtree.</p>
<p>Right.</p>
<p>And we'll go ahead and just test this out the gate.</p>
<p>But this is nothing fancy, really elegant code to look at the test cases here, we do have some a diverse output.</p>
<p>So this code does work on trees of all different shapes and sizes.</p>
<p>Something that helps me you know, really believe the magic of recursion is to just analyze the assumptions here, right? So let's say that I'm stepping through tree some and my root is this three over here, right? So I checked the base case, is this three node? No, it's not.</p>
<p>So I must make the recursive call, right.</p>
<p>And I know that when I break down this code recursively, I know my route that Val is going to be like three, so I'm kind of corresponding, this comment with the thing below, right? And then when I make the recursive call on tree, some root dot left, that means I'm asking for the total sum of this subtree starting at 11.</p>
<p>So I'm looking at the 11 for negative two subtree.</p>
<p>Right, if I take the total sum of just that left subtree, it looks like it's going to be just 13.</p>
<p>It's now I'm saying plus 13 over here, right? If I do the same thing on the right, subtree I know that this call is for this four node, right all of its children, that should just magically return by the power of recursion that should return five, right? I'm going to assume that that recursive call just works.</p>
<p>So you're out the five, right? If I take the total sum of these, three plus 13 1616 plus five is 21.</p>
<p>That would give me the correct answer, right.</p>
<p>So to have some confidence in my recursive code, I just write the code.</p>
<p>And then I assume correctness from my recursive calls.</p>
<p>And I figure out how I can take those sub valleys for my children, combine it with my own value, and that should be my final answer.</p>
<p>So here is the recursive version of this solution, which would be some sort of a depth first traversal, technically, because it's recursive.</p>
<p>And if you'd like, I can also show you the iterative version.</p>
<p>So let's just do that.</p>
<p>And I always practice usually my problems doing both the recursive as well as iterative version, if it's reasonable, and is really reasonable here.</p>
<p>Hopefully, you're familiar with our breadth first code by now, right? So I'm just gonna start by checking, hey, if you're given some root that is already know that that's kind of an edge case, I'll just go ahead and return zero, right? Because as some of that empty subtree, or that empty tree, rather, is just zero, that can begin my main code.</p>
<p>So while my queue is not empty, so I'll start with a Q, who begins with the Route Route, I want to loop while my queue is not empty.</p>
<p>So while q dot length is bigger than zero, I'll begin a single iteration of my while loop by just shifting out the front of my queue.</p>
<p>So in JavaScript, for me, that's q dot shift that removes the front element, and also returns it to me.</p>
<p>So I'll save in current.</p>
<p>And then from there, now that I have this current, I know that contains the value that I actually care about.</p>
<p>So what I would do is go ahead and track some running sum.</p>
<p>So I'll say let some member say let total sum equals zero.</p>
<p>And as I remove something from the front of the queue, I'll take it to value and add it to my total, something that will accumulate all of the values right into a sum.</p>
<p>And from there, I just need to add my classic logic of checking for my children, right? If they exist.</p>
<p>So if I have a left, so if current dot left is not equal to know, then what I'll do is add that left child into my queue.</p>
<p>So q dot, push my current dot left, again, make sure you're following your cue rules, right, so shifts removed from the front, push adds to the back, it's really important that my shift and my push or my add and remove methods work on opposite sides of my queue.</p>
<p>Otherwise, it's not a cue, right? So that looks good to go.</p>
<p>I'll write something symmetric.</p>
<p>For the right hand side over here.</p>
<p>By the end of my function, I'll just go ahead and return my total sum.</p>
<p>Nice, this would be my go to enter diversion.</p>
<p>course, it's technically a breadth first, and we'll give that a test.</p>
<p>Nice.</p>
<p>And here we have that solution.</p>
<p>So one thing to note, I think it's pretty important to be consistent how you implement these algorithms, I swear possible.</p>
<p>So you'll notice that I always am a fan of a writing my like processing logic for a node.</p>
<p>Here I consider like the processing logic, where I add the value of my current node into my total sum.</p>
<p>I do that processing logic, typically when a node leaves the queue, and not when the node is added to the queue, and just ends up being less repetitive that way, for example, I've seen some people write code like this, where it's like, Alright, well, you know, I guess since I'm adding my left child into my queue, that means it exists.</p>
<p>So not only will I push it, but I'll add it so I'll do I don't know total sum, plus equals current dot left dot Val, right, so I'm kind of adding the child's value as soon as it's added to the queue.</p>
<p>And you can write something symmetric for the right hand side, you can see that because of this, I kind of have to double up all of my code, which does not make it super clean.</p>
<p>And I think something that is even worse than that is well now you actually never added your root value into the your, your total sum.</p>
<p>So you'd have to begin your total sum as root dot value at this point, I'm like, I kind of just hate this code, right? So you can run this, this would probably work.</p>
<p>So this code totally works, but it's not what I think is the best design for this pattern.</p>
<p>So I'd rather write it like this, right? consume your values when they leave your queue because you know, eventually, everything's gonna leave, right? So I'll prefer it at least like this.</p>
<p>Cool.</p>
<p>So before you go on to the next problem, recommend you practice both versions.</p>
<p>I know of this problem.</p>
<p>So do it recursively do it iteratively have them both down pat because we're going to increase the difficulty right now.</p>
<p>Hey, programmers, Alan here right now.</p>
<p>One To go over the approach for this tree min value problem.</p>
<p>So just like we've been doing as of late, we're going to have to take in a binary tree as input into our function.</p>
<p>And we want to do is figure out what the smallest value within the tree is.</p>
<p>That is we want to find the minimum value.</p>
<p>So we can totally assume that the tree is going to be non empty, right? And so given that information, looking at this particular tree example, it's pretty plain for us to see that the smallest number in the tree is just this three.</p>
<p>Alright, so our function just needs to return of the number three.</p>
<p>So it's plain to see that the answer is three.</p>
<p>But how can we come up with an algorithm to do this for us? Well, we should look to our tools in our binary tree toolbox.</p>
<p>And that would mainly just be either a breadth first or a depth first traversal.</p>
<p>One obvious way to solve this one is to use either a depth first or breadth first iterative piece of code that does a traversal and travels through the tree, then you just need to maintain some outer variable to track the current minimum.</p>
<p>And whenever you hit a node that is smaller than your current minimum, then you replace that minimum variable.</p>
<p>And by the end of the code, you should have the true minimum.</p>
<p>So the iterative version, I think, is pretty straightforward.</p>
<p>And I'll be sure to walk through that when we get to the code walkthrough.</p>
<p>But for now, in terms of our approach, visual, I think we'll step through this one recursively, right, because it ends up being pretty succinct code.</p>
<p>And so let's take a look at this tree.</p>
<p>And let's pretend that we filled in all of the null pointers, like usual, right? So these dark nodes over here represent nodes that don't exist, meaning that there are no, right.</p>
<p>So for example, if I look at the three node, its left child is no, but its right child is 12.</p>
<p>And that's going to be very useful for us to at least visualize because I should make a base case about those null nodes, right? So I know in the long run, what I want to do is figure out what the smallest value within the tree is.</p>
<p>And so a great default value for our null nodes would be to return infinity.</p>
<p>And here's the reasoning why I know that I should not really consider any of the actual null nodes.</p>
<p>And so if I have them return positive infinity, I know that positive infinity is definitely not going to be the minimum compared to any numbers that are actually within the tree.</p>
<p>So we'll start to do is just fill in all of these infinite values.</p>
<p>In other words, every time we call upon a null node, or a null pointer, we're going to return infinity.</p>
<p>So I'd fill all of these in.</p>
<p>Now using those infinities as our basis, we can actually construct our return values.</p>
<p>So looking at this for node to the left, what I have to do is consider both of its children that it received, right, and also the value within the current node.</p>
<p>And so what I do is I check, alright, compared between infinity for an infinity, what's the smallest value among them? Well, I know positive infinity is a very large number.</p>
<p>So really, the smallest number here should be four.</p>
<p>And so this call should return four, right? This node should return for similar story for this 15 node.</p>
<p>Once I have my left and right return values ready, I do a comparison with those values against myself, right? So I check, what's the minimum among infinity? 15 and infinity, the minimum is 15.</p>
<p>I think it's gonna interesting now that we're at evaluating this 11 node, right? Now I have some actual numbers.</p>
<p>And so I do this comparison, right? I compare my left subtree value, which is four and my right subtree value, which is 15.</p>
<p>And also myself, which is 11.</p>
<p>So among 411, and 15.</p>
<p>What's the smallest number? Well, that would just be the four, right? So this node should return four.</p>
<p>And if I do a quick spot check, this makes some sense, because I have this answer for above the 11 node, that's telling me that, within that subtree rooted at 11, the smallest value was four, which is totally correct.</p>
<p>Now we'll just go ahead and valuate the rest of this tree.</p>
<p>Looking at this 12 over here, I know I can't evaluate the three because I need a value on the right hand side ready.</p>
<p>So I must evaluate this 12.</p>
<p>And I just do the comparison, right? What's the minimum among infinity 12 and infinity? Well, let's just definitely 12.</p>
<p>Finally, at this three node, I take the minimum of infinity three and 12, the minimum there is three.</p>
<p>And finally at the ultimate root, I do the comparison.</p>
<p>And I check what's the smallest among four, or five and three? And the answer is going to be the three, right, which is exactly what we expected.</p>
<p>And so just by adding a little variation to our classic depth first recursion, we can totally solve this problem.</p>
<p>The logic we need to use to combine our child sub solutions into our main solution is to just do a comparison, right? So overall, at every point of this tree, we asked ourselves, right, given the smallest value in the left subtree and given the smallest value in the right subtree.</p>
<p>I compare those to myself, and return the smallest among those three.</p>
<p>And then when it comes to the complexity of this, it's pretty straightforward.</p>
<p>We'll go ahead and say that n is the number of nodes within our input tree.</p>
<p>And we know that we're going to have a call for every node of this tree.</p>
<p>So that seems to be an O of n time.</p>
<p>In terms of the number of recursive calls, right, and we know within any particular recursive call, it sounds like we're just going to do some conditional logic, right, just find the minimum among three things.</p>
<p>Since three is a constant number, I'm pretty sure that we're going to have just an overall time complexity of O of n, considering the number of calls that we make.</p>
<p>Now, that being said, we'll also have O of n space complexity adjust due to the call stack that we use for baseline depth first traversal.</p>
<p>And that seems to be an optimal solution for this problem.</p>
<p>Because what we'll do, we'll go ahead and code this one up, and I'll catch in the next one.</p>
<p>Hey, programmers, Alvin here, right now I want to go over a JavaScript solution for this tree min value problem.</p>
<p>And of course, we'll solve this one a few different ways.</p>
<p>I think I'll start by showing y'all maybe some iterative solutions.</p>
<p>And so we'll just do some classic depth first and also breadth first, along the way, right.</p>
<p>So you know, you're going to need to iterate or hit every node within your binary tree.</p>
<p>So just go ahead and set up either a stack or a queue.</p>
<p>So I'll choose to start with a stack over here.</p>
<p>So I'll say Kant's, stack equals empty.</p>
<p>And one thing I'll have to be aware of is looking at the assumptions in the problem, they tell us that we can assume that the input tree is not empty.</p>
<p>And so that means I won't need to add a leading if statement checking if the top level root is null.</p>
<p>So I can just go ahead and initialize my stack with the root node inside.</p>
<p>Cool.</p>
<p>And then from there, you need your main loop to iterate through the different nodes.</p>
<p>So I'm going to loop while my stack is not empty.</p>
<p>So all stack dot length is bigger than zero.</p>
<p>Cool.</p>
<p>So if that's the case, and there are still some nodes to visit, and begin a single iteration of this algorithm, let's say depth first, by doing stack dot pop, so I removed the top of my stack, go ahead and call that my current.</p>
<p>And then from there, of course, we need to check if our children exist.</p>
<p>And if they do, I'll add them to the top of my stack, right? So I'll write a pattern like this, I'll say if, let's say current dot left, that is not equal to No, then I can go ahead and push that existing child on the stack, right? So stack dot push, and I'll push current left retinas a few times by now should it be second nature, I'll do some same code for the right hand side.</p>
<p>And this is kind of my baseline of a depth first traversal, right.</p>
<p>But as I look at this current node and its value, I want to by the end of my loop, have access to the minimum value within the tree.</p>
<p>And so because I need to find the minimum value in this function, we're going to use a variable that I'll update over time, right to track the current smallest thing I've seen.</p>
<p>So I'll initialize this as let smallest, I'm gonna have to think about a good default value for this.</p>
<p>And so I'll go ahead and initialize this to actually positive infinity.</p>
<p>So if you're unfamiliar with some JavaScript, infinity is basically just a number that is guaranteed to be bigger than all other numbers, except for itself infinity, right? And the reason I'm choosing a big number, like positive infinity, for my default value for the smallest variable, is because when I see any actual values of my tree, I know they're guaranteed to be less than infinity.</p>
<p>So these numbers would replace my infinity, just gives me a good initial value, right? That's a pretty common pattern, right? If you're looking for the minimum thing, and typically your default value is positive infinity.</p>
<p>If you're looking for a maximal thing, then your default value might be zero or negative infinity, depending on the problem you're trying to solve.</p>
<p>And so with that default value, where do I actually want to replace it, right.</p>
<p>And I'll choose to do that right after or something leaves my stack.</p>
<p>That way, you only have to say it once.</p>
<p>If I wrote it, when I added my children into the stack, what I'm saying twice, right, which is kind of annoying.</p>
<p>So I'll just check, hey, if current value, so be sure to compare the actual number value, current value is less than the smallest, then I've just found a new smallest, right? So just replace that variable with current value.</p>
<p>Of course, by the end of our while loop, we should just return that variable, right? And we should have the true minimum.</p>
<p>So let's give that a shot, run these test cases.</p>
<p>And this is our rendition of an iterative depth first, right? Awesome.</p>
<p>So if you wanted to switch it up, you know, writing the breadth first is super trivial in terms of the change we make, you can just make sure you do stack dot shift, right, because that would remove the front element of your queue now and if you push then you're still adding it to the back.</p>
<p>And I guess you should probably rename this guy to queue.</p>
<p>So very minute difference.</p>
<p>Well, tests that just give that a go.</p>
<p>Cool, passes all of them.</p>
<p>Nice.</p>
<p>And one thing to note.</p>
<p>So Alex in JavaScript, there is no immediately when I recorded this video, there is an immediately available, like optimal queue data structure just baked in, like you can't import it through a standard library.</p>
<p>And so when you actually do the array dot shift method, that line itself is going to run an O of n time, right, because if you remove the front element of an array in JavaScript, it will have to actually shift all the other elements over one position.</p>
<p>In other words, index one becomes index zero, index two becomes index one, and so on.</p>
<p>And so technically, if you implemented your breadth first exactly like this, just using a regular array, and you shift out, then this would probably be technically like an O n squared solution, which isn't the fastest, but we'll be able to pass the specs, typically n squared for most problems is kind of okay.</p>
<p>But you can avoid it if you want to get the blazing fast solution.</p>
<p>But now let's actually go ahead and implement my favorite version, which would be a recursive version, right, which is technically of the depth first.</p>
<p>Right? So we'll say const, trimming value, chattering min value, dream and value.</p>
<p>And to establish this one recursively will always start with our base case, right? That's when you saw these curly guys.</p>
<p>So I'll start my base case, I'll say if my routes is equal to null, then that kind of means I have the empty tree, what's like the minimum value in the empty tree? While that must be infinity, right? For the same reason we chose infinity before, right? It's just a good default value, because I'm going to minimize in the long run.</p>
<p>Cool.</p>
<p>And now what I want to do is I want to make my recursive call.</p>
<p>So if I call treeman value on my left child, and I call it on my right child, I'll just think about what these function calls return.</p>
<p>Right? Although they're recursive, if these calls work, they should give me back the smallest value in the left subtree.</p>
<p>And the smallest value in the right subtree.</p>
<p>So maybe, just to be clear, I'll go ahead and save the system variables.</p>
<p>So I'll say const, I'll say, left.</p>
<p>Min.</p>
<p>And also this should be the right men, right? So I found the smallest in the left and the smallest in the right.</p>
<p>But I also need to think about myself, right? I am ru dot Val.</p>
<p>So I need to choose the smallest of root Val left men and Reitman, right, so you can write like a conditional.</p>
<p>So just some if statements If you want, I think the best way to implement this in JavaScript is just to use the math dot min function.</p>
<p>So JavaScript, you always have access to the global capital math object has a few useful methods on it.</p>
<p>One we're going to find useful right now is math dot min.</p>
<p>If you do that, you can pass in some arguments and an arbitrary number of arguments.</p>
<p>So give me the smallest between route dot Val and be sure to access the value because you need to give numbers to men, right? Smaller between route dot Val, my left men and my right man.</p>
<p>Cool.</p>
<p>And this feels somewhat similar to the approach drawn we did right where we had to choose the smallest of these three numbers.</p>
<p>So before we run it, maybe you're unfamiliar with math dot min, I can quickly demo that for you.</p>
<p>Let's say I had some numbers, we had 10, we had three, we had six, and we had negative 12.</p>
<p>And also 100.</p>
<p>And if I console log with that returns, I'll just run this file as a script.</p>
<p>So I'm not going to execute the tests quite yet.</p>
<p>So I should get negative 12.</p>
<p>Because that's the smallest perfect.</p>
<p>And now I think we're ready to go ahead and test this.</p>
<p>So our recursive version, there we have it.</p>
<p>Cool.</p>
<p>Alright, so there, we have our JavaScript walkthrough for this tree minvalue problem, recommend you practice all of these different solutions, and then pick a favorite, maybe just have in your back pocket.</p>
<p>That way, you can always solve this problem in the future, right.</p>
<p>So you should have no issue thinking about how to solve like a tree maxvalue problem.</p>
<p>And by now, you know, we're getting pretty comfortable with trees.</p>
<p>And typically, we're always going to fall back to either a breadth first or a depth first traversal.</p>
<p>But in the next few problems, we're definitely going to look at some spin offs and some variations on how we can accomplish more complex logic using these algorithms as our baseline.</p>
<p>So I'll catch in the next one.</p>
<p>Hey, programmers, Alvin here, right now want to go over this max root to leaf path, some problem, pretty wordy title, let's take a look at what this problem asks us to do.</p>
<p>So we're going to be taking in a binary tree as input, and we want to do is really talk about the paths within this tree in particular, root to leaf paths.</p>
<p>So just to review, we know that a binary tree typically for us has a single root and you can identify the root by just looking at the topmost node, that is the node with no parent, right? And then also given this tree there are three leaves, right? a leaf is a node that has no children.</p>
<p>So do bear in mind right a root has no parent.</p>
<p>A leaf node has no children, some Like 11, and three in this picture, there are neither roots nor leaves, right.</p>
<p>So it could be the case that a tree has many leaves, like this tree, right has three leaves.</p>
<p>But a tree for us typically only has a single root.</p>
<p>And so what we want to do is consider all three of the different root to leave paths, right, so you must start at the root, and you must terminate at a leaf.</p>
<p>So one of those paths would just be this one, right 511 for, what we want to do is consider its total sum.</p>
<p>So just summing the values within the nodes along that path.</p>
<p>If I do five plus 11, plus four, that would give me a total sum of 20.</p>
<p>So that's just one of the possibilities.</p>
<p>If I look at another path, let's say this path of 511 to five plus 11, plus two would give me 18.</p>
<p>That's another option.</p>
<p>The only other option is is final path from five to one, five to five plus three plus one.</p>
<p>That gives me a total sum of nine, right? And now among those three options, I want to choose the maximal path some right? So that would be a final answer of 20.</p>
<p>So in the long run, we need to come up with some code that computes the maximal path sum from the root to any leaf.</p>
<p>And that sounds like a pretty hard problem, right? How can we go about doing that one? Well, hopefully you notice some similar patterns, right to problems we've done previously.</p>
<p>So just by looking at the name of this problem, I'm reminded of a few different patterns, right? I can think of the tree some problem seems pretty related here.</p>
<p>And can I also think about, like that minvalue.</p>
<p>Problem are, we had some minimization logic, except now, I want to maximize something here.</p>
<p>And so probably what I'll have to do in this one is combined some of my previous knowledge to come up with a pretty novel solution, but it's okay to rely heavily on our previous experiences, right.</p>
<p>And so let's start with something classic, I think we're gonna solve this one recursively.</p>
<p>And in the grand scheme of things, typically, for tree problems, that is, a recursive code is usually your best bet when it comes to like, pathfinding things, right, and building pads and determining pads.</p>
<p>And so we'll take a look at what we should have our base cases be, if we're gonna frame this one recursively.</p>
<p>So they tell us that, all right, you need to consider paths, but not just any paths, right? You always want to end at a leaf node.</p>
<p>So the leaf nodes, like the ending point, belief, notice the base case.</p>
<p>So my base case is going to be literally about a leaf node.</p>
<p>And recall that that's a node with no children.</p>
<p>So for example, let's say we had a node as input that had no children, then what's the total sum of that leaf node? Well would just be its inner value n, right? So kind of think about your base cases as if they're their own inputs, right? As a quick aside, right, so a totally separate scenario, right? Now, let's say I gave you a tree that contains only one node, and its value was 42.</p>
<p>And I asked you to, alright, tell me, what's the maximum path some of this tree, this tree is very small, right? If you identify the root in this tree, it's just the 42 node, right? Because it has no parent.</p>
<p>And I've also asked you for the leaves, there's only one leaf here.</p>
<p>And it's also the 42, right? Because it has no children, right? So the single note of 42, in this example, is the root and the leaf, which means that the maximum path, some would just be 42.</p>
<p>Cool.</p>
<p>So I'm thinking about my base cases as if they're their own inputs.</p>
<p>Nice.</p>
<p>And what you'd probably recognize here is, in this scenario, we're kind of considering a base case, that is not about a null node, right, we will need at least a separate base case that checks if we have an actual leaf node.</p>
<p>And that's very, very inherent and given in the problem, right? They say root to leaf path.</p>
<p>Awesome.</p>
<p>So if that's the case, I'm just going to locate all of my leaf nodes in this diagram.</p>
<p>And I know that they're going to return the values within them.</p>
<p>So just plugging those in, right? And now I can start reconstructing on my higher level solutions, right? So given this 11 node, what decision does this 11 node have to make to compute its answer, right? So let's read ourselves at this 11 node.</p>
<p>And we have to consider our left and right values, right.</p>
<p>And so if i route myself at 11, the four represents my max path sum through my left subtree.</p>
<p>And the right hand side to now represents the max path sum through my right subtree.</p>
<p>Since I want to maximize here, the key is to just choose between four and two, right? I choose the bigger of them, right? So four is bigger than two, so I must use the four.</p>
<p>And what I do is I take that four, and I add my current value of 11 into it, and that gives me 15.</p>
<p>And that would actually be the answer for this subtree.</p>
<p>In other words, I can check for correctness right now, if I root myself at 11.</p>
<p>I'm returning 15 to represent this path, right? I can either do 11 plus four, which is 15.</p>
<p>Or I can do 11 plus two, which is 13.</p>
<p>Right and that 13 is smaller, so I won't prefer it here.</p>
<p>Cool.</p>
<p>So so far, it seems like we're in good shape.</p>
<p>Now let's take a look at another node read to evaluate.</p>
<p>Let's look at this.</p>
<p>Three node.</p>
<p>So it has a value on its right hand side, right? It's receiving a one from its right child, but the left child doesn't exist, right? And if you want to be a little more explicit, we know that the left child or three dot left is going to be a null pointer.</p>
<p>All right? So kind of plug that in here.</p>
<p>And here's where we should work in possibly another base case, sometimes it's very natural to course correct as we go.</p>
<p>And so for a null node, what should we return? Well, we know that whenever we have a null node, it should never contribute to our final answer, we can kind of just ignore it, I guess, we want to make sure that it's compatible with the rest of our internal logic.</p>
<p>So bear in mind in this problem, I want to take the maximum right? Recall from our previous problem, right, the min value problem, we want to take the minimum.</p>
<p>And so we made our null nodes return infinity, right? Because if I want to find the minimum, and my null nodes, return infinity, by default, I know that infinity is never going to win a comparison, right? Because infinity is very large.</p>
<p>And we just want to flip that logic over here, right? So because in the long run, I want to find the maximum, I'll make my base case for the null nodes return negative infinity, right? Because I know negative infinity is never going to win any contest where we compare things, looking for the larger of the values, right? So for this null note, I'll plug in that negative infinity.</p>
<p>And now I shouldn't be able to do the same business logic as before, right? So I'm rooting myself at the three node, and I can look at the results I get for my children, right.</p>
<p>So between my two children in my left path, I get a negative infinity, or in my right path, I get a one, and I choose the maximum between them, right? One is bigger than negative infinity.</p>
<p>So I should use the one, right.</p>
<p>And what I do with that one is, I add my current value of three to it.</p>
<p>So three plus one gives me four, right.</p>
<p>And that makes some sense, because if I look at that small subtree, rooted in three, the biggest path from root to leaf, or sub root to leaf, I would indeed be a four.</p>
<p>Nice, and now we have ourselves at the ultimate root over here, I do that similar comparison, right? I check the bigger of my two children, so I'm going to keep the 15.</p>
<p>But then I add myself to it giving 20.</p>
<p>Like we said before, this 20 logically represents this path of five plus 11 plus four.</p>
<p>Cool, so there we have it.</p>
<p>And if you want to take a look at the complexity of this seems nothing unusual.</p>
<p>So we're going to have n as the number of nodes, we're going to have O of n runtime, because we're going to have to make a call a recursive call that is for every node within the tree.</p>
<p>And if I think about any particular call, we're going to make a foreign node, we're just going to do a comparison, right, I just choose the bigger of my two children.</p>
<p>So we're not going to have any, any loops within our calls, I believe.</p>
<p>Cool.</p>
<p>So it just seems to be O of n time.</p>
<p>Like we always say space complexity is O of n, just due to the call stack.</p>
<p>Nice.</p>
<p>So let's go ahead and code this one up.</p>
<p>And it should feel like a combination of our previous tree some problems, as well as some a min value max value logic.</p>
<p>Hey, programmers, welcome back, Ryan, I want to go over a JavaScript solution for this max root to leaf path, some problem.</p>
<p>So this is going to be a pretty interesting tree problem.</p>
<p>And we'll jump right into the code, please make sure you watch the approach video before this.</p>
<p>So I think should be all primed up with the logic that we want to implement here.</p>
<p>Right? And so we'll start by doing this recursively.</p>
<p>And I'd say that's probably the best way to solve this one.</p>
<p>So I think it's the only way I'll show you, when I want to do is start with a base case, right? So we said we want to figure out our root to leaf paths.</p>
<p>So our base case should be about whether I have a leaf, right? So I'm going to go ahead and check let's say, if my root left is equal to No, right? And root, right? Is equal to No, right? That's the definition of a leaf.</p>
<p>So if I have the left child and I have the right child, then I should return the value stored at this node, right? So root, dot Val.</p>
<p>Nice.</p>
<p>So again, we're kind of emphasizing here is that base case catches a scenario.</p>
<p>If we're at like four, right, we have no children.</p>
<p>Nice.</p>
<p>And we will need another base case in the long run.</p>
<p>For now, let's say we left it like this, right? So we said that in the context of solving this one recursively, the decision we make at every note is I choose the bigger result from my left column A right call, and then I add myself to it, right? So I know I'm going to do this recursively so I'm going to call the same function.</p>
<p>And right now you should be familiar with all right, you call your function on root left, and also root right? That I think about what those calls return, right? They give me back, the max pass some through my left subtree on the max path, some through my right subtree I just want to choose the bigger results between Windows two.</p>
<p>So no I swear to you saw me use the math dot min function here I'll use the math dot max function.</p>
<p>And I know that these calls these expressions evaluates to numbers.</p>
<p>So I can actually just pass these guys in, in line.</p>
<p>So I would just move this up like that.</p>
<p>So when finding the max between these two results, and I'll go ahead and call that we'll say, the max, your child, right? Maybe I'll write this online, they prefer.</p>
<p>And then from there, I just add myself to that max child, right? So I'm going to return route dot valance myself, plus max child.</p>
<p>And we'll call that max child path.</p>
<p>And that should be it except for one thing we're forgetting.</p>
<p>So take a moment, see if you can read between the lines here.</p>
<p>And what scenario Am I missing? We did mention it in the approach video.</p>
<p>So can you spot what is not present here? And that's something I find I do often right? If I'm able to really come up with a nice, meaningful and consistent picture, then everything I drew in the picture should translate to some piece of code over here.</p>
<p>Let's give it a shot.</p>
<p>Expect to fail this one.</p>
<p>See what we get? Yeah, so we're getting an error cannot read property left have no, right, I found on the very first example.</p>
<p>So I'll tell you that this is caused by an asymmetric node, like this four over here, right? This four has no left child.</p>
<p>So imagine what would happen in this instance, right? So if we're evaluating this code, we know that our route is going to be this four node.</p>
<p>And this if statement on line 10, is not hit, right? Because four is not a leaf, right? Because it has a right child's right child does not know.</p>
<p>So instead, it's going to run until 11.</p>
<p>And it's going to try to execute max path, some of root dot left root that left is no.</p>
<p>And so when we actually evaluate that call, now we're seeing is no, and we're gonna check no dot left over here.</p>
<p>And that's going to break right? It's exactly the line that's broken.</p>
<p>And so in addition to this base case, right, when we bought him out at a leaf node, what if we just end up at a null node, so if root is null, then we said that a good value to return would be negative infinity, right? Because I'm choosing to, in the long run, do like maximal logic and want to pick the max.</p>
<p>So if I choose a negative infinity, that won't interfere with any of us taking a max, right? Because imagine that this thing was negative infinity.</p>
<p>And I would just prefer the right hand side if it was not infinity, right? Negative infinity that is.</p>
<p>And so with that, let's go ahead and give this a go.</p>
<p>Cool.</p>
<p>And then we have a nice solution for our max root to leaf path some problem.</p>
<p>So notice how short the code is, by no means do I think this is simple code, though, right? At this point, it's okay if it feels a little tough.</p>
<p>But you understand how we have some familiar patterns, right, I still have those two recursive calls right over here.</p>
<p>And we typically only vary in how we take those recursive calls or the results from them, and combine them into our higher level answer.</p>
<p>So keep practicing this problem and I'll catch you in the next one.</p>
<p>All right programmers.</p>
<p>That wraps up our course on the introduction to binary trees.</p>
<p>If you want to explore this binary tree topic, or really any other data structures and algorithms topic more deeply.</p>
<p>Be sure to head destructing dotnet where we have all of these topics covered through tons of problems where we have video walkthroughs and illustrations for every single problem.</p>
<p>I think you'll find this especially useful if you're repairing and really cramming for those technical interviews.</p>
<p>Thanks for watching, and I'll see you there. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Coding Interview Graph Traversal Crash Course – The Only One You'll Ever Need ]]>
                </title>
                <description>
                    <![CDATA[ Are you preparing for coding interviews? I designed a crash course series to help you out. I'm Lynn, a software engineer and a recent graduate from the University of Chicago. This is the third course in my Coding Interview Crash Course Series. Feel f... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/coding-interview-graph-traversal-crash-course-the-only-one-youll-ever-need/</link>
                <guid isPermaLink="false">66d460157df3a1f32ee7f86d</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Lynn Zheng ]]>
                </dc:creator>
                <pubDate>Thu, 09 Sep 2021 17:24:25 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/08/Coding-Interview-Series-1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Are you preparing for coding interviews? I designed a crash course series to help you out.</p>
<p>I'm Lynn, a software engineer and a recent graduate from the University of Chicago. This is the third course in my Coding Interview Crash Course Series. Feel free to check out <a target="_blank" href="https://www.youtube.com/channel/UCZ2MeG5jTIqgzEMiByrIzsw">my YouTube channel, Lynn's DevLab</a>, to stay updated on this series.</p>
<p>This crash course is about <strong>Graph Traversal.</strong> If you just want to dive right in, you can find the course here (and linked at the bottom of this article). If you want a little more info, read on. 😎</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/d31vGF-Z69c" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-introduction">Introduction</h2>
<p>We will cover two common graph traversal techniques: <strong>Depth-First Search (DFS)</strong> and <strong>Breadth-First Search (BFS).</strong></p>
<p>We will first learn about how they work and how to implement them in code. Then we will see the algorithms in action by solving a LeetCode problem as well as looking at how I applied Graph Traversal when implementing an algorithm for my game, <a target="_blank" href="https://github.com/RuolinZheng08/unity-clicky-galaxy"><strong>Clicky Galaxy</strong></a> (also my first game in Unity when I was learning Unity 😉).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/clicky.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Clicky Galaxy, a game I made when learning Unity</em></p>
<h2 id="heading-course-outline">Course Outline</h2>
<p><a target="_blank" href="https://youtu.be/d31vGF-Z69c">This course video</a> runs for 1 hour and features:</p>
<ul>
<li><p>A high-level description of Graphs, DFS, and BFS</p>
</li>
<li><p>DFS implementation</p>
</li>
<li><p>BFS implementation</p>
</li>
<li><p>How to find a path between a source and a destination node</p>
</li>
<li><p>LeetCode Demo: 785. Is Graph Bipartite?</p>
</li>
<li><p>Clicky Galaxy Demo and Graph Traversal in Unity C# 🚀</p>
</li>
</ul>
<p>Graphs are a favorite interview subject among top tech companies like Google, Microsoft, and Facebook. More importantly, it's also fun and useful in practical software engineering like Game Development. Let's crunch this topic together in my course!</p>
<h2 id="heading-definition-of-a-graph">Definition of a Graph</h2>
<p>We will use the following graph to show the traversal path for the two traversal algorithms.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screen-Shot-2021-08-21-at-08.41.06.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We may represent the graph by mapping each node to its list of neighbors, as shown in this Python snippet:</p>
<pre><code class="lang-python">graph = {
    <span class="hljs-number">0</span>: [<span class="hljs-number">1</span>, <span class="hljs-number">4</span>],
    <span class="hljs-number">1</span>: [<span class="hljs-number">0</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>],
    <span class="hljs-number">2</span>: [<span class="hljs-number">1</span>, <span class="hljs-number">3</span>],
    <span class="hljs-number">3</span>: [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>],
    <span class="hljs-number">4</span>: [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>]
}
</code></pre>
<h2 id="heading-how-to-use-depth-first-search">How to Use Depth-First Search</h2>
<p>As its name suggests, DFS prioritizes depth in its search.</p>
<p>For a given node (say 1), after visiting one of its neighbors (say 0), instead of visiting the rest of the neighbors (nodes 2, 3, and 4) immediately, it caches those neighbors and immediately resumes its visit on 0's neighbors. Only when it has exhausted the depth will it return to those cached neighbors.</p>
<h3 id="heading-iterative-implementation">Iterative Implementation</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">dfs</span>(<span class="hljs-params">graph, start</span>):</span>
  visited, stack = set(), [start]
  <span class="hljs-keyword">while</span> stack:
    node = stack.pop()
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> node <span class="hljs-keyword">in</span> visited:
        <span class="hljs-comment"># perform some operations on the node</span>
        <span class="hljs-comment"># for example, we print out the node</span>
        print(<span class="hljs-string">'Now visiting'</span>, node)
    visited.add(node)
    <span class="hljs-keyword">for</span> neighbor <span class="hljs-keyword">in</span> graph[node]:
      <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> neighbor <span class="hljs-keyword">in</span> visited:
        stack.append(neighbor)
  <span class="hljs-keyword">return</span> visited
</code></pre>
<p>In this template, the commented lines are where we can perform some operations on the node: for example, printing out its value, checking for equality, and so on.</p>
<p>We keep track of a set named <strong>visited</strong> to avoid visiting the same node multiple times where there is a cycle in the graph, like in our example graph above.</p>
<p>Running this code on the graph we defined above results in the output below:</p>
<pre><code class="lang-python">Now visiting <span class="hljs-number">0</span>
Now visiting <span class="hljs-number">4</span>
Now visiting <span class="hljs-number">3</span>
Now visiting <span class="hljs-number">2</span>
Now visiting <span class="hljs-number">1</span>
</code></pre>
<h2 id="heading-how-to-use-breadth-first-search">How to Use Breadth-First Search</h2>
<p>BFS prioritizes breadth in its search. For a given node, it visits all of its immediate neighbors before moving onto the neighbors' neighbors.</p>
<h3 id="heading-iterative-implementation-1">Iterative Implementation</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bfs</span>(<span class="hljs-params">graph, start</span>):</span>
  visited, queue = set(), deque([start])
  <span class="hljs-keyword">while</span> queue:
    node = queue.popleft()
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> node <span class="hljs-keyword">in</span> visited:
        <span class="hljs-comment"># perform some operations on the node</span>
        print(<span class="hljs-string">'Now visiting'</span>, node)
    visited.add(node)
    <span class="hljs-keyword">for</span> neighbor <span class="hljs-keyword">in</span> graph[node]:
      <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> neighbor <span class="hljs-keyword">in</span> visited:
          queue.append(neighbor)
  <span class="hljs-keyword">return</span> visited
</code></pre>
<p>Running this code on the graph we defined above results in the output below:</p>
<pre><code class="lang-python">Now visiting <span class="hljs-number">0</span>
Now visiting <span class="hljs-number">1</span>
Now visiting <span class="hljs-number">4</span>
Now visiting <span class="hljs-number">2</span>
Now visiting <span class="hljs-number">3</span>
</code></pre>
<h2 id="heading-how-to-find-a-path-between-a-source-and-a-destination">How to Find a Path Between a Source and a Destination</h2>
<p>Now that we've seen how to use DFS and BFS to traverse the entire graph and print out the whole traversal history, we can make some small changes to the templates to find a <strong>path</strong> between any two nodes in the graph (if such path exists).</p>
<p>On a graph where each edge has the same weight, BFS is equivalent to <strong>Dijkstra's Shortest Path Algorithm</strong>. It finds the shortest path (path with the fewest number of nodes) between a source node and a destination node. This is a nice property that a path search with DFS doesn't have.</p>
<p>Here's how we adapt the DFS template to return a path given a <strong>src</strong> and a <strong>dst</strong> node:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">dfs_path</span>(<span class="hljs-params">graph, src, dst</span>):</span>
  stack = [(src, [src])]
  visited = set()
  <span class="hljs-keyword">while</span> stack:
    node, path = stack.pop()
    <span class="hljs-keyword">if</span> node <span class="hljs-keyword">in</span> visited:
      <span class="hljs-keyword">continue</span>
    <span class="hljs-keyword">if</span> node == dst:
      <span class="hljs-keyword">return</span> path
    visited.add(node)
    <span class="hljs-keyword">for</span> neighbor <span class="hljs-keyword">in</span> graph[node]:
      stack.append((neighbor, path + [neighbor]))
  <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>
</code></pre>
<p>Similarly for BFS:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bfs_path</span>(<span class="hljs-params">graph, src, dst</span>):</span>
  visited, queue = set(), deque([[src]])
  <span class="hljs-keyword">while</span> queue:
    path = queue.popleft()
    node = path[<span class="hljs-number">-1</span>]
    <span class="hljs-keyword">if</span> node <span class="hljs-keyword">in</span> visited:
      <span class="hljs-keyword">continue</span>
    <span class="hljs-keyword">if</span> node == dst:
      <span class="hljs-keyword">return</span> path
    <span class="hljs-keyword">for</span> neighbor <span class="hljs-keyword">in</span> graph[node]:
      queue.append(path + [neighbor])
  <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>
</code></pre>
<h2 id="heading-lets-solve-a-leetcode-problem">Let's Solve a LeetCode Problem!</h2>
<p>Let's now apply what we learned about Graph Traversal to solve a problem on <a target="_blank" href="https://leetcode.com/problems/is-graph-bipartite/">LeetCode, 785. Is Graph Bipartite?</a></p>
<p>According to <a target="_blank" href="https://www.geeksforgeeks.org/bipartite-graph/">this article</a>, a modified BFS algorithm is all we need:</p>
<blockquote>
<p>Following is a simple algorithm to find out whether a given graph is Bipartite or not using Breadth First Search (BFS).</p>
<ol>
<li><p>Assign RED color to the source vertex (putting into set U).</p>
</li>
<li><p>Color all the neighbors with BLUE color (putting into set V).</p>
</li>
<li><p>Color all neighbor’s neighbor with RED color (putting into set U).</p>
</li>
<li><p>This way, assign color to all vertices such that it satisfies all the constraints of m way coloring problem where m = 2.</p>
</li>
<li><p>While assigning colors, if we find a neighbor which is colored with same color as current vertex, then the graph cannot be colored with 2 vertices (or graph is not Bipartite)</p>
</li>
</ol>
</blockquote>
<p>Plugging our template, the solution is as simple as follows. Check out <a target="_blank" href="https://youtu.be/d31vGF-Z69c">my video</a> for a line-by-line explanation.</p>
<pre><code class="lang-python">RED = <span class="hljs-number">0</span>
BLUE = <span class="hljs-number">1</span>
<span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> deque

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">isBipartite</span>(<span class="hljs-params">self, graph: List[List[int]]</span>) -&gt; bool:</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> graph:
            <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
        queue, visited = deque([]), set()
        <span class="hljs-keyword">for</span> v <span class="hljs-keyword">in</span> range(len(graph)):
            <span class="hljs-keyword">if</span> v <span class="hljs-keyword">in</span> visited:
                <span class="hljs-keyword">continue</span>
            queue.append(v)
            node_colors = {v: RED}
            <span class="hljs-keyword">while</span> queue:
                node = queue.popleft()
                visited.add(node)
                my_color = node_colors[node]
                <span class="hljs-keyword">for</span> neighbor <span class="hljs-keyword">in</span> graph[node]:
                    <span class="hljs-keyword">if</span> neighbor <span class="hljs-keyword">in</span> node_colors <span class="hljs-keyword">and</span> node_colors[neighbor] == my_color:
                        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
                    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> neighbor <span class="hljs-keyword">in</span> visited:
                        queue.append(neighbor)
                    node_colors[neighbor] = RED <span class="hljs-keyword">if</span> my_color == BLUE <span class="hljs-keyword">else</span> BLUE

        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
</code></pre>
<h2 id="heading-graph-traversal-in-action-clicky-galaxy-a-game-by-me">Graph Traversal in Action: Clicky Galaxy, A Game by Me</h2>
<p>One more fun demo about Graph Traversal: Clicky Galaxy 🚀, a casual match-three game I built when I was learning Unity.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/clicky.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the game, you move a planet to an empty cell and score when there are three or more identical planets aligned horizontally or vertically. A planet can only move horizontally or vertically, and its movement path cannot be obstructed by other planets.</p>
<p>I applied Graph Traversal to check for a valid path between the planet the player clicked on and the destination cell to determine if the planet can move to that cell.</p>
<p>Each cell in the grid is a node and has four immediate neighbors: up, down, left, and right. As I want to find a short path between the source and the destination (if there exists one), <strong>BFS pathfinding</strong> is ideal for my use case.</p>
<p>Here is how my code looks like in C#. I used a helper named <strong>GetNeighbors</strong> to get the four immediate neighbors, ignoring out-of-bound ones.</p>
<pre><code class="lang-csharp"><span class="hljs-function">List&lt;Vector2Int&gt; <span class="hljs-title">BreadthFirstSearch</span>(<span class="hljs-params">Vector2Int srcIndices, Vector2Int dstIndices</span>)</span> {
    <span class="hljs-comment">// identify a path from srcIndices to dstIndices, could be null</span>
    <span class="hljs-comment">// the path include src and dst</span>
    HashSet&lt;Vector2Int&gt; visited = <span class="hljs-keyword">new</span> HashSet&lt;Vector2Int&gt;();
    Queue&lt;List&lt;Vector2Int&gt;&gt; pathQueue = <span class="hljs-keyword">new</span> Queue&lt;List&lt;Vector2Int&gt;&gt;();

    List&lt;Vector2Int&gt; startPath = <span class="hljs-keyword">new</span> List&lt;Vector2Int&gt;();
    startPath.Add(srcIndices);
    pathQueue.Enqueue(startPath);

    <span class="hljs-keyword">while</span> (pathQueue.Count &gt; <span class="hljs-number">0</span>) {
        List&lt;Vector2Int&gt; path = pathQueue.Dequeue();
        Vector2Int node = path[path.Count - <span class="hljs-number">1</span>];
        <span class="hljs-keyword">if</span> (visited.Contains(node)) {
            <span class="hljs-keyword">continue</span>;
        }
        <span class="hljs-keyword">if</span> (node == dstIndices) { <span class="hljs-comment">// done</span>
            <span class="hljs-keyword">return</span> path;
        }
        visited.Add(node);
        List&lt;Vector2Int&gt; neighbors = GetNeighbors(node);
        <span class="hljs-keyword">foreach</span> (Vector2Int neighbor <span class="hljs-keyword">in</span> neighbors) {
            Sprite sprite = GetSpriteAtIndices(neighbor.x, neighbor.y);
            <span class="hljs-keyword">if</span> (sprite == <span class="hljs-literal">null</span>) { <span class="hljs-comment">// can visit this next</span>
                List&lt;Vector2Int&gt; newPath = <span class="hljs-keyword">new</span> List&lt;Vector2Int&gt;(path);
                newPath.Add(neighbor);
                pathQueue.Enqueue(newPath);
            }
        }
    }

    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
}

<span class="hljs-function">List&lt;Vector2Int&gt; <span class="hljs-title">GetNeighbors</span>(<span class="hljs-params">Vector2Int indices</span>)</span> {
    <span class="hljs-comment">// return the four immediate neighbors, left, right, up, down</span>
    List&lt;Vector2Int&gt; neighbors = <span class="hljs-keyword">new</span> List&lt;Vector2Int&gt;();
    <span class="hljs-keyword">if</span> (indices.x &gt;= <span class="hljs-number">0</span> &amp;&amp; indices.x &lt; gridDimension &amp;&amp; indices.y &gt;= <span class="hljs-number">0</span> &amp;&amp; indices.y &lt; gridDimension) {
        <span class="hljs-keyword">if</span> (indices.y &gt;= <span class="hljs-number">1</span>) {
            neighbors.Add(<span class="hljs-keyword">new</span> Vector2Int(indices.x, indices.y - <span class="hljs-number">1</span>));
        }
        <span class="hljs-keyword">if</span> (indices.y &lt; gridDimension - <span class="hljs-number">1</span>) {
            neighbors.Add(<span class="hljs-keyword">new</span> Vector2Int(indices.x, indices.y + <span class="hljs-number">1</span>));
        }
        <span class="hljs-keyword">if</span> (indices.x &gt;= <span class="hljs-number">1</span>) {
            neighbors.Add(<span class="hljs-keyword">new</span> Vector2Int(indices.x - <span class="hljs-number">1</span>, indices.y));
        }
        <span class="hljs-keyword">if</span> (indices.x &lt; gridDimension - <span class="hljs-number">1</span>) {
            neighbors.Add(<span class="hljs-keyword">new</span> Vector2Int(indices.x + <span class="hljs-number">1</span>, indices.y));
        }
    }
    <span class="hljs-keyword">return</span> neighbors;
}
</code></pre>
<p>And my game came together really well with this algorithm!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/clicky-1.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>In this crash course, we learned about the two Graph Traversal algorithms, DFS and BFS. We saw them in implementation first and then in action in a LeetCode problem as well as in my game.</p>
<p>If you enjoyed Graphs, think about how they relate to Trees. Spoiler alert! Pre-order traversal in trees is essentially DFS in graphs and level-order traversal in trees is essentially BFS in graphs. 🤫</p>
<p>Try figuring this out on your own or watch <a target="_blank" href="https://youtu.be/uaeCfsCcYWo">my crash course on Tree Traversal</a> for a refresher. Trust me, algorithms can be fun! 😃</p>
<h2 id="heading-resources">Resources</h2>
<p>Watch the course here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/d31vGF-Z69c" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>Access the code template on my GitHub:</p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="a86a3940a23d653bae4d5c399c06639e">
        <script src="https://gist.github.com/RuolinZheng08/a86a3940a23d653bae4d5c399c06639e.js"></script></div><p> </p>
<p>Check out Clicky Galaxy on my GitHub:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/RuolinZheng08/unity-clicky-galaxy">https://github.com/RuolinZheng08/unity-clicky-galaxy</a></div>
<p> </p>
<p>Stay up-to-date with the whole crash course series:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/undefined" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>And lastly, feel free to subscribe to my YouTube channel for more content like this :)</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/undefined" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React Coding Interview – How to Stand Out and Ace the Challenges ]]>
                </title>
                <description>
                    <![CDATA[ By Iva Kop As a React developer, I have gone through my fair share of front-end coding interviews. Recently, I had the opportunity to experience the process from the other side – as an interviewer. Here is what I've learned. Coding interview usually ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-stand-out-during-your-react-coding-interview/</link>
                <guid isPermaLink="false">66d45f3538f2dc3808b790a1</guid>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interview tips ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Job Interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 20 Aug 2021 18:20:42 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/08/reactinterview.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Iva Kop</p>
<p>As a React developer, I have gone through my fair share of front-end coding interviews. Recently, I had the opportunity to experience the process from the other side – as an interviewer. Here is what I've learned.</p>
<p>Coding interview usually involve a multi-step process where interviewers assess everything from basic technical knowledge to culture fit. Every step of that process is important and should not be underestimated. Prepare for all of it and prepare well.</p>
<p>But there is one thing that is at the core of (almost) every React interview.</p>
<p>Inevitably, at some point, you have to build a React app.</p>
<h1 id="heading-the-app-assignment">The App Assignment</h1>
<p>Here is a short list of real app assignments I had to complete for my own React interviews over the years:</p>
<ul>
<li><strong>Support Desk app</strong> – an app to display a list of support desk employees and their contact information.</li>
<li><strong>Video app</strong> – an app where, given a YouTube video URL, it displays it on the page. Users can comment on it.</li>
<li><strong>Projects app</strong> – an app to display a list of on-going projects that users can subscribe to and follow.</li>
<li><strong>Articles app</strong> – an app to display a list of articles where users can leave nested comments for each one.</li>
</ul>
<p>These assignments are, in many ways, very similar to each other. The reason is that they are assessing the same set of basic React skills. Which skills are those? Let's break them down.</p>
<h2 id="heading-interview-skill-1-how-to-build-uis-with-react">Interview Skill #1 – How to Build UIs with React</h2>
<p>A primary job of a React developer is to build and structure React components in a meaningful way. </p>
<p>The assignments above are meant to test your ability to write code in a modular and reusable way while creating abstractions at the right level. </p>
<p>The main goal is for your app to work well. But, as a front-end developer, you are also expected to build UIs that look good, too.</p>
<p>Most of the time, the assignment will come with a concrete design you'll need to follow. If that is the case, it's important to stick closely to it. </p>
<p>But if you believe that there is a good reason to deviate, don't hesitate to do so. Just be prepared to explain why your solution is better.</p>
<p>If there is no design available, the interviewer is probably interested in understanding if you can create sensible UIs on your own. Although this could be more challenging, it also gives you the opportunity to show you are able to make conscious choices when it comes to the front-end.</p>
<p><strong>Tip:</strong> It is easy to assume that the expectation is that you have to build all components from scratch. Using a third party component library might feel like cheating in an interview context. But it is not! </p>
<p>Make sure to ask in advance what is expected. Taking advantage of component libraries like <a target="_blank" href="https://material-ui.com/">MaterialUI</a> or <a target="_blank" href="https://chakra-ui.com/">ChakraUI</a>  is a huge time saver during interview assignments and will allow you to focus on more interesting parts of the app.</p>
<h2 id="heading-interview-skill-2-state-management-in-react">Interview Skill #2 – State Management in React</h2>
<p>Another important challenge when it comes to building React apps is state management. There is a myriad of ways to go about this depending on your concrete use case and goals. Check out <a target="_blank" href="https://blog.whereisthemouse.com/how-to-think-about-react-state-management">my article</a> on the topic if you are curious to learn more.</p>
<p>Whatever approach you choose, what is important during as interview assignment is to show the interviewer that you understand and are able to reason about state management. </p>
<p>Your solution needs to make sense without being overly complex or convoluted. Be prepared to explain and defend your choices.</p>
<p><strong>Tip:</strong> It is a good idea to match your state management solution to the one used by the company your are interviewing for. </p>
<p>Do they use Redux? Then don't hesitate to include Redux in your project. Are they into state machines? Then xState is your friend, and so on. Make sure to ask the interviewer in advance what they would like to see implemented in your project.</p>
<h2 id="heading-interview-skill-3-data-fetching-in-react">Interview Skill #3 – Data-fetching in React</h2>
<p>As a front-end developer, normally you won't be expected to build your own back-end. But the assignment you are given will probably involve some form of data-fetching – likely either through a mock API of some kind or just a JSON file with the necessary data.</p>
<p>This part of the assignment is meant to test if you, as a front-end developer, know how to talk to the back-end. Can you get, display and update the data you receive from the back-end correctly? Do you understand how API requests work? </p>
<p>In a more advanced setting, there might be a conversation about data-fetching architecture, data state management, and front-end caching.</p>
<p><strong>Tip:</strong> Make an effort to implement a semi-realistic data-fetching mechanism in your app. In you are given a JSON file, don't just directly import the data in your components. Instead, use <code>fetch</code> or another more advanced (preferably async) approach to get it so that you are able to demonstrate your deeper understanding.</p>
<h2 id="heading-interview-skill-4-routing-in-react">Interview Skill #4 – Routing in React</h2>
<p>A lot of the time, creating a React project is synonymous with a single page application. So it is possible that the assignment involves implementing a routing solution. </p>
<p>Here the goal is to demonstrate that you understand the basics of client-side routing and are able to structure your app around it.</p>
<p><strong>Tip:</strong> Avoid creating your own client-side routing implementation, unless explicitly required. Opting for <a target="_blank" href="https://reactrouter.com/">React Router</a> or <a target="_blank" href="https://reach.tech/router/">Reach Router</a> is a perfectly acceptable choice.</p>
<h1 id="heading-how-to-stand-out-in-a-react-interview">How to Stand Out in a React Interview</h1>
<p>Getting a solid grasp on the basics discussed above is a must and it's a good start to earn points during an interview assignment. But to truly stand out, you have to go a step further.</p>
<p>Here is how.</p>
<h2 id="heading-understand-your-setup">Understand Your Setup</h2>
<p>Most of the time you can get away with using toolchains like Create React App (or similar) when building a React project for an interview. This will help you get started and save time. </p>
<p>In fact, it is important to use those tools in order to spend your time on meaningful development rather than setup. </p>
<p>But it's also important to understand and be able to explain the basic tooling you are using. During a React interview, expect to be asked questions about <a target="_blank" href="https://webpack.js.org/">Webpack</a> and <a target="_blank" href="https://babeljs.io/">Babel</a>, for example.</p>
<p>But what can really give you an edge is if you not only understand but are able to enhance your existing setup. One idea would be to add a linter (<a target="_blank" href="https://eslint.org/">eslint</a>) and a formatter (<a target="_blank" href="https://prettier.io/">prettier</a>) to your app. This shows that you really care about code quality and consistency.</p>
<p>Another would be to go even further and setup pre-commit hooks (<a target="_blank" href="https://github.com/typicode/husky">husky</a>) that lint and format your code with each commit. Crazy, I know!</p>
<p>These tools take minutes to setup but can seem like an impressive extra step in the eyes on an interviewer.</p>
<h2 id="heading-test-your-code">Test Your Code</h2>
<p>Very few assignments will explicitly state that tests are required. For this reason, many developers assume tests are not part of the task and completely ignore them. This is wrong!</p>
<p>Most of the time, an interviewer will be impressed to see that you understand the importance of testing your code. It is a very easy but powerful way to set yourself apart. </p>
<p>It is not necessary to have a test for every single line of code in your project. Several strategically selected tests covering the more complicated logic should do the trick just fine.</p>
<h2 id="heading-dont-ignore-responsiveness">Don't Ignore Responsiveness</h2>
<p>Here is another aspect of your React assignment that is not explicitly mentioned most of the time – responsiveness. </p>
<p>Even if you are given a design at the beginning of the task, almost always it will not be a responsive one. It is up to you care enough about responsiveness to figure it out on your own.</p>
<p>Same as testing, most developers will just ignore responsiveness. Which is good news for you – it gives you the opportunity to shine!</p>
<p>There is no need for the implementation to be perfect and work flawlessly on every screen and device. The mere fact that this is something you though about in your development process should be enough to score you some major points.</p>
<h2 id="heading-improve-accessibility">Improve Accessibility</h2>
<p>Accessibility is a huge concern for most modern web products. Taking even minor steps to improve the accessibility of your project, like adding <code>alt</code> text to your images, for example, can leave a really good impression.</p>
<p>Accessibility is also another reason why you might want to choose a third-party component library when building your assignment. Most components in these libraries are accessible out of the box.</p>
<p>Making your project as accessible as possible can truly make you stand out in an interview. But what is more, accessibility should be (and is becoming) the norm in web development. Make sure your future employer knows you understand that.</p>
<h2 id="heading-details-matter">Details Matter</h2>
<p>Everything in your code should tell the interviewer you are a competent developer – from basics like the way you name and structure your code to minor details like commit messages. </p>
<p>Given that these assignments are usually done under time constraints, it is tempting to just ignore these seemingly unimportant aspects. But getting them right can meaningfully set you apart.</p>
<p>Hopefully this article is useful for your next React interview. Let me know how it goes!</p>
<p><a target="_blank" href="https://twitter.com/iva_kop">Follow me</a> on Twitter for more tech content.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Coding Interview Tree Traversal Crash Course – The Only One You'll Ever Need ]]>
                </title>
                <description>
                    <![CDATA[ Are you preparing for coding interviews? I designed a crash course series to help you out. I'm Lynn, a software engineer and a recent graduate from the University of Chicago. This is the second course in my Coding Interview Crash Course Series. Feel ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/coding-interview-tree-traversal-crash-course-the-only-one-youll-ever-need/</link>
                <guid isPermaLink="false">66d4601755db48792eed3f73</guid>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interview tips ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Trees ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Lynn Zheng ]]>
                </dc:creator>
                <pubDate>Mon, 16 Aug 2021 23:49:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/08/tree-thumb.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Are you preparing for coding interviews? I designed a crash course series to help you out.</p>
<p>I'm Lynn, a software engineer and a recent graduate from the University of Chicago. This is the second course in my Coding Interview Crash Course Series. Feel free to check out <a target="_blank" href="https://www.youtube.com/channel/UCZ2MeG5jTIqgzEMiByrIzsw">my YouTube channel, Lynn's DevLab</a>, to stay updated on this series.</p>
<p>This crash course is about Tree Traversal. If you just want to dive right in, <a target="_blank" href="https://youtu.be/uaeCfsCcYWo">you can find the course here</a> (and linked at the bottom of this article). If you want a little more info, read on. 😎</p>
<h2 id="heading-who-is-the-course-for-and-what-are-tree-traversal-algorithms">Who is the Course for and What are Tree Traversal Algorithms? 🌳</h2>
<p>You will get the most of this course if you already know a bit about the <strong>Tree</strong> data structure. Check out <a target="_blank" href="https://www.freecodecamp.org/news/binary-data-structures-an-intro-to-trees-and-heaps-in-javascript-962ab536cb42/">these</a> <a target="_blank" href="https://www.freecodecamp.org/news/the-codeless-guide-to-tree-data-structures/">tutorials</a> if you need a refresher.</p>
<p>We will cover the traversal algorithms for both <strong>Binary Trees</strong> and <strong>N-ary Trees</strong> (in which each parent node has an arbitrary number of children).</p>
<p>If you have heard about Binary Search Trees (BST) before, that's a special type of Binary Tree so the techniques we are going to learn here also apply.</p>
<p>Trees are a favorite interview subject among top tech companies like Google, Microsoft, and Facebook, so let's crunch this topic!</p>
<p>We will learn about four traversal techniques and solve their corresponding LeetCode problems hands-on.</p>
<p>The four techniques are:</p>
<ul>
<li><p><strong>Pre-order (Depth-First Search, DFS)</strong></p>
</li>
<li><p><strong>Post-order</strong></p>
</li>
<li><p><strong>In-order</strong></p>
</li>
<li><p><strong>Level-order (Breadth-First Search, BFS).</strong></p>
</li>
</ul>
<h2 id="heading-course-outline">Course Outline</h2>
<p>This course video runs for a total of 30 minutes and features:</p>
<ul>
<li><p>A high-level description of the four traversal techniques: <strong>pre-order, post-order, in-order, and level-order</strong></p>
</li>
<li><p><strong>Recursive</strong> implementations of pre-order, post-order, and in-order (Note: this doesn't apply to level-order)</p>
</li>
<li><p><strong>Iterative</strong> implementations of pre-order, post-order, in-order, and level-order</p>
</li>
<li><p>An extension of the templates from <strong>Binary Trees</strong> to <strong>N-ary Trees</strong></p>
</li>
</ul>
<p>Let's dive into each of the four techniques below.</p>
<h2 id="heading-tree-traversal-demonstration-using-an-example-tree">Tree Traversal Demonstration Using an Example Tree</h2>
<p>We will use the following tree to demonstrate the output from the four traversal techniques.</p>
<p>Note that this tree is a simple Binary Tree, not a Binary Search Tree (BST). A BST is a special type of Binary Tree, so our techniques also apply. Also, <strong>in-order traversal</strong> becomes especially interesting when we work with a BST, as we will see below.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screen-Shot-2021-08-16-at-2.48.44-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>An example Binary Tree. Note that it's not a Binary Search Tree (BST).</em></p>
<p>Given this tree, the traversal result from the four techniques are as follows:</p>
<ul>
<li><p>Pre-order: 1, 2, 4, 5, 3</p>
</li>
<li><p>Post-order: 4, 5, 2, 3, 1</p>
</li>
<li><p>In-order: 4, 2, 5, 1, 3</p>
</li>
<li><p>Level-order: 1, 2, 3, 4, 5</p>
</li>
</ul>
<h3 id="heading-pre-order-traversal">Pre-order Traversal</h3>
<p>Pre-order traversal is also known as <strong>Depth-First Search (DFS)</strong> if we analyze the tree as a graph and take the tree root node as our starting node in the search.</p>
<p>As in the example above, we go all the way down to the <strong>leftmost</strong> node before visiting any other node that is a left child of some parent node.</p>
<p>Pre-order traversal allows us to explore roots before leaves, and is hence ideal for tasks like copying a tree.</p>
<h3 id="heading-post-order-traversal">Post-order Traversal</h3>
<p>Post-order traversal does the opposite of pre-order traversal, allowing us to explore leaves before roots.</p>
<h3 id="heading-in-order-traversal">In-order Traversal</h3>
<p>In-order traversal is especially useful for flattening a tree into an array representation.</p>
<p>For a Binary Search Tree like below, in-order traversal outputs an array in a sorted, non-decreasing order: -4, 3, 2, 5, 18.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screen-Shot-2021-08-16-at-2.51.44-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Binary Search Tree example</em></p>
<h3 id="heading-level-order-traversal">Level-order Traversal</h3>
<p>Level-order traversal is also known as <strong>Breadth-First Search (BFS)</strong> if we consider the tree as a graph and start our search from the tree root node.</p>
<p>We visit every node on the current level (depth) before moving onto those on the next level. Effectively, we visit the immediate neighbor of (one step away from) our current node before visiting neighbors that are farther away.</p>
<h2 id="heading-how-to-implement-these-four-techniques">How to Implement these Four Techniques</h2>
<p>We will use the following definition for a node of a Binary Tree:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Definition for a binary tree node.</span>
<span class="hljs-comment"># class TreeNode:</span>
<span class="hljs-comment">#     def __init__(self, val=0, left=None, right=None):</span>
<span class="hljs-comment">#         self.val = val</span>
<span class="hljs-comment">#         self.left = left</span>
<span class="hljs-comment">#         self.right = right</span>
</code></pre>
<h3 id="heading-recursive-implementation">Recursive implementation</h3>
<p>Recursive implementations are the most straightforward. The most important thing to remember is the order in which we concatenate the results from the two recursive calls (one on the left subtree and one on the right subtree) with the value of the current node.</p>
<pre><code class="lang-pgsql">def preorder(root):
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> root:
        <span class="hljs-keyword">return</span> []
    <span class="hljs-keyword">return</span> [root.val] + preorder(root.left) + preorder(root.right)
</code></pre>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">postorder</span>(<span class="hljs-params">root</span>):</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> root:
        <span class="hljs-keyword">return</span> []
    <span class="hljs-keyword">return</span> postorder(root.left) + postorder(root.right) + [root.val]
</code></pre>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inorder</span>(<span class="hljs-params">root</span>):</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> root:
        <span class="hljs-keyword">return</span> []
    <span class="hljs-keyword">return</span> inorder(root.left) + [root.val] + inorder(root.right)
</code></pre>
<h3 id="heading-iterative-implementation">Iterative implementation</h3>
<p>Compared to recursive implementations, iterative implementations are non-trivial. Most require that we use either a stack or a queue to keep track of the nodes that we need to visit.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">preorder</span>(<span class="hljs-params">self, root</span>):</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> root:
        <span class="hljs-keyword">return</span> []
    ret = []
    stack = [root]
    <span class="hljs-keyword">while</span> stack:
        node = stack.pop()
        ret.append(node.val)
        <span class="hljs-comment"># note that we append the right child before the left child</span>
        <span class="hljs-keyword">if</span> node.right:
            stack.append(node.right)
        <span class="hljs-keyword">if</span> node.left:
            stack.append(node.left)
    <span class="hljs-keyword">return</span> ret
</code></pre>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">postorder</span>(<span class="hljs-params">self, root</span>):</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> root:
        <span class="hljs-keyword">return</span> []
    <span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> deque
    ret = deque()
    stack = [root]
    <span class="hljs-keyword">while</span> stack:
        node = stack.pop()
        ret.appendleft(node.val)
        <span class="hljs-keyword">if</span> node.left:
            stack.append(node.left)
        <span class="hljs-keyword">if</span> node.right:
            stack.append(node.right)
    <span class="hljs-keyword">return</span> ret
</code></pre>
<p>The implementation for in-order traversal looks quite different from pre-order and post-order:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inorder</span>(<span class="hljs-params">self, root</span>):</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> root:
        <span class="hljs-keyword">return</span> []
    ret = []
    stack = []
    <span class="hljs-keyword">while</span> root <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span> <span class="hljs-keyword">or</span> stack:
        <span class="hljs-keyword">while</span> root <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
            stack.append(root)
            root = root.left
        root = stack.pop()
        ret.append(root.val)
        root = root.right
    <span class="hljs-keyword">return</span> ret
</code></pre>
<p>Lastly, we have level-order traversal, where we will output the result as <code>[[nodes on the first level], [nodes on the second level], [nodes on the third level], ...]</code>.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">levelorder</span>(<span class="hljs-params">self, root</span>):</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> root:
        <span class="hljs-keyword">return</span> []
    ret = []
    <span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> deque
    queue = deque([root])
    <span class="hljs-keyword">while</span> queue:
        ret_row = []
        <span class="hljs-comment"># fixed size for current level</span>
        <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(len(queue)):
            node = queue.popleft()
            ret_row.append(node.val)
            <span class="hljs-keyword">if</span> node.left:
                queue.append(node.left)
            <span class="hljs-keyword">if</span> node.right:
                queue.append(node.right)
        ret.append(ret_row)
    <span class="hljs-keyword">return</span> ret
</code></pre>
<h3 id="heading-n-ary-trees">N-ary Trees</h3>
<p>We now extend our templates from handling Binary Trees to handling N-ary Trees. We use the following definition for the node of an N-ary Tree:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, val=None, children=[]</span>):</span>
        self.val = val
        self.children = children
</code></pre>
<p>To extend our iterative implementations to handle N-ary Trees, all we need to do is to make sure that we are appending the child nodes that we will visit in a correct order.</p>
<p>Recall that in pre-order traversal, we appended the right child before the left child. So when appending the children of a node of an N-ary Tree, we need to reverse the list of children.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">preorder</span>(<span class="hljs-params">self, root</span>):</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> root:
        <span class="hljs-keyword">return</span> []
    ret = []
    stack = [root]
    <span class="hljs-keyword">while</span> stack:
        node = stack.pop()
        ret.append(node.val)
        <span class="hljs-comment"># reverse the list of children</span>
        <span class="hljs-keyword">for</span> child <span class="hljs-keyword">in</span> node.children[::<span class="hljs-number">-1</span>]:
            stack.append(child)
    <span class="hljs-keyword">return</span> ret
</code></pre>
<p>For the other traversal techniques, since we are appending the children from the left to the right, we can iterative over the list of children normally:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">postorder</span>(<span class="hljs-params">self, root</span>):</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> root:
        <span class="hljs-keyword">return</span> []
    <span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> deque
    ret = deque()
    stack = [root]
    <span class="hljs-keyword">while</span> stack:
        node = stack.pop()
        ret.appendleft(node.val)
        <span class="hljs-keyword">for</span> child <span class="hljs-keyword">in</span> node.children:
            stack.append(child)
    <span class="hljs-keyword">return</span> ret
</code></pre>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">levelorder</span>(<span class="hljs-params">self, root</span>):</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> root:
        <span class="hljs-keyword">return</span> []
    ret = []
    <span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> deque
    queue = deque([root])
    <span class="hljs-keyword">while</span> queue:
        ret_row = []
        <span class="hljs-comment"># fixed size for current level</span>
        <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(len(queue)):
            node = queue.popleft()
            ret_row.append(node.val)
            <span class="hljs-keyword">for</span> child <span class="hljs-keyword">in</span> node.children:
                queue.append(child)
        ret.append(ret_row)
    <span class="hljs-keyword">return</span> ret
</code></pre>
<p>And now we can apply our tree traversal templates to trees that have an arbitrary number of children at each node.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this crash course on tree traversal, we learned four techniques: pre-order, post-order, in-order, and level-order. We discussed how they differ and what tasks they are best for.</p>
<p>We also implemented them both in a recursive fashion and in an iterative one. Last but not least, we extended the techniques to deal with not only Binary Trees, but N-ary Trees.</p>
<p>I hope now you feel more confident about tree traversal interview questions. This is also a nice segue into the topic of my next crash course on graph traversal.</p>
<p>With the knowledge of pre-order traversal and level-order traversal, DFS and BFS won't be completely out of the blue for you 🤓 I will even talk about how I applied graph traversal when developing an algorithm for <a target="_blank" href="https://github.com/RuolinZheng08/unity-clicky-galaxy">my match-three game, Clicky Galaxy,</a> so stay tuned!</p>
<h2 id="heading-resources">Resources</h2>
<p>Watch the course here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/uaeCfsCcYWo" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>Access the code template on my GitHub:</p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="f6e55b09eb096fe5fe630249cd859b07">
        <script src="https://gist.github.com/RuolinZheng08/f6e55b09eb096fe5fe630249cd859b07.js"></script></div><p> </p>
<p>Check out the whole crash course series:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/undefined" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>And lastly, feel free to subscribe to my YouTube channel for more content like this :)</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/undefined" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Interview Prep Cheatsheet – Ace Your Coding Interviews with These Concepts ]]>
                </title>
                <description>
                    <![CDATA[ By rajat gupta I've carefully gone through over 50 resources, I've been through 10 JavaScript interviews, and I've landed a job at a unicorn startup. And throughout this entire process, I started to see a pattern in the most frequently asked JS inter... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-interview-prep-cheatsheet/</link>
                <guid isPermaLink="false">66d460c53bc3ab877dae2228</guid>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interview tips ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 07 Jul 2021 15:43:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/06/JS-Interview--2-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By rajat gupta</p>
<p>I've carefully gone through over <strong>50</strong> resources, I've been through <strong>10</strong> JavaScript interviews, and I've landed a <strong>job</strong> at a unicorn startup.</p>
<p>And throughout this entire process, I started to see a <em>pattern</em> in the most frequently asked JS interview questions. </p>
<p>In this article, I have tried to list the concepts which will cover <strong>80%</strong> of any good JS interview.</p>
<p>So, if you are prepping for your next JS interview this is the perfect cheatsheet for you to review and solidify your skills. Go through this and you'll be ready to rock. 💃</p>
<h2 id="heading-prerequisites">📝Prerequisites</h2>
<ul>
<li>Basic knowledge of the web and programming</li>
<li>Familiarity with HTML/CSS and JavaScript (especially ES6+ syntax)</li>
</ul>
<h2 id="heading-table-of-contents">Table Of Contents 📜</h2>
<ul>
<li><a class="post-section-overview" href="#heading-javascript-basics">JavaScript Basics</a> – JS Variables and Array Methods</li>
<li><a class="post-section-overview" href="#heading-functional-programming-in-javascript">Functional Programming in JavaScript</a> – Scope, Closures, and Hoisting</li>
<li><a class="post-section-overview" href="#heading-objects-in-javascript">Objects in JavaScript</a> – Prototypes and "this"</li>
<li><a class="post-section-overview" href="#heading-asynchronous-javascript">Asynchronous JavaScript</a> – Event Loops, Timers, and Promises</li>
<li><a class="post-section-overview" href="#heading-advanced-javascript-concepts-to-know">Advanced JavaScript Concepts to Know</a> - Async/defer, Polyfills, Debouncing, and Throttling </li>
<li><a class="post-section-overview" href="#heading-storage-in-javascript">Storage in JavaScript</a></li>
</ul>
<p><strong>Caveat:</strong> The focus here will largely be to cover concepts relevant to the interview and not to create a comprehensive booklet for learning the language. Treat this more like a cheatsheet.</p>
<p>If you want to dive in deeply and learn more JS concepts, check out <a target="_blank" href="https://www.freecodecamp.org/learn/">freeCodeCamp's curriculum</a>.</p>
<p>With that out of the way - let's go!</p>
<h2 id="heading-javascript-basics">JavaScript Basics 👶</h2>
<p>Let's start off with some basic concepts every JS developer needs to know.</p>
<h3 id="heading-variables-in-javascript">Variables in JavaScript 📥</h3>
<p>Variables are the building blocks of every programming language. You use them to store values. A variable can be a number, string, and many other types. </p>
<p>Now, JS is a <em>loosely-typed</em> language. You don't have to state the type of variable. You can just declare it, and JS will figure it out on its own. </p>
<p>Now, in JavaScript we have <strong>3</strong> ways to declare variables: <code>var</code>, <code>let</code>, and <code>const</code>.</p>
<p>Here are the key differences: </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/06/-wnr0JLxh.png" alt="-wnr0JLxh" width="600" height="400" loading="lazy"></p>
<p>Let's try to understand them through examples.</p>
<p>We will cover scope later on. For now, let's focus on the other differences.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> a = <span class="hljs-number">3</span>
<span class="hljs-keyword">var</span> a = <span class="hljs-number">4</span>

<span class="hljs-built_in">console</span>.log(a) <span class="hljs-comment">// 4 as var variables can be redeclared + updated</span>

<span class="hljs-keyword">let</span> b = <span class="hljs-number">3</span>
<span class="hljs-keyword">let</span> b = <span class="hljs-number">4</span>

<span class="hljs-built_in">console</span>.log(b) <span class="hljs-comment">// Syntax Error as let variables cannot be redeclared</span>

<span class="hljs-comment">// If we just do, it will work because it can be updated</span>
b = <span class="hljs-number">4</span> 

<span class="hljs-keyword">const</span> c = <span class="hljs-number">3</span>
<span class="hljs-keyword">const</span> c = <span class="hljs-number">4</span>

<span class="hljs-built_in">console</span>.log(c) <span class="hljs-comment">// Syntax Error as const variables cannot be redeclared or updated</span>

<span class="hljs-keyword">const</span> d

<span class="hljs-comment">// Will this throw an error? Go through the table and try to find the answer.</span>
</code></pre>
<p><strong>Note:</strong> In JavaScript, putting a semi-colon after the end of statement is optional. I will be skipping it here for the sake of readability.</p>
<h3 id="heading-vs-in-javascript">== vs === in JavaScript</h3>
<p>Let's compare some variables. There are two ways you can do that.</p>
<p><code>==</code> only checks for the value</p>
<p><code>===</code> checks for value + type</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">let</span> a = <span class="hljs-number">5</span> <span class="hljs-comment">// number</span>
<span class="hljs-keyword">let</span> b = <span class="hljs-string">'5'</span> <span class="hljs-comment">// string</span>

<span class="hljs-built_in">console</span>.log(a == b) <span class="hljs-comment">// true</span>

<span class="hljs-built_in">console</span>.log(a === b) <span class="hljs-comment">// false</span>
</code></pre>
<h3 id="heading-arrays-in-javascript">Arrays in JavaScript</h3>
<p>Now that we know a bit about variables, let's move on to arrays and array-methods. </p>
<p>If we have declared a lot of variables, it makes sense to store them somewhere. Otherwise it will be difficult to keep track of all of them. Arrays are one way of storing a variable. </p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">let</span> a = <span class="hljs-number">4</span>
<span class="hljs-keyword">const</span> b = <span class="hljs-number">5</span>
<span class="hljs-keyword">var</span> c = <span class="hljs-string">'hello'</span>

<span class="hljs-keyword">const</span> array = [a, b, c]

<span class="hljs-comment">// or you can just directly do</span>

<span class="hljs-keyword">const</span> arr = [<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-string">'hello'</span>]
</code></pre>
<p>But only storing variables in an array is kind of boring. We can do more <em>stuff</em> with this array (like accessing these variables or changing the order in which they are stored or how they are stored). </p>
<p>For that, JS has a lot of methods. Let's look at some of them now.</p>
<h2 id="heading-javascript-array-methods">JavaScript Array Methods 🧰</h2>
<p>The most frequently used array methods in JS are: <code>map</code>, <code>filter</code>, <code>find</code>, <code>reduce</code>, and <code>forEach</code>.</p>
<p>Let's cover <code>map</code>, <code>filter</code>, and <code>forEach</code>. You can explore more in <a target="_blank" href="https://www.freecodecamp.org/news/complete-introduction-to-the-most-useful-javascript-array-methods/">this helpful article</a>.</p>
<h3 id="heading-the-map-array-method">The <code>map</code> array method</h3>
<p><code>map</code> creates a new copy of the original array. We use it when we want to do something with the elements of the original array but don't want to change it.</p>
<p><code>map</code> iterates over the original array and takes a callback function (which we'll cover later) as an argument. In the callback function, we tell it what to do with the elements.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> a = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]

<span class="hljs-comment">// Create a new array which multiplies every element by 2</span>

<span class="hljs-keyword">const</span> d = a.map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item</span>)</span>{ <span class="hljs-keyword">return</span> item*<span class="hljs-number">2</span> })

<span class="hljs-built_in">console</span>.log(d) <span class="hljs-comment">// [2,4,6,8,10]</span>
</code></pre>
<h3 id="heading-the-filter-array-method">The <code>filter</code> array method</h3>
<p><code>filter</code> creates a new array with elements that meet the given condition(s).</p>
<p>Let's look at an example. I have used <a target="_blank" href="https://www.freecodecamp.org/news/arrow-function-javascript-tutorial-how-to-declare-a-js-function-with-the-new-es6-syntax/">arrow functions</a> here. If you are a little uncomfortable with functions, you can cover the next section first and come back.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Return the words with more than 6 letters</span>
<span class="hljs-keyword">const</span> words = [<span class="hljs-string">'react'</span>, <span class="hljs-string">'script'</span>, <span class="hljs-string">'interview'</span>, <span class="hljs-string">'style'</span>, <span class="hljs-string">'javascript'</span>]

<span class="hljs-keyword">const</span> ans = words.filter(<span class="hljs-function">(<span class="hljs-params">word</span>) =&gt;</span> word.length &gt; <span class="hljs-number">6</span>)

<span class="hljs-built_in">console</span>.log(ans) <span class="hljs-comment">// ['interview', 'javascript']</span>
</code></pre>
<p>Try to do the exercises yourself first to test your knowledge. If you come up with different or better solutions, let me know!</p>
<p>Generally, a follow up to this: can you do it without the array method?</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> newArr = []

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; words.length; i++) {
  <span class="hljs-keyword">if</span> (words[i].length &gt; <span class="hljs-number">6</span>) {
    newArr.push(words[i])
  }
}
<span class="hljs-built_in">console</span>.log(newArr)
</code></pre>
<h3 id="heading-the-foreach-array-method">The <code>forEach</code> array method</h3>
<p><code>forEach</code> is very similar to <code>map</code> but has two key differences:</p>
<p>First of all, <code>map</code> returns a new Array, but <code>forEach</code> doesn't.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Return a new array where even numbers are multiplied by 2 </span>
<span class="hljs-keyword">let</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>]

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">consoleEven</span>(<span class="hljs-params">arr</span>) </span>{
  <span class="hljs-keyword">let</span> data = arr.map(<span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> (num % <span class="hljs-number">2</span> === <span class="hljs-number">0</span> ? num * <span class="hljs-number">2</span> : num * <span class="hljs-number">1</span>))

  <span class="hljs-built_in">console</span>.log(data)  <span class="hljs-comment">// [1,  4, 3, 8, 5, 12, 7]</span>
}


<span class="hljs-comment">// ? is the ternary operator. If the condition is true - first statement is returned otherwise the second one.</span>


consoleEven(arr)
</code></pre>
<pre><code class="lang-javascript">
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">consoleEven</span>(<span class="hljs-params">arr</span>) </span>{
  <span class="hljs-keyword">let</span> data = arr.forEach(<span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> (num % <span class="hljs-number">2</span> === <span class="hljs-number">0</span> ? num * <span class="hljs-number">2</span> : num * <span class="hljs-number">1</span>))
  <span class="hljs-built_in">console</span>.log(data) <span class="hljs-comment">// undefined</span>
}

consoleEven(arr)
</code></pre>
<p>And second, you can do method chaining in <code>map</code> but not in <code>forEach</code>.</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// Convert  the new array back to original</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">consoleEven</span>(<span class="hljs-params">arr</span>) </span>{
  <span class="hljs-keyword">let</span> data = arr
    .map(<span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> (num % <span class="hljs-number">2</span> === <span class="hljs-number">0</span> ? num * <span class="hljs-number">2</span> : num * <span class="hljs-number">1</span>))
    .map(<span class="hljs-function">(<span class="hljs-params">item</span>) =&gt;</span> (item % <span class="hljs-number">2</span> === <span class="hljs-number">0</span> ? item / <span class="hljs-number">2</span> : item / <span class="hljs-number">1</span>))

  <span class="hljs-built_in">console</span>.log(data)
}

consoleEven(arr)
</code></pre>
<p><strong>Note:</strong> <code>map</code> and <code>forEach</code> don't mutate (change) the original array.</p>
<h2 id="heading-functional-programming-in-javascript">Functional Programming in JavaScript 🛠</h2>
<p>We have already used functions above. Let's cover them in more detail now. </p>
<p>Just like how we used variables to store values, we can use functions to store a piece of code which we can reuse.</p>
<p>You can make function in two ways:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">a</span>(<span class="hljs-params"></span>)</span>{
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I am a normal function'</span>);
 }

<span class="hljs-keyword">const</span> b = <span class="hljs-function">() =&gt;</span> {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I am an arrow function'</span>)
}

<span class="hljs-comment">// They are essentially the same but with a few differences which we will cover as we go along this tutorial. </span>

<span class="hljs-comment">// We can pass variables as arguments</span>

<span class="hljs-keyword">const</span> c = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My name is <span class="hljs-subst">${name}</span>`</span>)
}

<span class="hljs-comment">// `` template literal are a new addition to the language. Very useful for string formatting. Values are accessed using ${} inside them.</span>


<span class="hljs-comment">// We can even pass functions as arguments to a function. Will see more on this when we try to understand closures.</span>

<span class="hljs-keyword">const</span> greet = <span class="hljs-function">() =&gt;</span>  {
    <span class="hljs-keyword">const</span> prefix = <span class="hljs-string">'Mr'</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${prefix}</span> <span class="hljs-subst">${name}</span>, welcome!`</span>)
    }
}

<span class="hljs-built_in">console</span>.log(greet()(<span class="hljs-string">'Jack'</span>))
</code></pre>
<p>Now, let's cover some important concepts related to functions.</p>
<h3 id="heading-function-scope-in-javascript">Function Scope in JavaScript 🕵️</h3>
<p>Scope determines from where the variables are accessible.</p>
<p>There are three types of scope:</p>
<ul>
<li>Global (declaration outside of any function)</li>
<li>Function (declaration inside a function)</li>
<li>Block (declaration inside a block)</li>
</ul>
<p>Remember from before that <code>var</code> is globally scoped whereas <code>let</code> and <code>const</code> are block scoped. Let's understand that now.</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">var</span> a = <span class="hljs-number">5</span> <span class="hljs-comment">// we can access this a anywhere</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">adder</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">let</span> b = <span class="hljs-number">7</span>
    <span class="hljs-built_in">console</span>.log(a + b)
 }

<span class="hljs-built_in">console</span>.log(adder())

<span class="hljs-built_in">console</span>.log(b) <span class="hljs-comment">// Error as b is not accessible outside the function</span>

{
<span class="hljs-keyword">const</span> c = <span class="hljs-number">10</span>
<span class="hljs-built_in">console</span>.log(c) <span class="hljs-comment">// 10</span>
}

<span class="hljs-built_in">console</span>.log(c) <span class="hljs-comment">// Error as c is not accessible outside the block</span>
</code></pre>
<h3 id="heading-closures-in-javascript-important">Closures in JavaScript (❗important) 🔒</h3>
<p>We have already used a closure without even realizing it. In the example below, <code>prefix</code> is a closed-over-variable.</p>
<pre><code><span class="hljs-keyword">const</span> greet = <span class="hljs-function">() =&gt;</span>  {
    <span class="hljs-keyword">const</span> prefix = <span class="hljs-string">'Mr'</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${prefix}</span> <span class="hljs-subst">${name}</span>, welcome!`</span>)
    }
}

<span class="hljs-built_in">console</span>.log(greet()(<span class="hljs-string">'Jack'</span>))
</code></pre><p>This section will have a lot of fancy words, so bear with me. We will cover them one by one.</p>
<p>MDN says:</p>
<blockquote>
<p>A function bundled together with its lexical environment forms a closure.</p>
</blockquote>
<p>Okay, what is a lexical environment?</p>
<p>It is essentially the surrounding state – the <strong>local memory</strong> along with the lexical environment of its parent.</p>
<p>Whaaat? 🤯 I know it's a bit of a doozy. Let's understand it with a simple example.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">x</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> a = <span class="hljs-number">7</span>
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">y</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(a)
  }
  <span class="hljs-keyword">return</span> y
}

<span class="hljs-keyword">var</span> z = x()
<span class="hljs-built_in">console</span>.log(z) <span class="hljs-comment">// [Function: y]</span>
z()
</code></pre>
<p>When x is invoked, y is returned. Now, y is waiting to be executed. Kind of like a loaded gun waiting to be shot! 🔫</p>
<p>So, when we finally invoke z, y is invoked. Now, y has to log <code>a</code> so it first tries to find 🔍 it in the <strong>local memory</strong> but it's not there. It goes to its parent function. It finds <code>a</code> there.</p>
<p>Voila! There you have it - <a target="_blank" href="https://www.freecodecamp.org/news/closures-in-javascript/">this is closure</a>.</p>
<p>Even when functions are returned (in the above case y) they still remember their lexical scope (where it came from)</p>
<p>Totally unrelated quote for kicks 👻:</p>
<blockquote>
<p>They may forget what you said - but they will never forget how you made them feel - Carl W. Buehner</p>
</blockquote>
<p>I swear the rest of the article is legit 🤞 Keep reading.</p>
<h3 id="heading-advantages-of-closures-in-javascript">Advantages of Closures in JavaScript 😎</h3>
<ul>
<li>Currying</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> add = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">x</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">y</span>) </span>{
    <span class="hljs-built_in">console</span>.log(x + y)
  }
}

<span class="hljs-keyword">let</span> addByTwo = add(<span class="hljs-number">2</span>)
addByTwo(<span class="hljs-number">3</span>)
</code></pre>
<ul>
<li>Data Hiding/Encapsulation</li>
</ul>
<p>Suppose you want to create a counter application. Every time you call it, the count increases by 1. But you don't want to expose the variable outside the function. How to do it?</p>
<p>You guessed it – closures!</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> count = <span class="hljs-number">0</span>
  <span class="hljs-built_in">this</span>.incrementCount = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    count++
    <span class="hljs-built_in">console</span>.log(count)
  }
}

<span class="hljs-built_in">console</span>.log(count) <span class="hljs-comment">// Error: count is not defined</span>
<span class="hljs-keyword">var</span> adder = <span class="hljs-keyword">new</span> Counter()
adder.incrementCount() <span class="hljs-comment">// 1</span>
</code></pre>
<p>Don't worry about <code>this</code> and <code>new</code>. We have a whole section devoted to them down below.</p>
<h3 id="heading-disadvantages-of-closures-in-javascript">Disadvantages of Closures in JavaScript 😅</h3>
<ul>
<li>Overconsumption of memory or memory leaks can happen.</li>
</ul>
<p>For example, the closed-over-variable will not be garbage collected. This is because, even if the outer function has run, the returned inner function still has a reference to the closed-over-variable.</p>
<p><strong>Note:</strong> Garbage collection basically removes unused variables from the memory automatically.</p>
<h3 id="heading-hoisting-in-javascript">Hoisting in JavaScript 🚩</h3>
<p>This is JavaScript's default behavior of moving declarations to the top of the program.</p>
<ul>
<li><code>var</code> declaration is hoisted up and initialized with <code>undefined</code>.</li>
<li><code>let</code> and <code>const</code> declarations are hoisted up but not initialized.</li>
<li><code>function</code> definitions are also hoisted up and stored as they are.</li>
</ul>
<p>Let's look at an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">consoleNum</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(num)
  <span class="hljs-keyword">var</span> num = <span class="hljs-number">10</span>
}

consoleNum() <span class="hljs-comment">// undefined</span>

<span class="hljs-comment">// Why no error?</span>

<span class="hljs-comment">// This is how runtime sees this</span>
{
  <span class="hljs-keyword">var</span> num
  <span class="hljs-built_in">console</span>.log(num)
  num = <span class="hljs-number">9</span>
}

<span class="hljs-comment">// If instead of var -&gt; let, it will give an error as let values are not initialized</span>
</code></pre>
<p>Phew! I am done with functions here, but if you want more <a target="_blank" href="https://youtu.be/e-5obm1G_FY">check out this amazing talk by Anjana Vakil</a> on functional programming.</p>
<h2 id="heading-objects-in-javascript">Objects in JavaScript 🔮</h2>
<p>Just like arrays, objects are a way of storing data. We do so with the help of key-value pairs.</p>
<pre><code class="lang-javascript">
    <span class="hljs-keyword">const</span> developer = {
        <span class="hljs-attr">name</span>: <span class="hljs-string">"Raj"</span>,
        <span class="hljs-attr">age</span>: <span class="hljs-number">22</span>
        }
</code></pre>
<p><code>name</code> is the <code>key</code> and <code>Raj</code> is the <code>value</code>. Keys are generally the name of the properties of the object.</p>
<p>We can store all sorts of data like functions inside an object. You can explore more here on the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">MDN</a>.</p>
<h3 id="heading-what-is-this-in-javascript">What is <code>this</code> in JavaScript?</h3>
<p>Now, working with objects is different in JS than in other popular programming languages like C++. And to understand that properly, we need a good grasp of the <code>this</code> keyword.</p>
<p>Let's try to understand it step-by-step.</p>
<p>In a program, at times, we need a way to point at stuff. Like saying this function right here belongs to this object. <code>this</code> helps us get this context.</p>
<p>You will understand what I am saying better when we look at some examples.</p>
<p>For now, think of <code>this</code> as something which provides context. And remember this important thing: its value depends on how and where it is called.</p>
<p>I know, I know. A lot of <code>this</code> 😬. Let's go over all this slowly.</p>
<p>Start a new program and just log <code>this</code>.</p>
<pre><code class="lang-javascript">
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>)
</code></pre>
<p>It will point to the window object.</p>
<p>Now, let's take an example with an object:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunc</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>)     
  }

<span class="hljs-keyword">const</span> obj = {
  <span class="hljs-attr">bool</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">myFunc</span>: myFunc,
}

obj.myFunc()
</code></pre>
<p>Now, <code>this</code> will point to the object. So what's happening here?</p>
<p>In the first example, we had nothing left of the <code>.</code> so it defaulted to the <code>window</code> object. But in this example, we have the object <code>obj</code>.</p>
<p>If you do:</p>
<pre><code class="lang-javascript">
myFunc() <span class="hljs-comment">// window</span>
</code></pre>
<p>We again get the <code>window</code> object. So, we can see that the value of <code>this</code> depends on how and where are we doing the calling.</p>
<p>What we just did above is called <strong>Implicit Binding</strong>. The value of <code>this</code> got bound to the object.</p>
<p>There is another way to use <code>this</code>. <strong>Explicit binding</strong> is when you force a function to use a certain object as its <code>this</code>.</p>
<p>Let's understand why we need explicit binding through an example.</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> student_1 =  {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Randall'</span>,
    <span class="hljs-attr">displayName_1</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayName</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name)
    }
}
<span class="hljs-keyword">const</span> student_2 =  {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Raj'</span>,
    <span class="hljs-attr">displayName_2</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayName</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name)
    }
}

student_1.displayName_1()
student_2.displayName_2()
</code></pre>
<p>We are using <code>this</code> properly, but can you see the problem with the above code?</p>
<p>We are repeating code. And one of the principles of good programming is keep your code DRY! (Don't Repeat Yourself)</p>
<p>So, let's get rid of <code>displayName_2</code> and simply do:</p>
<pre><code class="lang-javascript">
student_1.displayName_1.call(student_2) <span class="hljs-comment">// Raj</span>
</code></pre>
<p><code>call</code> forced <code>displayName_1</code> to use the second object as its <code>this</code>.</p>
<p>There are a lot of other ways we can do this.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622489263380/UwpR9Rscv.png" alt="call-bind-apply.png" width="600" height="400" loading="lazy"></p>
<p>Try to solve the given problem yourself.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myData = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Rajat'</span>,
  <span class="hljs-attr">city</span>: <span class="hljs-string">'Delhi'</span>,
  <span class="hljs-attr">displayStay</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name, <span class="hljs-string">'stays in'</span>, <span class="hljs-built_in">this</span>.city)
  },
}
myData.displayStay()

<span class="hljs-comment">// create an object yourData and try to use displayStay</span>
<span class="hljs-keyword">const</span> yourData = {
 <span class="hljs-attr">name</span>: <span class="hljs-string">'name'</span>,
 <span class="hljs-attr">city</span>: <span class="hljs-string">'city'</span>
}


<span class="hljs-comment">// answer</span>
myData.displayStay.call(yourData)
</code></pre>
<p>Finally, remember that I said that there are differences between arrow and regular functions. </p>
<p>The case of <code>this</code> is one of them.</p>
<p>For an arrow function, the value depends on the lexical scope – that is to say, the outer function where the arrow function is declared.</p>
<p>So, if we make the <code>displayName()</code> from above an arrow function, nothing will work.</p>
<p>Arrow functions basically inherit the parent's context which in the above case is the <code>window</code>.</p>
<h3 id="heading-prototypes-and-prototypal-inheritance-in-javascript">Prototypes and Prototypal Inheritance in JavaScript 👪</h3>
<blockquote>
<p>Whenever we create anything (like an object or function) in JavaScript, the JS Engine automatically attaches that thing with some properties and methods.</p>
</blockquote>
<p>All this comes via <code>prototypes</code>.</p>
<p><code>__proto__</code> is the object where JS is putting it all.</p>
<p>Let's see some examples. Fire up your consoles!</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [<span class="hljs-string">'Rajat'</span>, <span class="hljs-string">'Raj'</span>]
<span class="hljs-built_in">console</span>.log(arr.__proto__.forEach)
<span class="hljs-built_in">console</span>.log(arr.__proto__) <span class="hljs-comment">// same as Array.prototype</span>
<span class="hljs-built_in">console</span>.log(arr.__proto__.__proto__) <span class="hljs-comment">// same as Object.prototype</span>
<span class="hljs-built_in">console</span>.log(arr.__proto__.__proto__.__proto__) <span class="hljs-comment">// null</span>
</code></pre>
<p>All this is called a <code>prototype chain</code>.</p>
<p>We can do the same with objects and functions as well.</p>
<p>We will always find <code>Object.prototype</code> behind the scenes. That's why you may have heard that everything in JS is an object. 🤯</p>
<h3 id="heading-what-is-prototypal-inheritance-in-javascript">What is Prototypal Inheritance in JavaScript?</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> object = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Rajat'</span>,
  <span class="hljs-attr">city</span>: <span class="hljs-string">'Delhi'</span>,
  <span class="hljs-attr">getIntro</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>, <span class="hljs-subst">${<span class="hljs-built_in">this</span>.city}</span>`</span>)
  },
}

<span class="hljs-keyword">let</span> object2 = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Aditya'</span>,
}
</code></pre>
<p><strong>Note:</strong> Don't modify prototypes this way. It's just for understanding. <a target="_blank" href="https://javascript.plainenglish.io/how-prototypal-inheritance-works-in-javascript-and-how-to-convert-it-to-class-based-inheritance-632e31e6350d">Here's the right way to do it</a>.</p>
<pre><code class="lang-javascript">object2.__proto__ = object
</code></pre>
<p>By doing this, <code>object2</code> gets access to the object's properties. So, now we can do:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(object2.city)
</code></pre>
<p>This is <strong>prototypal inheritance</strong>.</p>
<h2 id="heading-asynchronous-javascript">Asynchronous JavaScript ⚡</h2>
<p>So, JS is a <em>single-threaded</em> language. Things happen one at a time. Only after one thing is done can we move to the next thing. </p>
<p>But this creates problems in the real world, especially, when we are working with browsers.</p>
<p>For example, when we need to fetch data from the web - often times we don't know how long will it take to get it. And whether we will be able to get the data successfully. </p>
<p>To help with this, asynchronous JS comes into play. </p>
<p>And the most important concept to understand is the event loop.</p>
<h3 id="heading-event-loops-in-javascript">Event Loops in JavaScript ➰</h3>
<p>Instead of providing a half-baked explanation here, I highly recommend watching this video by Philip Roberts if you haven't already:</p>
<p><a target="_blank" href="https://youtu.be/8aGhZQkoFbQ">Learn all about event loops in JS here</a>.</p>
<h3 id="heading-timers-in-javascript-settimeout-setinterval-clearinterval">Timers in JavaScript – setTimeout, setInterval, clearInterval ⏱️</h3>
<p>I hope you watched the video. It mentioned timers. Let's talk about them more now. These are very frequently asked about in interviews.</p>
<p>The <code>setTimeout()</code> method calls a function or evaluates an expression after a specified number of milliseconds.</p>
<p><code>setInterval()</code> does the same for specified intervals.</p>
<pre><code class="lang-javascript">
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Here - I am after 2 seconds'</span>)
}, <span class="hljs-number">2000</span>);

<span class="hljs-keyword">const</span> timer = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I will keep on coming back until you clear me'</span>)
}, <span class="hljs-number">2000</span>);
</code></pre>
<p>You use <code>clearInterval()</code> to stop the timer.</p>
<pre><code><span class="hljs-built_in">clearInterval</span>(timer)
</code></pre><p>Let's go over some questions that use these concepts.</p>
<pre><code class="lang-javascript">  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello'</span>)
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'lovely'</span>)
  }, <span class="hljs-number">0</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'reader'</span>)

  <span class="hljs-comment">// output</span>
  Hello
  reader
  lovely
</code></pre>
<p>Here's a slightly trickier one:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">5</span>; i++) {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      <span class="hljs-built_in">console</span>.log(i)
    }, i * <span class="hljs-number">1000</span>)
  }

<span class="hljs-comment">// output</span>
<span class="hljs-number">6</span>
<span class="hljs-number">6</span>
<span class="hljs-number">6</span>
<span class="hljs-number">6</span>
<span class="hljs-number">6</span>
</code></pre>
<p>And here's a short explanation of what's going on there: when <code>setTimeout</code> comes again into the picture, the entire loop has run and the value of <code>i</code> has become 6,</p>
<p>Now, let's say we want the outcome to be 1 2 3 4 5 – what do we do?</p>
<p>Instead of <code>var</code> ➡️ use <code>let</code>.</p>
<p>Why this will work?</p>
<p><code>var</code> is globally scoped but <code>let</code> is locally scoped. So for <code>let</code> a new <code>i</code> is created for every iteration.</p>
<h3 id="heading-promises-in-javascript-important">Promises in JavaScript (❗important) 🤝</h3>
<p>Promises are at the heart of Asynchronous JS.</p>
<blockquote>
<p>The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.</p>
</blockquote>
<p>A promise can be in one of these three states:</p>
<ul>
<li>Pending: initial state, neither fulfilled nor rejected</li>
<li>Fulfilled: operation was completed successfully</li>
<li>Rejected: operation failed</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> value = <span class="hljs-literal">true</span>
  <span class="hljs-keyword">if</span> (value) {
    resolve(<span class="hljs-string">'hey value is true'</span>)
  } <span class="hljs-keyword">else</span> {
    reject(<span class="hljs-string">'there was an error, value is false'</span>)
  }
})

promise
  .then(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(x)
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(err))
</code></pre>
<p><strong>Note:</strong> <code>resolve</code> and <code>reject</code> are just conventional names. Call it pizza🍕 if you like.</p>
<p>Instead of <code>then/catch</code>, we can also use <code>async/await</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">asyncCall</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> promise
  <span class="hljs-built_in">console</span>.log(result)
}

asyncCall()
</code></pre>
<p>One of the advantages of promises is that they are a much cleaner syntax. Before we had promises, we could easily get stuck in <a target="_blank" href="http://callbackhell.com/">callback hell</a> 🌋</p>
<h2 id="heading-advanced-javascript-concepts-to-know">Advanced JavaScript Concepts to Know</h2>
<h3 id="heading-polyfills-in-javascript">📚 Polyfills in JavaScript</h3>
<blockquote>
<p>A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it. <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Polyfill">MDN</a></p>
</blockquote>
<ul>
<li>Let's implement it for <code>map</code>:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// this - array</span>
<span class="hljs-comment">// this[i] - current value</span>
<span class="hljs-built_in">Array</span>.prototype.myMap = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">cb</span>) </span>{
  <span class="hljs-keyword">var</span> arr = []
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.length; i++) {
    arr.push(cb(<span class="hljs-built_in">this</span>[i], i, <span class="hljs-built_in">this</span>))
  }
  <span class="hljs-keyword">return</span> arr
}

<span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
<span class="hljs-built_in">console</span>.log(arr.myMap(<span class="hljs-function">(<span class="hljs-params">a</span>) =&gt;</span> a * <span class="hljs-number">2</span>)) <span class="hljs-comment">// [2, 4, 6]</span>
</code></pre>
<p>Notice how we use <code>this</code>. Here, we have basically created a new array and are adding values to it.</p>
<h3 id="heading-async-and-defer-in-javascript">Async and defer in JavaScript ✔️</h3>
<p>These concepts are frequently asked about in interviews by big corporations like Amazon, Walmart, and Flipkart. 🏢</p>
<p>To understand <code>async</code> and <code>defer</code>, we need to have an idea of how browsers render a webpage. First, they parse the HTML and CSS. Then DOM trees are created. From these, a render tree is created. Finally, from the render tree - a layout is created and the painting happens.</p>
<p>For a more detailed look, check out <a target="_blank" href="https://youtu.be/SmE4OwHztCc">this video</a>.</p>
<p>Async and defer are <code>boolean</code> attributes which can be loaded along with the script tags. They are useful for loading external scripts into your web page.</p>
<p>Let's understand with the help of pictures.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621781371965/PciAdUTCL.png" alt="18-async-defer.png" width="600" height="400" loading="lazy">
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621781403795/VgIYFtP5T.png" alt="19-async-defer.png" width="600" height="400" loading="lazy">
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621781415787/mJEkxqe_i.png" alt="20-async.png" width="600" height="400" loading="lazy">
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621781428927/2nUaI8fjr.png" alt="21-defer.png" width="600" height="400" loading="lazy"></p>
<p>If there are multiple scripts which are dependant on each other, use <code>defer</code>. Defer script are executed in the order which they are defined.</p>
<p>If you want to load external script which is not dependant on the execution of any other scripts, use <code>async</code>. </p>
<p><strong>Note:</strong> The async attribute does not guarantee the order of execution of scripts.</p>
<h3 id="heading-debouncing-in-javascript">Debouncing in JavaScript ⛹️‍♂️</h3>
<p>Debouncing is another favorite topic of interviewers.</p>
<p>Let's understand it by creating a search bar.</p>
<p><strong>Demo:</strong> https://codesandbox.io/s/debounce-input-field-o5gml</p>
<p>Create a simple input field in <code>index.html</code> like this:</p>
<pre><code class="lang-javascript">&lt;input type=<span class="hljs-string">'text'</span> id=<span class="hljs-string">'text'</span> /&gt;
</code></pre>
<p>Now, in <code>index.js</code>. Don't forget to add it to <code>index.html</code> first:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> getData = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(e.target.value)
}
<span class="hljs-keyword">const</span> inputField = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'text'</span>)

<span class="hljs-keyword">const</span> debounce = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">fn, delay</span>) </span>{
  <span class="hljs-keyword">let</span> timer
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> context = <span class="hljs-built_in">this</span>
    <span class="hljs-built_in">clearTimeout</span>(timer)
    timer = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      fn.apply(context, <span class="hljs-built_in">arguments</span>)
    }, delay)
  }
}

inputField.addEventListener(<span class="hljs-string">'keyup'</span>, debounce(getData, <span class="hljs-number">300</span>))
</code></pre>
<p>First, we have selected the input and added an <code>event listener</code> to it. Then we created a debounce function which takes a callback function and delay.</p>
<p>Now, inside the debounce function we create a timer using <code>setTimeout</code>. Now, this timer's job is to make sure that the next call for <code>getData</code> only happens after 300 ms. This is what debouncing is.</p>
<p>Also, we use <code>clearTimeout</code> to remove it. Don't want too many of them hanging out there taking up memory space!</p>
<p>Phew! Lots of theory. Let's do a fun challenge. You must have seen the countdown before a game starts (it goes like 10, 9, 8, .... with some delay in between). Try to write a program for it.</p>
<p>Here's how you'd do it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> count = <span class="hljs-number">10</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) {
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">timer</span>(<span class="hljs-params">i</span>) </span>{
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(count)
      count--
    }, i * <span class="hljs-number">500</span>)
  }
  timer(i)
}
</code></pre>
<p>Were you able to solve it? Did you do it differently? Let me know your solution.</p>
<h3 id="heading-throttling-in-javascript">Throttling in JavaScript 🛑</h3>
<p>Let's look at an example again. Suppose that on every window resize event we call an expensive function. Now, we want it such that the expensive function will only be executed once in the given time interval. This is what throttling is.</p>
<p>Create an <code>index.html</code> and an <code>index.js</code> with the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> expensive = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'expensive'</span>)
}

<span class="hljs-keyword">const</span> throttle = <span class="hljs-function">(<span class="hljs-params">fn, limit</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> context = <span class="hljs-built_in">this</span>
  <span class="hljs-keyword">let</span> flag = <span class="hljs-literal">true</span>
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">if</span> (flag) {
      fn.apply(context, <span class="hljs-built_in">arguments</span>)
      flag = <span class="hljs-literal">false</span>
    }
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      flag = <span class="hljs-literal">true</span>
    }, limit)
  }
}
<span class="hljs-keyword">const</span> func = throttle(expensive, <span class="hljs-number">2000</span>)
<span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'resize'</span>, func)
</code></pre>
<p>Almost the same as debouncing. The key difference is the <code>flag</code> variable. Only, when it's true we are invoking the callback function. And it is set to <code>true</code> inside the <code>setTimeout</code>. So the value is <code>true</code> only after the desired time limit.</p>
<h3 id="heading-so-whats-the-difference-between-debounce-and-throttling">So, what's the difference between debounce and throttling❓</h3>
<p>Let's take the search bar 🔍 example from above. When we are debouncing the input field, we are saying to only fetch the data when the difference between two <code>keyup</code> events is at least 300 ms.</p>
<p>In the case of throttling, we make a function call only after a certain period of time. </p>
<p>Suppose that you are searching for an encyclopedia in the search bar. The first call is made on <code>e</code> and it took us 300 ms to reach <code>p</code>. The next call will be made then only. All the events in between will be ignored.</p>
<p>So, to summarize, debouncing is when the difference between two <code>keyup</code> events is 300 ms. And throttling is when the difference between two function calls is 300 ms. Basically, the function is called after a certain interval of time.</p>
<h2 id="heading-storage-in-javascript">Storage in JavaScript 💾</h2>
<p>Finally, a small but important topic to wrap things up.</p>
<p><strong>localStorage:</strong> Data persists even after closing your session</p>
<p><strong>sessionStorage:</strong> You lose your data when your session is over, like when you close the browser on the tab.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// save</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'key'</span>, <span class="hljs-string">'value'</span>)
<span class="hljs-comment">// get saved data</span>
<span class="hljs-keyword">let</span> data = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'key'</span>)
<span class="hljs-comment">// remove saved data</span>
<span class="hljs-built_in">localStorage</span>.removeItem(<span class="hljs-string">'key'</span>)
<span class="hljs-comment">// Same for sessionStorage</span>
</code></pre>
<p>And we are done! 🏁 I hope you feel more confident about your next JS interview now. I wish you all the best.</p>
<p>If you have any queries / suggestions / feedback, you can reach me on Twitter: <a target="_blank" href="https://twitter.com/rajatetc">https://twitter.com/rajatetc</a>.</p>
<h2 id="heading-main-references">🗃️ Main References</h2>
<ul>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/">MDN Docs</a></li>
<li><a target="_blank" href="https://www.youtube.com/channel/UC3N9i_KvKZYP4F84FPIzgPQ">Akshay Saini</a></li>
<li><a target="_blank" href="https://www.youtube.com/channel/UCMZFwxv5l-XtKi693qMJptA">Coding Addict</a></li>
<li><a target="_blank" href="https://www.instagram.com/javascript_interviews/">Javascript_Interviews</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Coding Interview Backtracking Problems Crash Course – The Only One You'll Ever Need ]]>
                </title>
                <description>
                    <![CDATA[ Whether you are new to coding interviews or are already familiar with the concept of backtracking algorithms, this is the crash course for you. In it, we will learn about an all-purpose coding template for solving backtracking problems and apply it t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/coding-interview-backtracking-problems-crash-course/</link>
                <guid isPermaLink="false">66d4601355db48792eed3f6b</guid>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interview tips ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Job Interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ leetcode ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Lynn Zheng ]]>
                </dc:creator>
                <pubDate>Tue, 29 Jun 2021 20:00:32 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/06/1080P-Thumbnails-1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Whether you are new to coding interviews or are already familiar with the concept of <strong>backtracking</strong> algorithms, this is the crash course for you.</p>
<p>In it, we will learn about <strong>an all-purpose coding template</strong> for solving backtracking problems and apply it to <strong>two LeetCode hard problems</strong>. Ready to crunch your next coding interview? Let's go!</p>
<p>If you just want to dive right in, <a target="_blank" href="https://www.youtube.com/watch?v=H2gnD7Ixeao">you can find the course here</a> (and linked at the bottom of this article). If you want a little more info, read on. :)</p>
<h2 id="heading-who-is-the-course-for-and-what-is-the-backtracking-algorithm">Who is the Course for and What is the Backtracking Algorithm?</h2>
<p>This course is suitable for anyone who is preparing for coding interviews, especially those who are looking to hone their skills in solving <strong>backtracking</strong> problems.</p>
<p>Backtracking is a common category for questions in coding interviews. The algorithm for solving those problems usually involves <strong>recursion</strong> and <strong>building incrementally on previous states</strong> to arrive at the ultimate valid solution.</p>
<p>Backtracking is a favorite topic among top tech companies like Google, Microsoft, and Facebook, precisely because it requires robust reasoning and coding competence to nail those questions.</p>
<p>However, because of its recursive nature and complex problem definition, backtracking problems are usually a major source of confusion among devs who are preparing for coding interviews.</p>
<p>To address this confusion, this crash course aims to arm with you a concise, 20-line template that you can apply to the majority of backtracking problems.</p>
<h2 id="heading-course-outline">Course Outline</h2>
<p>This course runs for a total of 40 minutes and the structure is as follows:</p>
<ul>
<li><p>An 8-minute introduction to <a target="_blank" href="https://gist.github.com/RuolinZheng08/cdd880ee748e27ed28e0be3916f56fa6">the template</a></p>
</li>
<li><p>A 15-minute hands-on code-along session for <a target="_blank" href="https://leetcode.com/problems/n-queens/">LeetCode Question 51. N-Queens</a></p>
</li>
<li><p>A 15-minute hands-on code-along session for <a target="_blank" href="https://leetcode.com/problems/sudoku-solver/">LeetCode Question 37. Sudoku Solver</a></p>
</li>
</ul>
<h2 id="heading-the-all-purpose-template">The All-Purpose Template</h2>
<p>For your convenience, I've copied the template over. This is exactly the same template that I use for my coding interviews, or when I'm developing algorithms for my indie games. I even used it once in my research on a non-convex optimization problem.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_valid_state</span>(<span class="hljs-params">state</span>):</span>
    <span class="hljs-comment"># check if it is a valid solution</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_candidates</span>(<span class="hljs-params">state</span>):</span>
    <span class="hljs-keyword">return</span> []

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">search</span>(<span class="hljs-params">state, solutions</span>):</span>
    <span class="hljs-keyword">if</span> is_valid_state(state):
        solutions.append(state.copy())
        <span class="hljs-comment"># return</span>

    <span class="hljs-keyword">for</span> candidate <span class="hljs-keyword">in</span> get_candidates(state):
        state.add(candidate)
        search(state, solutions)
        state.remove(candidate)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">solve</span>():</span>
    solutions = []
    state = set()
    search(state, solutions)
    <span class="hljs-keyword">return</span> solutions
</code></pre>
<p>The first three are all helper functions, and the last and most important one, <code>solve</code>, is essentially the one that a LeetCode problem is asking you to write.</p>
<h2 id="heading-solving-leetcode-problems-hands-on">Solving LeetCode Problems Hands-On</h2>
<p>We will next apply this template to solving two LeetCode hard problems: <a target="_blank" href="https://leetcode.com/problems/n-queens/">LeetCode Question 51. N-Queens</a> and <a target="_blank" href="https://leetcode.com/problems/sudoku-solver/">LeetCode Question 37. Sudoku Solver</a>.</p>
<p>To illustrate the flexibility of the template, see below for how we solve the N-Queens problem by doing nothing fancy other than adapting the four functions (renaming <code>solve</code> to <code>solveNQueens</code>). The complete code for either problem is available <a target="_blank" href="https://gist.github.com/RuolinZheng08/cdd880ee748e27ed28e0be3916f56fa6">in my GitHub gist</a>.</p>
<p>Watch <a target="_blank" href="https://youtu.be/H2gnD7Ixeao">the video course</a> to follow along my analysis and adaptation of the template.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-comment"># solveNQueens is essentially the solve function</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">solveNQueens</span>(<span class="hljs-params">self, n: int</span>) -&gt; List[List[str]]:</span>
        solutions = []
        state = []
        self.search(state, solutions, n)
        <span class="hljs-keyword">return</span> solutions

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_valid_state</span>(<span class="hljs-params">self, state, n</span>):</span>
        <span class="hljs-comment"># check if it is a valid solution</span>
        <span class="hljs-keyword">return</span> len(state) == n

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_candidates</span>(<span class="hljs-params">self, state, n</span>):</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> state:
            <span class="hljs-keyword">return</span> range(n)

        <span class="hljs-comment"># find the next position in the state to populate</span>
        position = len(state)
        candidates = set(range(n))
        <span class="hljs-comment"># prune down candidates that place the queen into attacks</span>
        <span class="hljs-keyword">for</span> row, col <span class="hljs-keyword">in</span> enumerate(state):
            <span class="hljs-comment"># discard the column index if it's occupied by a queen</span>
            candidates.discard(col)
            dist = position - row
            <span class="hljs-comment"># discard diagonals</span>
            candidates.discard(col + dist)
            candidates.discard(col - dist)
        <span class="hljs-keyword">return</span> candidates

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">search</span>(<span class="hljs-params">self, state, solutions, n</span>):</span>
        <span class="hljs-keyword">if</span> self.is_valid_state(state, n):
            state_string = self.state_to_string(state, n)
            solutions.append(state_string)
            <span class="hljs-keyword">return</span>

        <span class="hljs-keyword">for</span> candidate <span class="hljs-keyword">in</span> self.get_candidates(state, n):
            <span class="hljs-comment"># recurse</span>
            state.append(candidate)
            self.search(state, solutions, n)
            state.pop()
</code></pre>
<p>Check out the video course here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/H2gnD7Ixeao" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>You can access the template as well as the solutions to the two LeetCode problems (<strong>N-Queens</strong> and <strong>Sudoku Solver</strong>) in my GitHub gist:</p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="cdd880ee748e27ed28e0be3916f56fa6">
        <script src="https://gist.github.com/RuolinZheng08/cdd880ee748e27ed28e0be3916f56fa6.js"></script></div><p> </p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>Remember that practice makes perfect, so do try applying this template to <a target="_blank" href="https://leetcode.com/tag/backtracking/">more backtracking problems on LeetCode.</a> Best of luck crunching your next coding interview!</p>
<p>For more content like this, check out my YouTube channel:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/undefined" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Ace Your Coding Interview – Advice from a Senior Software Engineer ]]>
                </title>
                <description>
                    <![CDATA[ By Daniel Chae Technical interviews are one of the most stressful parts of landing a job in tech.  You don't know what questions the interviewer is going to ask. What if you have no idea how to solve the problem in front of you? What if you freeze up... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-acing-your-coding-interview-advice-from-senior-software-engineer/</link>
                <guid isPermaLink="false">66d45e04aad1510d0766b5f9</guid>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interview tips ]]>
                    </category>
                
                    <category>
                        <![CDATA[ self-improvement  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 10 May 2021 17:04:31 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/05/kaleidico-3V8xo5Gbusk-unsplash--2-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Daniel Chae</p>
<p>Technical interviews are one of the most stressful parts of landing a job in tech. </p>
<p>You don't know what questions the interviewer is going to ask. What if you have no idea how to solve the problem in front of you? What if you freeze up and look like you don't know what you're doing?</p>
<p>Many aspiring programmers work themselves up into a frenzy as they try to memorize every coding interview question. You and I both know this approach is unsustainable. I'm here to tell you there's an easier way. </p>
<p>I recently sat down with my friend Michelle, who's a senior software engineer at Stitch Fix (a recently IPO'd company). She shared the kinds of qualities she looks for in developers that she interviews. </p>
<p>Honestly, the qualities might surprise you. I promise they don't include memorizing coding interview questions and solutions.</p>
<p>The rest of this article will unpack the qualities Michelle looks for in developer candidates. I'll translate each of these qualities into key interview behaviors. Then I'll tell you how you can implement them in your own interviews. Let's get started.</p>
<h2 id="heading-qualities-you-should-have-going-into-the-coding-interview">Qualities you should have going into the coding interview</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/rachel-mcdermott-0fN7Fxv1eWA-unsplash.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>When I sat down with Michelle, a part of me imagined I was getting a secret code to cracking the coding interview. I thought I'd hear the ultimate algorithm to solving every problem out there. </p>
<p>While we know a universal algorithm doesn't exist, she did share something even better: how to create a mental a framework for interviewing.</p>
<p>Success is not about memorizing every problem and solution. Rather, it's about learning how to solve problems. </p>
<p>As a developer, there won't be a cookie-cutter LeetCode type of answer. This is where mental frameworks are incredibly helpful. They create just enough problem solving certainty to overcome a seemingly ambiguous problem. </p>
<p>Here are Michelle's key components to building a killer mindset framework for your coding interview.</p>
<h2 id="heading-be-curious">Be curious</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/ayo-ogunseinde-sibVwORYqs0-unsplash.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>One of Michelle's biggest tips for developer candidates is to be curious. Clarify the problem and ask questions. Share any thoughts you have on the problem you're facing. Interviewers aren't just looking for the right solution. They want to see how you think. </p>
<p>The best way you can show how you think is by asking questions. Let's say an interviewer asks you to check if a string contains any digits. You should clarify the question in your own words, something like:</p>
<p>"So I need to find a way to verify if a set of characters contains any numbers?"</p>
<p>When you say this you're giving interviewers insight into your logic. You're also showing them you're interested in the problem. </p>
<p>And don't be afraid to ask follow-up questions. Using the same example above, here are a few questions you can ask:</p>
<p>"Do the numbers I'm looking for contain decimals?"</p>
<p>"Do I need to sort the characters in any way before checking them?" </p>
<h2 id="heading-be-open-to-suggestions">Be open to suggestions</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/christina-wocintechchat-com-IxmHiUC-yOw-unsplash.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>One thing that is easy to forget is that interviewers want you to succeed. Most interviewers want to provide real-time feedback and suggestions to candidates. But candidates often take a non-verbal, siloed approach to the coding interview. </p>
<p>One way you can be more open to suggestions is by engaging your interviewer. Verbalize your logic and take them along your problem solving journey. </p>
<p>We'll use the same problem as above. Here are a few ways you can verbalize your logic from the get-go:</p>
<p>"So I'll need to establish a way to separate characters from numbers, right?"</p>
<p>"I'm thinking about iterating through the set of characters from end to end."</p>
<p>"I want a programmatic way to iterate through characters, but stop at numbers."</p>
<p>The more insight you can provide, the more your interviewer will feel inclined to help. </p>
<h2 id="heading-work-collaboratively">Work collaboratively</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/airfocus-v89zhr0iBFY-unsplash.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This goes hand in hand with the above. The idea that a developer works siloed and alone is a myth. You have version control and project management tools that require collaboration. </p>
<p>You should verbalize your approach, ask great questions, and loop your interviewer in. You'll arrive at the solution much more quickly. But you'll also show your interviewer you can effectively collaborate with other developers. </p>
<p>Here are a few ways you can loop your interviewer in:</p>
<p>"Would a for loop be too simple/complex for this solution?"</p>
<p>"How important is it to establish if there are floats or not?"</p>
<p>"Is there any type of solution you have in mind?"</p>
<h2 id="heading-be-willing-to-just-go-for-it">Be willing to just go for it</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/dayne-topkin-XQWtAFOO7zc-unsplash.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Finally, Michelle suggested that developer candidates should just go for it. Meaning, go for the success you want to see. </p>
<p>One of the most common occurrences for candidates is that they freeze up. While this is understandable, no one wins in this situation. You can't show how incredible you are and the interviewer can't help you. Here's what Michelle said to "just go for it":</p>
<blockquote>
<p>Even if you have to pseudocode your implementation, that’s better than being too nervous to try. Putting something on the board/coderpad will invite discussion, a chance to share your thoughts, and an opportunity to learn.   </p>
<p>Don’t be afraid to fail! It just means you’re one step closer to succeeding. :)</p>
</blockquote>
<p>"Just go for it" can mean a lot of things. That said, here are a few examples of what that can look like:</p>
<ul>
<li>Write pseudocode on the whiteboard, paper, or coderpad</li>
<li>Note exactly where you are stuck in your logic</li>
<li>Verbalize the solution you wish you could come up with</li>
</ul>
<h2 id="heading-use-the-mindset-framework-to-ace-your-coding-interview">Use the Mindset Framework to Ace Your Coding Interview!</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/denys-nevozhai-z0nVqfrOqWA-unsplash.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Coding interviews can be scary and there's always the fear that you'll freeze up. Part of this fear stems from not knowing which questions will show up. </p>
<p>The great thing is that you no longer have to memorize coding questions and solutions. Instead, build a mindset framework with the key interview behaviors you read about today. </p>
<p>You want to be curious and open to suggestions. You should work in collaboration with your interviewer. Be willing to go for the success you want to see. Happy interviewing! </p>
<p>If you want to see more of this type of content, subscribe to my newsletter at <a target="_blank" href="https://coursetohire.com/">Course to Hire</a>. I'll help you learn how to code and break into tech. Feel free to add me on <a target="_blank" href="https://www.linkedin.com/in/daniel-chae11/">LinkedIn</a> as well.</p>
<p>P.S. – if you're interested in connecting with Michelle, ping me on Course to Hire or LinkedIn and I can make the intro.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Solve Coding Problems with a Simple Four Step Method ]]>
                </title>
                <description>
                    <![CDATA[ By Madison Kanna I had fifteen minutes left, and I knew I was going to fail. I had spent two months studying for my first technical interview.  I thought I was prepared, but as the interview came to a close, it hit me: I had no idea how to ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-solve-coding-problems/</link>
                <guid isPermaLink="false">66d8518c62a291dea89878dc</guid>
                
                    <category>
                        <![CDATA[ coding challenge ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interview tips ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Problem Solving ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 04 Feb 2021 18:33:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/01/iStock-527234840.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Madison Kanna</p>
<p>I had fifteen minutes left, and I knew I was going to fail.</p>
<p>I had spent two months studying for my first technical interview. </p>
<p>I thought I was prepared, but as the interview came to a close, it hit me: I had no idea how to solve coding problems. </p>
<p>Of all the tutorials I had taken when I was learning to code, not one of them had included an approach to solving coding problems. </p>
<p>I had to find a method for problem-solving—my career as a developer depended on it.</p>
<p>I immediately began researching methods. And I found one. In fact, what I uncovered was an invaluable strategy. It was a time-tested four-step method that was somehow under the radar in the developer ecosystem.</p>
<p>In this article, I’ll go over this four-step problem-solving method that you can use to start confidently solving coding problems. </p>
<p>Solving coding problems is not only part of the developer job interview process—it’s what a developer does all day. After all, <em>writing code is problem-solving.</em></p>
<h2 id="heading-a-method-for-solving-problems">A method for solving problems</h2>
<p>This method is from the book <em>How to Solve It</em> by George Pólya. It originally came out in 1945 and has sold over one million copies. </p>
<p>His problem-solving method has been used and taught by many programmers, from computer science professors (see Udacity’s Intro to CS course taught by professor David Evans) to modern web development teachers like Colt Steele.</p>
<p>Let’s walk through solving a simple coding problem using the four-step problem-solving method. This allows us to see the method in action as we learn it. We'll use JavaScript as our language of choice. Here’s the problem:</p>
<p>Create a function that adds together two numbers and returns that value.  </p>
<p>There are four steps to the problem-solving method:</p>
<ol>
<li>Understand the problem.</li>
<li>Devise a plan.</li>
<li>Carry out the plan.</li>
<li>Look back. </li>
</ol>
<p>Let’s get started with step one.</p>
<h2 id="heading-step-1-understand-the-problem">Step 1: Understand the problem.</h2>
<p>When given a coding problem in an interview, it’s tempting to rush into coding. This is hard to avoid, especially if you have a time limit. </p>
<p>However, try to resist this urge. Make sure you actually understand the problem before you get started with solving it.</p>
<p>Read through the problem. If you’re in an interview, you could read through the problem out loud if that helps you slow down. </p>
<p>As you read through the problem, clarify any part of it you do not understand. If you’re in an interview, you can do this by asking your interviewer questions about the problem description. If you’re on your own, think through and/or Google parts of the question you might not understand.</p>
<p><strong>This first step is vital as we often don’t take the time to fully understand the problem. When you don’t fully understand the problem, you’ll have a much harder time solving it.</strong></p>
<p>To help you better understand the problem, ask yourself:</p>
<h3 id="heading-what-are-the-inputs">What are the inputs?</h3>
<p>What kinds of inputs will go into this problem? In this example, the inputs are the arguments that our function will take. </p>
<p>Just from reading the problem description so far, we know that the inputs will be numbers. But to be more specific about what the inputs will be, we can ask:</p>
<p>Will the inputs always be just two numbers? What should happen if our function receives as input <em>three</em> numbers? </p>
<p>Here we could ask the interviewer for clarification, or look at the problem description further. </p>
<p>The coding problem might have a note saying, “You should only ever expect two inputs into the function.” If so, you know how to proceed. You can get more specific, as you’ll likely realize that you need to ask more questions on what kinds of inputs you might be receiving.</p>
<p>Will the inputs always be numbers? What should our function do if we receive the inputs “a” and “b”? Clarify whether or not our function will always take in numbers.</p>
<p>Optionally, you could write down possible inputs in a code comment to get a sense of what they’ll look like: </p>
<p><code>//inputs: 2, 4</code></p>
<p>Next, ask:</p>
<h3 id="heading-what-are-the-outputs">What are the outputs?</h3>
<p>What will this function return? In this case, the output will be one number that is the result of the two number inputs. Make sure you understand what your outputs will be.</p>
<h3 id="heading-create-some-examples">Create some examples.</h3>
<p>Once you have a grasp of the problem and know the possible inputs and outputs, you can start working on some concrete examples.</p>
<p>Examples can also be used as sanity checks to test your eventual problem. Most code challenge editors that you’ll work in (whether it’s in an interview or just using a site like Codewars or HackerRank) have examples or test cases already written for you. Even so, writing out your own examples can help you cement your understanding of the problem.</p>
<p>Start with a simple example or two of possible inputs and outputs. Let's return to our addition function.</p>
<p>Let’s call our function “add.”</p>
<p>What’s an example input? Example input might be:</p>
<p><code>// add(2, 3)</code> </p>
<p>What is the output to this? To write the example output, we can write: </p>
<p><code>// add(2, 3) ---&gt; 5</code></p>
<p>This indicates that our function will take in an input of 2 and 3 and return 5 as its output.</p>
<h3 id="heading-create-complex-examples">Create complex examples.</h3>
<p>By walking through more complex examples, you can take the time to look for edge cases you might need to account for.</p>
<p>For example, what should we do if our inputs are strings instead of numbers? What if we have as input two strings, for example, add('a', 'b')?</p>
<p>Your interviewer might possibly tell you to return an error message if there are any inputs that are not numbers. If so, you can add a code comment to handle this case if it helps you remember you need to do this.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// return error if inputs are not numbers.</span>
</code></pre>
<p>Your interviewer might also tell you to assume that your inputs will always be numbers, in which case you don’t need to write any extra code to handle this particular input edge case.</p>
<p>If you don’t have an interviewer and you’re just solving this problem, the problem might say what happens when you enter invalid inputs. </p>
<p>For example, some problems will say, “If there are zero inputs, return undefined.” For cases like this, you can optionally write a comment.</p>
<p><code>// check if there are no inputs.</code></p>
<p><code>// If no inputs, return undefined.</code></p>
<p>For our purposes, we’ll assume that our inputs will always be numbers. But generally, it’s good to think about edge cases. </p>
<p>Computer science professor Evans says to write what developers call <em>defensive</em> code. Think about what could go wrong and how your code could defend against possible errors.  </p>
<p>Before we move on to step 2, let’s summarize step 1, understand the problem: </p>
<p><code>-Read through the problem.</code></p>
<p><code>-What are the inputs?</code></p>
<p><code>-What are the outputs?</code></p>
<p><code>Create simple examples, then create more complex ones.</code></p>
<h2 id="heading-2-devise-a-plan-for-solving-the-problem">2. Devise a plan for solving the problem.</h2>
<p>Next, devise a plan for how you’ll solve the problem. As you devise a plan, write it out in pseudocode. </p>
<p>Pseudocode is a plain language description of the steps in an algorithm. In other words, your pseudocode is your step-by-step plan for how to solve the problem.</p>
<p>Write out the steps you need to take to solve the problem. For a more complicated problem, you’d have more steps. For this problem, you could write:</p>
<p><code>// Create a sum variable.</code></p>
<p><code>Add the first input to the second input using the addition operator</code>.</p>
<p><code>// Store value of both inputs into sum variable.</code></p>
<p><code>// Return as output the sum variable.</code>  </p>
<p>Now you have your step-by-step plan to solve the problem.  </p>
<p>For more complex problems, professor Evans notes, “Consider systematically how a human solves the problem.” That is, forget about how your code might solve the problem for a moment, and think about how <em>you</em> would solve it as a human. This can help you see the steps more clearly.</p>
<h2 id="heading-3-carry-out-the-plan-solve-the-problem">3. Carry out the plan (Solve the problem!)</h2>
<p><img src="https://cdn.pixabay.com/photo/2017/04/06/15/02/hand-2208491_960_720.jpg" alt="Hand, Rubik, Cube, Puzzle, Game, Rubik Cube" width="600" height="400" loading="lazy"></p>
<p>The next step in the problem-solving strategy is to solve the problem. Using your pseudocode as your guide, write out your actual code. </p>
<p>Professor Evans suggests focusing on a simple, mechanical solution. The easier and simpler your solution is, the more likely you can program it correctly.</p>
<p>Taking our pseudocode, we could now write this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>) </span>{
 <span class="hljs-keyword">const</span> sum = a + b;
 <span class="hljs-keyword">return</span> sum;
}
</code></pre>
<p>Professor Evans adds, remember not to <em>prematurely optimize.</em> That is, you might be tempted to start saying, “Wait, I’m doing this and it’s going to be inefficient code!”</p>
<p>First, just get out your simple, mechanical solution.</p>
<p>What if you can’t solve the entire problem? What if there's a part of it you still don't know how to solve? </p>
<p>Colt Steele gives great advice here: If you can’t solve part of the problem, ignore that hard part that’s tripping you up. Instead, focus on everything else that you can start writing. </p>
<p>Temporarily ignore that difficult part of the problem you don’t quite understand and write out the other parts. Once this is done, come back to the harder part.</p>
<p>This allows you to get at least <em>some</em> of the problem finished. And often, you’ll realize how to tackle that harder part of the problem once you come back to it.</p>
<h2 id="heading-step-4-look-back-over-what-youve-done">Step 4: Look back over what you've done.</h2>
<p>Once your solution is working, take the time to reflect on it and figure out how to make improvements. This might be the time you refactor your solution into a more efficient one. </p>
<p>As you look at your work, here are some questions Colt Steele suggests you ask yourself to figure out how you can improve your solution:</p>
<ul>
<li>Can you derive the result differently? What other approaches are there that are viable?</li>
<li>Can you understand it at a glance? Does it make sense?</li>
<li>Can you use the result or method for some other problem?</li>
<li>Can you improve the performance of your solution?</li>
<li>Can you think of other ways to refactor?</li>
<li>How have other people solved this problem?</li>
</ul>
<p>One way we might refactor our problem to make our code more concise: removing our variable and using an implicit return:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>) </span>{
 <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>With step 4, your problem might never feel finished. Even great developers still write code that they later look at and want to change. These are guiding questions that can help you.</p>
<p>If you still have time in an interview, you can go through this step and make your solution better. If you are coding on your own, take the time to go over these steps. </p>
<p>When I’m practicing coding on my own, I almost always look at the solutions out there that are more elegant or effective than what I’ve come up with. </p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this post, we’ve gone over the four-step problem-solving strategy for solving coding problems. </p>
<p>Let's review them here:</p>
<ul>
<li>Step 1: <strong>understand the problem.</strong> </li>
<li>Step 2: <strong>create a step-by-step plan for how you’ll solve it</strong>. </li>
<li>Step 3: <strong>carry out the plan</strong> and write the actual code. </li>
<li>Step 4: <strong>look back</strong> and possibly refactor your solution if it could be better.</li>
</ul>
<p>Practicing this problem-solving method has immensely helped me in my technical interviews and in my job as a developer.  </p>
<p>If you don't feel confident when it comes to solving coding problems, just remember that problem-solving is a skill that anyone can get better at with time and practice.</p>
<p>Good luck!</p>
<h3 id="heading-if-you-enjoyed-this-post-join-my-coding-clubhttpsmadisonkannaus14list-managecomsubscribepostu323fd92759e9e0b8d4083d008ampid033dfeb98f-where-we-tackle-coding-challenges-together-every-sunday-and-support-each-other-as-we-learn-new-technologies">If you enjoyed this post, join my <a target="_blank" href="https://madisonkanna.us14.list-manage.com/subscribe/post?u=323fd92759e9e0b8d4083d008&amp;id=033dfeb98f">coding club</a>, where we tackle coding challenges together every Sunday and support each other as we learn new technologies.</h3>
<h3 id="heading-if-you-have-feedback-or-questions-on-this-post-feel-free-to-tweet-me-madisonkannahttpstwittercommadisonkanna">If you have feedback or questions on this post, feel free to Tweet me <a target="_blank" href="https://twitter.com/Madisonkanna">@madisonkanna</a>.</h3>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Prepare for a Software Developer Interview ]]>
                </title>
                <description>
                    <![CDATA[ By Martin Cartledge In my last article, I shared my thoughts on how to get an interview as a software developer. This week, I will share my thoughts on how you should prepare for that interview once you get it.  Tech interviews are notoriously nerve-... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-prepare-for-a-software-developer-interview/</link>
                <guid isPermaLink="false">66d46016e39d8b5612bc0db4</guid>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interview tips ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interviewing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Job Interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ self-improvement  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 08 Dec 2020 19:54:16 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/12/bridge.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Martin Cartledge</p>
<p>In my last article, I shared my thoughts on <a target="_blank" href="https://www.martincartledge.io/get-software-developer-interview/">how to get an interview as a software developer</a>. This week, I will share my thoughts on how you should prepare for that interview once you get it. </p>
<p>Tech interviews are notoriously nerve-racking and unpredictable. But there are steps you can take to mitigate a lot of these feelings.</p>
<h2 id="heading-phases-of-the-interview-process">Phases of the interview process</h2>
<p>Most software development interviews have a similar structure - it's kind of like the modern foundation for these interviews. </p>
<p>You'll typically find the following phases in your interview process:</p>
<ul>
<li>Phone screen</li>
<li>Technical phone interview</li>
<li>On-site</li>
</ul>
<p>Let's look at each of these in a bit more depth.</p>
<h2 id="heading-what-questions-should-i-expect">What questions should I expect?</h2>
<p>Interviews in the tech industry are far from uniform, but I like to think of that as a positive thing. This keeps things interesting and can allow you to show off your skills in a new way each time. </p>
<p>This includes the questions that you will most likely be asked in your interview, but don't worry. There are lots of common questions that will help you be prepared for your big day. </p>
<p>From my perspective, these questions can be broken down into two categories, company-specific and situational (hypothetical).</p>
<h3 id="heading-company-specific-questions">Company-specific questions</h3>
<p>Depending on the size and type of company you are interviewing at, the way they interview might differ. I suggest you use websites such as <a target="_blank" href="https://www.teamblind.com/">Blind</a> or <a target="_blank" href="https://www.glassdoor.com/">Glassdoor</a> to gain insight into company-specific interview topics and questions.</p>
<p>As an example, <a target="_blank" href="https://theinterviewguys.com/amazon-interview-questions/">The Interview Guys put together a great article</a> that discusses Amazon's top interview questions. </p>
<p>If you spend a little bit of time searching around on the web, you should be able to find some questions that a certain company traditionally asks. This will give you a leg up on your preparation.</p>
<h3 id="heading-situational-hypothetical-questions">Situational (hypothetical) questions</h3>
<p>You can expect these questions to touch on your work style, recent achievements, and your technical competency. A few topics that you can expect to be asked about are:</p>
<ul>
<li>Tell me about a time that you had to deal with a tricky bug. How did you fix it? What was the outcome?</li>
<li>Do you prefer to work by collaborating (pairing) with others or on your own?</li>
<li>What do you like about the programming language you use?</li>
<li>Which new features of the language do you use most and why?</li>
<li>Describe your team’s typical workflow for a project. What do you like about it? What don’t you like about it?</li>
</ul>
<p>Remember, stay positive as much as you can. Although the interviewer is genuinely interested in your responses, they are also looking for any signs of negativity or difficulty you might bring into their current team dynamic.</p>
<p>Try to avoid talking down about a particular piece of technology you have used in the past. Instead, spin your response in a positive way.</p>
<p>For example, instead of saying “I don’t like using the spread operator in JavaScript, it’s too confusing”, you can say, “I know the spread operator is a newer feature of JavaScript, I look forward to learning more about it and how to use it efficiently in my code.”</p>
<p>Now that you have a good idea of what some common questions are and some elements to include in your responses, let's dive into each step in the interview process. The first step is the <em>phone screen.</em> </p>
<h2 id="heading-first-things-first-tell-me-about-yourself">First things first, "tell me about yourself"</h2>
<p>After you apply and a company has an interest in you, the first step is usually to schedule a <em>phone interview</em>. This is typically a pretty relaxed conversation with a member of HR. </p>
<p>You can expect them to ask primarily about your job history, what you are looking for next, and most importantly, why you are applying for a position at their company.</p>
<p>Just because this is typically <em>easier</em> than the other phases of the interview process does not mean you should not prepare for it. A few questions to prepare for are:</p>
<p><strong>Tell me a little bit about yourself</strong></p>
<p>This is a good time to give your “elevator pitch”. This will likely be one of the first questions you are asked and usually can be a great tone-setter for the remainder of the interview. </p>
<p>If you tend to talk fast, take a deep breath before you answer and try to speak slowly and clearly. A few items you want to mention in your response are:</p>
<ul>
<li>Ethos or interests you share with the company</li>
<li>What excites <em>you</em> about software development</li>
<li>Future goals that (hopefully) this company can help fulfill (that is, technical and professional growth)</li>
</ul>
<p><strong>What is a recent project you worked on that you are proud of?</strong></p>
<p>Like most of these questions, the interviewer is not solely curious about your technical achievements. They are also looking for cues that convey you can communicate well, are reliable, and are someone who would get along with the other members of the team. </p>
<p>Try to be enthusiastic and answer questions fully, without rambling too much. An effective framework for answering these types of questions is:</p>
<ul>
<li>Give a quick overview of what the project is and the problem it solves</li>
<li>Mention the technologies you used in this project</li>
<li>Communicate any metrics that demonstrate any positive impact (like time-saving metrics, open-source contributors, number of active users)</li>
</ul>
<p><strong>Why are you looking to leave your current company?</strong></p>
<p>This might be one of the trickier questions to answer. Make sure you have a solid answer for this one prepared prior to the interview, as it can tell a lot about a candidate pretty quickly. </p>
<p>Here are a few things you should <strong>avoid</strong> when answering this question:</p>
<ul>
<li>Being negative. Turn any potentially negative factor into a positive one. For example, “I am bored and unsatisfied with the work I do here” can be said instead like, “I am looking for a new challenge that cultivates my growth as a developer and an individual”.</li>
<li>Talking about current coworkers or managers – keep them out of the conversation</li>
<li>Discussing compensation and benefits</li>
</ul>
<p>I think one of the best answers you can give to this question is an honest one – you are looking for something new. That is a perfectly reasonable answer! </p>
<p>The only pieces I might add to this response are your interest in new challenges, enthusiasm for the company, or a piece of technology that you know this company uses.</p>
<h2 id="heading-how-to-prepare-for-the-technical-phone-interview">How to prepare for the technical phone interview</h2>
<p>Ok, you were enthusiastic, personable, and well prepared for your phone interview. The next step in this process is generally a <em>technical phone interview</em>. </p>
<p>Before your technical phone interview, it's important to make sure you know which programming language you will use.</p>
<h3 id="heading-which-programming-language-should-i-use">Which programming language should I use?</h3>
<p>Before you start preparing for the other steps of the interview process, it would be prudent to have a good idea of which programming language you will use during the interview.</p>
<p>When it comes to this question, I have some pretty simple advice: <em>embrace what you are comfortable with, and stick to what you know.</em></p>
<p>It is fairly common to want to use (or learn) multiple languages in our field. But, when preparing for an interview, it is best to stick with just one. </p>
<p>This will help shift your focus from worrying about which language you will use, to thinking of problems you have solved with the language you are most comfortable with.</p>
<p>Once you know which programming language you will use, you are ready to take on the challenge of the <em>technical phone interview.</em></p>
<h3 id="heading-discussing-technical-achievements-and-high-level-programming-topics">Discussing technical achievements and high-level programming topics</h3>
<p>In a typical technical phone interview, you'll have a conversation with a senior member of the team you would join or with the manager of that team. You can expect a lot of this conversation to be focused on two things:</p>
<ul>
<li>Recent problems you have experienced in your current position and the solutions you implemented for them, and</li>
<li>General language familiarity (such as when would you want to use an array instead of a hash table (object)?)</li>
</ul>
<p>To help prepare for this interview, I suggest you start to write down answers to these questions. </p>
<p>Personally, I have used an Excel or Google sheet document that consists of 3 columns: <em>questions</em>, <em>answers</em>, and <em>notes</em>. You will find that taking the action of writing your answers down will help you come up with a concise and impactful answer.</p>
<p>There are a lot of resources online that list common interview questions, for <a target="_blank" href="https://github.com/h5bp/Front-end-Developer-Interview-Questions">frontend</a>, <a target="_blank" href="https://github.com/arialdomartini/Back-End-Developer-Interview-Questions">backend</a>, or <a target="_blank" href="https://github.com/aershov24/full-stack-interview-questions">full-stack</a> roles.</p>
<p>This might seem like a lot of work upfront, but trust me – spending the time to prepare and convert your thoughts to pen and paper will really help you mentally flesh out your answers.</p>
<p>Okay, you've spent ample time preparing and you impressed your interviewer! The next step you can expect is the "on-site" interview.</p>
<h2 id="heading-what-is-the-on-site-interview-all-about">What is the on-site interview all about?</h2>
<p>The final stage of the interview process is usually referred to as the <em>on-site</em>. This is often the most in-depth and the most important to perform well at.</p>
<p>One of the main questions the company would like to have a good answer for is, <em>how does this person work?</em> The answer to this question is usually echoed through multiple levels as well, personal, technical, and professional.</p>
<p>Companies seek this answer by giving the candidate various exercises, technical and interpersonal, to gauge your skills and how well you will fit in at their company.</p>
<p>Depending on the company this interview can include various elements, but a few that are most common are:</p>
<ul>
<li>Pair programming</li>
<li>Take-home assignments</li>
<li>Whiteboarding</li>
</ul>
<h3 id="heading-excel-during-your-pair-programming-session">Excel during your pair programming session</h3>
<p>One of the most common methods of gauging your skills is to pair program with a member of the team you might work with. </p>
<p>This session is usually 20 to 30 minutes and the problem you are given is generally something you will see on the job at this company. </p>
<p>There are a few things to keep in mind if you have a session like this:</p>
<ul>
<li>Try to stay calm and remember that <em>you are interviewing here for a reason</em>, they like you and see promise in you.</li>
<li>Communicate out loud as much as possible, even if you think you are talking too much. It’s better to over-communicate in these exercises than to sit in silence typing away at the keyboard.</li>
<li>Don’t be afraid to ask questions, they’re on your side! The interviewer has probably left out critical details on purpose to test your communication skills while working with other developers.</li>
</ul>
<p>Ultimately, try and be conscious of the fact that this company sees promise in you on a personal and technical level. Be yourself and be confident!</p>
<p>If the company does not have a pair programming exercise included in their process, another common exercise is to give you a project or a collection of problems to solve on your own.</p>
<h3 id="heading-crush-your-take-home-assignment">Crush your take-home assignment</h3>
<p>If the company wants to gauge your work through the lens of how you work as an individual, they might ask you to complete a take-home assignment.</p>
<p>These can range from completing timed exercises on <a target="_blank" href="https://www.hackerrank.com/">HackerRank</a> to completing a small project with written instructions from the interviewer themselves.</p>
<p>Regardless of the style of take-home assignment, there are a few things I think you should keep in mind to increase your chances of success:</p>
<ul>
<li>Ensure you are in a distraction-free area for the entire allotted time</li>
<li>Put any distraction-prone devices away</li>
<li>Read <em>all</em> instructions to the problem(s), and then read them again</li>
</ul>
<p>If your assignment is timed and you do not think you will have enough time to finish, write comments throughout the assignment with what your next steps would be if you had more time. </p>
<p>To be honest, a lot of these assignments are supposed to take longer than the scheduled time to complete.</p>
<p>The interviewer is always primarily focused on how you <em>communicate</em>, not that you can write code the fastest, or solve every algorithm you see.</p>
<h3 id="heading-conquer-the-whiteboard-exercise">Conquer the whiteboard exercise</h3>
<p>Sometimes a company would prefer to take a look at your technical skills and ability to break down complex problems in more of an abstract way. The most common way of testing a candidate this way is by having them complete a whiteboard exercise.</p>
<p>This method of interviewing might be the most talked about, and the most feared. If you are asked to use a whiteboard to solve a question remember this: they are (usually) far more interested in <em>how</em> you communicate your problem-solving process, not that you can solve the problem.</p>
<p>If the problem they give you seems really hard, that is not because they are trying to stump you. They want to get a feel for how you tackle a hard problem. If you don’t end up solving the problem, that does not mean you blew your chance. </p>
<p>If you keep these things in mind during this exercise, it will increase your chances of impressing your interviewer:</p>
<ul>
<li>Repeat the question back to the interviewer</li>
<li>Ask clarifying question about edge cases</li>
<li>Confirm optimal results of the problem</li>
<li>Write your code legibly</li>
<li>Communicate each step you take</li>
</ul>
<p>If you answered the question successfully by the time the session ends, ask your interviewer if that was the solution they commonly got. If not, ask what other candidates have done or what you could have done differently. This shows that you are engaged and curious.</p>
<p>If you did not answer the question successfully, write comments throughout the code about where you might continue to find the solution if you had more time. Again, a lot of these sessions are not focused solely on getting the “right” answer, but to get a good idea of how you approach new problems.</p>
<h2 id="heading-practice-interviewing-without-the-pressure">Practice interviewing, without the pressure</h2>
<p>As I mentioned earlier, interviews are tough and can be hard to prepare for. However, I am a firm believer that the best way to ensure a higher chance of success is to practice, practice, practice.</p>
<p>Have you ever practiced a big presentation for school in front of friends or family? You might have still been nervous but, it sure does help you feel more comfortable speaking about your topic.</p>
<p>Interviewing is also a presentation, and the concept of practice runs are just as important. In the 2020 world, most interviews are completed remotely, which makes performing mock interviews feel more <em>real</em>.</p>
<p>If you know someone who is currently in the software industry, I would ask them if they would be willing to set aside an hour or so a week to perform these mock interviews with you. If they currently work in a similar role that you are interviewing for, even better!</p>
<p>A few other options are <a target="_blank" href="https://www.pramp.com/">Pramp</a> and <a target="_blank" href="https://codeinterview.io/">CodeInterview</a>. These sites allow you to schedule an interview, and pick a primary focus (topic), language, and area of expertise (frontend, backend, and so on). </p>
<p>These platforms also give you more flexibility so you do not have to worry about scheduling time with someone you personally know.</p>
<p>Interviews are nerve-racking, but I am confident as you complete more of them your confidence and comfort level will increase.</p>
<h2 id="heading-should-i-cram-the-day-before">Should I cram the day before?</h2>
<p>As the days go by, you are feeling more confident. You are tired from preparation, but excited to show this company what you are made of. It's finally the day before the interview – what is the best use of your time?</p>
<p>It might be tempting for candidates to cram as many <a target="_blank" href="https://leetcode.com/">Leetcode</a> problems or whiteboard questions as possible the day before. But I believe the best thing you can do for your mind is to <strong>rest</strong>.</p>
<p><strong>Celebrate your achievement</strong>, getting interviews is <em>not</em> an easy task. Be nice to yourself. Relax and spend the day doing any activity that brings you joy and (ideally) relaxes you.</p>
<p>This might sound counterintuitive, but I think it is the best thing for you to do. You will need your brain to work well at your interview. Therefore, giving it rest the day before is exactly what it needs.</p>
<h2 id="heading-in-summary">In Summary</h2>
<p>If you are reading this because you are going to start to prepare for an interview, congrats! I hope my insights can help in your preparation and your headspace as you approach your big day. </p>
<p>Ultimately, remember to take a deep breath, relax, and be confident in yourself. Whoever you interview with sees promise in your skills. You got this!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
