<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Siddharth Yadav on Medium]]></title>
        <description><![CDATA[Stories by Siddharth Yadav on Medium]]></description>
        <link>https://medium.com/@siddharthyadav_1?source=rss-2a4360227bf2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*24oqahtwDAMzpjiMyjyyKw.jpeg</url>
            <title>Stories by Siddharth Yadav on Medium</title>
            <link>https://medium.com/@siddharthyadav_1?source=rss-2a4360227bf2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 09:12:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@siddharthyadav_1/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Graphs with Golang: Breadth-First Search]]></title>
            <link>https://medium.com/@siddharthyadav_1/graphs-with-golang-breadth-first-search-e0b34f538d08?source=rss-2a4360227bf2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0b34f538d08</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Siddharth Yadav]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 14:22:36 GMT</pubDate>
            <atom:updated>2024-11-21T14:22:36.083Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>A simple implementation of the standard BFS graph traversal algorithm using Go</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c0fYv7ZEEjMa1JHo" /><figcaption>Photo by <a href="https://unsplash.com/@clintadair?utm_source=medium&amp;utm_medium=referral">Clint Adair</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The last article explored <a href="https://medium.com/@siddharthyadav_1/graphs-with-golang-three-ways-to-represent-graphs-in-go-68dd9c3b98d5">how graphs are stored and represented in Golang</a>. This article will explore the Breadth First Search (BFS) algorithm. Studying graph traversal algorithms is the first step toward mastering the graph data structure.</p><p>Graph traversal algorithms explore the nodes and edges in a graph. Applications of graph traversal algorithms are vast, like:</p><ul><li>Finding degrees of connection in social networks,</li><li>Pathfinding in video games like generating paths for agents in grid-based maps,</li><li>Indexing pages while web crawling and many more.</li></ul><p>The Breadth First Search (BFS) algorithm traverses the graph by exploring nodes at the current depth level before moving on to the nodes at the next depth level. <strong>The BFS algorithm starts at a randomly chosen point and traverses its neighbors first, then moves step by step to the next level of neighbors, i.e., traversing neighbors of neighbors till a certain condition is met or the entire graph has been traversed.</strong></p><h3>The BFS Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*FSfEYDTsz2JNhXJFkiTNiw.png" /><figcaption>Generated by ChatGPT</figcaption></figure><h3>The Dry Run</h3><p>Let’s try to understand this by completely traversing the following graph with the BFS approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*TAFcT4qId2_aZMUBwYVEhA.png" /></figure><p>B will be the starting point. We will maintain a list and a queue while exploring the graph. The list contains the visited nodes and the queue contains the nodes to be visited.</p><p>Current status of the list and queue:</p><p>Visited Nodes: { } Queue: [B]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*JWA6eMxo0VLnK9NkpICDFQ.png" /></figure><p>Visited Nodes: {B} Queue: [C D A]</p><p>After visiting node B, its neighboring nodes were added to the queue. Next in the queue is node C.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*OuILIyV2QCR5pOUGUVDy8g.png" /></figure><p>Visited Nodes: {B C} Queue: [D A]</p><p>Since node C has no neighbors, no new node is added to the queue. Next, we will visit node D.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*9HDL5LvCZc6IYzOPEuoKWw.png" /></figure><p>Visited Nodes: {B C D} Queue: [A]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*goSzX5Cqi_n-mp0WD3WpkA.png" /></figure><p>Visited Nodes: {B C D A} Queue: [F E]</p><p>Since node A has 2 neighbors nodes F and E, they have been added to the queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*cvOjHmHhNkcRNzLJsLcJdA.png" /></figure><p>Visited Nodes: {B C D A F} Queue: [E G]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*HBpDj4S32r3gque8G1UYew.png" /></figure><p>Visited Nodes: {B C D A F E} Queue: [G H I]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*cZhieDAwjvt8ARNEzjANBw.png" /></figure><p>Visited Nodes: {B C D A F E G} Queue: [H I]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*KpwNryS-a9b59A0b-Dn4mg.png" /></figure><p>Visited Nodes: {B C D A F E G H} Queue: [I J K]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*dwxdRw66niNusvooHTd_dg.png" /></figure><p>Visited Nodes: {B C D A F E G H I} Queue: [J K]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*a_DfsLPhevfi48WSpQrQSA.png" /></figure><p>Visited Nodes: {B C D A F E G H I J} Queue: [K]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*nNzqHkrmF3ZC7O-z3-g3iQ.png" /></figure><p>Visited Nodes: {B C D A F E G H I J K} Queue: []</p><p>Since the queue is empty and all the nodes are in the Visited Nodes list, we have traversed the entire graph.</p><h3>Golang implementation</h3><p>To implement the BFS algorithm using Golang, we can ideally store and represent the graph in the adjacency list form.</p><p>An adjacency list is expressed as a map in Go where each key or index is a node of the graph and points to a list (slice in Go) of its neighboring nodes. This is how the graph would be represented as an adjacency list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*hz7p6pQ3jWtrcYnpmrPdUA.png" /></figure><p>The adjacency list is stored as a <em>map</em> of <em>slices</em> of <em>runes</em> i.e., <strong>map[rune][]rune </strong>in our case. Both index and value are <em>runes </em>because the nodes are represented by single uppercase alphabets.</p><p>Here’s how the adjacency list approach can be implemented in Go</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*tcHdev4Tvbr72jHbPDIZqQ.png" /></figure><p><a href="https://medium.com/@siddharthyadav_1/graphs-with-golang-three-ways-to-represent-graphs-in-go-68dd9c3b98d5">Click on the link for a detailed explanation of the adjacency list implementation and other approaches.</a></p><p>We can now create a function receiver <em>BFS </em>to implement the Breadth-First Search algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*rTXNFzfpMP-4lf7UJp-a1Q.png" /></figure><p>This approach is identical to the above pseudocode. Let’s create the above graph and apply BFS to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*kleFYATQv_VeVp9AVUuyfg.png" /></figure><p>Run all the above code. Following is the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*5PgGgRP5pT_te280-y2Duw.png" /></figure><p>The output of BFS traversal is identical to that of the dry run. Your output can differ based on the order of nodes and their neighbors in the adjacency list.</p><p>We can further optimize the BFS algorithm. Note that while checking if the neighbors of a node are in the Visited Nodes list, we have to iterate over that list for each neighbor. This results in O(n) complexity for each check. We can reduce it to O(1) complexity by using a <strong>map[rune]bool </strong>variable to track visited nodes. Here’s the improved BFS implementation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*eumrX2WD0IRRxOByPTpJ1w.png" /></figure><p>You can re-run the code with the new implementation. You won’t notice much improvement in performance as the graph chosen for BFS traversal is small and sparse. The runtime will be significantly faster for the O(1) check implementation for larger and denser graphs.</p><p>We have successfully implemented the BFS traversal algorithm. Next time, we will study the Depth-First Seach (DFS) algorithm for graph traversal.</p><p><strong>References:</strong></p><ul><li><a href="https://youtu.be/YtD2KGRdn3s?si=K-9MsE1yobweFBpI">Breadth First Search Algorithm Explained (With Example and Code)</a> by <a href="https://www.youtube.com/@FelixTechTips">FelixTechTips</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0b34f538d08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graphs with Golang: Three Ways to Represent Graphs in Go]]></title>
            <link>https://medium.com/@siddharthyadav_1/graphs-with-golang-three-ways-to-represent-graphs-in-go-68dd9c3b98d5?source=rss-2a4360227bf2------2</link>
            <guid isPermaLink="false">https://medium.com/p/68dd9c3b98d5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Siddharth Yadav]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 13:58:10 GMT</pubDate>
            <atom:updated>2024-11-18T14:05:32.653Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>LLMs have revived my interest in the graph data structure. I believe the best way to revise a topic is to teach it. So, this is the first article in a series of many.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4-AFvIy9BasVhewl" /><figcaption>Photo by <a href="https://unsplash.com/@theshubhamdhage?utm_source=medium&amp;utm_medium=referral">Shubham Dhage</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Given basic requirements and preferences, many ways exist to define and represent graphs. Here, we will cover 3 ways to define and store graphs using Golang.</p><h3><strong>What are graphs?</strong></h3><p>A graph is a data structure in which data is stored in vertices (or nodes) and edges. Pairs of vertices in a graph are connected through edges. Graphs are ideal for representing relationships between entities. Graphs are used to model real-world problems in domains like social networks, transportation, logistics, navigation, artificial intelligence, electrical circuits, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*31mbkyi1XuTLFUOW3UsEsQ.jpeg" /><figcaption>Source: <a href="https://www.linkedin.com/pulse/how-graph-theory-maps-untamed-landscape-social-networks-t-erzic/">How Graph Theory Maps the Untamed Landscape of Social Networks</a> by <a href="https://www.linkedin.com/in/vijayadharshini-t/">Vijaya Dharshini T</a></figcaption></figure><h3><strong>Components of a graph</strong></h3><ul><li><strong>Vertices or Nodes:</strong> Represent the entities or objects in the graph. For example, every person in a social network is a node.</li><li><strong>Edges:</strong> Represent the connections or relationships between pairs of vertices. These relationships can be bidirectional (the edge is undirected) or unidirectional (directed edge).</li><li>For example, in a social network, if two nodes Brad and Jill are friends, they have a bidirectional relationship represented by an <strong>undirected edge</strong>. <em>See Fig 1(a)</em></li><li>On the other hand, if Jill follows Brad but Brad doesn’t follow Jill, this is a unidirectional relationship represented by a <strong>directed edge.</strong> The edge here looks like a line connecting Brad and Jill with an arrow pointing towards Brad. <em>See Fig 1(b)</em></li><li>If Brad follows back Jill, yet another edge connects Brad and Jill but its arrow now points towards Jill. The relationship can now be called bidirectional. <em>See Fig 1(c)</em></li><li><strong>Weights:</strong> An optional numerical value stored on an edge representing cost, distance, or any plausible metric.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*DyMnpFMolReaR-HPat5STQ.png" /></figure><h3>Adjacency Matrix</h3><p>An adjacency matrix stores a graph in a 2D matrix. Suppose a 2D array M stores a graph where all edges are undirected and unweighted. If node A is connected to node B, then the matrix elements M[A][B] and M[B][A] hold the value 1.</p><ul><li>For weighted graphs, M[A][B] = M[B][A] = weight of the edge connecting A and B</li><li>For directed graphs, if A and B are connected and the edge is directed towards B, only M[A][B] = 1 as the relationship is now unidirectional</li><li>The space complexity of the adjacency matrix is O(V²) where V is the number of vertices</li></ul><p>Using an Adjacency Matrix to store a graph facilitates fast edge lookups (O(1) time complexity). This approach works well with dense graphs but should not be used for storing sparse graphs due to high memory usage.</p><p>Adjacency matrices can be used to store social network data with many relationships and connections.</p><p>In Golang, a 2D matrix or 2D array can be represented as a slice of integer slices i.e., <strong>[][]int</strong>. To be able to print this adjacency matrix, we might need to use a more complex data structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*DbiSF0KJW7NFJxaP5Hl-Uw.png" /></figure><p>So, we will use a <em>struct </em>called <em>GraphMatrix</em> to store the graph. While its attribute <em>matrix </em>stores the adjacency matrix, its other attributes <em>vertices </em>and <em>indexMap</em> map the vertices to their indices and vice-versa. This mapping is useful for printing the adjacency matrix and preventing duplicity of vertices in the <em>matrix</em>.</p><p>For the data structure GraphMatrix, we will then introduce two function receivers <em>AddVertex</em> and <em>AddEdge </em>to populate the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*6F_rYwUC177R_4oFJjSmMg.png" /></figure><p>Whenever a new edge is added, vertices are added only if they don’t already exist in the map <em>vertices.</em></p><p>Finally, we will add the function receiver <em>Print </em>to display the adjacency matrix with its rows and columns labeled with the vertices they represent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*SWAwDMMpG53Pc2IDoDmu_A.png" /></figure><p>We will use the following graph to create the adjacency matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*tldlWKAho95jny1_s7YbZA.png" /></figure><p>Since an uppercase character represents each vertex, the <em>GraphMatrix</em> structure uses Go’s <em>rune</em> data type to store vertices wherever required. Let’s create this graph next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*5ZSa2V6c4vVImtjS2HByew.png" /></figure><p>Run all the code above to store and represent the above graph as an adjacency matrix. Following is the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*m22HKxypu4J7HplOAFQG9Q.png" /></figure><h3>Adjacency List</h3><p>An adjacency list is expressed as a dictionary (or a map in Go) of lists where each key or index is a node and the value it points to is the list of nodes connected to this index node.</p><ul><li>The space complexity of adjacency lists is O(V+E) where V is the number of vertices and E is the number of edges.</li><li>While adjacency lists are memory efficient for sparse graphs and ideal for traversing or accessing neighbor nodes, edge lookups are slower in this approach.</li><li>Sparse graphs like road networks can be efficiently stored as adjacency lists.</li></ul><p>In Golang, an adjacency list is stored as a <em>map</em> of <em>slices</em> of <em>runes</em> where the index type of the map is also <em>rune</em> i.e., <strong>map[rune][]rune </strong>in our case. We use <em>rune</em> as the index type of the <em>map. Runes </em>are<em> </em>also stored in <em>slices </em>to store a single character in each node. If we were to store entire text passages, the adjacency list would be represented as <strong>map[string][]string.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*vJRzOBm-72m8Y2KeQmEcCQ.png" /></figure><p>Just like in the matrix approach, a new vertex is added only after checking the index of the adjList attribute of the struct GraphList. If the vertex is new, it’s added to the index and points to an empty <em>slice</em> of <em>runes.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*I1WOvnAgBzaIv0Cj-xhCyA.png" /></figure><p>The <em>Print</em> function receiver is also much simpler. Let’s display an adjacency list for the same graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*rMVjY7DJdD22r5eQBUFDvA.png" /></figure><h3>Edge List</h3><p>This approach involves storing the graph as a list of edges. In Golang, this will be represented as <strong>[][2]rune</strong> i.e., a <em>slice</em> of edges where an edge is a <em>slice</em> containing exactly two <em>runes</em>, the start (or first) node and the end (second) node of an edge.</p><ul><li>The space complexity is O(E). Much better than the adjacency matrix</li><li>This approach is memory efficient for just storing edges and ideal when using graph algorithms like Kruskal’s algorithm</li><li>The edge list approach is inefficient for accessing neighbor nodes or performing graph traversals.</li></ul><p>Let’s implement this approach in Golang for the same graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*aOlV0wHbwVxr9-Or3xATeQ.png" /></figure><p>The output should be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/98/1*Yg3ufGoOO2C88o1W_xPRGQ.png" /></figure><p>The output has double the number of edges because this is an undirected graph so each edge creates a bidirectional relationship.</p><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*VOqRVafycARLP7HViPDXrQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68dd9c3b98d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I used ChatGPT and LeetCode to gain expertise in Golang]]></title>
            <link>https://medium.com/@siddharthyadav_1/i-used-chatgpt-and-leetcode-to-gain-expertise-in-golang-bee4728f4cfa?source=rss-2a4360227bf2------2</link>
            <guid isPermaLink="false">https://medium.com/p/bee4728f4cfa</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Siddharth Yadav]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 16:33:01 GMT</pubDate>
            <atom:updated>2024-09-13T16:41:00.459Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Kb1rJ7x0Mz91YEhsHF7GgA.png" /><figcaption>Source: <a href="https://medium.com/@jamesotoole/golang-and-why-it-matters-1710b3af96f7">Golang and why it matters</a> on <a href="https://medium.com/">Medium</a></figcaption></figure><p>I have been coding in Python for 6 years now. While I am quite good at Python, I always wanted to learn a programming language with faster compile times. This year, I finally took the Golang course at <a href="https://www.boot.dev/">boot.dev</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IWbIOr9Rd5WCV0_K" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin?utm_source=medium&amp;utm_medium=referral">Caspar Camille Rubin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Getting into Golang was easier than I thought. I breezed through the course. I liked the Golang syntax and the cool features. Even though I knew it was fast, I was still surprised by its compile times and portability. Having gained a beginner’s knowledge of Golang, I wanted to practice more. I have built basic REST APIs and simple ETL tools in Go but wanted to be as efficient at writing code in Go as I am at Python.</p><h3><strong>Just solve two DSA problems</strong></h3><p>I have come up with a technique that has worked great for me. Every day after having my morning coffee, I sit down to solve two easy or medium-level Leetcode problems.</p><p><strong>First Problem:</strong> Solve the problem using Python and then try to code the same in Golang. If I get stuck while coming up with the code in Go for more than 15 minutes, I ask ChatGPT for the code with a simple prompt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*QxoCmqV_XkRVXfOSak-sRg.png" /><figcaption>ChatGPT prompt for basic Trie implementation</figcaption></figure><p>Following is the code generated by ChatGPT:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>// Trie represents the trie data structure<br>type Trie struct {<br> root      *Node<br> endSymbol rune<br>}<br><br>// Node represents a node in the trie<br>type Node struct {<br> children map[rune]*Node<br> isEnd    bool<br>}<br><br>// NewTrie initializes and returns a new Trie<br>func NewTrie() *Trie {<br> return &amp;Trie{<br>  root:      &amp;Node{children: make(map[rune]*Node)},<br>  endSymbol: &#39;*&#39;, // Not strictly necessary for Go version<br> }<br>}<br><br>// Add adds a word to the trie<br>func (t *Trie) Add(word string) {<br> current := t.root<br> for _, letter := range word {<br>  if _, found := current.children[letter]; !found {<br>   current.children[letter] = &amp;Node{children: make(map[rune]*Node)}<br>  }<br>  current = current.children[letter]<br> }<br> current.isEnd = true<br>}<br><br>// LongestCommonPrefix finds the longest common prefix in the trie<br>func (t *Trie) LongestCommonPrefix() string {<br> current := t.root<br> prefix := &quot;&quot;<br><br> for {<br>  if current.isEnd {<br>   break<br>  }<br><br>  // Get all children keys<br>  var children []rune<br>  for key := range current.children {<br>   children = append(children, key)<br>  }<br><br>  // Check for end symbol or multiple children<br>  if len(children) != 1 {<br>   break<br>  }<br><br>  // Append to prefix and move to next node<br>  prefix += string(children[0])<br>  current = current.children[children[0]]<br> }<br><br> return prefix<br>}<br><br>// Solution represents a solution to find the longest common prefix<br>type Solution struct{}<br><br>// LongestCommonPrefix finds the longest common prefix among a list of strings<br>func (s *Solution) LongestCommonPrefix(strs []string) string {<br> trie := NewTrie()<br> for _, word := range strs {<br>  trie.Add(word)<br> }<br> return trie.LongestCommonPrefix()<br>}<br><br>func main() {<br> solution := Solution{}<br> words := []string{&quot;flower&quot;, &quot;flow&quot;, &quot;flight&quot;}<br> fmt.Println(solution.LongestCommonPrefix(words)) // Output: &quot;fl&quot;<br>}</pre><p>The generated code was correct and I could easily learn how data structures like Tries are implemented in Go by feeding ChatGPT the equivalent Python implementation. Go differs from Python in that it uses pointers, receiver functions, and structs instead of Classes. Using this approach, I have grown accustomed to both styles.</p><p><strong>Second Problem: </strong>This problem should be similar to the first, preferably requiring the use of a similar data structure or algorithm. This should be solved only using Go. ChatGPT can be utilized for syntax-related doubts. I don’t use ChatGPT for hints or solutions before 15 minutes have passed or before I have an implementation that at least passes some cases.</p><h3>Dry Run: A secret weapon</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wT46gPjfVrAvOqfr" /><figcaption>Photo by <a href="https://unsplash.com/@firmbee?utm_source=medium&amp;utm_medium=referral">Firmbee.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Apart from learning Go, it is also important to be able to solve DSA problems faster and understand how the code works for each test case. I perform dry runs to get a better understanding of the problem and its solution.</p><p>A dry run is a simulated execution of code step-by-step to gauge the code’s correctness, behavior, and impact before actually executing it.</p><p>For example, I performed a dry run using ChatGPT for <a href="https://leetcode.com/problems/swap-nodes-in-pairs/"><strong>Leetcode Problem #24: Swap Nodes in Pairs</strong></a><strong> </strong>to better understand the how the code works. Following is the Go code generated by ChatGPT when provided with the correct Python code:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// ListNode represents a node in the linked list.<br>type ListNode struct {<br> Val  int<br> Next *ListNode<br>}<br><br>// swapPairs swaps adjacent pairs of nodes in the linked list.<br>func swapPairs(head *ListNode) *ListNode {<br> if head == nil || head.Next == nil {<br>  return head<br> }<br><br> flag := true<br> p := head<br> var pr *ListNode // previous node for linking the swapped pairs<br><br> for p.Next != nil {<br>  q := p<br>  r := p.Next<br>  p = p.Next<br>  q.Next = r.Next<br>  r.Next = q<br><br>  if flag {<br>   head = p<br>   flag = false<br>  } else {<br>   pr.Next = r<br>  }<br><br>  p = p.Next<br>  if p != nil &amp;&amp; p.Next != nil {<br>   p = p.Next<br>  }<br>  pr = q<br> }<br><br> return head<br>}<br><br>// Helper function to print the list<br>func printList(head *ListNode) {<br> for head != nil {<br>  fmt.Printf(&quot;%d -&gt; &quot;, head.Val)<br>  head = head.Next<br> }<br> fmt.Println(&quot;nil&quot;)<br>}<br><br>func main() {<br> // Example usage<br> head := &amp;ListNode{Val: 1}<br> head.Next = &amp;ListNode{Val: 2}<br> head.Next.Next = &amp;ListNode{Val: 3}<br> head.Next.Next.Next = &amp;ListNode{Val: 4}<br><br> fmt.Println(&quot;Original list:&quot;)<br> printList(head)<br><br> newHead := swapPairs(head)<br> fmt.Println(&quot;List after swapping pairs:&quot;)<br> printList(newHead)<br>}</pre><p>Then, I asked ChatGPT to perform a dry run for a simple test case with the following prompt:</p><p><strong><em>Give me a dry run for a linked list [1,2,3,4]</em></strong></p><p>Following is the dry run performed instantly by ChatGPT:</p><p>Let’s go through a dry run of the swapPairs function with the linked list [1, 2, 3, 4]. Here’s a step-by-step breakdown of how the function processes the list:</p><h4>Initial Setup</h4><ul><li>Input list: [1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; nil]</li><li>Pointers:</li><li>p starts at the head (1).</li><li>flag is true.</li><li>pr (previous node pointer) is initially nil.</li></ul><h4>Step 1: First Pair Swap (1 and 2)</h4><ul><li>q = p (q points to 1)</li><li>r = p.Next (r points to 2)</li><li>Move p to p.Next (p points to 2)</li><li>Update q.Next to r.Next (1.Next points to 3)</li><li>Update r.Next to q (2.Next points to 1)</li></ul><p>Now the list looks like: [2 -&gt; 1 -&gt; 3 -&gt; 4 -&gt; nil]</p><ul><li>Since flag is true, update the head to p (2), and set flag to false.</li><li>Set pr = q (pr points to 1).</li><li>Move p to p.Next (p points to 3).</li></ul><h4>Step 2: Second Pair Swap (3 and 4)</h4><ul><li>q = p (q points to 3)</li><li>r = p.Next (r points to 4)</li><li>Move p to p.Next (p points to 4)</li><li>Update q.Next to r.Next (3.Next points to nil)</li><li>Update r.Next to q (4.Next points to 3)</li></ul><p>Now the list looks like: [2 -&gt; 1 -&gt; 4 -&gt; 3 -&gt; nil]</p><ul><li>Since flag is false, update pr.Next to r (1.Next points to 4), linking the previous swapped nodes with the new ones.</li><li>Set pr = q (pr points to 3).</li><li>Move p to p.Next (p is now nil), ending the loop.</li></ul><h4>Final List</h4><p>The list after all swaps is: [2 -&gt; 1 -&gt; 4 -&gt; 3 -&gt; nil].</p><h3>Summary of Changes:</h3><ol><li><strong>Initial List</strong>: [1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; nil]</li><li><strong>After First Swap</strong>: [2 -&gt; 1 -&gt; 3 -&gt; 4 -&gt; nil]</li><li><strong>After Second Swap</strong>: [2 -&gt; 1 -&gt; 4 -&gt; 3 -&gt; nil]</li></ol><p>The swapPairs function correctly swaps adjacent pairs of nodes. Let me know if you have more questions about this!</p><p>The above information greatly improves my intuition and saves time. Performing the same dry run on paper would take me several minutes and would still not be as organized or verbose as the above result.</p><p>I do dry runs on paper when I first encounter any new Leetcode problem but for tough problems with complex solutions, dry runs using ChatGPT bring efficiency to problem-solving and I can avoid unnecessary frustration.</p><p>If you don’t entirely agree with this approach, you can always tweak it according to your requirements. My aim here is to show how advancements in AI can improve the pace of learning and skill development with a simple yet well-defined process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bee4728f4cfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>