<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Farai Bvuma</title>
    <description>The latest articles on DEV Community by Farai Bvuma (@faraib).</description>
    <link>https://dev.to/faraib</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1067273%2Ff2afdc90-473b-4fd7-aa86-6c5976c29157.jpeg</url>
      <title>DEV Community: Farai Bvuma</title>
      <link>https://dev.to/faraib</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/faraib"/>
    <language>en</language>
    <item>
      <title>Setup Tailwind CSS v4.0 with Vite + React</title>
      <dc:creator>Farai Bvuma</dc:creator>
      <pubDate>Thu, 25 Sep 2025 23:49:03 +0000</pubDate>
      <link>https://dev.to/faraib/setup-tailwind-css-v40-with-vite-react-41k6</link>
      <guid>https://dev.to/faraib/setup-tailwind-css-v40-with-vite-react-41k6</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;I recently ran into some trouble trying to setup Tailwind CSS v4.0 with a new Vite + React project. If you are stuck trying to figure out how to proceed, here is a quick step-by-step guide to help you. &lt;/p&gt;

&lt;h2&gt;
  
  
  Configuration
&lt;/h2&gt;

&lt;p&gt;In the project directory, run the following command to install tailwind.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm &lt;span class="nb"&gt;install &lt;/span&gt;tailwindcss @tailwindcss/vite
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Update your vite.config.ts file, importing tailwind and adding it as a plugin.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;defineConfig&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;vite&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;react&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;@vitejs/plugin-react&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;tailwindcss&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;@tailwindcss/vite&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="nf"&gt;defineConfig&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
  &lt;span class="na"&gt;plugins&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nf"&gt;react&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt; &lt;span class="nf"&gt;tailwindcss&lt;/span&gt;&lt;span class="p"&gt;()],&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add the tailwind import to your global css file, in my case it was my &lt;code&gt;src/index.css&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight css"&gt;&lt;code&gt;&lt;span class="k"&gt;@import&lt;/span&gt; &lt;span class="s1"&gt;"tailwindcss"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now go ahead and test your setup, this can be done in the &lt;code&gt;App.tsx&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight tsx"&gt;&lt;code&gt;      &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;div&lt;/span&gt; &lt;span class="na"&gt;className&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"text-3xl font-bold underline bg-red-700"&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
        Hello World!
      &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;div&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;I hope this guide will help you with your setup, feel free to reach out if you have any questions. &lt;/p&gt;

</description>
      <category>react</category>
      <category>tailwindcss</category>
      <category>beginners</category>
      <category>vite</category>
    </item>
    <item>
      <title>Dynamic Styling with Props in Styled-Components</title>
      <dc:creator>Farai Bvuma</dc:creator>
      <pubDate>Tue, 15 Jul 2025 02:08:33 +0000</pubDate>
      <link>https://dev.to/faraib/dynamic-styling-with-props-in-styled-components-2p7k</link>
      <guid>https://dev.to/faraib/dynamic-styling-with-props-in-styled-components-2p7k</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Have you ever been stuck trying to figure out how to manipulate the styles of a prop in React using &lt;code&gt;styled-components&lt;/code&gt;? What about when you want to directly apply CSS rules based on a prop's value, even if that prop is not a standard CSS property? Here is a quick guide on how you can get this done. &lt;/p&gt;

&lt;p&gt;Let's say that you have a button component with a prop called &lt;code&gt;state&lt;/code&gt;(&lt;code&gt;isLoading&lt;/code&gt;, &lt;code&gt;isActive&lt;/code&gt; etc), and you want to change how this React component is displayed based on whether the &lt;code&gt;state&lt;/code&gt; is &lt;code&gt;true&lt;/code&gt; or &lt;code&gt;false&lt;/code&gt;. Simply follow the below example, swapping out the CSS rules that you wish to conditionally apply. We are using TypeScript and &lt;code&gt;styled-components&lt;/code&gt; in the below example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;StyledComponent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;styled&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;button&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;?:&lt;/span&gt; &lt;span class="nx"&gt;boolean&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="s2"&gt;`
   // The base CSS styles for the button go here
   background-color: blue;

   // Styles will be conditionally applied based on the 'state' prop
   &lt;/span&gt;&lt;span class="p"&gt;${({&lt;/span&gt; &lt;span class="nx"&gt;state&lt;/span&gt; &lt;span class="p"&gt;})&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;state&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="s2"&gt;`
    // These CSS rules will apply only when the 'state' prop is true
    border: 1px solid darkblue;
    opacity: 0.8;
  `&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;
`&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How it works
&lt;/h2&gt;

&lt;p&gt;Since &lt;code&gt;state&lt;/code&gt; is not a CSS property(like &lt;code&gt;color&lt;/code&gt; or &lt;code&gt;padding&lt;/code&gt;), we use a JavaScript template literal( &lt;code&gt;${}&lt;/code&gt; ) to inject our custom logic directly into the CSS. &lt;/p&gt;

&lt;p&gt;Inside the template literal, we provide a callback function(&lt;code&gt;({ state }) =&amp;gt; ...&lt;/code&gt; ) that is used by &lt;code&gt;styled-components&lt;/code&gt; to pass the component's props. We have also used object destructuring( &lt;code&gt;{state}&lt;/code&gt; ) to easily access the prop's value. &lt;/p&gt;

&lt;p&gt;As previously mentioned, the aim is to conditionally render the button based on the &lt;code&gt;state&lt;/code&gt; prop, and we do this by using the logical AND operator( &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; ), where if the &lt;code&gt;state&lt;/code&gt; prop is truthy, the expression evaluates to the CSS string inside of the inner backticks, with &lt;code&gt;styled-components&lt;/code&gt; proceeding to apply the CSS. Otherwise, if the &lt;code&gt;state&lt;/code&gt; prop is falsy, no CSS is injected from the block.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Using this pattern to conditionally render components in React based on values of props is a great way to create dynamic components. Be sure to give it a try.  &lt;/p&gt;

</description>
      <category>react</category>
      <category>frontend</category>
      <category>intermediate</category>
      <category>styledcomponents</category>
    </item>
    <item>
      <title>Build Apps with Google AI Studio: Anime Greetings Cards</title>
      <dc:creator>Farai Bvuma</dc:creator>
      <pubDate>Sat, 05 Jul 2025 01:46:54 +0000</pubDate>
      <link>https://dev.to/faraib/build-apps-with-google-ai-studio-anime-greetings-cards-9ek</link>
      <guid>https://dev.to/faraib/build-apps-with-google-ai-studio-anime-greetings-cards-9ek</guid>
      <description>&lt;p&gt;&lt;em&gt;This post is my submission for &lt;a href="https://dev.to/deved/build-apps-with-google-ai-studio"&gt;DEV Education Track: Build Apps with Google AI Studio&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What I Built
&lt;/h2&gt;

&lt;p&gt;I set out to build anime inspired AI generated greetings cards. This is the prompt that I used:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Please create an app that generates cute and unique greetings cards, using Imagen for anime inspired visuals, and Gemini for heartfelt messages. I will need to be able to export the finished app to run locally with minimal setup and then host it on Vercel.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Demo
&lt;/h2&gt;

&lt;p&gt;Here is a link of the version I deployed to &lt;a href="https://ai-anime-greeting-card-generator-qw.vercel.app/" rel="noopener noreferrer"&gt;Vercel&lt;/a&gt; because I do not have a billed account. Here is the repo on &lt;a href="https://github.com/FaraiB/ai-anime-greeting-card-generator" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffiyl58acnpodrngwiv7j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffiyl58acnpodrngwiv7j.png" alt="Greeting card app" width="592" height="999"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  My Experience
&lt;/h2&gt;

&lt;p&gt;Getting this app up and running took way more time than advertised. On my first attempt, I couldn't get the app to render in the Google AI Studio's preview tab. After a little back and forth with the AI agent, I got it to work. Following the tutorial I tried to get it to deploy to cloudrun, only to hit a major roadblock because I do not have billing activated on my Google Cloud account. This was rather frustrating, so together with the AI agent we came up with a workaround, deploy to Vercel! Unbeknownst to me at the time, this would bring its own set of problems, mainly that the code used to build in the Google Studio does not immediately work when run locally, nor does it deploy in Vercel. I tried to work out a solution with the AI Agent only for it to completely stop working.&lt;/p&gt;

&lt;p&gt;This is a really cool concept so I decided to give it another go, scrapping the original app and creating a new app with a new prompt. This time it worked right off the bat. I had to direct the agent to fix an issue with the greetings messages, where the app was displaying three messages instead of one. Since I have a bad habit of doing things the hard way, I decided to try running the app locally and deploying to Vercel. Unfortunately the agent was of no real help when it came to this. The agent became fixated on the importmap script, which is necessary to render the app in the preview tab of Google AI Studio, but not necessary for local builds and Vercel deployment. I discovered that the AI agent has a stubborn streak, even after being told numerous times to ignore the "issue", it repeatedly came back to it. It was an endless loop where it would analyse its own code, recognise that importmap in unnecessary for local builds, suggest deletion of the script, run the suggested upgrade only for it to automatically add the script again and then suggest its removal. Because of this it wasn't of much help when it came to running the app locally, even less so for deploying on Vercel. Thanks to my professional experience and help from another LLM, I was able to figure it out. &lt;/p&gt;

&lt;p&gt;You would think this would be the end of it but unfortunately I ran into one more issue when deploying to Vercel, Imagen does not generate images unless the Gemini API Key is connected to a billed account, and a little bit of research shows that this can get quite expensive.  &lt;/p&gt;

&lt;p&gt;So what did I learn? Google's AI Studio is a really cool tool with potential to get your app ideas off the ground in record time, but pray that you do not need any fine tweaking. If it wasn't for my experience as a software developer I probably wouldn't have noticed some of the issues, and I definitely would not have been able to fix most of them. The initial app is serviceable, but after all this effort I'm too drained to ask it to fine tweak the presentation.&lt;/p&gt;

</description>
      <category>deved</category>
      <category>learngoogleaistudio</category>
      <category>ai</category>
      <category>gemini</category>
    </item>
    <item>
      <title>GitHub Issue Importer</title>
      <dc:creator>Farai Bvuma</dc:creator>
      <pubDate>Fri, 30 May 2025 15:40:16 +0000</pubDate>
      <link>https://dev.to/faraib/github-issue-importer-2efl</link>
      <guid>https://dev.to/faraib/github-issue-importer-2efl</guid>
      <description>&lt;p&gt;Did you know that GitHub does not offer a way to import multiple issues at once? I came across this problem whilst laying out my plans for a new project. I had created a number of tasks and I wanted to add these tasks as issues to my project in GitHub. Faced with the daunting task of manually adding all of these tasks as issues, I decided to peruse the web for an easy solution but came up empty handed. Since I had some free time, I decided to try developing a tool that will do all of this for me. &lt;/p&gt;

&lt;p&gt;If you would like to import a number of issues in one go, all you need to do is create a CSV file with the issues in the following format:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;title,body,labels
"Issue Title","Issue Description","Labels"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is what such a file might look like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;title,body,labels
"Add dark mode","Implement dark mode toggle","feature,UI"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you don't already have one, next you need to create a personal access token on GitHub. This can be done by accessing the developer settings in your GitHub profile.&lt;/p&gt;

&lt;p&gt;Finally, clone the &lt;a href="https://github.com/FaraiB/csv-to-github" rel="noopener noreferrer"&gt;repo&lt;/a&gt; and follow the instructions. &lt;/p&gt;

&lt;p&gt;Hopefully this will save you time if you ever wish to import multiple tasks automatically. &lt;/p&gt;

</description>
      <category>python</category>
      <category>github</category>
      <category>programming</category>
    </item>
    <item>
      <title>GitHub Issue Importer</title>
      <dc:creator>Farai Bvuma</dc:creator>
      <pubDate>Sun, 30 Mar 2025 04:00:55 +0000</pubDate>
      <link>https://dev.to/faraib/github-issue-importer-56gd</link>
      <guid>https://dev.to/faraib/github-issue-importer-56gd</guid>
      <description>&lt;p&gt;Did you know that GitHub does not offer a way to import multiple issues at once? I came across this problem whilst laying out my plans for a new project. I had created a number of tasks and I wanted to add these tasks as issues to my project in GitHub. Faced with the daunting task of manually adding all of these tasks as issues, I decided to peruse the web for an easy solution but came up empty handed. Since I had some free time, I decided to try developing a tool that will do all of this for me. &lt;/p&gt;

&lt;p&gt;If you would like to import a number of issues in one go, all you need to do is create a CSV file with the issues in the following format:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;title,body,labels
"Issue Title","Issue Description","Labels"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is what such a file might look like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;title,body,labels
"Add dark mode","Implement dark mode toggle","feature,UI"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you don't already have one, next you need to create a personal access token on GitHub. This can be done by accessing the developer settings in your GitHub profile.&lt;/p&gt;

&lt;p&gt;Finally, clone the &lt;a href="https://github.com/FaraiB/csv-to-github" rel="noopener noreferrer"&gt;repo&lt;/a&gt; and follow the instructions. &lt;/p&gt;

&lt;p&gt;Hopefully this will save you time if you ever wish to import multiple tasks automatically. &lt;/p&gt;

</description>
      <category>python</category>
      <category>github</category>
      <category>programming</category>
    </item>
    <item>
      <title>Data Structures and Algorithms: Dijkstra's Algorithm</title>
      <dc:creator>Farai Bvuma</dc:creator>
      <pubDate>Fri, 20 Sep 2024 01:01:13 +0000</pubDate>
      <link>https://dev.to/faraib/data-structures-and-algorithms-dijkstras-algorithm-ah4</link>
      <guid>https://dev.to/faraib/data-structures-and-algorithms-dijkstras-algorithm-ah4</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Dijkstra's Algorithm is a greedy algorithm that is used to find the shortest path from a source vertex to all of the other vertices on a weighted directed graph. Being a greedy algorithm, an attempt is made to find the optimal solution by breaking the problem up into steps and solving these steps one at a time. The optimal solution in this case is the next vertex with shortest path. It is important to note that this algorithm cannot be used in a graph with negative weights. &lt;/p&gt;

&lt;h2&gt;
  
  
  Dijkstra's Algorithm Walkthrough
&lt;/h2&gt;

&lt;p&gt;The algorithm starts by initialising the starting vertex of the graph with a distance of zero and all other vertices with distances of infinity. At this point all of the vertices are marked as unvisited. The algorithm will also initialise a priority queue to keep track of the vertices with the shortest known distances. The starting vertex is then dequeued(as it has a distance of zero) and is marked as visited. The algorithm will now check the edges of the adjacent vertices, calculating a new potential distance to each vertex by adding the weight to the distance from the current vertex. If the new distance is smaller than the currently known distance to the vertex, this distance is updated and the vertex is enqueued. The algorithm will then go on to select the next vertex from the priority queue(i.e. the vertex with the smallest distance), mark it as visited and will repeat the process until all of the vertices in the graph have been visited. We can illustrate this using the following graph:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn4sjznvhdimnc7eu0cqg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn4sjznvhdimnc7eu0cqg.png" alt="Weighted graph" width="800" height="454"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Starting at vertex &lt;strong&gt;A&lt;/strong&gt; with a distance of zero, the distances from A to all of the remaining vertices will be set as infinity. &lt;strong&gt;A&lt;/strong&gt; is then added to a priority queue, before being dequeued, marked as visited and checking the distances to vertices &lt;strong&gt;B&lt;/strong&gt; and &lt;strong&gt;D&lt;/strong&gt;. As these distances are less than infinity, their calculated distances are updated as 2 and 6 respectively. Both vertices are then added to the priority queue. &lt;/p&gt;

&lt;p&gt;As &lt;strong&gt;B&lt;/strong&gt; has the shortest distance, it will be the next vertex to be dequeued, marked as visited and processed by the algorithm. The algorithm now checks &lt;strong&gt;B&lt;/strong&gt;'s adjacent vertices(&lt;strong&gt;D&lt;/strong&gt; and &lt;strong&gt;C&lt;/strong&gt;) and checks their distances from the starting node, &lt;strong&gt;A -&amp;gt; B -&amp;gt; C&lt;/strong&gt;(2 + 3 = 5) and &lt;strong&gt;A -&amp;gt; B -&amp;gt; D&lt;/strong&gt;(2 + 7 = 9). The algorithm then compares these newly calculated distances to the previously stored distances. The distance to &lt;strong&gt;C&lt;/strong&gt; is updated to 5 and the distance to &lt;strong&gt;D&lt;/strong&gt; remains unchanged at 6. &lt;strong&gt;C&lt;/strong&gt; is now also added to the priority queue. &lt;/p&gt;

&lt;p&gt;The shortest distance is now 5 so the vertex &lt;strong&gt;C&lt;/strong&gt; is dequeued and marked as visited. It only has &lt;strong&gt;E&lt;/strong&gt; as an adjacent vertex, with a distance of 2 + 3 + 5 = 10(&lt;strong&gt;A -&amp;gt; B -&amp;gt; C -&amp;gt; E&lt;/strong&gt;). The vertex &lt;strong&gt;E&lt;/strong&gt; is also added to the priority queue. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;D&lt;/strong&gt; is the next vertex to be dequeued and marked as visited since it has a distance of 6(&lt;strong&gt;A -&amp;gt; D&lt;/strong&gt;). The algorithm will now check &lt;strong&gt;D&lt;/strong&gt;'s adjacent vertices. Vertex &lt;strong&gt;C&lt;/strong&gt; has already been visited so no further action will be taken. Finally the algorithm will finish by dequeuing &lt;strong&gt;E&lt;/strong&gt; and processing it. &lt;/p&gt;

&lt;h2&gt;
  
  
  Implementing Dijkstra's Algorithm in JavaScript
&lt;/h2&gt;

&lt;p&gt;To implement Dijkstra's Algorithm in JavaScript, we can start off by creating a &lt;code&gt;PriorityQueue&lt;/code&gt; class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class PriorityQueue {
  constructor() {
    this.elements = [];
  }

  enqueue(node, weight) {
    this.elements.push({ node, weight });
    this.elements.sort((a, b) =&amp;gt; a.weight - b.weight);
  }

  dequeue() {
    return this.elements.shift(); 
  }

  isEmpty() {
    return this.elements.length === 0;
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Along with the constructor, we will create an &lt;code&gt;enqueue()&lt;/code&gt; method to add a vertex and its weight to the priority queue. These vertices are then sorted according to their weights, that is to say, the vertex with the smallest weight(or distance) will come first. The &lt;code&gt;dequeue()&lt;/code&gt; method is used to return the vertex with the smallest weight from the priority queue and the &lt;code&gt;isEmpty()&lt;/code&gt; method is used to check if the priority queue has any vertices.&lt;/p&gt;

&lt;p&gt;Next we will create a &lt;code&gt;Graph&lt;/code&gt; class which will have a constructor. This constructor will use an object to store an adjacency list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  constructor() {
    this.adjacencyList = {}; 
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;Graph&lt;/code&gt; class will also have the &lt;code&gt;addNode()&lt;/code&gt; method which will be used to add a vertex and the &lt;code&gt;addEdge()&lt;/code&gt; method which will be used to add edges to a vertex.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  addNode(node) {
    this.adjacencyList[node] = [];
  }

  addEdge(node1, node2, weight) {
    this.adjacencyList[node1].push({ node: node2, weight });
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;addNode()&lt;/code&gt; method will initialize an empty array for the adjacency list for a given vertex. This array will then go on to store all of the edges for the node provided in the &lt;code&gt;addEdge()&lt;/code&gt; method. For example, to add nodes A and B from our graph, we will use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph.addNode('A');
graph.addNode('B');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The adjacency lists for the two nodes will look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  A: [],
  B: []
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And then the edge can be added as follows&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph.addEdge('A', 'B', 2);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This results in the adjacency list looking like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  A: [{ node: 'B', weight: 2 }],
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will also need to create the &lt;code&gt;dijkstra()&lt;/code&gt; method to run the algorithm:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dijkstra(start) {
    const distances = {};
    const previous = {};
    const pQueue = new PriorityQueue();

    for (const node in this.adjacencyList) {
      distances[node] = Infinity;
      previous[node] = null;
    }

    distances[start] = 0;
    pQueue.enqueue(start, 0);

    while (!pQueue.isEmpty()) {
      const { node: currentNode } = pQueue.dequeue();

      for (const neighbor of this.adjacencyList[currentNode]) {
        const { node: adjacent, weight } = neighbor;
        const newDist = distances[currentNode] + weight;

        if (newDist &amp;lt; distances[adjacent]) {
          distances[adjacent] = newDist;
          previous[adjacent] = currentNode;
          pQueue.enqueue(adjacent, newDist); 
        }
      }
    }

   return { distances, previous };
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This method will have a &lt;code&gt;distances&lt;/code&gt; object to map the calculated distances from the starting vertex to all of the remaining vertices in the graph, a &lt;code&gt;previous&lt;/code&gt; object to keep track of each vertex's previous vertex and a priority queue which will be used to keep track of the vertices with the shortest distances. These will be initialised and the distances from the starting vertex will be calculated, before returning the &lt;code&gt;distances&lt;/code&gt; and &lt;code&gt;previous&lt;/code&gt; objects. &lt;/p&gt;

&lt;p&gt;Lastly we will create the &lt;code&gt;getShortestPath()&lt;/code&gt; method, which will be used to return the shortest path between two vertices.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; getShortestPath(start, end) {
    const { distances, previous } = this.dijkstra(start);
    const path = [];
    let currentNode = end;

    while (currentNode !== null) {
      path.push(currentNode);
      currentNode = previous[currentNode];
    }

    return {
      distance: distances[end],
      path: path.reverse(),
    };
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;This article explains the logic behind Dijkstra's Algorithm to find the shortest path in a graph. This article also shows how the algorithm can be implemented in JavaScript using a priority queue, although this could be done more efficiently using a min-heap. Some real world applications of Dijkstra's Algorithm include GPS and mapping software(Google Maps), route optimization in public transport systems, finding the most efficient route for sending data packets in internet routing protocols and AI pathfinding in video games. &lt;/p&gt;

</description>
      <category>javascript</category>
      <category>intermediate</category>
      <category>dsa</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>Data Structures and Algorithms: Graphs</title>
      <dc:creator>Farai Bvuma</dc:creator>
      <pubDate>Thu, 05 Sep 2024 03:05:57 +0000</pubDate>
      <link>https://dev.to/faraib/data-structures-and-algorithms-graphs-3b6c</link>
      <guid>https://dev.to/faraib/data-structures-and-algorithms-graphs-3b6c</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;A graph is a data structure with a number of vertices(nodes) and edges(connections) between them.&lt;/p&gt;

&lt;p&gt;A tree is an example of a graph. Every tree is a graph but not every graph is a tree, for example, graphs that have cycles are not trees. A tree will have one root and one unique path between two nodes whilst a graph can have many roots and multiple paths between vertices. &lt;/p&gt;

&lt;h2&gt;
  
  
  Basic Terminology
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Vertex&lt;/em&gt;:&lt;/strong&gt; A node in a graph. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Edge&lt;/em&gt;:&lt;/strong&gt; The connection between two vertices. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4dui8g0oub5md7zkh548.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4dui8g0oub5md7zkh548.png" alt="Simple graph showing vertices and edges" width="800" height="478"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Directed&lt;/em&gt;:&lt;/strong&gt; When the connection between two vertices has a direction. This implies that there is only one way to get from one vertex to another. An example could be graph showing the cities(vertices) and the routes(edges) between them.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Facqs35hritmc1wlhjux2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Facqs35hritmc1wlhjux2.png" alt="Directed graph" width="800" height="492"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Undirected&lt;/em&gt;:&lt;/strong&gt; When the connection between two vertices on a graph goes both ways. An example could be a graph showing people(vertices) connected by their friendships. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flwp4kr5ze4k71ckebc74.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flwp4kr5ze4k71ckebc74.png" alt="Undirected graph" width="800" height="478"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Degree&lt;/em&gt;:&lt;/strong&gt; The number of edges connected to a vertex. The vertices of a directed graph can have an indegree or an outdegree, which is the number of edges pointing towards and away from the vertex respectively. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Weighted&lt;/em&gt;:&lt;/strong&gt; A graph in which the edges have values as weights. An example could be a road map, where the distances between nodes are represented as weights. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F371y1fp8pcj79z8mht7m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F371y1fp8pcj79z8mht7m.png" alt="Weighted graph" width="800" height="538"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Cyclic&lt;/em&gt;:&lt;/strong&gt; A graph that has a path from at least one vertex back to itself.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9fz9zls8yg99d15v4e2o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9fz9zls8yg99d15v4e2o.png" alt="Cyclic graph" width="800" height="516"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Acyclic&lt;/em&gt;:&lt;/strong&gt; A graph that has no cycles, that is to say, no node has a path back to itself. A &lt;strong&gt;Directed Acyclic Graph&lt;/strong&gt; is a type of graph that can be used to show data processing flows. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Dense&lt;/em&gt;:&lt;/strong&gt; When a graph has close to the maximum possible number of edges&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Sparse&lt;/em&gt;:&lt;/strong&gt; When a graph has close to the minimum possible number of edges. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Self-loop&lt;/em&gt;:&lt;/strong&gt; When an edge has one vertex linking to itself. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Multi-edge&lt;/em&gt;:&lt;/strong&gt; When a graph has multiple edges between two vertices. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Simple&lt;/em&gt;:&lt;/strong&gt; When a graph has no self-loops nor multi-edges.&lt;/p&gt;

&lt;p&gt;To get the maximum number of edges in a simple directed graph: &lt;code&gt;n*(n-1)&lt;/code&gt; where n is the number of nodes.&lt;/p&gt;

&lt;p&gt;To get the maximum number of edges in a simple undirected graph: &lt;code&gt;n*(n-1)/2&lt;/code&gt; where n is the number of nodes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementing graphs in JavaScript
&lt;/h2&gt;

&lt;p&gt;To implement a graph, we can start by specifying the vertices and edges of a graph, below is an example of how to do this given the following graph: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft43dp9o125wqzt5kx4k8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft43dp9o125wqzt5kx4k8.png" alt="Sample graph" width="800" height="503"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const vertices = ["A", "B", "C", "D", "E"];

const edges = [
  ["A", "B"],
  ["A", "D"],
  ["B", "D"],
  ["B", "E"],
  ["C", "D"],
  ["D", "E"],
];

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we can create a function to find what is adjacent to a given vertex:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const findAdjacentNodes = function (node) {
  const adjacentNodes = [];
  for (let edge of edges) {
    const nodeIndex = edge.indexOf(node);
    if (nodeIndex &amp;gt; -1) {
      let adjacentNode = nodeIndex === 0 ? edge[1] : edge[0];
      adjacentNodes.push(adjacentNode);
    }
  }
  return adjacentNodes;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And another function to check if two vertices are connected:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const isConnected = function (node1, node2) {
  const adjacentNodes = new Set(findAdjacentNodes(node1));
  return adjacentNodes.has(node2);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Adjacency List
&lt;/h2&gt;

&lt;p&gt;An adjacency list is a representation of a graph where all of the vertices that are connected to a node are stored as a list. Below is a graph and a visual representation of its corresponding adjacency list. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft43dp9o125wqzt5kx4k8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft43dp9o125wqzt5kx4k8.png" alt="Sample graph" width="800" height="503"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fidd9o40zbp7tkkmhvwhk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fidd9o40zbp7tkkmhvwhk.png" alt="Adjacency List" width="495" height="314"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;An adjacency list can be implemented in JavaScript by creating two classes, a &lt;code&gt;Node&lt;/code&gt; class and a &lt;code&gt;Graph&lt;/code&gt; class. The &lt;code&gt;Node&lt;/code&gt; class will consist of a &lt;code&gt;constructor&lt;/code&gt; and a &lt;code&gt;connect()&lt;/code&gt; method to join two vertices. It will also have the &lt;code&gt;isConnected()&lt;/code&gt; and &lt;code&gt;getAdjacentNodes()&lt;/code&gt; methods which work in exactly the same manner as shown above.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Node {
  constructor(value) {
    this.value = value;
    this.edgesList = [];
  }
  connect(node) {
    this.edgesList.push(node);
    node.edgesList.push(this);
  }
  getAdjNodes() {
    return this.edgesList.map((edge) =&amp;gt; edge.value);
  }
  isConnected(node) {
    return this.edgesList.map((edge) =&amp;gt; 
    edge.value).indexOf(node.value) &amp;gt; -1;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;Graph&lt;/code&gt; class consists of a &lt;code&gt;constructor&lt;/code&gt; and the &lt;code&gt;addToGraph()&lt;/code&gt; method which adds a new vertex to the graph.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Graph {
  constructor(nodes) {
    this.nodes = [...nodes];
  }
  addToGraph(node) {
    this.nodes.push(node);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Adjacency Matrix
&lt;/h2&gt;

&lt;p&gt;A 2-D array where each array represents a vertex and each index represents a possible connection between vertices. An adjacency matrix is filled with 0s and 1s, with 1 representing a connection. The value at adjacencyMatrix[node1][node2] will show whether or not there is a connection between the two specified vertices. Below is is a graph and its visual representation as an adjacency matrix.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft43dp9o125wqzt5kx4k8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft43dp9o125wqzt5kx4k8.png" alt="Sample graph" width="800" height="503"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvl54on7jdmg0mqj21zy8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvl54on7jdmg0mqj21zy8.png" alt="Adjacency Matrix" width="552" height="349"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To implement this adjacency matrix in JavaScript, we start by creating two classes, the first being the &lt;code&gt;Node&lt;/code&gt; class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Node {
  constructor(value) {
    this.value = value;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We then create the &lt;code&gt;Graph&lt;/code&gt; class which will contain the &lt;code&gt;constructor&lt;/code&gt; for creating the 2-D array initialized with zeros.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Graph {
  constructor(nodes) {
    this.nodes = [...nodes];
    this.adjacencyMatrix = Array.from({ length: nodes.length },   
    () =&amp;gt; Array(nodes.length).fill(0));
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will then add the &lt;code&gt;addNode()&lt;/code&gt; method which will be used to add new vertices to the graph.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  addNode(node) {
    this.nodes.push(node);
    this.adjacencyMatrix.forEach((row) =&amp;gt; row.push(0));
    this.adjacencyMatrix.push(new Array(this.nodes.length).fill(0));
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next is the &lt;code&gt;connect()&lt;/code&gt; method which will add an edge between two vertices.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  connect(node1, node2) {
    const index1 = this.nodes.indexOf(node1);
    const index2 = this.nodes.indexOf(node2);

    if (index1 &amp;gt; -1 &amp;amp;&amp;amp; index2 &amp;gt; -1) {
      this.adjacencyMatrix[index1][index2] = 1;
      this.adjacencyMatrix[index2][index1] = 1; 
    }
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will also create the &lt;code&gt;isConnected()&lt;/code&gt; method which can be used to check if two vertices are connected.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  isConnected(node1, node2) {
    const index1 = this.nodes.indexOf(node1);
    const index2 = this.nodes.indexOf(node2);

    if (index1 &amp;gt; -1 &amp;amp;&amp;amp; index2 &amp;gt; -1) {
      return this.adjacencyMatrix[index1][index2] === 1;
    }
    return false;
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lastly we will add the &lt;code&gt;printAdjacencyMatrix()&lt;/code&gt; method to the &lt;code&gt;Graph&lt;/code&gt; class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  printAdjacencyMatrix() {
    console.log(this.adjacencyMatrix);
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Breadth First Search
&lt;/h2&gt;

&lt;p&gt;Similar to a Breadth First Search in a tree, the vertices adjacent to the current vertex are visited before visiting any subsequent children. A queue is the data structure of choice when performing a Breadth First Search on a graph. &lt;/p&gt;

&lt;p&gt;Below is a graph of international airports and their connections and we will use a Breadth First Search to find the shortest route(path) between two airports(vertices).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F02g11dhkj5est66bg5lm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F02g11dhkj5est66bg5lm.png" alt="Graph of international airports and their connections" width="800" height="567"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In order to implement this search algorithm in JavaScript, we will use the same &lt;code&gt;Node&lt;/code&gt; and &lt;code&gt;Graph&lt;/code&gt; classes we implemented the adjacency list above. We will create a &lt;code&gt;breadthFirstTraversal()&lt;/code&gt; method and add it to the &lt;code&gt;Graph&lt;/code&gt; class in order to traverse between two given vertices. This method will have the &lt;code&gt;visitedNodes&lt;/code&gt; object, which will be used to store the visited vertices and their predecessors. It is initiated as null to show that the first vertex in our search has no predecessors.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;breathFirstTraversal(start, end) {
    const queue = [start];
    const visitedNodes = {};
    visitedNodes[start.value] = null;

    while (queue.length &amp;gt; 0) {
      const node = queue.shift();

      if (node.value === end.value) {
        return this.reconstructedPath(visitedNodes, end);
      }
      for (const adjacency of node.edgesList) {
        if (!visitedNodes.hasOwnProperty(adjacency.value)) {
          visitedNodes[adjacency.value] = node;
          queue.push(adjacency);
        }
      }
    }
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the end vertex is found, we will use the &lt;code&gt;reconstructedPath()&lt;/code&gt; method in the &lt;code&gt;Graph&lt;/code&gt; class in order to return the shortest path between two vertices. Each vertex is added iteratively to the &lt;code&gt;shortestPath&lt;/code&gt; array, which in turn must be reversed in order to come up with the correct order for the shortest path.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;reconstructedPath(visitedNodes, endNode) {
    let currNode = endNode;

    const shortestPath = [];

    while (currNode !== null) {
      shortestPath.push(currNode.value);
      currNode = visitedNodes[currNode.value];
    }
    return shortestPath.reverse();
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the case of the graph of international airports, &lt;code&gt;breathFirstTraversal(JHB, LOS)&lt;/code&gt; will return &lt;strong&gt;JHB -&amp;gt; LUA -&amp;gt; LOS&lt;/strong&gt; as the shortest path. In the case of a weighted graph, we would use Dijkstra's algorithm to find the shortest path. &lt;/p&gt;

&lt;h2&gt;
  
  
  Depth First Search
&lt;/h2&gt;

&lt;p&gt;Similar to a depth first search in a tree, this algorithm will fully explore every descendant of a vertex, before backtracking to the root. A stack is the data structure of choice for depth first traversals in a graph. &lt;/p&gt;

&lt;p&gt;A depth first search can be used to detect a cycle in a graph. We will use the same graph of international airports to illustrate this in JavaScript. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F02g11dhkj5est66bg5lm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F02g11dhkj5est66bg5lm.png" alt="Graph of international airports and their connections" width="800" height="567"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Similar to the Breadth First Search algorithm above, this implementation of a Depth First Search algorithm in JavaScript will use the previously created &lt;code&gt;Node&lt;/code&gt; and &lt;code&gt;Graph&lt;/code&gt; classes. We will create a helper function called &lt;code&gt;depthFirstTraversal()&lt;/code&gt; and add it to the &lt;code&gt;Graph&lt;/code&gt; class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  depthFirstTraversal(start, visitedNodes = {}, parent = null) {
    visitedNodes[start.value] = true;

    for (const adjacency of start.edgesList) {
      if (!visitedNodes[adjacency.value]) {
        if (this.depthFirstTraversal(adjacency, visitedNodes, start)) {
          return true;
        }
      } else if (adjacency !== parent) {
        return true;
      }
    }

    return false;
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will perform the Depth First Traversal of the graph, using the &lt;code&gt;parent&lt;/code&gt; parameter to keep track of the previous vertex and prevent the detection of a cycle when revisiting the parent vertex. Visited vertices will be marked as &lt;code&gt;true&lt;/code&gt; in the &lt;code&gt;visitedNodes&lt;/code&gt; object. This method will then use recursion to visit previously unvisited vertices. If the vertex has already been visited, we check it against the &lt;code&gt;parent&lt;/code&gt; parameter. A cycle has been found if the vertex has already been visited and it is not the parent.&lt;/p&gt;

&lt;p&gt;We will also create the wrapper function &lt;code&gt;hasCycle()&lt;/code&gt; in the &lt;code&gt;Graph&lt;/code&gt; class. This function is used to detect a cycle in a disconnected graph. It will initialize the &lt;code&gt;visitedNodes&lt;/code&gt; object and loop through all of the vertices in the graph.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;hasCycle() {
    const visitedNodes = {};

    for (const node of this.nodes) {
      if (!visitedNodes[node.value]) {
        if (this.depthFirstTraversal(node, visitedNodes)) {
          return true;
        }
      }
    }
    return false;
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the case of the graph of international airports, the code will return &lt;code&gt;true&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Depth First Traversal of a graph is also useful for pathfinding(not necessarily shortest path) and for solving mazes. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;A firm understanding of graphs as a data structure and of their associated algorithms is absolutely necessary when furthering one's studies of data structures and algorithms. Although not as beginner friendly as the previous posts in this series, this guide should prove useful to deepen your understanding of data structures and algorithms.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>dsa</category>
      <category>algorithms</category>
      <category>intermediate</category>
    </item>
    <item>
      <title>Data Structures and Algorithms: Breadth First Search</title>
      <dc:creator>Farai Bvuma</dc:creator>
      <pubDate>Wed, 22 May 2024 01:28:58 +0000</pubDate>
      <link>https://dev.to/faraib/data-structures-and-algorithms-breadth-first-search-3aid</link>
      <guid>https://dev.to/faraib/data-structures-and-algorithms-breadth-first-search-3aid</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In a breadth first search, we traverse a tree one level at a time, visiting each node on a level before visiting any potential children nodes. We will use a queue to explore this data structure.  See &lt;a href="https://dev.to/faraib/data-structures-and-algorithms-queues-1p3f"&gt;part three &lt;/a&gt; of this series for further details on queues.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Breadth First Traversal
&lt;/h2&gt;

&lt;p&gt;Considering the root of the tree, we add the root to the queue. We then remove the node at the front of the queue and print out its value. We also consider any children the node might have and then add them to the back of the queue, going from left to right. We repeat this process until the queue is empty. We can use the following binary tree to illustrate this. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fceb6r09qjxlky1gbzgby.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fceb6r09qjxlky1gbzgby.png" alt="Binary tree" width="800" height="629"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example we start by adding the root to our queue. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;[a]&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We remove the node at the front of the queue, printing out its value. We then add any children that this node might have to the back of the queue. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;[b, c]&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We repeat the process, removing the node at the front of the queue and printing its value, and then we add any of its children to the back of the queue. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;[c, d, e]&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We continue the process until the queue is empty. The resulting breadth first traversal of our example tree will be: &lt;strong&gt;a, b, c, d, e, f, g&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;A breadth first traversal can be achieved in javascript using the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const breathFirstTraversal = (root) =&amp;gt; {
  let queue = [root];

  while (queue.length &amp;gt; 0) {
    let currentNode = queue.shift();

    console.log(currentNode.val);

    if (currentNode.left !== null) {
      queue.push(currentNode.left);
    }
    if (currentNode.right !== null) {
      queue.push(currentNode.right);
    }
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Breadth First Search
&lt;/h2&gt;

&lt;p&gt;Knowing how to implement a breadth first traversal, we can now proceed to implement a breadth first search in order to find a target value in a tree. Here is how this can be done in javascript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const breathFirstSearch = (root, target) =&amp;gt; {
  let queue = [root];

  while (queue.length &amp;gt; 0) {
    let currentNode = queue.shift();

    if (currentNode.val === target) {
      return true;
    }

    if (currentNode.left !== null) {
      queue.push(currentNode.left);
    }
    if (currentNode.right !== null) {
      queue.push(currentNode.right);
    }
  }

  return false;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A breadth first traversal can also be used to add up all of the node values in a tree. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;This concludes the basics of a breadth first traversal and how this can be used as a basis for a breadth first search. As previously stated, the implicit data structure used in a breadth first traversal is a queue.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>dsa</category>
      <category>javascript</category>
      <category>trees</category>
    </item>
    <item>
      <title>Data Structures and Algorithms: Depth First Search</title>
      <dc:creator>Farai Bvuma</dc:creator>
      <pubDate>Fri, 03 May 2024 03:39:39 +0000</pubDate>
      <link>https://dev.to/faraib/data-structures-and-algorithms-depth-first-search-4c0e</link>
      <guid>https://dev.to/faraib/data-structures-and-algorithms-depth-first-search-4c0e</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In Depth First Search(DFS), we use an algorithm to traverse data structures such as trees and graphs. Starting with the root node, we traverse as deeply as possible on a branch(arriving at a leaf) before backtracking to a parent node and visiting its other children nodes. In code, this can either be done iteratively or recursively. &lt;/p&gt;

&lt;h2&gt;
  
  
  Types of Traversal
&lt;/h2&gt;

&lt;p&gt;Traversal is the process by which we can visit each and every node within in a tree. I will use the following tree to demonstrate the 3 types of traversal in a DFS.  &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F953ikza7txptd46b7j73.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F953ikza7txptd46b7j73.png" alt="Binary tree" width="800" height="552"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Pre-order
&lt;/h3&gt;

&lt;p&gt;In a pre-order traversal, we print out the value of the parent node before printing out the values of the children nodes. Here is some pseudocode showing the process.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;visitNode() 
recurseLeft()
recurseRight()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is some code showing how pre-order traversal can be achieved iteratively using a stack.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const preOrderTraversal = (root) =&amp;gt; {
  const stack = [root];
  while (stack.length &amp;gt; 0) {
    const node = stack.pop();
    console.log(node.val);
    if (node.right !== null) {
      stack.push(node.right);
    }
    if (node.left !== null) {
      stack.push(node.left);
    }
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The current node is pushed onto the stack and its value is printed out. If the current node has children, they are pushed onto the stack, starting with the right child followed by the left child. &lt;/p&gt;

&lt;p&gt;Alternatively, the same result can be achieved recursively. A good base case will be when the tree is empty, that is to say, when it has no leaves. This can be done as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const preOrderTraversal = (root) =&amp;gt; {
  if (root === null) {
    return;
  }

  console.log(root.val);
  preOrderTraversal(root.left);
  preOrderTraversal(root.right);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the above binary tree as an example, the result of a pre-order traversal will be: &lt;strong&gt;4, 21, 5, 8, 7, 13, 2&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;It is worth noting that the root will always be at the beginning of a pre-order traversal. &lt;/p&gt;

&lt;h3&gt;
  
  
  2. In-order
&lt;/h3&gt;

&lt;p&gt;In the case of an in-order traversal, we start at root and go left as deep into the tree as possible. When we reach a leaf(a node with no children), we print its value, print the value of the parent and then the value of the right leaf. The process is then repeated up the tree. The following is the pseudocode:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;recurseLeft()
visitNode() 
recurseRight()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As with the pre-order traversal, an in-order traversal can also be achieved iteratively:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const inOrderTraversal = (root) =&amp;gt; {
  const tempStack = [];
  const inOrder = [];

  while (true) {
    if (root !== null) {
      tempStack.push(root);
      root = root.left;
    } else {
      if (tempStack.length === 0) break;

      root = tempStack.pop();
      inOrder.push(root.val);
      root = root.right;
    }
  }
  return console.log(inOrder);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;An in-order traversal can also be achieved recursively:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const inOrderTraversal = (root) =&amp;gt; {
  if (root === null) {
    return;
  }

  inOrderTraversal(root.left);
  console.log(root.val);
  inOrderTraversal(root.right);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the above binary tree as an example, the result of an in-order traversal will be: &lt;strong&gt;5, 21, 8, 4, 13, 7, 2&lt;/strong&gt;. It is interesting to note that the root will always be somewhere in the middle of an in-order traversal.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Post-order
&lt;/h3&gt;

&lt;p&gt;As for a post-order traversal, we start at the root and go left until we reach a leaf. The value of this leaf is printed and then we go back up one and then go right, printing the value of the right leaf. Finally we go back up and print the value of the parent, before repeating the process up the tree. Here is the pseudocode:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;recurseLeft()
recurseRight()
visitNode()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is how a post-order traversal can be achieved iteratively utilizing a stack and an array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const postOrderTraversal = (root) =&amp;gt; {
  if (!root) return [];

  const tempStack = [root];
  const postOrder = [];

  while (tempStack.length) {
    const node = tempStack.pop();

    postOrder.unshift(node.val);

    if (node.left) {
      tempStack.push(node.left);
    }
    if (node.right) {
      tempStack.push(node.right);
    }
  }
  return console.log(postOrder);
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we use the temporary stack,&lt;code&gt;tempStack&lt;/code&gt;, to keep track of the nodes to be visited. In each iteration we remove a node from this temporary stack and add its value to the &lt;code&gt;postOrder&lt;/code&gt; array. If children nodes exist, they are pushed onto the temporary stack. &lt;/p&gt;

&lt;p&gt;Similar to the previous two types of traversal, a a post-order traversal can also be achieved recursively:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const postOrderTraversal = (root) =&amp;gt; {
  if (root === null) {
    return;
  }

  postOrderTraversal(root.left);
  postOrderTraversal(root.right);
  console.log(root.val);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the above binary tree as an example, the result of a post-order traversal will be: &lt;strong&gt;5, 8, 21, 13, 2, 7, 4&lt;/strong&gt;.&lt;br&gt;
It is also worth noting that the root will always be at the end of a post-order traversal. This is because we will visit and print the values of all of the children before printing out the value of the parent node. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;This concludes the three types of traversal that can be used in a depth first search. The implicit data structure used here is a stack. A depth first search can be useful when you want to compare the shape and structure of two trees. &lt;/p&gt;

</description>
      <category>beginners</category>
      <category>dsa</category>
      <category>javascript</category>
      <category>trees</category>
    </item>
    <item>
      <title>Data Structures and Algorithms: Trees</title>
      <dc:creator>Farai Bvuma</dc:creator>
      <pubDate>Fri, 26 Apr 2024 00:14:30 +0000</pubDate>
      <link>https://dev.to/faraib/data-structures-and-algorithms-trees-34c4</link>
      <guid>https://dev.to/faraib/data-structures-and-algorithms-trees-34c4</guid>
      <description>&lt;p&gt;Trees are a hierarchical data structure represented by nodes. Each node will have a value and possible children. &lt;/p&gt;

&lt;h2&gt;
  
  
  Terminology
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Root&lt;/strong&gt; - The first node in a tree.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Height&lt;/strong&gt; - The length of the longest path from the root to the furthest child node.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Leaves&lt;/strong&gt; - Nodes without children.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9gj95t2piqtr3ggj9tnu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9gj95t2piqtr3ggj9tnu.png" alt="Binary tree" width="800" height="474"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Binary Tree&lt;/strong&gt; - A tree that has at most 2 children. Usually described as left or right. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;General Tree&lt;/strong&gt; -  any tree with 0 or more children.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Binary Search Tree&lt;/strong&gt; - a tree which has a specific ordering and at most 2 children nodes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Balanced&lt;/strong&gt; -  a tree is considered to be balanced when the left and right children are of the same height.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Branching Factor&lt;/strong&gt; - the amount of children that a tree has, for example, a binary tree has a branching factor of 2.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Traversal&lt;/strong&gt; - The process by which each node in a tree is visited. The two main methods for tree traversal are Depth First Traversal and Breadth First Traversal. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The aim of this article was to serve as an introduction to trees. The next articles will go into detail about the types of tree traversal. &lt;/p&gt;

</description>
      <category>beginners</category>
      <category>trees</category>
      <category>datastructures</category>
    </item>
    <item>
      <title>Data Structures and Algorithms: Quick Sort</title>
      <dc:creator>Farai Bvuma</dc:creator>
      <pubDate>Wed, 13 Mar 2024 02:10:10 +0000</pubDate>
      <link>https://dev.to/faraib/data-structures-and-algorithms-quick-sort-pi</link>
      <guid>https://dev.to/faraib/data-structures-and-algorithms-quick-sort-pi</guid>
      <description>&lt;p&gt;The quick sort is a divide and conquer algorithm. This algorithm can be used to quickly order any given array. &lt;/p&gt;

&lt;h2&gt;
  
  
  How it works
&lt;/h2&gt;

&lt;p&gt;Given an array as input, we start by selecting an element of the array to act as the pivot. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkax3lbky5g22p8rmqcxv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkax3lbky5g22p8rmqcxv.png" alt="Unsorted array" width="582" height="298"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We then walk through the array, comparing each element to the pivot. Elements that are less than the pivot are placed to the left whilst elements that are greater than than the pivot are placed to the right. This will result in a weakly sorted array after the first run through.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa47sz0lsm32vu3tn872s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa47sz0lsm32vu3tn872s.png" alt="Weakly sorted array" width="230" height="75"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In order to further sort the array, we now select a pivot for the elements to the left and a separate pivot for the elements on the right. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwukr7hqh6jipsjnjvqfr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwukr7hqh6jipsjnjvqfr.png" alt="Subarray pivots" width="740" height="294"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We then proceed to repeat the process until we get to an empty array or an array with a single element.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqn2girl39us84vhgldl0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqn2girl39us84vhgldl0.png" alt="Sorting elements" width="800" height="814"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The single element arrays are then concatenated into a new sorted array. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm6jc9t2q2retu8becw69.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm6jc9t2q2retu8becw69.png" alt="Sorted array" width="298" height="94"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Below I will demonstrate how this can be applied in JavaScript using recursion.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Select pivot
&lt;/h3&gt;

&lt;p&gt;There are many ways in which a pivot can be selected. Some prefer to use the first element in the array and others prefer to select an element from somewhere in the middle. As a personal preference I like to select the last element of the array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  let pivot = array[array.length - 1];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. Establish base case
&lt;/h3&gt;

&lt;p&gt;Following the lead from the previous article, we will proceed to establish a base case for the recursive algorithm. When the array has only one element it will no longer need to call the function, as this single element array is already sorted.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; if (array.length &amp;lt;= 1) {
    return array;
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. Split
&lt;/h3&gt;

&lt;p&gt;Now we will split our array into two separate subarrays. All elements of the array found to have values smaller than the pivot will be put into one subarray, and all elements found to have values greater than the pivot will be put into another subarray.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  let low = [];
  let high = [];

  for (let i = 0; i &amp;lt; array.length - 1; i++) {
    if (array[i] &amp;lt; pivot) {
      low.push(array[i]);
    } else {
      high.push(array[i]);
    }
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. Establish recursive case
&lt;/h3&gt;

&lt;p&gt;Lastly, we need to provide the recursive case for the function. Here the quick sort function will be called on the two separate subarrays until they reach the base case, at which point they will be concatenated with the pivot to return a sorted array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return [...QuickSort(low), pivot, ...QuickSort(high)];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we use the spread operator(...) to merge the elements of the subarrays into the sorted array. &lt;/p&gt;

&lt;p&gt;Here is the complete code for the algorithm.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function QuickSort(array) {
  if (array.length &amp;lt;= 1) {
    return array;
  }
  let pivot = array[array.length - 1];
  let low = [];
  let high = [];

  for (let i = 0; i &amp;lt; array.length - 1; i++) {
    if (array[i] &amp;lt; pivot) {
      low.push(array[i]);
    } else {
      high.push(array[i]);
    }
  }
  return [...QuickSort(low), pivot, ...QuickSort(high)];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;This concludes the basics of the quick sort algorithm. It is an incredibly popular algorithm, mainly due to its relative speed and its simplicity, with the added advantage of not needing extra memory. It is a great choice when one wants to search a dataset for information. &lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>dsa</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>Data Structures and Algorithms: Recursion</title>
      <dc:creator>Farai Bvuma</dc:creator>
      <pubDate>Fri, 02 Feb 2024 02:30:15 +0000</pubDate>
      <link>https://dev.to/faraib/data-structures-and-algorithms-recursion-49ha</link>
      <guid>https://dev.to/faraib/data-structures-and-algorithms-recursion-49ha</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Recursion is a programming technique where a function calls itself repeatedly until it reaches a base case, which is the point at which the problem is solved. &lt;/p&gt;

&lt;p&gt;There are two steps to recursion:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Base case&lt;/li&gt;
&lt;li&gt;Recursive case&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Solving a problem with recursion
&lt;/h2&gt;

&lt;p&gt;We can use recursion to solve the problem of finding the factorial of any given integer. &lt;/p&gt;

&lt;h3&gt;
  
  
  Base Case
&lt;/h3&gt;

&lt;p&gt;To solve this with recursion, first we must create our base case. We will use the base case to prevent the function from running forever, at which point it will stop calling itself to return a result. &lt;/p&gt;

&lt;p&gt;Given that the factorial of a number n is the product of all positive integers less than or equal to n, the function will stop calling itself once n is equal to 1. At this point the return value will be 1.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if(n === 1) {
   return 1;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Recursive Case
&lt;/h3&gt;

&lt;p&gt;The second part is recursive case, where the function will call itself until it reaches the base case. &lt;br&gt;
In order to find the factorial, the function will be call itself whilst decrementing the value of n.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;n * factorial(n - 1);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The recursive case can be divided into 3 steps:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Pre: where an operation is performed before recursing, for example, multiplying the function by n.&lt;/li&gt;
&lt;li&gt;Recursion: where the function is called.&lt;/li&gt;
&lt;li&gt;Post: where n operation is performed after recursing, for example, logging the value of n.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;With the base case and recursive case defined, we can now write out the function to find the factorial of an integer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function factorial(n){
  if (n === 1) {
    return 1;
  }
  return n * factorial(n - 1);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Recursion can be a useful tool for breaking down complex programming problems. It is often used as an alternative to iteration(for and while loops) and is very useful for traversing trees and graphs. &lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>algorithms</category>
      <category>datastructures</category>
    </item>
  </channel>
</rss>
